@code-yeongyu/senpi-agent-core 2026.11.3-2 → 2026.11.3-3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.d.ts +14 -0
- package/dist/conformance/index.js +8 -0
- package/dist/conformance/registry.js +22 -0
- package/dist/execution/coordinator-codec.d.ts +5 -0
- package/dist/execution/coordinator-codec.js +93 -0
- package/dist/execution/coordinator-plan.d.ts +33 -0
- package/dist/execution/coordinator-plan.js +106 -0
- package/dist/execution/coordinator-types.d.ts +116 -0
- package/dist/execution/coordinator-types.js +2 -0
- package/dist/execution/coordinator.d.ts +25 -0
- package/dist/execution/coordinator.js +132 -0
- package/dist/execution/grant-verify.d.ts +70 -0
- package/dist/execution/grant-verify.js +87 -0
- package/dist/execution/ledger.d.ts +2 -0
- package/dist/execution/ledger.js +1 -0
- package/dist/execution/remote-executor.d.ts +64 -0
- package/dist/execution/remote-executor.js +159 -0
- package/dist/execution/remote-hand-ledger.d.ts +40 -0
- package/dist/execution/remote-hand-ledger.js +137 -0
- package/dist/execution/remote-protocol.d.ts +87 -0
- package/dist/execution/remote-protocol.js +88 -0
- package/dist/execution/remote-tool-host.d.ts +29 -0
- package/dist/execution/remote-tool-host.js +155 -0
- package/dist/execution/testing/batch-cases.d.ts +6 -0
- package/dist/execution/testing/batch-cases.js +210 -0
- package/dist/execution/testing/batch-executor.d.ts +34 -0
- package/dist/execution/testing/batch-executor.js +141 -0
- package/dist/execution/testing/batch-harness.d.ts +36 -0
- package/dist/execution/testing/batch-harness.js +208 -0
- package/dist/execution/testing/batch-registry.d.ts +3 -0
- package/dist/execution/testing/batch-registry.js +30 -0
- package/dist/execution/testing/fault-hand-cases.d.ts +6 -0
- package/dist/execution/testing/fault-hand-cases.js +70 -0
- package/dist/execution/testing/hand-harness.d.ts +48 -0
- package/dist/execution/testing/hand-harness.js +136 -0
- package/dist/execution/testing/kill-batch.d.ts +12 -0
- package/dist/execution/testing/kill-batch.js +70 -0
- package/dist/execution/testing/kill-hand.d.ts +16 -0
- package/dist/execution/testing/kill-hand.js +75 -0
- package/dist/execution/testing/multi-hand-cases.d.ts +6 -0
- package/dist/execution/testing/multi-hand-cases.js +44 -0
- package/dist/harness/env/nodejs.js +4 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +8 -0
- package/package.json +3 -3
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A hand's offline check of the sender's capability grant (brain/hand split S27b; relay decision 0009, R14): before
|
|
3
|
+
* anything of a call runs, the hand verifies that the link's authenticated peer holds `execute` toward this hand for
|
|
4
|
+
* the workspace the call's root lies in, from a local snapshot of the verified roster. Nothing is contacted per call.
|
|
5
|
+
*
|
|
6
|
+
* The embedder (the device service) verifies the signed roster, installs snapshots with a non-decreasing `rv` and, during
|
|
7
|
+
* the v1 dual-serve, derives the rows by 0009's role backfill. It also owns the peer binding: one executor per
|
|
8
|
+
* authenticated-sender link, no other sender's frames routed into it, and a carrier re-attach only for the same sender.
|
|
9
|
+
*/
|
|
10
|
+
/** The capability a hand requires: a tool call is the shell/files/process effect 0014 and 0016 define as `execute`. */
|
|
11
|
+
export declare const HAND_CAPABILITY = "execute";
|
|
12
|
+
/** The workspace label of a configured root that names none (0009's default workspace). */
|
|
13
|
+
export declare const DEFAULT_WORKSPACE = "omo";
|
|
14
|
+
/** One 0009 grant row: `holder` may do `capability` on `target` in `workspace`. Exact; no capability implies another. */
|
|
15
|
+
export interface GrantRow {
|
|
16
|
+
readonly holder: string;
|
|
17
|
+
readonly target: string;
|
|
18
|
+
readonly workspace: string;
|
|
19
|
+
readonly capability: string;
|
|
20
|
+
}
|
|
21
|
+
/** A verified roster's grants as the hand holds them. `expiresAt` is the roster's `exp_ms`. */
|
|
22
|
+
export interface GrantSnapshot {
|
|
23
|
+
readonly rv: number;
|
|
24
|
+
readonly expiresAt: number;
|
|
25
|
+
readonly grants: readonly GrantRow[];
|
|
26
|
+
}
|
|
27
|
+
export type GrantRefusal = "grant_missing" | "grant_expired" | "workspace_unknown";
|
|
28
|
+
export type GrantVerdict = {
|
|
29
|
+
readonly ok: true;
|
|
30
|
+
readonly root: string;
|
|
31
|
+
} | {
|
|
32
|
+
readonly ok: false;
|
|
33
|
+
readonly reason: GrantRefusal;
|
|
34
|
+
};
|
|
35
|
+
export interface WorkspaceRoot {
|
|
36
|
+
readonly root: string;
|
|
37
|
+
readonly label?: string;
|
|
38
|
+
}
|
|
39
|
+
export interface GrantVerifierOptions {
|
|
40
|
+
/** This hand's device ID: the target of every grant it accepts. */
|
|
41
|
+
readonly self: string;
|
|
42
|
+
/** The roots this hand serves; a call's root must lie inside one of them. */
|
|
43
|
+
readonly workspaces: readonly WorkspaceRoot[];
|
|
44
|
+
/** The canonical form of an existing path (the real path); throws for a path that does not exist or cannot be read. */
|
|
45
|
+
readonly canonicalize: (path: string) => string;
|
|
46
|
+
readonly now?: () => number;
|
|
47
|
+
}
|
|
48
|
+
export interface GrantVerifier {
|
|
49
|
+
/** Reads one snapshot; never what the session says about itself (R16). */
|
|
50
|
+
verify(peer: string, scopeRoot: string): GrantVerdict;
|
|
51
|
+
/** Replaces the snapshot. A lower `rv` than the installed one is ignored (rollback); a non-finite `rv` or `expiresAt` throws. */
|
|
52
|
+
install(snapshot: GrantSnapshot): void;
|
|
53
|
+
/** Called after every replacement, so running calls can be re-verified. Returns the unsubscribe. */
|
|
54
|
+
onReplace(listener: () => void): () => void;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Whose calls an executor runs: its own device's (`self`: fused and split-local, no grant needed, 0009) or one
|
|
58
|
+
* authenticated peer's, every call checked by `verifier`. Required, so a peer link without a verifier cannot be built.
|
|
59
|
+
*/
|
|
60
|
+
export type HandAuthority = {
|
|
61
|
+
readonly kind: "self";
|
|
62
|
+
} | {
|
|
63
|
+
readonly kind: "peer";
|
|
64
|
+
readonly peer: string;
|
|
65
|
+
readonly verifier: GrantVerifier;
|
|
66
|
+
};
|
|
67
|
+
/** The root a call may open its scope on, or why it is refused; a self link keeps the call's root as given. */
|
|
68
|
+
export declare function authorize(authority: HandAuthority, scopeRoot: string): GrantVerdict;
|
|
69
|
+
export declare function createGrantVerifier(options: GrantVerifierOptions): GrantVerifier;
|
|
70
|
+
//# sourceMappingURL=grant-verify.d.ts.map
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A hand's offline check of the sender's capability grant (brain/hand split S27b; relay decision 0009, R14): before
|
|
3
|
+
* anything of a call runs, the hand verifies that the link's authenticated peer holds `execute` toward this hand for
|
|
4
|
+
* the workspace the call's root lies in, from a local snapshot of the verified roster. Nothing is contacted per call.
|
|
5
|
+
*
|
|
6
|
+
* The embedder (the device service) verifies the signed roster, installs snapshots with a non-decreasing `rv` and, during
|
|
7
|
+
* the v1 dual-serve, derives the rows by 0009's role backfill. It also owns the peer binding: one executor per
|
|
8
|
+
* authenticated-sender link, no other sender's frames routed into it, and a carrier re-attach only for the same sender.
|
|
9
|
+
*/
|
|
10
|
+
/** The capability a hand requires: a tool call is the shell/files/process effect 0014 and 0016 define as `execute`. */
|
|
11
|
+
export const HAND_CAPABILITY = "execute";
|
|
12
|
+
/** The workspace label of a configured root that names none (0009's default workspace). */
|
|
13
|
+
export const DEFAULT_WORKSPACE = "omo";
|
|
14
|
+
/** The root a call may open its scope on, or why it is refused; a self link keeps the call's root as given. */
|
|
15
|
+
export function authorize(authority, scopeRoot) {
|
|
16
|
+
return authority.kind === "self"
|
|
17
|
+
? { ok: true, root: scopeRoot }
|
|
18
|
+
: authority.verifier.verify(authority.peer, scopeRoot);
|
|
19
|
+
}
|
|
20
|
+
const SEPARATORS = /[\\/]+$/;
|
|
21
|
+
/** `child` is `root` or lies under it, compared by whole path components (`/ws` never contains `/ws2`). */
|
|
22
|
+
function contains(root, child) {
|
|
23
|
+
const base = root.replace(SEPARATORS, "");
|
|
24
|
+
if (child === base)
|
|
25
|
+
return true;
|
|
26
|
+
if (!child.startsWith(base))
|
|
27
|
+
return false;
|
|
28
|
+
const next = child.charAt(base.length);
|
|
29
|
+
return next === "/" || next === "\\";
|
|
30
|
+
}
|
|
31
|
+
export function createGrantVerifier(options) {
|
|
32
|
+
const { self, canonicalize } = options;
|
|
33
|
+
const now = options.now ?? Date.now;
|
|
34
|
+
const listeners = new Set();
|
|
35
|
+
let snapshot;
|
|
36
|
+
const canonical = (path) => {
|
|
37
|
+
try {
|
|
38
|
+
return canonicalize(path);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
const workspaceOf = (root) => {
|
|
45
|
+
let best;
|
|
46
|
+
for (const workspace of options.workspaces) {
|
|
47
|
+
const resolved = canonical(workspace.root);
|
|
48
|
+
if (resolved === undefined || !contains(resolved, root))
|
|
49
|
+
continue;
|
|
50
|
+
if (best === undefined || resolved.length > best.length)
|
|
51
|
+
best = { label: workspace.label ?? DEFAULT_WORKSPACE, length: resolved.length };
|
|
52
|
+
}
|
|
53
|
+
return best?.label;
|
|
54
|
+
};
|
|
55
|
+
return {
|
|
56
|
+
verify(peer, scopeRoot) {
|
|
57
|
+
const root = canonical(scopeRoot);
|
|
58
|
+
const workspace = root === undefined ? undefined : workspaceOf(root);
|
|
59
|
+
if (root === undefined || workspace === undefined)
|
|
60
|
+
return { ok: false, reason: "workspace_unknown" };
|
|
61
|
+
if (peer === self)
|
|
62
|
+
return { ok: true, root };
|
|
63
|
+
const current = snapshot;
|
|
64
|
+
if (current === undefined || now() >= current.expiresAt)
|
|
65
|
+
return { ok: false, reason: "grant_expired" };
|
|
66
|
+
const granted = current.grants.some((row) => row.holder === peer &&
|
|
67
|
+
row.target === self &&
|
|
68
|
+
row.workspace === workspace &&
|
|
69
|
+
row.capability === HAND_CAPABILITY);
|
|
70
|
+
return granted ? { ok: true, root } : { ok: false, reason: "grant_missing" };
|
|
71
|
+
},
|
|
72
|
+
install(next) {
|
|
73
|
+
if (!Number.isFinite(next.rv) || !Number.isFinite(next.expiresAt))
|
|
74
|
+
throw new Error("A grant snapshot needs a finite rv and expiresAt; the installed snapshot is kept");
|
|
75
|
+
if (snapshot !== undefined && next.rv < snapshot.rv)
|
|
76
|
+
return;
|
|
77
|
+
snapshot = next;
|
|
78
|
+
for (const listener of [...listeners])
|
|
79
|
+
listener();
|
|
80
|
+
},
|
|
81
|
+
onReplace(listener) {
|
|
82
|
+
listeners.add(listener);
|
|
83
|
+
return () => listeners.delete(listener);
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
//# sourceMappingURL=grant-verify.js.map
|
|
@@ -7,6 +7,8 @@ export interface ExecutionLedger {
|
|
|
7
7
|
read(key: ExecutionKey): Promise<ExecutionEntry | undefined>;
|
|
8
8
|
/** Called once on endpoint restart; also expires overdue leases and reconciliation deadlines. */
|
|
9
9
|
recover(now: number): Promise<void>;
|
|
10
|
+
/** Every execution row this ledger holds, in key order. */
|
|
11
|
+
scan(): Promise<ExecutionEntry[]>;
|
|
10
12
|
}
|
|
11
13
|
/** All ledgers sharing a writable store epoch must share its single admission line. */
|
|
12
14
|
export declare function createExecutionLedger(options: {
|
package/dist/execution/ledger.js
CHANGED
|
@@ -84,6 +84,7 @@ export function createExecutionLedger(options) {
|
|
|
84
84
|
await persist(entry, "admit");
|
|
85
85
|
return applied(entry);
|
|
86
86
|
}),
|
|
87
|
+
scan: async () => (await store.scanDocuments(PREFIX)).map((document) => decodeExecution(document.data)),
|
|
87
88
|
recover: async (now) => {
|
|
88
89
|
for (const document of await store.scanDocuments(PREFIX)) {
|
|
89
90
|
const entry = decodeExecution(document.data);
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { Transport } from "../transport/transport.ts";
|
|
2
|
+
import type { AgentToolResult } from "../types.ts";
|
|
3
|
+
import { type HandAuthority } from "./grant-verify.ts";
|
|
4
|
+
import type { HandLedger } from "./remote-hand-ledger.ts";
|
|
5
|
+
import type { ExecutionScope } from "./tool-host.ts";
|
|
6
|
+
/** One call as a hand runs it: the raw name and arguments, never anything about the session that sent it. */
|
|
7
|
+
export interface HandCall {
|
|
8
|
+
readonly toolCallId: string;
|
|
9
|
+
readonly name: string;
|
|
10
|
+
readonly arguments: unknown;
|
|
11
|
+
readonly signal: AbortSignal;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* What a hand runs a scope's calls on. `run` owns the whole call: name resolution, argument preparation and
|
|
15
|
+
* validation, the extensions' `tool_call`/`tool_result` handlers and the tool; it never rejects for a tool failure.
|
|
16
|
+
*/
|
|
17
|
+
export interface HandScope {
|
|
18
|
+
run(call: HandCall): Promise<AgentToolResult<unknown>>;
|
|
19
|
+
/** A tool that must not overlap other calls of its scope (`executionMode: "sequential"`). */
|
|
20
|
+
isSequential(name: string): boolean;
|
|
21
|
+
dispose(): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
export type OpenHandScope = (scope: ExecutionScope) => Promise<HandScope>;
|
|
24
|
+
export interface RemoteExecutorOptions {
|
|
25
|
+
/** The hand's end of the link; lanes are execution scope IDs. */
|
|
26
|
+
readonly transport: Transport;
|
|
27
|
+
/** Opens a scope lazily on its first call, bound to the scope's root (the canonical one a peer's grant check resolved). */
|
|
28
|
+
readonly openScope: OpenHandScope;
|
|
29
|
+
/**
|
|
30
|
+
* Whose calls this executor runs. A peer's call is checked against its grant before anything of it is recorded or
|
|
31
|
+
* opened, and a replaced grant snapshot re-checks every running call, aborting the ones it no longer allows (S27b).
|
|
32
|
+
*/
|
|
33
|
+
readonly authority: HandAuthority;
|
|
34
|
+
/**
|
|
35
|
+
* The hand's durable record of its calls. With it, a call is recorded as dispatched before it runs, a restarted hand
|
|
36
|
+
* answers its interrupted calls `hand_restarted` without running them again, and a re-delivered invoke gets the
|
|
37
|
+
* recorded outcome. Without it, the hand remembers execution IDs only while it lives.
|
|
38
|
+
*/
|
|
39
|
+
readonly ledger?: HandLedger;
|
|
40
|
+
/** This hand process's identity in its `hello`; a fresh one per start by default. */
|
|
41
|
+
readonly instance?: string;
|
|
42
|
+
/**
|
|
43
|
+
* A call the hand could not record or answer (its durable record failed): the call gets no reply from this process,
|
|
44
|
+
* as from a hand that died, and a restarted hand answers it from the record. A failed restart recovery is reported
|
|
45
|
+
* here too, and this process then answers no frame. Reported here, never swallowed. The embedder owns the restart:
|
|
46
|
+
* close this executor and start a new one on the same store, or the call stays unanswered while this process lives.
|
|
47
|
+
*/
|
|
48
|
+
readonly onFault: (error: unknown) => void;
|
|
49
|
+
}
|
|
50
|
+
export interface RemoteExecutor {
|
|
51
|
+
/** Execution IDs this hand has accepted, in arrival order (each runs at most once). */
|
|
52
|
+
readonly accepted: () => readonly string[];
|
|
53
|
+
/** Settles once a restarted hand has recovered its record and re-sent the outcomes the session has not acknowledged. */
|
|
54
|
+
readonly ready: Promise<void>;
|
|
55
|
+
close(): Promise<void>;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The hand's side of remote tool execution (brain/hand split, S27a). Each scope keeps its own state, opened lazily and
|
|
59
|
+
* bound to the root it was opened with: a later call naming the same scope with another root is refused, as is any
|
|
60
|
+
* execution ID the hand has already accepted (dispatch at most once). The session reference a call carries is never
|
|
61
|
+
* passed on: the hand keys on the scope and does not know the session (R16).
|
|
62
|
+
*/
|
|
63
|
+
export declare function createRemoteExecutor(options: RemoteExecutorOptions): RemoteExecutor;
|
|
64
|
+
//# sourceMappingURL=remote-executor.d.ts.map
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { decodeRemoteMessage, encodeRemoteMessage, HAND_CONTROL_LANE, toRemoteToolResult, } from "./remote-protocol.js";
|
|
2
|
+
import { authorize } from "./grant-verify.js";
|
|
3
|
+
/**
|
|
4
|
+
* The hand's side of remote tool execution (brain/hand split, S27a). Each scope keeps its own state, opened lazily and
|
|
5
|
+
* bound to the root it was opened with: a later call naming the same scope with another root is refused, as is any
|
|
6
|
+
* execution ID the hand has already accepted (dispatch at most once). The session reference a call carries is never
|
|
7
|
+
* passed on: the hand keys on the scope and does not know the session (R16).
|
|
8
|
+
*/
|
|
9
|
+
export function createRemoteExecutor(options) {
|
|
10
|
+
const { transport, openScope, ledger, authority } = options;
|
|
11
|
+
const scopes = new Map();
|
|
12
|
+
const accepted = [];
|
|
13
|
+
const seen = new Set();
|
|
14
|
+
const running = new Map();
|
|
15
|
+
let closed = false;
|
|
16
|
+
const stopWatching = authority.kind === "peer"
|
|
17
|
+
? authority.verifier.onReplace(() => {
|
|
18
|
+
for (const { controller, root } of running.values())
|
|
19
|
+
if (!authority.verifier.verify(authority.peer, root).ok)
|
|
20
|
+
controller.abort();
|
|
21
|
+
})
|
|
22
|
+
: () => { };
|
|
23
|
+
const reply = (lane, message) => {
|
|
24
|
+
void transport.send(lane, encodeRemoteMessage(message)).catch(() => undefined);
|
|
25
|
+
};
|
|
26
|
+
const refuse = (lane, executionId, reason) => reply(lane, { kind: "refused", executionId, reason });
|
|
27
|
+
const stateOf = (scope) => {
|
|
28
|
+
const known = scopes.get(scope.id);
|
|
29
|
+
if (known !== undefined)
|
|
30
|
+
return known.root === scope.root ? known : "scope_binding_mismatch";
|
|
31
|
+
const opened = openScope(scope);
|
|
32
|
+
opened.catch(() => undefined);
|
|
33
|
+
const state = { root: scope.root, opened, lastSequential: undefined, wave: [] };
|
|
34
|
+
scopes.set(scope.id, state);
|
|
35
|
+
return state;
|
|
36
|
+
};
|
|
37
|
+
const invoke = async (lane, call) => {
|
|
38
|
+
if (closed)
|
|
39
|
+
return refuse(lane, call.executionId, "hand_closed");
|
|
40
|
+
if (lane !== call.scope.id)
|
|
41
|
+
return refuse(lane, call.executionId, "scope_lane_mismatch");
|
|
42
|
+
const verdict = authorize(authority, call.scope.root);
|
|
43
|
+
if (!verdict.ok)
|
|
44
|
+
return refuse(lane, call.executionId, verdict.reason);
|
|
45
|
+
if (ledger === undefined && seen.has(call.executionId))
|
|
46
|
+
return refuse(lane, call.executionId, "duplicate_execution");
|
|
47
|
+
seen.add(call.executionId);
|
|
48
|
+
const state = stateOf({ id: call.scope.id, root: verdict.root });
|
|
49
|
+
if (typeof state === "string")
|
|
50
|
+
return refuse(lane, call.executionId, state);
|
|
51
|
+
let scope;
|
|
52
|
+
try {
|
|
53
|
+
scope = await state.opened;
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
57
|
+
return refuse(lane, call.executionId, `scope_unavailable: ${reason}`);
|
|
58
|
+
}
|
|
59
|
+
if (ledger !== undefined) {
|
|
60
|
+
const admission = await ledger.admit(call);
|
|
61
|
+
if (admission.kind === "reply")
|
|
62
|
+
return reply(lane, admission.message);
|
|
63
|
+
if (admission.kind === "in_flight")
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
accepted.push(call.executionId);
|
|
67
|
+
const controller = new AbortController();
|
|
68
|
+
running.set(call.executionId, { controller, root: verdict.root });
|
|
69
|
+
const sequential = scope.isSequential(call.name);
|
|
70
|
+
const dependencies = sequential
|
|
71
|
+
? [...(state.lastSequential ? [state.lastSequential] : []), ...state.wave]
|
|
72
|
+
: state.lastSequential
|
|
73
|
+
? [state.lastSequential]
|
|
74
|
+
: [];
|
|
75
|
+
const done = (async () => {
|
|
76
|
+
await Promise.allSettled(dependencies);
|
|
77
|
+
let result;
|
|
78
|
+
try {
|
|
79
|
+
// The grant must still hold when the call starts: a snapshot installed while it waited (scope opening,
|
|
80
|
+
// durable admission, earlier calls of its scope) may have revoked it, and then the tool never runs.
|
|
81
|
+
if (controller.signal.aborted || !authorize(authority, call.scope.root).ok)
|
|
82
|
+
throw new Error("The call's grant was revoked before it ran");
|
|
83
|
+
result = await scope.run({
|
|
84
|
+
toolCallId: call.toolCallId,
|
|
85
|
+
name: call.name,
|
|
86
|
+
arguments: call.arguments,
|
|
87
|
+
signal: controller.signal,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
92
|
+
result = { content: [{ type: "text", text }], details: {}, isError: true };
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
running.delete(call.executionId);
|
|
96
|
+
}
|
|
97
|
+
const settled = toRemoteToolResult(result);
|
|
98
|
+
reply(lane, ledger === undefined
|
|
99
|
+
? { kind: "settled", executionId: call.executionId, result: settled }
|
|
100
|
+
: await ledger.settle(call, settled));
|
|
101
|
+
})();
|
|
102
|
+
done.catch((error) => options.onFault(error));
|
|
103
|
+
if (sequential) {
|
|
104
|
+
state.lastSequential = done;
|
|
105
|
+
state.wave = [];
|
|
106
|
+
}
|
|
107
|
+
else
|
|
108
|
+
state.wave.push(done);
|
|
109
|
+
};
|
|
110
|
+
const ready = (async () => {
|
|
111
|
+
if (ledger === undefined)
|
|
112
|
+
return;
|
|
113
|
+
for (const { lane, message } of await ledger.recover())
|
|
114
|
+
reply(lane, message);
|
|
115
|
+
reply(HAND_CONTROL_LANE, { kind: "hello", instance: options.instance ?? crypto.randomUUID() });
|
|
116
|
+
})();
|
|
117
|
+
ready.catch((error) => options.onFault(error));
|
|
118
|
+
transport.onFrame(async (frame) => {
|
|
119
|
+
try {
|
|
120
|
+
await ready;
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
let message;
|
|
126
|
+
try {
|
|
127
|
+
message = decodeRemoteMessage(frame.payload);
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
if (message.kind === "invoke")
|
|
134
|
+
await invoke(frame.lane, message);
|
|
135
|
+
else if (message.kind === "abort")
|
|
136
|
+
running.get(message.executionId)?.controller.abort();
|
|
137
|
+
else if (message.kind === "ack")
|
|
138
|
+
await ledger?.ack(message.executionId);
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
options.onFault(error);
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
return {
|
|
145
|
+
accepted: () => [...accepted],
|
|
146
|
+
ready,
|
|
147
|
+
async close() {
|
|
148
|
+
closed = true;
|
|
149
|
+
stopWatching();
|
|
150
|
+
for (const { controller } of running.values())
|
|
151
|
+
controller.abort();
|
|
152
|
+
const opened = await Promise.allSettled([...scopes.values()].map((state) => state.opened));
|
|
153
|
+
scopes.clear();
|
|
154
|
+
await Promise.allSettled(opened.flatMap((outcome) => (outcome.status === "fulfilled" ? [outcome.value.dispose()] : [])));
|
|
155
|
+
transport.close();
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
//# sourceMappingURL=remote-executor.js.map
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { ExecutionLedger } from "./ledger.ts";
|
|
2
|
+
import type { RemoteHandMessage, RemoteInvoke, RemoteToolResult } from "./remote-protocol.ts";
|
|
3
|
+
export interface HandLedgerOptions {
|
|
4
|
+
readonly ledger: ExecutionLedger;
|
|
5
|
+
/** This hand's identity, the ledger's executor. */
|
|
6
|
+
readonly executor: string;
|
|
7
|
+
/** The authenticated session the calls come from, the ledger's issuer. */
|
|
8
|
+
readonly issuer: string;
|
|
9
|
+
readonly workspace: string;
|
|
10
|
+
readonly now: () => number;
|
|
11
|
+
/** How long an admitted call may live; the ledger caps it at 24 hours. */
|
|
12
|
+
readonly leaseMs: number;
|
|
13
|
+
}
|
|
14
|
+
/** What an invoke may do: run now, be answered from the record (an outcome or a refusal), or wait on its own run. */
|
|
15
|
+
export type HandAdmission = {
|
|
16
|
+
readonly kind: "run";
|
|
17
|
+
} | {
|
|
18
|
+
readonly kind: "reply";
|
|
19
|
+
readonly message: RemoteHandMessage;
|
|
20
|
+
} | {
|
|
21
|
+
readonly kind: "in_flight";
|
|
22
|
+
};
|
|
23
|
+
export interface HandLedger {
|
|
24
|
+
admit(invoke: RemoteInvoke): Promise<HandAdmission>;
|
|
25
|
+
settle(invoke: RemoteInvoke, result: RemoteToolResult): Promise<RemoteHandMessage>;
|
|
26
|
+
ack(executionId: string): Promise<void>;
|
|
27
|
+
/** Runs the ledger's restart recovery, then returns every outcome the session has not acknowledged, by lane. */
|
|
28
|
+
recover(): Promise<Array<{
|
|
29
|
+
readonly lane: string;
|
|
30
|
+
readonly message: RemoteHandMessage;
|
|
31
|
+
}>>;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* A hand's durable record of the calls it runs (brain/hand split, S27a), on the execution ledger. A call is admitted and
|
|
35
|
+
* walked to `dispatched` BEFORE its handlers and tool run, so a hand that dies mid-call recovers it as `hand_restarted`
|
|
36
|
+
* (uncertain) and never runs it again; a re-delivered invoke is answered from the record. Today's run is one unit
|
|
37
|
+
* (handlers, then the tool), so a call is frozen with its raw name and arguments.
|
|
38
|
+
*/
|
|
39
|
+
export declare function createHandLedger(options: HandLedgerOptions): HandLedger;
|
|
40
|
+
//# sourceMappingURL=remote-hand-ledger.d.ts.map
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
const GENERATION = 1;
|
|
2
|
+
function outcomeOf(entry) {
|
|
3
|
+
const executionId = entry.commandId;
|
|
4
|
+
if (entry.progress.state === "acked")
|
|
5
|
+
return { kind: "refused", executionId, reason: "result_expired" };
|
|
6
|
+
if (entry.progress.state !== "settled")
|
|
7
|
+
return undefined;
|
|
8
|
+
const { outcome } = entry.progress;
|
|
9
|
+
if (outcome.reason === "result") {
|
|
10
|
+
const result = JSON.parse(String(outcome.value));
|
|
11
|
+
return { kind: "settled", executionId, result };
|
|
12
|
+
}
|
|
13
|
+
// A hand settles a call only with `result` (settle) or a recovery terminal. A `blocked` outcome is the brain's
|
|
14
|
+
// prepared executor's (S09): a record holding one was not written by this hand, so it is refused, never reported as run.
|
|
15
|
+
if (outcome.reason === "blocked")
|
|
16
|
+
return { kind: "refused", executionId, reason: "foreign_outcome" };
|
|
17
|
+
return {
|
|
18
|
+
kind: "terminal",
|
|
19
|
+
executionId,
|
|
20
|
+
reason: outcome.reason,
|
|
21
|
+
uncertain: outcome.uncertain,
|
|
22
|
+
hooksRan: outcome.hooksRan,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function asStoreValue(value) {
|
|
26
|
+
return value === undefined ? null : JSON.parse(JSON.stringify(value));
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A hand's durable record of the calls it runs (brain/hand split, S27a), on the execution ledger. A call is admitted and
|
|
30
|
+
* walked to `dispatched` BEFORE its handlers and tool run, so a hand that dies mid-call recovers it as `hand_restarted`
|
|
31
|
+
* (uncertain) and never runs it again; a re-delivered invoke is answered from the record. Today's run is one unit
|
|
32
|
+
* (handlers, then the tool), so a call is frozen with its raw name and arguments.
|
|
33
|
+
*/
|
|
34
|
+
export function createHandLedger(options) {
|
|
35
|
+
const { ledger, executor, issuer, workspace, now, leaseMs } = options;
|
|
36
|
+
const keyOf = (executionId) => ({ issuer, commandId: executionId });
|
|
37
|
+
const apply = (executionId, event, actor) => ledger.apply({ key: keyOf(executionId), generation: GENERATION, actor: { id: actor }, now: now(), event });
|
|
38
|
+
/** Calls this process admitted or runs; a duplicate invoke for one of them waits on that run. */
|
|
39
|
+
const owned = new Set();
|
|
40
|
+
const replyFrom = (reply, executionId) => {
|
|
41
|
+
if (reply.status === "refused")
|
|
42
|
+
return { kind: "refused", executionId, reason: reply.reason };
|
|
43
|
+
if (reply.status === "result_expired")
|
|
44
|
+
return { kind: "refused", executionId, reason: "result_expired" };
|
|
45
|
+
return outcomeOf(reply.entry) ?? { kind: "refused", executionId, reason: "not_settled" };
|
|
46
|
+
};
|
|
47
|
+
const admitNew = (invoke, digest) => {
|
|
48
|
+
const admittedAt = now();
|
|
49
|
+
return ledger.admit({
|
|
50
|
+
issuer,
|
|
51
|
+
commandId: invoke.executionId,
|
|
52
|
+
executor,
|
|
53
|
+
workspace,
|
|
54
|
+
scope: invoke.scope.id,
|
|
55
|
+
generation: GENERATION,
|
|
56
|
+
requestDigest: digest,
|
|
57
|
+
admittedAt,
|
|
58
|
+
leaseUntil: admittedAt + leaseMs,
|
|
59
|
+
reconcilable: false,
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Walks a call to `dispatched` from whatever its record holds: a new call from admission, a `prepared` or
|
|
64
|
+
* `released` call that survived a restart from there. It runs only when THIS walk's `dispatch` applied. A record
|
|
65
|
+
* that holds another request under this execution ID (other name, arguments or scope) is refused
|
|
66
|
+
* `identity_conflict`, as the ledger refuses such an admission: a resumed call runs only what was frozen.
|
|
67
|
+
*/
|
|
68
|
+
const advance = async (invoke) => {
|
|
69
|
+
const { executionId } = invoke;
|
|
70
|
+
const args = asStoreValue(invoke.arguments);
|
|
71
|
+
const frozen = { name: invoke.name, args, digest: JSON.stringify([invoke.name, args]) };
|
|
72
|
+
const prior = await ledger.read(keyOf(executionId));
|
|
73
|
+
if (prior !== undefined && (prior.requestDigest !== frozen.digest || prior.scope !== invoke.scope.id))
|
|
74
|
+
return { kind: "reply", message: { kind: "refused", executionId, reason: "identity_conflict" } };
|
|
75
|
+
const settled = prior === undefined ? undefined : outcomeOf(prior);
|
|
76
|
+
if (settled !== undefined)
|
|
77
|
+
return { kind: "reply", message: settled };
|
|
78
|
+
const fromStart = [
|
|
79
|
+
() => admitNew(invoke, frozen.digest),
|
|
80
|
+
() => apply(executionId, { kind: "prepare" }, executor),
|
|
81
|
+
() => apply(executionId, { kind: "effect" }, executor),
|
|
82
|
+
() => apply(executionId, { kind: "freeze", call: frozen, awaitingConsent: false }, executor),
|
|
83
|
+
];
|
|
84
|
+
const state = prior?.progress.state;
|
|
85
|
+
const steps = state === undefined ? fromStart : state === "prepared" || state === "released" ? [] : undefined;
|
|
86
|
+
if (steps === undefined)
|
|
87
|
+
return { kind: "in_flight" };
|
|
88
|
+
for (const step of [...steps, () => apply(executionId, { kind: "release" }, issuer)]) {
|
|
89
|
+
const reply = await step();
|
|
90
|
+
if (reply.status === "replayed" && reply.entry.progress.state !== "settled")
|
|
91
|
+
continue;
|
|
92
|
+
if (reply.status !== "applied" || reply.entry.progress.state === "settled")
|
|
93
|
+
return { kind: "reply", message: replyFrom(reply, executionId) };
|
|
94
|
+
}
|
|
95
|
+
const dispatched = await apply(executionId, { kind: "dispatch" }, executor);
|
|
96
|
+
if (dispatched.status === "applied" && dispatched.entry.progress.state === "dispatched")
|
|
97
|
+
return { kind: "run" };
|
|
98
|
+
if (dispatched.status === "replayed" && dispatched.entry.progress.state !== "settled")
|
|
99
|
+
return { kind: "in_flight" };
|
|
100
|
+
return { kind: "reply", message: replyFrom(dispatched, executionId) };
|
|
101
|
+
};
|
|
102
|
+
return {
|
|
103
|
+
async admit(invoke) {
|
|
104
|
+
const { executionId } = invoke;
|
|
105
|
+
if (owned.has(executionId))
|
|
106
|
+
return { kind: "in_flight" };
|
|
107
|
+
owned.add(executionId);
|
|
108
|
+
const admission = await advance(invoke).catch((error) => {
|
|
109
|
+
owned.delete(executionId);
|
|
110
|
+
throw error;
|
|
111
|
+
});
|
|
112
|
+
if (admission.kind !== "run")
|
|
113
|
+
owned.delete(executionId);
|
|
114
|
+
return admission;
|
|
115
|
+
},
|
|
116
|
+
async settle(invoke, result) {
|
|
117
|
+
try {
|
|
118
|
+
const reply = await apply(invoke.executionId, { kind: "result", value: JSON.stringify(result) }, executor);
|
|
119
|
+
return replyFrom(reply, invoke.executionId);
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
owned.delete(invoke.executionId);
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
async ack(executionId) {
|
|
126
|
+
await apply(executionId, { kind: "ack" }, issuer);
|
|
127
|
+
},
|
|
128
|
+
async recover() {
|
|
129
|
+
await ledger.recover(now());
|
|
130
|
+
return (await ledger.scan()).flatMap((entry) => {
|
|
131
|
+
const message = entry.progress.state === "settled" ? outcomeOf(entry) : undefined;
|
|
132
|
+
return message === undefined ? [] : [{ lane: entry.scope, message }];
|
|
133
|
+
});
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=remote-hand-ledger.js.map
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { ImageContent, JsonValue, TextContent } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { AgentToolResult } from "../types.ts";
|
|
3
|
+
import type { ExecutionScope } from "./tool-host.ts";
|
|
4
|
+
/**
|
|
5
|
+
* The wire messages between a session's remote ToolHost and the hand that runs its tool calls (brain/hand split, S27a).
|
|
6
|
+
* One transport lane per execution scope; a transport never inspects these payloads.
|
|
7
|
+
*
|
|
8
|
+
* The hand receives the model's raw call (name and arguments, before preparation, validation and hooks) and runs all of
|
|
9
|
+
* those steps itself. `sessionRef` is what the session chose to say about itself: the hand passes it to nothing.
|
|
10
|
+
*/
|
|
11
|
+
export type RemoteHandMessage = RemoteInvoke | RemoteAbort | RemoteAck | RemoteSettled | RemoteTerminal | RemoteRefused | RemoteHello;
|
|
12
|
+
/** The lane a hand announces itself on; execution scope lanes carry everything else. */
|
|
13
|
+
export declare const HAND_CONTROL_LANE = "hand.control";
|
|
14
|
+
/**
|
|
15
|
+
* A hand with a durable record announces itself when it (re)starts, after re-sending the outcomes the session has not
|
|
16
|
+
* acknowledged. The session then re-sends every call still waiting: the record answers a call it already holds, and
|
|
17
|
+
* runs only a call whose admission never became durable (nothing of it ran).
|
|
18
|
+
*/
|
|
19
|
+
export interface RemoteHello {
|
|
20
|
+
readonly kind: "hello";
|
|
21
|
+
readonly instance: string;
|
|
22
|
+
}
|
|
23
|
+
export interface RemoteInvoke {
|
|
24
|
+
readonly kind: "invoke";
|
|
25
|
+
/** Unique per call per session; a hand runs one execution ID at most once. */
|
|
26
|
+
readonly executionId: string;
|
|
27
|
+
readonly batchId: string;
|
|
28
|
+
/** Position in the batch, in the model's source order. */
|
|
29
|
+
readonly index: number;
|
|
30
|
+
readonly scope: ExecutionScope;
|
|
31
|
+
readonly toolCallId: string;
|
|
32
|
+
readonly name: string;
|
|
33
|
+
readonly arguments: unknown;
|
|
34
|
+
readonly sessionRef?: string;
|
|
35
|
+
}
|
|
36
|
+
export interface RemoteAbort {
|
|
37
|
+
readonly kind: "abort";
|
|
38
|
+
readonly executionId: string;
|
|
39
|
+
}
|
|
40
|
+
/** The session has its outcome: the hand may forget it (a later replay is `result_expired`). */
|
|
41
|
+
export interface RemoteAck {
|
|
42
|
+
readonly kind: "ack";
|
|
43
|
+
readonly executionId: string;
|
|
44
|
+
}
|
|
45
|
+
/** The reasons a call can end on a hand without a tool result (the endpoint state machine's terminal reasons). */
|
|
46
|
+
export type RemoteTerminalReason = "cancelled" | "lease_expired" | "hand_restarted" | "uncertain";
|
|
47
|
+
/**
|
|
48
|
+
* The call ended without a tool result, for example because the hand restarted while it ran. `uncertain` says its
|
|
49
|
+
* effects may have happened; `hooksRan` says its `tool_call` handlers may have run. It is never run again.
|
|
50
|
+
*/
|
|
51
|
+
export interface RemoteTerminal {
|
|
52
|
+
readonly kind: "terminal";
|
|
53
|
+
readonly executionId: string;
|
|
54
|
+
readonly reason: RemoteTerminalReason;
|
|
55
|
+
readonly uncertain: boolean;
|
|
56
|
+
readonly hooksRan: boolean;
|
|
57
|
+
}
|
|
58
|
+
/** The call ran to an outcome on the hand (an `isError` result included: a blocked, invalid or failing call). */
|
|
59
|
+
export interface RemoteSettled {
|
|
60
|
+
readonly kind: "settled";
|
|
61
|
+
readonly executionId: string;
|
|
62
|
+
readonly result: RemoteToolResult;
|
|
63
|
+
}
|
|
64
|
+
/** The hand refused the call before anything ran (duplicate execution, scope binding, an unopenable scope). */
|
|
65
|
+
export interface RemoteRefused {
|
|
66
|
+
readonly kind: "refused";
|
|
67
|
+
readonly executionId: string;
|
|
68
|
+
readonly reason: string;
|
|
69
|
+
}
|
|
70
|
+
/** The serializable part of an {@link AgentToolResult}. */
|
|
71
|
+
export interface RemoteToolResult {
|
|
72
|
+
readonly content: (TextContent | ImageContent)[];
|
|
73
|
+
readonly details: JsonValue | undefined;
|
|
74
|
+
readonly isError: boolean;
|
|
75
|
+
readonly structuredContent?: JsonValue;
|
|
76
|
+
readonly terminate?: boolean;
|
|
77
|
+
readonly addedToolNames?: readonly string[];
|
|
78
|
+
}
|
|
79
|
+
export declare class RemoteProtocolError extends Error {
|
|
80
|
+
constructor(message: string);
|
|
81
|
+
}
|
|
82
|
+
export declare function encodeRemoteMessage(message: RemoteHandMessage): Uint8Array;
|
|
83
|
+
/** Parses one frame payload. Anything that is not exactly one of the messages is refused; nothing guesses. */
|
|
84
|
+
export declare function decodeRemoteMessage(payload: Uint8Array): RemoteHandMessage;
|
|
85
|
+
/** What a hand sends back for a tool result, keeping only what crosses the wire. */
|
|
86
|
+
export declare function toRemoteToolResult(result: AgentToolResult<unknown>): RemoteToolResult;
|
|
87
|
+
//# sourceMappingURL=remote-protocol.d.ts.map
|