Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .pylon/features.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -215,17 +215,19 @@ decisions:
owner: shared
decision: hybridize
pylon_refs:
- https://github.com/pylon-code/pylon/issues/557
- https://github.com/pylon-code/prime-agent/issues/11
- https://github.com/pylon-code/prime-agent/pull/14
- https://github.com/pylon-code/pylon/issues/114
- https://github.com/rynfar/comet/issues/5
upstream_refs:
- https://github.com/PrimeIntellect-ai/prime-agent/issues/1908
- https://github.com/PrimeIntellect-ai/prime-agent/pull/1756
- https://github.com/PrimeIntellect-ai/prime-agent/pull/1858
- https://github.com/PrimeIntellect-ai/prime-agent/pull/1864
- https://github.com/PrimeIntellect-ai/prime-agent/pull/1882
fork_change: negotiated-authoritative-owned-session-cleanup-v1
upstream_support: Prime through a903d4b6768f has recovery-aware reuse, owner-checked opens, bounded daemon-close bash draining, per-command abort ownership, client-owned sessions, and best-effort owner cleanup, but another host process cannot prove exact worker-generation and durable-descriptor absence after the owner connection disappears.
fork_change: negotiated-authoritative-owned-session-cleanup-v1-and-local-settlement-observation
upstream_support: Reviewed again 2026-09-18; upstream issue 1908 concerns PID-based session lease cleanup, not a public read-only settlement proof for prior caller-owned roots across socket namespaces. Prime through a903d4b6768f has recovery-aware reuse, owner-checked opens, bounded daemon-close bash draining, per-command abort ownership, client-owned sessions, and best-effort owner cleanup, but another host process cannot prove exact worker-generation and durable-descriptor absence after the owner connection disappears.
revisit_when:
- Prime upstream exposes an equivalent privacy-safe, capability-negotiated cleanup proof with durable descriptor-last retries.
- Comet and Pylon can remove the fork capability without weakening crash cleanup or stock-Prime fallback behavior.
Expand Down
11 changes: 11 additions & 0 deletions .pylon/upstream-review.md
Original file line number Diff line number Diff line change
Expand Up @@ -378,3 +378,14 @@ Follow-up: Task10 builds/packs the exact merged tree into a private prefix and r
- Add an optional original timestamp to both custom append methods and pass it from every AgentSession custom-message write: delivered/queued messages, direct messages, session commands, Python state, harness digests, refinement and compaction outcomes. Calls that originate durable markers without a live message retain their existing current-time default. Invalid or lossy timestamps fail before publication.
- No daemon command, event, response shape, protocol/schema revision, artifact recipe or capability changes. Historical files are not rewritten. An older custom record whose live and persisted timestamps already disagree remains unproved; Pylon must not relax history matching to accept it. New managed bytes are required for the correction.
- Validation: 165 focused tests pass across the timestamp regression, session persistence/rollback, compaction and input queue. The regression deliberately advances the clock at the persistence boundary and verifies the exact live, pre-compaction tree, current context and reopened session messages. `npm run check` and required hosted checks accompany the PR.

## 2026-09-18: legacy caller-owned settlement observation

