aiterm-mcp 0.70.4 → 0.70.6

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/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ import { loadAgentMetadata } from "./agent-metadata-reader.js";
2
3
  import { remoteInputDescription, remoteInputSchema, terminalArgumentDescription, terminalArgumentSchema } from "./remote-contract.js";
3
- import { boundTerminalTarget, bindTerminalSession, ensureSeatForward, extractMcpHeaders, maintainSeatForwards, REMOTE_MINIMUM_VERSION, seatIngressPort, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
4
+ import { boundTerminalTarget, bindTerminalSession, terminalSeatGroups, ensureSeatForward, extractMcpHeaders, maintainSeatForwards, REMOTE_MINIMUM_VERSION, seatIngressPort, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
4
5
  import { launchEnvValue } from "./private-env.js";
5
6
  import { AuthResponseError, authUiSchema, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
6
7
  import { configurationRequestSchema, configurationToolOutputSchema, applyConfigurationRequest, reconcileConfigurationRequest } from "./configure-request.js";
@@ -18,7 +19,7 @@ import { AitermError, AgentAuthenticationPreflightError, AgentResumeUnavailableE
18
19
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
19
20
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
20
21
  import { readPrivateEnvLine, setPrivateEnv } from "./private-env.js";
21
- import { withTerminalLaunchAction } from "./terminal-launch-error.js";
22
+ import { withTerminalLaunchAction, withErrorCode, launchNotStartedMeta } from "./terminal-launch-error.js";
22
23
  import { CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
23
24
  import { z } from "zod";
24
25
  import { agentModelsResult } from "./model-catalog.js";
@@ -258,6 +259,9 @@ export function createAitermServer(options = {}) {
258
259
  structuredContent: { schema: "aiterm.agent-launch-error.v1", harness: "claude-code", code: e.reasonCode,
259
260
  phase: "authentication_preflight", effect: "not_issued", session_created: false, message: msg },
260
261
  };
262
+ if (e instanceof AitermError && e.launchNotStarted)
263
+ return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
264
+ _meta: launchNotStartedMeta(e.launchNotStarted.harness) };
261
265
  return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true };
262
266
  }
263
267
  /**
@@ -317,14 +321,18 @@ export function createAitermServer(options = {}) {
317
321
  function remoteNote(target, result) {
318
322
  return { type: "text", text: `remote=${remoteLabel(target)} remote_aiterm=${result.remote_version ?? "unknown"}` };
319
323
  }
320
- async function forwardRemote(target, name, args) {
321
- const result = await callRemoteTool(target, name, args);
324
+ /** The remote result as this tool's own: request and result _meta pass unchanged (DESIGN.md 別端末の子). */
325
+ function remoteResult(target, result, structuredContent = result.structuredContent) {
322
326
  return {
323
327
  content: [...result.content, remoteNote(target, result)],
324
- ...(result.structuredContent ? { structuredContent: result.structuredContent } : {}),
328
+ ...(structuredContent ? { structuredContent } : {}),
325
329
  ...(result.isError ? { isError: true } : {}),
330
+ ...(result._meta ? { _meta: result._meta } : {}),
326
331
  };
327
332
  }
333
+ async function forwardRemote(target, name, args, extra) {
334
+ return remoteResult(target, await callRemoteTool(target, name, args, undefined, undefined, extra?._meta));
335
+ }
328
336
  function registerRemoteAwareTool(name, config, handler, remoteHandler = remoteToolHandler(name)) {
329
337
  server.registerTool(name, { ...config, inputSchema: { ...config.inputSchema, remote: remoteInputField } }, async ({ remote, ...args }, extra) => {
330
338
  try {
@@ -335,39 +343,39 @@ export function createAitermServer(options = {}) {
335
343
  const result = await remoteHandler(target, args, extra);
336
344
  if (name === "pty_close" && !remote && !result?.isError)
337
345
  unbindTerminalSession(args.session_id);
338
- return result;
346
+ return remote ? result : withErrorCode(result);
339
347
  }
340
348
  catch (e) {
341
- return fail(e);
349
+ return remote ? fail(e) : withErrorCode(fail(e));
342
350
  }
343
351
  });
344
352
  }
345
353
  /** 配送の登録や事前確保が要るtoolだけ専用の中継にし、他は同じtoolをそのまま現地へ呼ぶ。 */
346
354
  function remoteToolHandler(name) {
347
355
  switch (name) {
348
- case "agent_configure": return async (target, args) => {
356
+ case "agent_configure": return async (target, args, extra) => {
349
357
  // Older remote servers strip unknown input fields and could apply without tracking.
350
358
  if (args.request || args.action === "reconcile")
351
359
  throw new Error("REMOTE_UNSUPPORTED: tracked configuration requires the exact local connection; not issued");
352
- return forwardRemote(target, name, args);
360
+ return forwardRemote(target, name, args, extra);
353
361
  };
354
362
  case "pty_send": return sendRemote;
355
- case "pty_close": return async (target, args) => {
363
+ case "pty_close": return async (target, args, extra) => {
356
364
  await remoteParentDelivery?.beforeChange(deliveryKey(args.session_id, target));
357
- return forwardRemote(target, name, args);
365
+ return forwardRemote(target, name, args, extra);
358
366
  };
359
- case "pty_observe": return async (target, args) => {
360
- const result = await forwardRemote(target, name, args);
367
+ case "pty_observe": return async (target, args, extra) => {
368
+ const result = await forwardRemote(target, name, args, extra);
361
369
  if (!remoteParentDelivery || !result.structuredContent)
362
370
  return result;
363
371
  return { ...result, structuredContent: { ...result.structuredContent, parent_deliveries: remoteParentDelivery.status(deliveryKey(args.session_id, target)) } };
364
372
  };
365
- case "claude_turn": return async (target, args) => {
373
+ case "claude_turn": return async (target, args, extra) => {
366
374
  if (args.action === "issue")
367
375
  throw new core.AitermError("REMOTE_UNSUPPORTED: 別端末のclaude_turn issueには未対応です。pty_sendを使ってください", 2);
368
- return forwardRemote(target, name, args);
376
+ return forwardRemote(target, name, args, extra);
369
377
  };
370
- default: return (target, args) => forwardRemote(target, name, args);
378
+ default: return (target, args, extra) => forwardRemote(target, name, args, extra);
371
379
  }
372
380
  }
373
381
  async function sendRemote(target, args, extra) {
@@ -381,11 +389,10 @@ export function createAitermServer(options = {}) {
381
389
  // 終わった依頼の回答は送る前に保存する。実行中の依頼は残る。現地が差し込みを選べばその依頼が回答を受け取る。
382
390
  if (delivery)
383
391
  await remoteParentDelivery.beforeChange(key);
384
- const result = await callRemoteTool(target, "pty_send", args);
392
+ const result = await callRemoteTool(target, "pty_send", args, undefined, undefined, extra?._meta);
385
393
  const structured = result.structuredContent;
386
- if (result.isError || !structured || structured.mode !== "agent_dispatch") {
387
- return { content: [...result.content, remoteNote(target, result)], ...(structured ? { structuredContent: structured } : {}), ...(result.isError ? { isError: true } : {}) };
388
- }
394
+ if (result.isError || !structured || structured.mode !== "agent_dispatch")
395
+ return remoteResult(target, result);
389
396
  try {
390
397
  // 現地がdispatchを選んだのは子がidleだった時なので、前の依頼はもう保存できる。残っていれば登録しない。
391
398
  if (delivery)
@@ -398,10 +405,8 @@ export function createAitermServer(options = {}) {
398
405
  return fail(new Error(`別端末へのdispatchは済みましたが、回答配送を登録できませんでした: ${e instanceof Error ? e.message : String(e)}`));
399
406
  }
400
407
  const waited = await remoteCompletionWait(delivery, target, structured.session_id, structured.event_cursor, structured.input_id);
401
- return {
402
- content: [...result.content, remoteNote(target, result), { type: "text", text: deliveryIdLine(delivery).trim() || "completion=wait_process" }],
403
- structuredContent: { ...structured, wait_process: waited.wait_process, ...(delivery?.result() ? { parent_delivery: delivery.result() } : {}) },
404
- };
408
+ const relayed = remoteResult(target, result, { ...structured, wait_process: waited.wait_process, ...(delivery?.result() ? { parent_delivery: delivery.result() } : {}) });
409
+ return { ...relayed, content: [...relayed.content, { type: "text", text: deliveryIdLine(delivery).trim() || "completion=wait_process" }] };
405
410
  }
406
411
  /** 別端末の子の依頼を、この端末の親への配送に登録する。launch_idは現地の完了観測から取る。 */
407
412
  async function registerRemoteDelivery(delivery, target, sessionId, eventCursor, operationId = null, inputId) {
@@ -821,7 +826,7 @@ export function createAitermServer(options = {}) {
821
826
  try {
822
827
  await core.maintainAgentIdleClocks();
823
828
  const result = core.listSessionsResult(env_keys);
824
- return { ...ok(core.listSessions(result)), structuredContent: { ...result }, ...seatTurnsMeta(result.sessions, extra._meta) };
829
+ return { ...ok(core.listSessions(result)), structuredContent: { ...result }, ...await seatTurnsMeta(result.sessions, extra._meta) };
825
830
  }
826
831
  catch (e) {
827
832
  return fail(e);
@@ -829,11 +834,21 @@ export function createAitermServer(options = {}) {
829
834
  });
830
835
  // Declared controller caller markers opt into current-turn metadata (ADR 0122).
831
836
  // 説明と引数には出さない(steer-follow.ts の冒頭)。それ以外の呼び手には何も足さない。
832
- function seatTurnsMeta(sessions, requestMeta) {
837
+ async function seatTurnsMeta(sessions, requestMeta) {
833
838
  if (!interimCallerFromMeta(requestMeta, server.server.getClientVersion()?.name, server.server.getClientCapabilities()))
834
839
  return {};
835
840
  try {
836
- return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: core.readSeatTurns(sessions.filter(session => session.harness !== null).map(session => session.session_id)) } };
841
+ const local = core.readSeatTurns(sessions.filter(session => session.harness !== null).map(session => session.session_id));
842
+ // Terminal seats: the same call relayed with the same _meta; each terminal answers only for its own bound sessions.
843
+ // Inside the caller's 5 s pty_list budget (tool catalog timeout_ms): a slow or unreachable terminal contributes no rows.
844
+ const remote = await Promise.all(terminalSeatGroups().map(({ target, sessions: bound }) => Promise.race([
845
+ callRemoteTool(target, "pty_list", {}, 4_000, undefined, requestMeta).then(result => {
846
+ const seats = result._meta?.[SEAT_TURNS_RESULT_META_KEY]?.seats;
847
+ return Array.isArray(seats) ? seats.filter((seat) => bound.includes(seat?.session_id)) : [];
848
+ }, () => []),
849
+ new Promise(resolve => setTimeout(resolve, 4_000, []).unref()),
850
+ ])));
851
+ return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { ...local, seats: [...local.seats, ...remote.flat()] } } };
837
852
  }
838
853
  catch (e) {
839
854
  return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { schema: "aiterm.seat-turns.v1", error: e instanceof Error ? e.message : String(e) } } };
@@ -1204,9 +1219,16 @@ export function createAitermServer(options = {}) {
1204
1219
  async function launchRemoteAgent(target, harness, args, extra, privateEnv) {
1205
1220
  if (args.image && args.image.length > 0)
1206
1221
  throw new core.AitermError("REMOTE_IMAGE_UNSUPPORTED: 別端末への画像添付には未対応です", 2);
1222
+ // An Aiterm without fork_from would drop it and start a writable seat (ADR 0140): check the version first.
1223
+ if (args.fork_from) {
1224
+ const version = (await callRemoteTool(target, "pty_list", {}, 60_000)).remote_version ?? "0.0.0";
1225
+ if (!versionAtLeast(version, FORK_MINIMUM_VERSION))
1226
+ throw new AitermError(`REMOTE_AITERM_TOO_OLD: the remote runs Aiterm ${version}; fork_from needs ${FORK_MINIMUM_VERSION} or later`, 2);
1227
+ }
1207
1228
  const delivery = args.prompt || args.throughline_source_session ? await deliveryForRequest(extra, true) : null;
1208
1229
  // A terminal's claude_agent takes append_system_prompt / mcp_config since 0.65.0; its agent_launch drops them until this release.
1209
- const result = target.trusted_ref && harness === "claude-code"
1230
+ // claude_agent has no fork_from, so a fork always goes through agent_launch.
1231
+ const result = target.trusted_ref && harness === "claude-code" && !args.fork_from
1210
1232
  ? await callRemoteTool(target, "claude_agent", args, 600_000, privateEnv)
1211
1233
  : await callRemoteTool(target, "agent_launch", { harness, ...args }, 600_000, privateEnv);
1212
1234
  const structured = result.structuredContent;
@@ -1235,6 +1257,8 @@ export function createAitermServer(options = {}) {
1235
1257
  ...(result.isError && !unconfirmed ? { isError: true } : {}),
1236
1258
  };
1237
1259
  }
1260
+ /** First release whose agent_launch knows fork_from (ADR 0140). */
1261
+ const FORK_MINIMUM_VERSION = "0.70.6";
1238
1262
  const terminalVersions = new Map();
1239
1263
  /** A seat on a BellTeam terminal (remote-terminal.md "One launch path"). Same launch arguments plus terminal + cwd. */
1240
1264
  async function launchTerminalAgent(harness, terminal, args, extra) {
@@ -1276,15 +1300,15 @@ export function createAitermServer(options = {}) {
1276
1300
  const session = result?.structuredContent?.session_id;
1277
1301
  if (typeof session === "string")
1278
1302
  bindTerminalSession(session, target.trusted_ref);
1279
- return withTerminalLaunchAction(result);
1303
+ return withErrorCode(withTerminalLaunchAction(result));
1280
1304
  }
1281
1305
  catch (e) {
1282
- return withTerminalLaunchAction(fail(e));
1306
+ return withErrorCode(withTerminalLaunchAction(fail(e)));
1283
1307
  }
1284
1308
  }
1285
1309
  async function launchAgent(kind, args, extra) {
1310
+ const { prompt, image, throughline_source_session, throughline_supplement_file, model, reasoning_effort, fast, env_vars, cwd, session_name, launch_operation_id, write_scope, trust_project, require_existing_resume, configuration_root, append_system_prompt, mcp_config, fork_from } = args;
1286
1311
  const supportsWriteScope = kind !== "claude";
1287
- const { prompt, image, throughline_source_session, throughline_supplement_file, model, reasoning_effort, fast, env_vars, cwd, session_name, launch_operation_id, write_scope, trust_project, require_existing_resume, configuration_root, append_system_prompt, mcp_config } = args;
1288
1312
  let delivery = null;
1289
1313
  try {
1290
1314
  if (!supportsWriteScope && write_scope !== undefined) {
@@ -1316,7 +1340,9 @@ export function createAitermServer(options = {}) {
1316
1340
  mcp_config,
1317
1341
  launch_operation_id: launch_operation_id ?? undefined,
1318
1342
  ...(supportsWriteScope ? { write_scope } : {}),
1343
+ ...(fork_from ? { fork_from } : {}),
1319
1344
  });
1345
+ const forkOf = fork_from ? loadAgentMetadata(sid).fork_of : undefined;
1320
1346
  const structured = {
1321
1347
  schema: "aiterm.agent-launch-result.v1",
1322
1348
  provider: kind,
@@ -1340,6 +1366,7 @@ export function createAitermServer(options = {}) {
1340
1366
  : "declaration_only_unsupported",
1341
1367
  }
1342
1368
  : {}),
1369
+ ...(forkOf ? { fork_of: { session_id: forkOf.session_id, vendor_session_id: forkOf.vendor_session_id, write_ban: forkOf.write_ban } } : {}),
1343
1370
  };
1344
1371
  // 開始未確認(submitted_unconfirmed)は誤りにしない。sessionは立ち、promptは入力欄を離れ、配送も登録済み。
1345
1372
  // 誤りで返すとClaude Code親は受け口のhookを走らせず、子の回答が届かない(ADR 0093)。状態はinitial_promptと本文で伝える。
@@ -1472,6 +1499,10 @@ export function createAitermServer(options = {}) {
1472
1499
  terminal: terminalArgumentSchema.optional().describe(terminalArgumentDescription),
1473
1500
  append_system_prompt: z.string().min(1).optional().describe("claude-code only. Launch instructions added to the system prompt; kept in Aiterm state, not in the project or home. Never put secrets here"),
1474
1501
  mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("claude-code only. Extra MCP servers for this seat. Secret header values: write ${NAME} and list NAME in env_vars"),
1502
+ fork_from: z.object({
1503
+ session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/).describe("The main Aiterm seat on the same machine (the terminal or remote when given)"),
1504
+ fork_id: z.string().min(1).max(200).optional().describe("Caller's fork ID, passed to the seat as THROUGHLINE_FORK_ID"),
1505
+ }).strict().optional().describe("claude-code and codex-cli. Start a disposable fork of that seat's latest saved conversation, in its cwd, with the main's tools and MCP. Every write inside that cwd (the project folder) is refused below the tools for the whole process tree (Linux Landlock, macOS sandbox-exec); everything else is allowed. Windows answers READONLY_UNENFORCEABLE. Requires a prompt; no write_scope. Close it after its answer"),
1475
1506
  },
1476
1507
  outputSchema: {
1477
1508
  schema: z.literal("aiterm.agent-launch-result.v1"),
@@ -1493,6 +1524,8 @@ export function createAitermServer(options = {}) {
1493
1524
  fast_error: fastModeFailureSchema.nullable().optional().describe("fastを頼まれたが、通常の速度で起こした時の訳"),
1494
1525
  write_scope: z.string().optional(),
1495
1526
  write_scope_enforcement: z.enum(["enforced_read_only", "declaration_only_unsupported"]).optional(),
1527
+ fork_of: z.object({ session_id: z.string(), vendor_session_id: z.string(),
1528
+ write_ban: z.object({ path: z.string(), method: z.enum(["landlock", "seatbelt"]) }) }).optional().describe("The seat this fork copies and the folder it cannot write"),
1496
1529
  },
1497
1530
  }, async ({ harness, remote, terminal, ...args }, extra) => {
1498
1531
  if (harness !== "claude-code" && (args.append_system_prompt !== undefined || args.mcp_config !== undefined))
@@ -5,9 +5,11 @@ import { z } from "zod";
5
5
  import { agentMetadataPath, writeJson0600 } from "./agent-shared.js";
6
6
  import { readProcessIdentities, observeExecutionActor } from "./process-runtime.js";
7
7
  const stamp = z.string().refine(value => Number.isFinite(Date.parse(value)));
8
- const spanSchema = z.object({ turn_id: z.string().regex(/^managed:[a-f0-9]{32}$/), started_at: stamp }).strict();
8
+ const spanSchema = z.object({ turn_id: z.string().regex(/^managed:[a-f0-9]{32}$/), started_at: stamp,
9
+ interim_from: z.string().nullable().optional() }).strict();
9
10
  const recordSchema = z.object({ binding: z.string().min(1), span: spanSchema.nullable(), terminal: z.string().nullable(),
10
- ready: z.object({ since: stamp, terminal: z.string().nullable() }).strict().nullable() }).strict();
11
+ ready: z.object({ since: stamp, terminal: z.string().nullable() }).strict().nullable(),
12
+ settled_from: z.string().nullable().optional() }).strict();
11
13
  const ownerSchema = z.object({ pid: z.number().int().positive(), started_identity: stamp, token: z.string() }).strict();
12
14
  export const managedSpanDirectory = (meta) => agentMetadataPath(meta.aiterm_session, meta.launch_id).replace(/\.agent\.json$/, ".seat-span.d");
13
15
  /** Same callback owns live capture and the short identity transaction. Never waits or sends input. */
@@ -61,7 +63,7 @@ export function withManagedSpan(meta, capture) {
61
63
  }
62
64
  }
63
65
  /** Persistence keeps identity only; evidence must come from a new validated native read. */
64
- export function observeManagedSpan(file, binding, evidence, terminal, at) {
66
+ export function observeManagedSpan(file, binding, evidence, terminal, at, position = () => null) {
65
67
  stamp.parse(at);
66
68
  let record = null;
67
69
  try {
@@ -80,14 +82,17 @@ export function observeManagedSpan(file, binding, evidence, terminal, at) {
80
82
  return null;
81
83
  if (evidence === "busy") {
82
84
  if (!record?.span) {
83
- record = { binding, span: { turn_id: `managed:${randomBytes(16).toString("hex")}`, started_at: at }, terminal, ready: null };
85
+ // Words of this span start where the same binding last settled idle; a span never seen idle has no start.
86
+ record = { binding, span: { turn_id: `managed:${randomBytes(16).toString("hex")}`, started_at: at,
87
+ interim_from: record?.settled_from ?? null }, terminal, ready: null, settled_from: null };
84
88
  writeJson0600(file, record);
85
89
  }
86
90
  else if (record.ready) {
87
91
  record.ready = null;
88
92
  writeJson0600(file, record);
89
93
  }
90
- return { state: "running", ...record.span, event_cursor: null, interim_from: null, wait_process: null };
94
+ const { turn_id, started_at, interim_from = null } = record.span;
95
+ return { state: "running", turn_id, started_at, event_cursor: null, interim_from, wait_process: null };
91
96
  }
92
97
  // A launch that never showed busy nor any terminal has no turn to hide: its settled ready is idle.
93
98
  if (!terminal && (record?.span || record?.terminal) || record?.span && terminal === record.terminal)
@@ -101,9 +106,11 @@ export function observeManagedSpan(file, binding, evidence, terminal, at) {
101
106
  }
102
107
  if (Date.parse(at) - Date.parse(record.ready.since) < 250)
103
108
  return null;
104
- if (record.span) {
109
+ const settled = position();
110
+ if (record.span || (record.settled_from ?? null) !== settled) {
105
111
  record.span = null;
106
112
  record.terminal = terminal;
113
+ record.settled_from = settled;
107
114
  writeJson0600(file, record);
108
115
  }
109
116
  return { state: "idle" };
@@ -620,6 +620,18 @@ export function unbindTerminalSession(session) {
620
620
  delete seats[session];
621
621
  writeSeats(seats);
622
622
  }
623
+ /** Bound sessions grouped by terminal, for relaying a session-less call (pty_list seat_turns). An unreadable binding is skipped. */
624
+ export function terminalSeatGroups() {
625
+ const groups = new Map();
626
+ for (const [session, ref] of Object.entries(readSeats()))
627
+ groups.set(ref, [...groups.get(ref) ?? [], session]);
628
+ return [...groups].flatMap(([ref, sessions]) => { try {
629
+ return [{ target: trustedTarget(binding(ref)), sessions }];
630
+ }
631
+ catch {
632
+ return [];
633
+ } });
634
+ }
623
635
  /** A later call's target, by session only. null = a local session. */
624
636
  export function boundTerminalTarget(session) {
625
637
  if (typeof session !== "string")
package/dist/remote.js CHANGED
@@ -146,7 +146,7 @@ export function remoteServerCommand(shell) {
146
146
  return shell === "posix" ? posixCommand("exec aiterm-mcp") : "aiterm-mcp";
147
147
  }
148
148
  /** 現地のaiterm-mcpへ1回だけMCP接続し、指定toolを呼んで閉じる。privateEnvは暗号化されたstdinの先頭行だけで渡す(remote-terminal.md R5)。 */
149
- export async function callRemoteTool(target, name, args, timeoutMs = 600_000, privateEnv) {
149
+ export async function callRemoteTool(target, name, args, timeoutMs = 600_000, privateEnv, meta) {
150
150
  if (privateEnv && !target.trusted_ref)
151
151
  throw new AitermError("REMOTE_PRIVATE_ENV_UNSUPPORTED: private values travel only to a terminal binding", 2);
152
152
  const shell = await remoteShell(target);
@@ -173,11 +173,15 @@ export async function callRemoteTool(target, name, args, timeoutMs = 600_000, pr
173
173
  const detail = stderr.trim().split("\n").slice(-3).join(" / ") || (error instanceof Error ? error.message : String(error));
174
174
  throw new AitermError(`REMOTE_CONNECT_FAILED: ${remoteLabel(target)} のAitermへ接続できません(${detail})`, 2);
175
175
  }
176
- const result = await client.callTool({ name, arguments: args }, undefined, { timeout: timeoutMs, resetTimeoutOnProgress: true });
176
+ // Request _meta is opaque to the relay; progressToken belongs to this hop's client, not the caller's.
177
+ const { progressToken: _hop, ...forwarded } = meta ?? {};
178
+ const request = Object.keys(forwarded).length ? { name, arguments: args, _meta: forwarded } : { name, arguments: args };
179
+ const result = await client.callTool(request, undefined, { timeout: timeoutMs, resetTimeoutOnProgress: true });
177
180
  return {
178
181
  content: result.content ?? [],
179
182
  ...(result.structuredContent ? { structuredContent: result.structuredContent } : {}),
180
183
  ...(result.isError ? { isError: true } : {}),
184
+ ...(result._meta ? { _meta: result._meta } : {}),
181
185
  remote_version: client.getServerVersion()?.version ?? null,
182
186
  };
183
187
  }
@@ -24,6 +24,7 @@ const ACTIONS = {
24
24
  REMOTE_AITERM_TOO_OLD: "端末のAitermが古いため起こせません。端末のAitermを更新してください。",
25
25
  SEAT_FORWARD_UNAVAILABLE: "端末からBellTeamへ戻る通り道がまだ用意できていません。少し待ってから起こし直してください。",
26
26
  CWD_UNAVAILABLE: "端末に作業フォルダがありません。メンバーの作業フォルダを選び直すか、そのフォルダを作ってください。",
27
+ AGENT_LAUNCH_NOT_STARTED: "席を作る途中で失敗しました。席は残っていません。もう一度起こし直します。",
27
28
  CLAUDE_AUTH_NOT_AUTHENTICATED: "端末のClaude Codeにログインしていません。端末でClaude Codeにログインしてください。",
28
29
  CLAUDE_AUTH_STATUS_UNCONFIRMED: "端末のClaude Codeのログイン状態を確かめられませんでした。少し待ってから起こし直してください。",
29
30
  CLAUDE_AUTH_STATUS_TIMEOUT: "端末のClaude Codeのログイン状態を時間内に確かめられませんでした。少し待ってから起こし直してください。",
@@ -36,6 +37,20 @@ export function terminalLaunchAction(code) {
36
37
  return typeof code === "string" && Object.hasOwn(ACTIONS, code) ? ACTIONS[code] : null;
37
38
  }
38
39
  export const LAUNCH_ERROR_META = "aiterm/launch_error";
40
+ export const ERROR_CODE_META = "aiterm/error_code";
41
+ /** R18 for a local launch: the fresh native creation left no seat (core.freshLaunchFailure). */
42
+ export function launchNotStartedMeta(harness) {
43
+ const code = "AGENT_LAUNCH_NOT_STARTED";
44
+ return { [LAUNCH_ERROR_META]: { schema: "aiterm.agent-launch-error.v1", harness, code, phase: "native_create",
45
+ effect: "not_started", session_created: false, action: ACTIONS[code] } };
46
+ }
47
+ /** R19: the leading symbolic code of a refused call, so the caller does not parse text. It claims no effect. */
48
+ export function withErrorCode(result) {
49
+ if (!result?.isError)
50
+ return result;
51
+ const code = errorCode(result.content?.find((item) => item.type === "text")?.text ?? "");
52
+ return code ? { ...result, _meta: { ...result._meta, [ERROR_CODE_META]: { schema: "aiterm.error-code.v1", code } } } : result;
53
+ }
39
54
  /** Adds R18's `_meta` to a failed terminal launch result; a result whose code is not listed is returned unchanged.
40
55
  * `_meta`, not structuredContent: SDK clients that listed the tools validate structuredContent against the
41
56
  * success outputSchema even on isError, and would turn this refusal into a protocol error. */