aiterm-mcp 0.60.0 → 0.61.0

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +25 -1
  2. package/README.ja.md +1 -1
  3. package/README.md +1 -1
  4. package/dist/claude-operation-marker.js +11 -0
  5. package/dist/claude-stop-hook.js +5 -9
  6. package/dist/core.js +538 -45
  7. package/dist/execution-checkpoint.js +83 -0
  8. package/dist/execution-close.js +82 -0
  9. package/dist/execution-context.js +19 -0
  10. package/dist/execution-contract.js +263 -0
  11. package/dist/execution-dispatch.js +285 -0
  12. package/dist/execution-effect.js +411 -0
  13. package/dist/execution-immediate-stop.js +68 -0
  14. package/dist/execution-interruption.js +150 -0
  15. package/dist/execution-inventory.js +100 -0
  16. package/dist/execution-lock.js +136 -0
  17. package/dist/execution-native-server.js +140 -0
  18. package/dist/execution-native-setup.js +64 -0
  19. package/dist/execution-parent-alias.js +75 -0
  20. package/dist/execution-parent-claude-records.js +136 -0
  21. package/dist/execution-parent-endpoint.js +92 -0
  22. package/dist/execution-parent-manager.js +89 -0
  23. package/dist/execution-parent-native.js +179 -0
  24. package/dist/execution-parent-process.js +29 -0
  25. package/dist/execution-parent-producer.js +129 -0
  26. package/dist/execution-parent-queue.js +84 -0
  27. package/dist/execution-parent-source.js +200 -0
  28. package/dist/execution-parent-worker.js +89 -0
  29. package/dist/execution-parent.js +345 -0
  30. package/dist/execution-participant-store.js +107 -0
  31. package/dist/execution-participant.js +78 -0
  32. package/dist/execution-runtime.js +182 -0
  33. package/dist/execution-service.js +1334 -0
  34. package/dist/execution-steer.js +37 -0
  35. package/dist/execution-store.js +206 -0
  36. package/dist/execution-tools.js +151 -0
  37. package/dist/execution-wire.js +129 -0
  38. package/dist/harnesses/claude.js +2 -0
  39. package/dist/harnesses/codex.js +111 -0
  40. package/dist/harnesses/cursor.js +13 -0
  41. package/dist/harnesses/grok.js +2 -0
  42. package/dist/index.js +1196 -1122
  43. package/dist/parent-delivery.js +408 -41
  44. package/dist/process-runtime.js +28 -0
  45. package/dist/tmux-runtime.js +30 -4
  46. package/docs/DESIGN.md +60 -0
  47. package/docs/RELEASE.md +19 -1
  48. package/package.json +4 -3