Decision: hybridize the existing descriptor-last cleanup invariant with a public,
read-only local SDK observation. Upstream #1908 requests PID-based lease sweeping;
it does not cover a host-private acquired receipt lacking a recovery handle and
old socket identity. Existing public replacement-client cleanup remains unchanged.
The SDK token gates the new local API; daemon wire shapes and stock behavior do
not change. Validation: focused malformed/private/path/registration cases and a real
isolated supervisor/owned-worker test prove registered before cleanup and settled
after exact owned cleanup and supervisor exit. Pylon delivery tracked in [pylon#557](https://github.com/pylon-code/pylon/issues/557).
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Added read-only settlement observation for a local host retaining a proved caller-owned session receipt after restart.
20 changes: 20 additions & 0 deletions packages/coding-agent/docs/sdk.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,26 @@ The contract proof contains only the feature/status, protocol identity, schema r

Use `disposeOwnedSession({ timeoutMs })` when cleanup must be observable. Concurrent calls join one operation, and `timeoutMs` is one strict total deadline for reconnection, authoritative queries, completion, side-question aborts, and unsupported-peer finalization. Its fixed statuses are `completed`, `already_completed`, `replacement_settled`, `owner_mismatch`, `uncertain`, `transport_failure`, and `unsupported`; `uncertain` also reports whether the last authoritative state was `active` or `stopping`. `replacement_settled` means an authenticated supervisor with a different generation answered the read-only cleanup query with `settled` for the connection's previously proved opaque route. Cleanup never sends completion on a replacement or pending route without a current internal attach proof. Each strict cleanup request is transport-bound and is never replayed after reconnect. Public attachment proof remains absent throughout disposal. Results never return raw errors or environment identity. `dispose()` remains the legacy best-effort `Promise<void>` API.

### Observing settlement after a host restart

A local POSIX host retaining a prior `caller_owned_session_environment_cleanup_v1`
attachment proof may use the frozen SDK feature `owned_session_settlement_observation_v1`
and public `observeOwnedSessionSettlement({ agentDir, activeSessionId, contractProof })`.
Pass the exact canonical agent home and root route saved with that proof. This read-only
operation scans Prime's durable registration namespaces, including prior temporary socket
locations, without creating a daemon, claiming ownership, sending completion, or signaling
processes. It returns only the feature token and `settled`, `registered`, or `unavailable`.

Only `settled` permits retirement of that exact legacy host receipt. A capable supervisor
persists registration before releasing its worker startup gate, retains it during recovery,
and removes it last after joining cleanup. This observation relies on that prior contract;
it is not a general orphan-process detector or authority for stock/descriptorless work,
copied state, or a different agent home. Missing, changing, malformed, oversized, aliased,
or nonprivate registries return `unavailable`. Existing registrations return `registered`
even if their socket and PID are gone. Retain quarantine in either case. Native Windows
is unsupported. Hosts must compare and remove their exact receipt atomically and must
continue using recovery-handle adoption for recoverable sessions.

### Recoverable caller-owned daemon sessions

Native detached-daemon hosts can opt into same-supervisor recovery with `recoverable_owned_session_adoption_v1`. The complete pre-create gate requires schema revision 30, the frozen package-root SDK tokens `recoverable_owned_session_adoption_v1` and `caller_owned_session_environment_cleanup_v1`, and connected hello offers for `daemon_recoverable_owned_session_adoption_v1`, `caller_owned_session_environment_cleanup_v1`, and `authoritative_owned_session_cleanup_v1`. If any proof is absent, select ACP before creating a native worker. This is a POSIX detached-daemon contract; it does not provide resident promotion, cross-host recovery, or recovery after supervisor process replacement.
Expand Down
4 changes: 2 additions & 2 deletions packages/coding-agent/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@
"copy-assets": "shx mkdir -p dist/modes/interactive/theme && shx cp src/modes/interactive/theme/*.json dist/modes/interactive/theme/ && shx mkdir -p dist/modes/interactive/assets && shx cp src/modes/interactive/assets/*.png dist/modes/interactive/assets/ && shx mkdir -p dist/core/export-html/vendor && shx cp src/core/export-html/template.html src/core/export-html/template.css src/core/export-html/template.js dist/core/export-html/ && shx cp src/core/export-html/vendor/*.js dist/core/export-html/vendor/ && shx rm -rf dist/prime-agent-runtime && shx cp -r ../../prime-agent-runtime dist/prime-agent-runtime && shx rm -rf dist/skills && shx cp -r skills dist/skills",
"copy-binary-assets": "shx cp package.json dist/ && shx cp README.md dist/ && shx cp CHANGELOG.md dist/ && shx mkdir -p dist/theme && shx cp src/modes/interactive/theme/*.json dist/theme/ && shx mkdir -p dist/assets && shx cp src/modes/interactive/assets/*.png dist/assets/ && shx mkdir -p dist/export-html/vendor && shx cp src/core/export-html/template.html dist/export-html/ && shx cp src/core/export-html/vendor/*.js dist/export-html/vendor/ && shx cp -r docs dist/ && shx cp -r examples dist/ && shx cp ../../node_modules/@silvia-odwyer/photon-node/photon_rs_bg.wasm dist/ && shx rm -rf dist/skills && shx cp -r skills dist/skills",
"test": "vitest --run",
"test:ci": "tsx src/core/kernel/bootstrap-cli.ts && vitest --run --exclude test/daemon-supervisor-process.test.ts",
"test:process": "vitest --run test/daemon-supervisor-process.test.ts",
"test:ci": "tsx src/core/kernel/bootstrap-cli.ts && vitest --run --exclude test/daemon-supervisor-process.test.ts --exclude test/owned-session-settlement-process.test.ts",
"test:process": "vitest --run --no-file-parallelism test/daemon-supervisor-process.test.ts test/owned-session-settlement-process.test.ts",
"test:process-stress": "vitest --run --tagsFilter process-stress test/daemon-supervisor-process.test.ts",
"postinstall": "node postinstall.cjs",
"prepublishOnly": "npm run clean && npm run build",
Expand Down
5 changes: 5 additions & 0 deletions packages/coding-agent/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,11 @@ export {
type RecoverableOwnedSessionCreateOptions,
type RecoverableOwnedSessionCreation,
} from "./modes/agent-connection/recoverable-owned-session.js";
export {
OWNED_SESSION_SETTLEMENT_OBSERVATION_FEATURE,
type OwnedSessionSettlementObservation,
observeOwnedSessionSettlement,
} from "./modes/daemon/owned-session-settlement.js";
// Run modes for programmatic SDK usage
export {
ClientPromptStashStore,
Expand Down
160 changes: 160 additions & 0 deletions packages/coding-agent/src/modes/daemon/owned-session-settlement.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { createHash } from "node:crypto";
import { constants } from "node:fs";
import { lstat, open, readdir, realpath } from "node:fs/promises";
import { isAbsolute, join } from "node:path";
import { CALLER_OWNED_SESSION_ENVIRONMENT_CLEANUP_FEATURE } from "../../sdk-features.js";
import type { DaemonOwnedSessionContractProof } from "../agent-connection/daemon-agent-connection.js";
import type { DaemonWorkerDescriptor } from "./daemon-worker-protocol.js";

export const OWNED_SESSION_SETTLEMENT_OBSERVATION_FEATURE = "owned_session_settlement_observation_v1" as const;

export interface OwnedSessionSettlementObservation {
readonly feature: typeof OWNED_SESSION_SETTLEMENT_OBSERVATION_FEATURE;
readonly status: "settled" | "registered" | "unavailable";
}

function validRegistration(value: unknown, scope: string): value is DaemonWorkerDescriptor {
if (!value || typeof value !== "object") return false;
const d = value as Partial<DaemonWorkerDescriptor>;
return (
(d.version === 1 || d.version === 2) &&
typeof d.supervisorSocketPath === "string" &&
isAbsolute(d.supervisorSocketPath) &&
createHash("sha256").update(d.supervisorSocketPath).digest("hex").slice(0, 12) === scope &&
typeof d.workerId === "string" &&
d.workerId.length > 0 &&
Number.isInteger(d.pid) &&
(d.pid ?? 0) > 0 &&
(d.processStartId === undefined || typeof d.processStartId === "string") &&
(d.ownerClientId === undefined || typeof d.ownerClientId === "string") &&
(d.callerOwnedEnvironmentContract === undefined || d.callerOwnedEnvironmentContract === true) &&
typeof d.socketPath === "string" &&
typeof d.authenticationToken === "string" &&
typeof d.rootActiveSessionId === "string" &&
d.rootActiveSessionId.length > 0 &&
typeof d.createdAt === "string" &&
typeof d.updatedAt === "string" &&
Number.isInteger(d.consecutiveFailures) &&
d.createCommand?.type === "create"
);
}

/**
* Read-only local-host recovery for a previously proved caller-owned root.
* Capable supervisors persist registration before releasing the worker startup gate,
* retain it across recovery, and remove it last after joining all cleanup. Inspect
* every socket namespace in the exact agent home: a legacy host may have lost its
* temporary socket path. This never adopts, completes, signals, or launches work.
* A proof from before the caller-owned contract cannot certify descriptorless work.
*/
export async function observeOwnedSessionSettlement(input: {
readonly agentDir: string;
readonly activeSessionId: string;
readonly contractProof: DaemonOwnedSessionContractProof;
}): Promise<OwnedSessionSettlementObservation> {
const result = (status: OwnedSessionSettlementObservation["status"]): OwnedSessionSettlementObservation =>
Object.freeze({ feature: OWNED_SESSION_SETTLEMENT_OBSERVATION_FEATURE, status });
const proof = input.contractProof;
if (
!isAbsolute(input.agentDir) ||
!input.activeSessionId ||
input.activeSessionId.length > 256 ||
proof?.feature !== CALLER_OWNED_SESSION_ENVIRONMENT_CLEANUP_FEATURE ||
proof.status !== "attached" ||
proof.daemon?.protocolName !== "prime-agent.daemon" ||
!Number.isSafeInteger(proof.daemon.protocolVersion) ||
proof.daemon.protocolVersion < 7 ||
!Number.isSafeInteger(proof.daemon.schemaRevision) ||
proof.daemon.schemaRevision < 0 ||
!Number.isSafeInteger(proof.daemon.transportGeneration) ||
proof.daemon.transportGeneration < 0 ||
!proof.daemon.supervisorGeneration
)
return result("unavailable");
const uid = process.getuid?.();
if (uid === undefined || process.platform === "win32") return result("unavailable");
const deadline = Date.now() + 10_000;
let inspectedBytes = 0;
let inspectedFiles = 0;
try {
if ((await realpath(input.agentDir)) !== input.agentDir) return result("unavailable");
const root = join(input.agentDir, "daemon-workers");
const privateDirectory = async (path: string) => {
const info = await lstat(path);
if (!info.isDirectory() || info.isSymbolicLink() || info.uid !== uid || (info.mode & 0o077) !== 0) {
throw new Error("Unproved registry directory");
}
return info;
};
const rootIdentity = await privateDirectory(root);
const scopes = (await readdir(root)).sort();
if (scopes.length > 2048) return result("unavailable");
for (const scope of scopes) {
if (!/^[a-f0-9]{12}$/.test(scope) || Date.now() >= deadline) return result("unavailable");
const directory = join(root, scope);
const identity = await privateDirectory(directory);
const names = (await readdir(directory)).sort();
for (const name of names) {
if (!name.endsWith(".json")) continue;
if (++inspectedFiles > 16384 || Date.now() >= deadline) return result("unavailable");
const file = await open(
join(directory, name),
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
);
try {
const before = await file.stat();
inspectedBytes += before.size;
if (
!before.isFile() ||
before.uid !== uid ||
(before.mode & 0o077) !== 0 ||
before.size > 1024 * 1024 ||
inspectedBytes > 64 * 1024 * 1024
)
return result("unavailable");
const descriptor: unknown = JSON.parse(
await (async () => {
const buffer = Buffer.alloc(before.size + 1);
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
if (bytesRead !== before.size) throw new Error("Changing registration");
return buffer.subarray(0, bytesRead).toString("utf8");
})(),
);
const after = await file.stat();
const linked = await lstat(join(directory, name));
if (
linked.isSymbolicLink() ||
linked.dev !== before.dev ||
linked.ino !== before.ino ||
before.size !== after.size ||
before.mtimeMs !== after.mtimeMs ||
!validRegistration(descriptor, scope)
)
return result("unavailable");
if (descriptor.rootActiveSessionId === input.activeSessionId) return result("registered");
} finally {
await file.close();
}
}
const after = await privateDirectory(directory);
if (
after.dev !== identity.dev ||
after.ino !== identity.ino ||
after.mtimeMs !== identity.mtimeMs ||
JSON.stringify((await readdir(directory)).sort()) !== JSON.stringify(names)
)
return result("unavailable");
}
const after = await privateDirectory(root);
if (
after.dev !== rootIdentity.dev ||
after.ino !== rootIdentity.ino ||
after.mtimeMs !== rootIdentity.mtimeMs ||
JSON.stringify((await readdir(root)).sort()) !== JSON.stringify(scopes)
)
return result("unavailable");
return result(Date.now() >= deadline ? "unavailable" : "settled");
} catch {
return result("unavailable");
}
}
1 change: 1 addition & 0 deletions packages/coding-agent/src/sdk-features.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export const CALLER_OWNED_SESSION_ENVIRONMENT_CLEANUP_FEATURE = "caller_owned_se
export const RECOVERABLE_OWNED_SESSION_ADOPTION_FEATURE = "recoverable_owned_session_adoption_v1" as const;

export const PRIME_AGENT_SDK_FEATURES = Object.freeze([
"owned_session_settlement_observation_v1",
"bounded_daemon_ingress_v1",
"negotiated_daemon_session_capabilities_v1",
CALLER_OWNED_SESSION_ENVIRONMENT_CLEANUP_FEATURE,
Expand Down
1 change: 1 addition & 0 deletions packages/coding-agent/test/daemon-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ describe("DaemonClient", () => {
it("exports the bounded-ingress SDK proof and validates finite byte limits", () => {
const rootOptions: RootDaemonClientOptions = { maxInboundFrameBytes: 1 };
const rootFeatures: RootPrimeAgentSdkFeature[] = [
"owned_session_settlement_observation_v1",
"bounded_daemon_ingress_v1",
"negotiated_daemon_session_capabilities_v1",
"caller_owned_session_environment_cleanup_v1",
Expand Down
Loading
Loading