@@ -0,0 +1,285 @@
1
+ // Request-local adapter for the serving stdio dispatcher. No live I/O, core
2
+ // imports or public mount at import. Uncovered ordinary/native/remote targets
3
+ // fail before the handler; they must acquire their own generation adapter.
4
+ import { executionLaunchSchema, executionPointSchema, executionRequestSchema } from "./execution-contract.js";
5
+ import { executionSourceFromEnvironment } from "./execution-runtime.js";
6
+ import { runDeferredBoundExecution } from "./execution-tools.js";
7
+ import { ExecutionError, executionErrorResult, executionRefFromMeta, executionHostSourceFromMeta, EXECUTION_REQUEST_META_KEY, EXECUTION_ERROR_META_KEY } from "./execution-wire.js";
8
+ import { EXECUTION_SOURCE_META_KEY } from "./execution-wire.js";
9
+ import { withExecutionRequest } from "./execution-context.js";
10
+ import { readExecutionSendBoundary } from "./execution-effect.js";
11
+ const launches = new Set(["agent_launch", "claude_agent", "codex_agent", "grok_agent"]);
12
+ const reads = new Set(["diagnostics", "pty_list", "pty_read", "pty_observe", "agent_models"]);
13
+ const controls = new Set(["agent_execution", "agent_execution_roots", "agent_stop"]);
14
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
15
+ function routeFor(name, args) {
16
+ if (reads.has(name))
17
+ return null;
18
+ if ((name === "agent_approval" || name === "claude_approval") && args.action === "inspect")
19
+ return null;
20
+ if (name === "claude_turn" && args.action === "recover")
21
+ return null;
22
+ if (name === "agent_auth" && args.action === "status" && args.session_id === undefined)
23
+ return null;
24
+ let tool = name;
25
+ if (["agent_auth", "agent_approval", "claude_approval", "claude_turn"].includes(name)) {
26
+ const actions = name === "agent_auth" ? ["start", "status", "cancel"]
27
+ : name === "claude_turn" ? ["issue"] : ["respond"];
28
+ if (!actions.includes(String(args.action)))
29
+ throw new ExecutionError("EXECUTION_INVALID");
30
+ tool += "." + args.action;
31
+ }
32
+ const nativeTool = executionRequestSchema.options[4].shape.tool.safeParse(tool);
33
+ if (!nativeTool.success)
34
+ throw new ExecutionError("EXECUTION_UNSUPPORTED");
35
+ const target = launches.has(name) ? args.session_name : name === "pty_open" ? args.name : args.session_id;
36
+ // Automatic names are selected inside existing core today. Do not guess the
37
+ // future name or act before reserving it at the actual selection boundary.
38
+ if (target === undefined || target === null)
39
+ throw new ExecutionError("EXECUTION_UNSUPPORTED");
40
+ const session = executionLaunchSchema.shape.session_id.safeParse(target);
41
+ if (!session.success)
42
+ throw new ExecutionError("EXECUTION_INVALID");
43
+ return { tool: nativeTool.data, target: session.data, stage: launches.has(name) ? "launch" : "send" };
44
+ }
45
+ // The SDK signal belongs to this serving RPC, not to a whole CLI turn. Keep
46
+ // an immediate local gate while the shared metadata lock may be awaiting I/O.
47
+ // The durable tombstone also fences later parent-return workers. Neither path
48
+ // sends a key, closes a session, or discards an issued action's late receipt.
49
+ function requestCancellation(service, request, input) {
50
+ if (input === undefined)
51
+ return undefined;
52
+ if (!(input instanceof AbortSignal))
53
+ throw new ExecutionError("EXECUTION_UNSUPPORTED");
54
+ const signal = input;
55
+ let cancelled = signal.aborted;
56
+ let pending;
57
+ let failure;
58
+ const persist = () => {
59
+ pending = service.cancelRequestActions(request).catch(error => { failure = error; });
60
+ };
61
+ const abort = () => { cancelled = true; persist(); };
62
+ signal.addEventListener("abort", abort, { once: true });
63
+ if (cancelled)
64
+ persist();
65
+ return {
66
+ assert() { if (cancelled)
67
+ throw new ExecutionError("EXECUTION_STOPPING"); },
68
+ async finish() {
69
+ signal.removeEventListener("abort", abort);
70
+ if (!cancelled)
71
+ return;
72
+ await pending;
73
+ // Cancellation may have arrived before register created the record.
74
+ // Reconcile the same ref only; do not retry any native action.
75
+ await service.cancelRequestActions(request);
76
+ if (failure)
77
+ throw failure;
78
+ },
79
+ };
80
+ }
81
+ export function createExecutionDispatcher(bindings) {
82
+ const captureNativeParent = bindings.captureNativeParent;
83
+ if (captureNativeParent !== undefined && typeof captureNativeParent !== "function")
84
+ throw new ExecutionError("EXECUTION_UNSUPPORTED");
85
+ const environment = { ...bindings.sourceEnvironment };
86
+ const directSource = executionSourceFromEnvironment(environment);
87
+ const native = bindings.nativeIdentity && { ...bindings.nativeIdentity };
88
+ const directSeat = environment.AITERM_SESSION_ID ?? environment.AITERM_AGENT_SESSION_ID ?? null;
89
+ const sourceFieldsPresent = ["AITERM_SESSION_ID", "AITERM_AGENT_SESSION_ID", "AITERM_AGENT_LAUNCH_ID"]
90
+ .some(name => environment[name] !== undefined);
91
+ let registeredControls = false;
92
+ const observe = async (session) => {
93
+ const value = await bindings.observeSessionGeneration(session);
94
+ if (!value || value.schema !== "aiterm.pty-observe-result.v1" || value.session_id !== session
95
+ || typeof value.exists !== "boolean")
96
+ throw new ExecutionError("EXECUTION_UNCONFIRMED");
97
+ if (!value.exists) {
98
+ if (value.launch_id !== null)
99
+ throw new ExecutionError("EXECUTION_UNCONFIRMED");
100
+ return { state: "absent", point: null };
101
+ }
102
+ const launch = executionLaunchSchema.safeParse({ session_id: session, launch_id: value.launch_id });
103
+ if (!launch.success)
104
+ throw new ExecutionError("EXECUTION_UNSUPPORTED");
105
+ return { state: "present", point: { launch: launch.data, boundary: null } };
106
+ };
107
+ return {
108
+ prepareControlRegistration(service) {
109
+ if (service !== bindings.service)
110
+ throw new ExecutionError("EXECUTION_UNSUPPORTED");
111
+ bindings.assertParticipant?.();
112
+ return { sourceContext: extra => executionHostSourceFromMeta(extra._meta, bindings.initializedClientName()),
113
+ activate: () => { registeredControls = true; } };
114
+ },
115
+ async dispatch(name, input, extra, body) {
116
+ let cancellation;
117
+ const run = async () => {
118
+ try {
119
+ bindings.assertParticipant?.();
120
+ // Fix input/transport context synchronously, before any async lookup.
121
+ // Handlers must consume these copies, not their mutable ingress object.
122
+ const args = structuredClone(input), fixedExtra = { ...extra,
123
+ requestId: extra.requestId, _meta: extra._meta === undefined ? undefined : structuredClone(extra._meta) };
124
+ if (controls.has(name)) {
125
+ if (!registeredControls || args.remote !== undefined)
126
+ throw new ExecutionError("EXECUTION_UNSUPPORTED");
127
+ // Only the same server's registered typed handlers run here. They
128
+ // already own metadata admission/stop; no synthetic send edge/frame.
129
+ executionHostSourceFromMeta(fixedExtra._meta, bindings.initializedClientName());
130
+ return await body(args, fixedExtra);
131
+ }
132
+ const route = routeFor(name, args);
133
+ if (!route)
134
+ return await body(args, fixedExtra);
135
+ const client = bindings.initializedClientName();
136
+ const host = executionHostSourceFromMeta(fixedExtra._meta, client);
137
+ const source = host !== undefined ? host.source : directSource;
138
+ // Partial/mismatched stdio identity is not an independent operator.
139
+ if (host === undefined && sourceFieldsPresent && !source)
140
+ throw new ExecutionError("EXECUTION_UNCONFIRMED");
141
+ const context = { schema: "aiterm.execution-source.v1", source };
142
+ const supplied = executionRefFromMeta(fixedExtra._meta);
143
+ if (args.remote !== undefined && args.remote !== null)
144
+ throw new ExecutionError("EXECUTION_UNSUPPORTED");
145
+ let reference = supplied;
146
+ let directRequest = null;
147
+ let frozenParent = null;
148
+ if (!reference && client !== "bellteam" && native) {
149
+ directRequest = executionRequestSchema.options[4].parse({ kind: "mcp", process_pid: native.pid,
150
+ process_started_identity: native.started_identity, request_id: fixedExtra.requestId,
151
+ tool: route.tool, target_session_id: route.target });
152
+ cancellation = requestCancellation(bindings.service, directRequest, fixedExtra.signal);
153
+ cancellation?.assert();
154
+ if (captureNativeParent) {
155
+ const ingress = { source, client_name: client ?? null, native_identity: native,
156
+ metadata: fixedExtra._meta === undefined ? null : fixedExtra._meta };
157
+ const captured = withExecutionRequest(directRequest, captureNativeParent, ingress);
158
+ if (captured && typeof captured.then === "function") {
159
+ void Promise.resolve(captured).catch(() => undefined);
160
+ throw new ExecutionError("EXECUTION_UNSUPPORTED");
161
+ }
162
+ frozenParent = captured === null ? null : structuredClone(captured);
163
+ }
164
+ }
165
+ if (reference) {
166
+ // External host refs are created by the real Bridge ingress. Direct
167
+ // model requests cannot borrow another call's reservation or choose
168
+ // a native control label to suppress an invocation edge.
169
+ if (client !== "bellteam" || reference.request.kind === "mcp"
170
+ || (route.tool !== "agent_launch" && route.tool !== "pty_send"))
171
+ throw new ExecutionError("EXECUTION_UNSUPPORTED");
172
+ const record = await bindings.service.execute({ action: "status", request: reference.request });
173
+ if (record.reservation.target.session_id !== route.target)
174
+ throw new ExecutionError("EXECUTION_CONFLICT");
175
+ // register fixed and verified the original HTTP ingress source. The
176
+ // subsequent host launch/send carries that same existing ref, not a
177
+ // new source context requirement. If supplied, an explicit context
178
+ // must still match; absence must not overwrite it with host env/null.
179
+ const hasContext = fixedExtra._meta && typeof fixedExtra._meta === "object"
180
+ && EXECUTION_SOURCE_META_KEY in fixedExtra._meta;
181
+ if (hasContext && (!same(record.reservation.source.launch, source?.launch ?? null)
182
+ || (record.reservation.source.boundary && !same(record.reservation.source.boundary, source?.boundary ?? null))))
183
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
184
+ cancellation = requestCancellation(bindings.service, reference.request, fixedExtra.signal);
185
+ cancellation?.assert();
186
+ }
187
+ else {
188
+ // BellTeam must retain its existing delivery/room/call reference.
189
+ if (client === "bellteam" || !directRequest)
190
+ throw new ExecutionError("EXECUTION_UNSUPPORTED");
191
+ const current = await observe(route.target);
192
+ if (route.stage === "send" && !current.point)
193
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
194
+ const request = directRequest;
195
+ cancellation?.assert();
196
+ await bindings.service.execute({ action: "register", source_session_id: source?.launch.session_id ?? directSeat,
197
+ reservation: { schema: "aiterm.execution-reservation.v1", request,
198
+ source: { launch: source?.launch ?? null, boundary: source?.boundary ?? null },
199
+ target: { session_id: route.target, expected_launch_id: current.point?.launch.launch_id ?? null } } }, context);
200
+ reference = { schema: "aiterm.execution-ref.v1", request };
201
+ }
202
+ cancellation?.assert();
203
+ const status = await bindings.service.execute({ action: "status", request: reference.request });
204
+ const expected = status.relation.target?.launch ?? (status.reservation.target.expected_launch_id
205
+ ? { session_id: route.target, launch_id: status.reservation.target.expected_launch_id } : null);
206
+ const requestMeta = { ...fixedExtra._meta, [EXECUTION_REQUEST_META_KEY]: reference };
207
+ return await runDeferredBoundExecution(bindings.service, requestMeta, route.stage, route.target, async () => {
208
+ const result = await withExecutionRequest(reference.request, () => body(args, { ...fixedExtra, _meta: requestMeta }), {
209
+ source: status.source.status === "verified" ? status.source.point : null,
210
+ client_name: client ?? null, native_identity: native,
211
+ metadata: fixedExtra._meta === undefined ? null : fixedExtra._meta,
212
+ ...(captureNativeParent ? { native_parent: frozenParent } : {}),
213
+ });
214
+ if (result.isError)
215
+ throw new ExecutionError("EXECUTION_UNCONFIRMED");
216
+ // Missing/invalid binding evidence is returned as null. The wrapper
217
+ // retains the genuine successful receipt if binding then fails; it
218
+ // must not turn a valid accepted action into permission to resend.
219
+ let target = null;
220
+ try {
221
+ if (route.tool === "pty_close")
222
+ target = expected ? { launch: expected, boundary: null } : null;
223
+ else {
224
+ const current = await observe(route.target);
225
+ target = current.point;
226
+ const receipt = result.structuredContent;
227
+ if (receipt && receipt.session_id !== undefined && receipt.session_id !== route.target)
228
+ target = null;
229
+ else if (receipt?.launch_id !== undefined && receipt.launch_id !== null
230
+ && receipt.launch_id !== target?.launch.launch_id)
231
+ target = null;
232
+ if (target && (launches.has(name) || name === "pty_send")) {
233
+ const cursor = receipt?.event_cursor;
234
+ const steer = result._meta?.["aiterm/steer"];
235
+ if (Number.isSafeInteger(cursor) && Number(cursor) >= 0 && receipt?.mode !== "sent") {
236
+ const candidate = executionPointSchema.safeParse({ launch: target.launch, boundary: {
237
+ event_cursor: cursor, operation_id: null, turn_id: null,
238
+ steer_id: receipt?.mode === "agent_steer" ? steer?.steer_id : null
239
+ } });
240
+ // An untracked steer is a generation edge, not a fabricated
241
+ // new dispatch boundary. Preserve its lifetime uncertainty.
242
+ if (candidate.success)
243
+ target = candidate.data;
244
+ }
245
+ }
246
+ const captured = readExecutionSendBoundary(route.target);
247
+ if (target && captured && receipt?.mode !== "agent_steer") {
248
+ // This came from actual core before_send in the same admitted
249
+ // request, not args/result.operation_id or a current-file read.
250
+ // Contradictory successful receipts remain successful receipts,
251
+ // with unknown binding and no permission to resend.
252
+ if (!same(captured.launch, target.launch) || receipt?.mode === "sent"
253
+ || (receipt?.event_cursor !== undefined && receipt.event_cursor !== captured.boundary?.event_cursor)
254
+ || (receipt?.operation_id !== undefined && receipt.operation_id !== captured.boundary?.operation_id))
255
+ target = null;
256
+ else
257
+ target = captured;
258
+ }
259
+ }
260
+ }
261
+ catch {
262
+ target = null; /* preserve receipt and let service mark binding unknown */
263
+ }
264
+ return { result, target };
265
+ }, cancellation?.assert);
266
+ }
267
+ catch (error) {
268
+ return executionErrorResult(error);
269
+ }
270
+ };
271
+ const result = await run();
272
+ try {
273
+ await cancellation?.finish();
274
+ }
275
+ catch {
276
+ const failure = executionErrorResult(new ExecutionError("EXECUTION_UNCONFIRMED", "possible"));
277
+ // Preserve a genuine accepted result even when cancellation recording
278
+ // failed. Status-only uncertainty must never become permission to resend.
279
+ return result.isError ? failure : { ...result, _meta: { ...result._meta,
280
+ [EXECUTION_ERROR_META_KEY]: failure._meta[EXECUTION_ERROR_META_KEY] } };
281
+ }
282
+ return result;
283
+ },
284
+ };
285
+ }