aiterm-mcp 0.70.4 → 0.70.5

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/CHANGELOG.md CHANGED
@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.70.5] - 2026-11-10
11
+
12
+ - A fresh managed launch (Claude Code, Codex) whose terminal session could not be set up no longer answers `AGENT_RESUME_UNCONFIRMED: 復帰したnative端末の本人性を確認できません`. That one sentence came from fifteen places, on fresh launches as well as resumes, and a fresh launch refused on a Mac terminal on 2026-11-10 could not be traced to its place afterwards. Every such refusal now names its place as `native_reason=<site>`; a failed tmux command adds its name, exit code and first error line, an unreadable creation receipt adds the output size.
13
+ - After a failed setup Aiterm closes the session it created and then reads the complete session list. When the name is absent and no hibernated seat holds it, the launch answers `AGENT_LAUNCH_NOT_STARTED` with `_meta["aiterm/launch_error"]` (`effect: "not_started"`, `session_created: false`, `phase: "native_create"`; on a terminal seat `phase: "terminal"`, projected by the server like the other not-started codes). The caller can launch again; nothing was typed and nothing remains. When the created session is still listed, or the list cannot be read, the text keeps `creation_rollback_unconfirmed` and no not-started result is given. Before, a failed `has-session` of any kind was read as "already gone". A fresh launch whose identity check fails without that proof answers `AGENT_LAUNCH_UNCONFIRMED`; `pty_close` of the name, then a new launch, is the way out. Resumes keep `AGENT_RESUME_UNCONFIRMED`. A terminal must run this release to answer the new codes.
14
+ - A launch refused because a live session already has the name answers `SESSION_EXISTS: session '<name>' は既に存在します…`.
15
+ - A refused launch on a terminal, and a refused tool forwarded to a terminal seat by its session (`pty_close`, `pty_send`, `pty_observe`, …), carry `_meta["aiterm/error_code"]` = `{schema: "aiterm.error-code.v1", code}` whenever the refusal text starts with a symbolic code, whether the container raised it before SSH (`CREDENTIAL_NOT_LOADED`, `UNREACHABLE`, …) or the terminal answered it. The code gives the reason only and claims nothing about the effect. Callers no longer need to parse the leading `aiterm: CODE:` text.
16
+ - Tools relayed to a terminal (by `remote` or by a terminal seat's session) pass the request `_meta` to the terminal's Aiterm unchanged, except the hop-local `progressToken`, and return the terminal's result `_meta` unchanged. Before, both were dropped: a terminal Claude seat called by BellTeam never answered `aiterm/interim_words` on `pty_observe`, and `pty_send` steers came back without `_meta["aiterm/steer"]`, so the caller could not follow them. Container-side change; the terminal answers the markers it already supports.
17
+ - `aiterm/seat_turns` (`pty_list` for a declared controller caller): a Claude Code or Grok running row that the caller did not start now carries `interim_from`, the interim-words token (`v1:<c>:b:<byte>` Claude, `v1:<c>:u:<users>` Grok) at which its words begin, taken at the seat's last settled idle. Pass it as `aiterm/interim_from` to read only that turn's words. A row whose seat was never seen settled idle under the same binding, and Cursor and Antigravity rows, keep `null`. `event_cursor` and `wait_process` stay `null`. The rows also list terminal seats: each terminal with bound sessions is asked once per call (same `_meta`, 4 s limit) and contributes rows for its own bound sessions; a slow or unreachable terminal contributes none. Terminals need this release for `interim_from` on their rows.
18
+ - `pty_open` with `pwsh` on Linux and macOS: the first `pty_send` no longer garbles or loses its line. PowerShell mangled text typed before its line editor started (Unicode became single bytes and the line was redrawn without running), so `pty_open` now returns after the first prompt, waiting at most 10 s. On Linux the pane also ran PowerShell under a forked `/bin/sh`, so `mark` wrote a POSIX sentinel into PowerShell; a plain shell name is now exec'd, so the pane's foreground is the shell itself (as on macOS).
19
+ - CI: the macOS environment is now `macos-hosted`, a GitHub-hosted `macos-latest` runner (free for this public repository), for the full and selected tests and for the macOS terminal runtime build. No Aiterm job runs on the self-hosted Mac that carries production terminal seats any more. Linux and Windows stay on the factory runners.
20
+
10
21
  ## [0.70.4] - 2026-11-10
11
22
 
12
23
  - `agent_configure` on Claude Code reads both `/model` picker layouts. Claude Code 2.1.322 shows, per session, either versioned rows (`Opus 5.5`) or alias rows with the model the alias resolves to in the second column (`Opus ✔ Opus 5.5 · …`). Rows now match by their first column or, outside the `Default` row and only when unique, by that resolved model, so `opus`, `sonnet`, `haiku` and `claude-opus-5-5` work on alias pickers. Before, every model change on an alias picker was refused with `CLAUDE_MODEL_NOT_IN_PICKER`. An alias still matches the native catalog's model, not the picker's alias row: where the session's `Fable` row resolves to Fable 5.1 and the catalog names Fable 5.2, `fable` and `claude-fable-5-2` are refused rather than selecting the older model. The refusal now lists alias rows with their resolved model, e.g. `Fable (Fable 5.1)`. A missing Claude CLI during this lookup now reports `CLAUDE_MODEL_CATALOG_UNAVAILABLE` instead of `CLAUDE_MODEL_NOT_IN_PICKER`.
@@ -3178,7 +3189,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3178
3189
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3179
3190
  provenance.
3180
3191
 
3181
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.4...HEAD
3192
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.5...HEAD
3193
+ [0.70.5]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.4...v0.70.5
3182
3194
  [0.70.4]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.3...v0.70.4
3183
3195
  [0.70.3]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.2...v0.70.3
3184
3196
  [0.70.2]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.1...v0.70.2
package/README.ja.md CHANGED
@@ -215,7 +215,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
215
215
  場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
216
216
  Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
217
217
 
218
- **状態:** 開発継続中 · 現行公開版 **v0.70.4** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.5** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
219
219
 
220
220
  ### 更新と巻き戻し
221
221
 
package/README.md CHANGED
@@ -227,7 +227,7 @@ collection is off by default and performs no network I/O. It ships via
227
227
  tag-triggered CI with npm provenance (OIDC Trusted Publishing); the GitHub
228
228
  Release re-registers the Official MCP Registry entry.
229
229
 
230
- **Status:** actively maintained · current public release **v0.70.4** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
230
+ **Status:** actively maintained · current public release **v0.70.5** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
231
231
 
232
232
  ### Update and rollback
233
233
 
package/dist/core.js CHANGED
@@ -67,7 +67,7 @@ import { grokAuthPlan, grokAuthStatus, grokAuthPane, GROK_MODEL_DEFAULTS, realGr
67
67
  import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, codexWorkingResumeConfiguration, captureCodexRecoveryProof, captureCodexResumeProof, readCodexResumeProof, codexResumeProofDigest, codexRootTranscript, codexRunningTurn, codexInterruptionRecord, observeCodexDone, buildCodexAgentCmd, codexAgentArgv, codexResumeArgv, codexLaunchNote, codexPaneObservation, CODEX_INTERRUPT_KEY, codexHelperProcess, codexRateLimitModelSwitchDialog, codexApprovalDialog, codexStartupAction, codexModelChoice, codexEffortChoice, codexMoreReasoningChoice, codexTranscriptText, createCodexAgentMetadata, codexModelChoices, codexFastCommandOffered, codexFooterShowsFast, codexServiceTierNotices, restoreCodexDefaults, restoreCodexDefaultInFile, } from "./harnesses/codex.js";
68
68
  import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, OPERATION_ID_RE, CLAUDE_RESULT_MAX_BYTES, CLAUDE_EFFORTS, agentClaudeOperationPath, agentClaudeApprovalReceiptPath, agentClaudeDispatchReceiptPath, validateOperationId, readClaudeResultText, assertClaudeAuthenticationReady, claudeModelChoices, claudeConfigDir, claudeProjectSlug, claudeFastIndicatorShown, claudeFastResult, buildClaudeAgentCmd, claudeAgentArgv, claudeResumeArgv, claudeLaunchNote, claudePaneObservation, CLAUDE_INTERRUPT_KEY, claudeUsageLimit, claudeLiveSelectMenu, claudeStartupAction, createClaudeAgentMetadata, writeClaudeCallerFiles, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, claudeApiErrorEndingTurn, claudeFailureCategory, } from "./harnesses/claude.js";
69
69
  import { cursorAuthPlan, cursorAuthStatus, cursorAuthPane, bindCursorTranscriptSession, cursorTurnBoundary, latestCursorCompletion, cursorTranscript, cursorTranscriptSessionId, observeCursorDone, cursorTranscriptText, assertCursorAuthenticationReady, assertCursorModelAvailable, cursorModelChoices, cursorModelIsFastVariant, cursorFastParameter, cursorHeaderShowsFast, cursorPickerView, cursorEffortSelected, cursorParameterRows, cursorUserConfigPath, CURSOR_DEFAULT_MODEL_KEYS, realCursorHome, buildCursorAgentCmd, cursorAgentArgv, cursorPromptWithLineage, createCursorAgentMetadata, cursorLaunchNote, cursorEffortNavigation, cursorTuiReady, cursorPaneObservation, CURSOR_INTERRUPT_KEY, cursorPromptHooksRunning, cursorUsageLimit, CURSOR_SUBMIT_SEQUENCE, validateCursorModelEffort, } from "./harnesses/cursor.js";
70
- import { interimFromNow, readInterimWords, recordInterimBoundary } from "./interim-words.js";
70
+ import { interimFromNow, interimFromToken, readInterimWords, recordInterimBoundary } from "./interim-words.js";
71
71
  import { codexSeatTurn, grokSteerAcceptance, observeSteerDone, readSteerEntry, recordSteer } from "./steer-follow.js";
72
72
  import { resolveAgentBin, resolveThroughlineBin, runThroughlineHandoffContext, isWindowsNativeExecutable, isUsableAgentExecutableFile, agentBinForPaneShell, resolveWinPaneShell, windowsAgentArgv, windowsAgentLaunchLine } from "./agent-resolver.js";
73
73
  export { AitermError } from "./errors.js";
@@ -689,7 +689,7 @@ function openSessionInternal(name, shell, envVars, preserveAgentState) {
689
689
  throw new AitermError("openSession: 自動採番のリトライ上限(tmux new-session が重複以外で失敗し続けている可能性)", 2);
690
690
  if (sessionExists(nm)) {
691
691
  if (explicit)
692
- throw new AitermError(`session '${nm}' は既に存在します(list で確認)`, 2);
692
+ throw new AitermError(`SESSION_EXISTS: session '${nm}' は既に存在します(list で確認)`, 2);
693
693
  }
694
694
  else {
695
695
  const environment = [...banner, ...envVars.filter(key => key !== "AITERM_SESSION_ID" && launchEnvValue(key) !== undefined)
@@ -766,6 +766,15 @@ function openSessionInternal(name, shell, envVars, preserveAgentState) {
766
766
  catch (error) {
767
767
  ownTelemetryFailure("AITERM.PERSISTENCE_WRITE_FAILED", error);
768
768
  }
769
+ // PowerShell on POSIX garbles input typed before its line editor starts (bash keeps it as a line). Wait, bounded,
770
+ // until a prompt leaves the cursor off column 0; a pane that never shows one is returned as before.
771
+ if (process.platform !== "win32" && /^pwsh(?:-preview)?$/u.test(path.basename(shell))) {
772
+ for (const deadline = Date.now() + 10_000; Date.now() < deadline; pauseSync(100)) {
773
+ const cursor = tmux("display-message", "-p", "-t", nm, "#{cursor_x}");
774
+ if (cursor.code !== 0 || Number(cursor.stdout.trim()) > 0)
775
+ break;
776
+ }
777
+ }
769
778
  return [nm, attachHint(nm)];
770
779
  });
771
780
  }
@@ -3796,6 +3805,17 @@ function managedSeatTerminal(meta) {
3796
3805
  return null;
3797
3806
  }
3798
3807
  }
3808
+ /** Where a later self-started turn's words begin. Cursor rewrites its tail at turn start and Antigravity has no word reader: null. */
3809
+ function managedSpanStart(meta) {
3810
+ if (meta.kind !== "claude" && meta.kind !== "grok")
3811
+ return null;
3812
+ try {
3813
+ return interimFromToken(interimFromNow(meta, agentCompletionCursor(meta)));
3814
+ }
3815
+ catch {
3816
+ return null;
3817
+ }
3818
+ }
3799
3819
  function readManagedSeatTurn(meta) {
3800
3820
  const started = performance.now();
3801
3821
  const result = withManagedSpan(meta, file => {
@@ -3825,7 +3845,7 @@ function readManagedSeatTurn(meta) {
3825
3845
  || performance.now() - started >= 15_000)
3826
3846
  return null;
3827
3847
  const binding = JSON.stringify([meta.aiterm_session, meta.launch_id, meta.kind, conversation, proof, live.pane_process, live.harness_process]);
3828
- return observeManagedSpan(file, binding, evidence, terminal, new Date().toISOString());
3848
+ return observeManagedSpan(file, binding, evidence, terminal, new Date().toISOString(), () => managedSpanStart(meta));
3829
3849
  });
3830
3850
  return performance.now() - started < 15_000 ? result : null;
3831
3851
  }
@@ -7884,6 +7904,9 @@ function prepareAgentLaunch(kind, opts = {}) {
7884
7904
  verifyCreatedNative(initialNative);
7885
7905
  }, create);
7886
7906
  }
7907
+ catch (error) {
7908
+ throw freshLaunchFailure(error, agentHarness(kind));
7909
+ }
7887
7910
  finally {
7888
7911
  if (initialAdmission) {
7889
7912
  const { name } = initialAdmission;
@@ -7892,6 +7915,29 @@ function prepareAgentLaunch(kind, opts = {}) {
7892
7915
  }
7893
7916
  };
7894
7917
  }
7918
+ /** remote-terminal.md R18: a fresh launch never answers the resume code. A setup failure whose session name a
7919
+ * complete listing proved absent, with no dormant record under it, left no seat. */
7920
+ function freshLaunchFailure(error, harness) {
7921
+ if (!(error instanceof AitermError))
7922
+ return error;
7923
+ const resume = "AGENT_RESUME_UNCONFIRMED: ";
7924
+ const cause = error.message.startsWith(resume) ? error.message.slice(resume.length) : error.message;
7925
+ let absent = error.nativeSessionAbsent !== undefined;
7926
+ if (absent)
7927
+ try {
7928
+ assertNoDormantSession(error.nativeSessionAbsent);
7929
+ }
7930
+ catch {
7931
+ absent = false;
7932
+ }
7933
+ if (absent) {
7934
+ error.message = `AGENT_LAUNCH_NOT_STARTED: 新しい端末を作成できませんでした。席は作られていません。${cause}`;
7935
+ error.launchNotStarted = { harness };
7936
+ }
7937
+ else if (cause !== error.message)
7938
+ error.message = `AGENT_LAUNCH_UNCONFIRMED: 新規起動の結果を確認できません。${cause}`;
7939
+ return error;
7940
+ }
7895
7941
  export class AgentLaunchPromptError extends AitermError {
7896
7942
  session_id;
7897
7943
  initial_prompt;
package/dist/errors.js CHANGED
@@ -6,6 +6,10 @@ export class AitermError extends Error {
6
6
  configurationFailure;
7
7
  /** Claudeの選ぶ画面での拒否。selection_excludedは、sを打つ前に断り、閉じた画面を読んだ時だけtrue。 */
8
8
  configureRefusal;
9
+ /** Native setup failed and a complete listing then showed this session name absent (tmux-runtime). */
10
+ nativeSessionAbsent;
11
+ /** remote-terminal.md R18: a fresh launch that left no seat. */
12
+ launchNotStarted;
9
13
  constructor(message, code = 1) {
10
14
  super(message);
11
15
  this.code = code;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  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";
3
+ import { boundTerminalTarget, bindTerminalSession, terminalSeatGroups, ensureSeatForward, extractMcpHeaders, maintainSeatForwards, REMOTE_MINIMUM_VERSION, seatIngressPort, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
4
4
  import { launchEnvValue } from "./private-env.js";
5
5
  import { AuthResponseError, authUiSchema, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
6
6
  import { configurationRequestSchema, configurationToolOutputSchema, applyConfigurationRequest, reconcileConfigurationRequest } from "./configure-request.js";
@@ -18,7 +18,7 @@ import { AitermError, AgentAuthenticationPreflightError, AgentResumeUnavailableE
18
18
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
19
19
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
20
20
  import { readPrivateEnvLine, setPrivateEnv } from "./private-env.js";
21
- import { withTerminalLaunchAction } from "./terminal-launch-error.js";
21
+ import { withTerminalLaunchAction, withErrorCode, launchNotStartedMeta } from "./terminal-launch-error.js";
22
22
  import { CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
23
23
  import { z } from "zod";
24
24
  import { agentModelsResult } from "./model-catalog.js";
@@ -258,6 +258,9 @@ export function createAitermServer(options = {}) {
258
258
  structuredContent: { schema: "aiterm.agent-launch-error.v1", harness: "claude-code", code: e.reasonCode,
259
259
  phase: "authentication_preflight", effect: "not_issued", session_created: false, message: msg },
260
260
  };
261
+ if (e instanceof AitermError && e.launchNotStarted)
262
+ return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
263
+ _meta: launchNotStartedMeta(e.launchNotStarted.harness) };
261
264
  return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true };
262
265
  }
263
266
  /**
@@ -317,14 +320,18 @@ export function createAitermServer(options = {}) {
317
320
  function remoteNote(target, result) {
318
321
  return { type: "text", text: `remote=${remoteLabel(target)} remote_aiterm=${result.remote_version ?? "unknown"}` };
319
322
  }
320
- async function forwardRemote(target, name, args) {
321
- const result = await callRemoteTool(target, name, args);
323
+ /** The remote result as this tool's own: request and result _meta pass unchanged (DESIGN.md 別端末の子). */
324
+ function remoteResult(target, result, structuredContent = result.structuredContent) {
322
325
  return {
323
326
  content: [...result.content, remoteNote(target, result)],
324
- ...(result.structuredContent ? { structuredContent: result.structuredContent } : {}),
327
+ ...(structuredContent ? { structuredContent } : {}),
325
328
  ...(result.isError ? { isError: true } : {}),
329
+ ...(result._meta ? { _meta: result._meta } : {}),
326
330
  };
327
331
  }
332
+ async function forwardRemote(target, name, args, extra) {
333
+ return remoteResult(target, await callRemoteTool(target, name, args, undefined, undefined, extra?._meta));
334
+ }
328
335
  function registerRemoteAwareTool(name, config, handler, remoteHandler = remoteToolHandler(name)) {
329
336
  server.registerTool(name, { ...config, inputSchema: { ...config.inputSchema, remote: remoteInputField } }, async ({ remote, ...args }, extra) => {
330
337
  try {
@@ -335,39 +342,39 @@ export function createAitermServer(options = {}) {
335
342
  const result = await remoteHandler(target, args, extra);
336
343
  if (name === "pty_close" && !remote && !result?.isError)
337
344
  unbindTerminalSession(args.session_id);
338
- return result;
345
+ return remote ? result : withErrorCode(result);
339
346
  }
340
347
  catch (e) {
341
- return fail(e);
348
+ return remote ? fail(e) : withErrorCode(fail(e));
342
349
  }
343
350
  });
344
351
  }
345
352
  /** 配送の登録や事前確保が要るtoolだけ専用の中継にし、他は同じtoolをそのまま現地へ呼ぶ。 */
346
353
  function remoteToolHandler(name) {
347
354
  switch (name) {
348
- case "agent_configure": return async (target, args) => {
355
+ case "agent_configure": return async (target, args, extra) => {
349
356
  // Older remote servers strip unknown input fields and could apply without tracking.
350
357
  if (args.request || args.action === "reconcile")
351
358
  throw new Error("REMOTE_UNSUPPORTED: tracked configuration requires the exact local connection; not issued");
352
- return forwardRemote(target, name, args);
359
+ return forwardRemote(target, name, args, extra);
353
360
  };
354
361
  case "pty_send": return sendRemote;
355
- case "pty_close": return async (target, args) => {
362
+ case "pty_close": return async (target, args, extra) => {
356
363
  await remoteParentDelivery?.beforeChange(deliveryKey(args.session_id, target));
357
- return forwardRemote(target, name, args);
364
+ return forwardRemote(target, name, args, extra);
358
365
  };
359
- case "pty_observe": return async (target, args) => {
360
- const result = await forwardRemote(target, name, args);
366
+ case "pty_observe": return async (target, args, extra) => {
367
+ const result = await forwardRemote(target, name, args, extra);
361
368
  if (!remoteParentDelivery || !result.structuredContent)
362
369
  return result;
363
370
  return { ...result, structuredContent: { ...result.structuredContent, parent_deliveries: remoteParentDelivery.status(deliveryKey(args.session_id, target)) } };
364
371
  };
365
- case "claude_turn": return async (target, args) => {
372
+ case "claude_turn": return async (target, args, extra) => {
366
373
  if (args.action === "issue")
367
374
  throw new core.AitermError("REMOTE_UNSUPPORTED: 別端末のclaude_turn issueには未対応です。pty_sendを使ってください", 2);
368
- return forwardRemote(target, name, args);
375
+ return forwardRemote(target, name, args, extra);
369
376
  };
370
- default: return (target, args) => forwardRemote(target, name, args);
377
+ default: return (target, args, extra) => forwardRemote(target, name, args, extra);
371
378
  }
372
379
  }
373
380
  async function sendRemote(target, args, extra) {
@@ -381,11 +388,10 @@ export function createAitermServer(options = {}) {
381
388
  // 終わった依頼の回答は送る前に保存する。実行中の依頼は残る。現地が差し込みを選べばその依頼が回答を受け取る。
382
389
  if (delivery)
383
390
  await remoteParentDelivery.beforeChange(key);
384
- const result = await callRemoteTool(target, "pty_send", args);
391
+ const result = await callRemoteTool(target, "pty_send", args, undefined, undefined, extra?._meta);
385
392
  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
- }
393
+ if (result.isError || !structured || structured.mode !== "agent_dispatch")
394
+ return remoteResult(target, result);
389
395
  try {
390
396
  // 現地がdispatchを選んだのは子がidleだった時なので、前の依頼はもう保存できる。残っていれば登録しない。
391
397
  if (delivery)
@@ -398,10 +404,8 @@ export function createAitermServer(options = {}) {
398
404
  return fail(new Error(`別端末へのdispatchは済みましたが、回答配送を登録できませんでした: ${e instanceof Error ? e.message : String(e)}`));
399
405
  }
400
406
  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
- };
407
+ const relayed = remoteResult(target, result, { ...structured, wait_process: waited.wait_process, ...(delivery?.result() ? { parent_delivery: delivery.result() } : {}) });
408
+ return { ...relayed, content: [...relayed.content, { type: "text", text: deliveryIdLine(delivery).trim() || "completion=wait_process" }] };
405
409
  }
406
410
  /** 別端末の子の依頼を、この端末の親への配送に登録する。launch_idは現地の完了観測から取る。 */
407
411
  async function registerRemoteDelivery(delivery, target, sessionId, eventCursor, operationId = null, inputId) {
@@ -821,7 +825,7 @@ export function createAitermServer(options = {}) {
821
825
  try {
822
826
  await core.maintainAgentIdleClocks();
823
827
  const result = core.listSessionsResult(env_keys);
824
- return { ...ok(core.listSessions(result)), structuredContent: { ...result }, ...seatTurnsMeta(result.sessions, extra._meta) };
828
+ return { ...ok(core.listSessions(result)), structuredContent: { ...result }, ...await seatTurnsMeta(result.sessions, extra._meta) };
825
829
  }
826
830
  catch (e) {
827
831
  return fail(e);
@@ -829,11 +833,21 @@ export function createAitermServer(options = {}) {
829
833
  });
830
834
  // Declared controller caller markers opt into current-turn metadata (ADR 0122).
831
835
  // 説明と引数には出さない(steer-follow.ts の冒頭)。それ以外の呼び手には何も足さない。
832
- function seatTurnsMeta(sessions, requestMeta) {
836
+ async function seatTurnsMeta(sessions, requestMeta) {
833
837
  if (!interimCallerFromMeta(requestMeta, server.server.getClientVersion()?.name, server.server.getClientCapabilities()))
834
838
  return {};
835
839
  try {
836
- return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: core.readSeatTurns(sessions.filter(session => session.harness !== null).map(session => session.session_id)) } };
840
+ const local = core.readSeatTurns(sessions.filter(session => session.harness !== null).map(session => session.session_id));
841
+ // Terminal seats: the same call relayed with the same _meta; each terminal answers only for its own bound sessions.
842
+ // Inside the caller's 5 s pty_list budget (tool catalog timeout_ms): a slow or unreachable terminal contributes no rows.
843
+ const remote = await Promise.all(terminalSeatGroups().map(({ target, sessions: bound }) => Promise.race([
844
+ callRemoteTool(target, "pty_list", {}, 4_000, undefined, requestMeta).then(result => {
845
+ const seats = result._meta?.[SEAT_TURNS_RESULT_META_KEY]?.seats;
846
+ return Array.isArray(seats) ? seats.filter((seat) => bound.includes(seat?.session_id)) : [];
847
+ }, () => []),
848
+ new Promise(resolve => setTimeout(resolve, 4_000, []).unref()),
849
+ ])));
850
+ return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { ...local, seats: [...local.seats, ...remote.flat()] } } };
837
851
  }
838
852
  catch (e) {
839
853
  return { _meta: { [SEAT_TURNS_RESULT_META_KEY]: { schema: "aiterm.seat-turns.v1", error: e instanceof Error ? e.message : String(e) } } };
@@ -1276,10 +1290,10 @@ export function createAitermServer(options = {}) {
1276
1290
  const session = result?.structuredContent?.session_id;
1277
1291
  if (typeof session === "string")
1278
1292
  bindTerminalSession(session, target.trusted_ref);
1279
- return withTerminalLaunchAction(result);
1293
+ return withErrorCode(withTerminalLaunchAction(result));
1280
1294
  }
1281
1295
  catch (e) {
1282
- return withTerminalLaunchAction(fail(e));
1296
+ return withErrorCode(withTerminalLaunchAction(fail(e)));
1283
1297
  }
1284
1298
  }
1285
1299
  async function launchAgent(kind, args, extra) {
@@ -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. */
@@ -16,7 +16,9 @@ import { parseNativeSessionReceipt, nativePaneTarget, nativeSessionTarget, nativ
16
16
  const nativeTargets = new AsyncLocalStorage();
17
17
  const nativeReads = new Set(["list-sessions", "list-commands", "list-panes", "list-windows", "has-session", "display-message", "capture-pane", "show-environment", "show-options"]);
18
18
  const nativePanes = new Set(["send-keys", "paste-buffer", "pipe-pane", "capture-pane", "display-message", "list-panes", "rename-window", "set-window-option"]);
19
- const nativeTargetUnavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰したnative端末の本人性を確認できません。", 2);
19
+ // Every site names itself: the same refusal text from fifteen places could not be traced (macbook 2026-11-10).
20
+ const nativeTargetUnavailable = (reason) => new AitermError(`AGENT_RESUME_UNCONFIRMED: native端末の本人性を確認できません。native_reason=${reason}`, 2);
21
+ const tmuxFailure = (r) => `rc=${r.code} ${r.stderr.trim().split("\n")[0].slice(0, 160)}`.trim();
20
22
  function verifyNativeTarget(frame) {
21
23
  if (frame.checking)
22
24
  return;
@@ -32,7 +34,7 @@ function verifyNativeTarget(frame) {
32
34
  export function withNativeSessionTarget(target, verify, body, allowExitedPane = false) {
33
35
  const enclosing = nativeTargets.getStore();
34
36
  if (enclosing && JSON.stringify(enclosing.target) !== JSON.stringify(target))
35
- throw nativeTargetUnavailable();
37
+ throw nativeTargetUnavailable("enclosing_target_differs");
36
38
  const frame = { session: target.session_id, target, verify, allowExitedPane };
37
39
  return nativeTargets.run(frame, () => { verifyNativeTarget(frame); return body(); });
38
40
  }
@@ -45,7 +47,7 @@ export function hasVerifiedNativeSessionTarget(name) {
45
47
  }
46
48
  export function withNativeSessionCreation(session, created, verify, body) {
47
49
  if (nativeTargets.getStore())
48
- throw nativeTargetUnavailable();
50
+ throw nativeTargetUnavailable("nested_creation");
49
51
  return nativeTargets.run({ session, target: null, created, verify }, body);
50
52
  }
51
53
  const CREATION_TOKEN_OPTION = "@aiterm_create_token";
@@ -62,43 +64,61 @@ export function withNativeSessionSetupRollback(shell, body) {
62
64
  return body();
63
65
  }
64
66
  catch (error) {
65
- if (setup.target) {
66
- try {
67
- const closed = creationCommand(setup, ["kill-session", "-t", setup.target.session_id], true);
68
- // An already absent native is a finished rollback: the created callback may have closed it.
69
- if (closed.code !== 0 && creationCommand(setup, ["has-session", "-t", setup.target.session_id]).code === 0)
70
- throw nativeTargetUnavailable();
71
- }
72
- catch {
73
- if (error instanceof Error)
74
- error.message += "\ncreation_rollback_unconfirmed: 作成した端末の片付けを確認できません。";
75
- }
67
+ const created = setup.target, name = created?.session_id ?? frame.session;
68
+ let rows = null;
69
+ try {
70
+ if (created)
71
+ creationCommand(setup, ["kill-session", "-t", created.session_id], true);
72
+ rows = nativeSessionRows();
73
+ }
74
+ catch { /* an unavailable listing proves nothing */ }
75
+ // Only a complete listing proves absence; an already absent native (the created callback may have closed it) is a finished rollback.
76
+ if (rows && name !== null && !rows.some(row => row[1] === name)) {
77
+ if (error instanceof AitermError)
78
+ error.nativeSessionAbsent = name;
76
79
  }
80
+ else if (created && (!rows || rows.some(row => row[0] === created.native_id)) && error instanceof Error)
81
+ error.message += "\ncreation_rollback_unconfirmed: 作成した端末の片付けを確認できません。";
77
82
  throw error;
78
83
  }
79
84
  finally {
80
85
  delete frame.setup;
81
86
  }
82
87
  }
88
+ /** [native id, name] of every session, or null when the listing is unavailable. Reads absence as core.listNativeSessionsResult does. */
89
+ function nativeSessionRows() {
90
+ // Outside the creation frame: its verify would throw on the non-zero exit that proves the server is gone.
91
+ const list = () => nativeTargets.exit(() => runTmux(false, undefined, ["list-sessions", "-F", "#{session_id}\t#{session_name}"]));
92
+ let listed = list();
93
+ // A server that just lost its last session answers this for a moment before "no server running" (macOS, 2026-10-23).
94
+ for (const deadline = performance.now() + 500; listed.code !== 0 && /server exited unexpectedly/i.test(listed.stderr) && performance.now() < deadline;) {
95
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
96
+ listed = list();
97
+ }
98
+ if (listed.code === 0)
99
+ return listed.stdout.split(/\r?\n/).filter(Boolean).map(row => row.split(/[\t ]/));
100
+ return /no server running|No such file or directory/i.test(listed.stderr) ? [] : null;
101
+ }
83
102
  // This scope is private to marker transfer and rollback; ordinary effects still require OS birth identity.
84
103
  function creationCommand(setup, args, allowRefusal = false) {
85
104
  const target = setup.target;
86
105
  const creationCondition = `#{||:#{==:#{window_name},${setup.window}},#{==:#{${CREATION_TOKEN_OPTION}},${setup.token}}}`;
87
106
  return nativeTargets.run({ session: target.session_id, target, verify: () => { }, creationCondition, allowRefusal }, () => runTmux(false, undefined, args));
88
107
  }
89
- function captureNativeSessionReceipt(receipt) {
108
+ const receiptUnparsed = (r) => `receipt_unparsed(stdout_bytes=${Buffer.byteLength(r.stdout)}; ${tmuxFailure(r)})`;
109
+ function captureNativeSessionReceipt(created) {
90
110
  const frame = nativeTargets.getStore();
91
111
  if (!frame?.created || frame.target)
92
- throw nativeTargetUnavailable();
112
+ throw nativeTargetUnavailable("receipt_not_expected");
93
113
  let target;
94
114
  try {
95
- target = parseNativeSessionReceipt(receipt);
115
+ target = parseNativeSessionReceipt(created.stdout);
96
116
  }
97
117
  catch {
98
- throw nativeTargetUnavailable();
118
+ throw nativeTargetUnavailable(receiptUnparsed(created));
99
119
  }
100
120
  if (frame.session !== null && target.session_id !== frame.session)
101
- throw nativeTargetUnavailable();
121
+ throw nativeTargetUnavailable("receipt_name_differs");
102
122
  frame.session = target.session_id;
103
123
  frame.target = target;
104
124
  if (frame.setup) {
@@ -109,14 +129,16 @@ function captureNativeSessionReceipt(receipt) {
109
129
  if (isWin) {
110
130
  const inherited = creationCommand(setup, ["show-options", "-t", target.session_id, "-v", "automatic-rename"]);
111
131
  if (inherited.code !== 0 || !["on", "off"].includes(inherited.stdout.trim()))
112
- throw nativeTargetUnavailable();
132
+ throw nativeTargetUnavailable(`automatic_rename_unread(${tmuxFailure(inherited)})`);
113
133
  commands.push(["set-window-option", "-t", target.session_id, "automatic-rename", inherited.stdout.trim()]);
114
134
  }
115
135
  else
116
136
  commands.push(["set-window-option", "-t", target.session_id, "-u", "automatic-rename"]);
117
- for (const command of commands)
118
- if (creationCommand(setup, command).code !== 0)
119
- throw nativeTargetUnavailable();
137
+ for (const command of commands) {
138
+ const result = creationCommand(setup, command);
139
+ if (result.code !== 0)
140
+ throw nativeTargetUnavailable(`creation_command_failed(${command[0]}; ${tmuxFailure(result)})`);
141
+ }
120
142
  }
121
143
  frame.created({ ...frame.target });
122
144
  verifyNativeTarget(frame);
@@ -137,7 +159,7 @@ function nativeSessionArgs(input) {
137
159
  if (command === "new-session") {
138
160
  const named = args.findIndex((value, index) => index > start && index < end && value === "-s");
139
161
  if (frame.target || !frame.created || named < 0 || frame.session !== null && args[named + 1] !== frame.session)
140
- throw nativeTargetUnavailable();
162
+ throw nativeTargetUnavailable("new_session_not_admitted");
141
163
  }
142
164
  const at = args.findIndex((value, index) => index > start && index < end && value === "-t");
143
165
  if (at >= 0) {
@@ -150,7 +172,7 @@ function nativeSessionArgs(input) {
150
172
  const own = named?.[1] === frame.session || raw === frame.target?.native_id || raw === frame.target?.pane_id
151
173
  || frame.target !== null && raw === nativePaneTarget(frame.target);
152
174
  if (!own || (!frame.target && !nativeReads.has(command)))
153
- throw nativeTargetUnavailable();
175
+ throw nativeTargetUnavailable(`target_not_owned(${command})`);
154
176
  args[at + 1] = frame.target ? (nativePanes.has(command) ? nativePaneTarget(frame.target) : nativeSessionTarget(frame.target)) : `=${frame.session}`;
155
177
  }
156
178
  start = end + 1;
@@ -159,7 +181,7 @@ function nativeSessionArgs(input) {
159
181
  if (frame.target)
160
182
  verifyNativeTarget(frame);
161
183
  else if (!args.includes("new-session") && !(args.length === 3 && args[0] === "set-option" && args[1] === "-gu" && args[2] === "update-environment"))
162
- throw nativeTargetUnavailable();
184
+ throw nativeTargetUnavailable(`effect_before_creation(${args[0]})`);
163
185
  }
164
186
  return args;
165
187
  }
@@ -489,7 +511,7 @@ function runTmux(observe, input, args, session, deadline) {
489
511
  }
490
512
  const native = nativeTargets.getStore();
491
513
  if (native?.target && !native.allowRefusal && args[0] === "if-shell" && (r.stdout ?? "").trim() === NATIVE_REFUSED)
492
- throw nativeTargetUnavailable();
514
+ throw nativeTargetUnavailable("native_condition_refused");
493
515
  if (native?.target && r.status !== 0)
494
516
  verifyNativeTarget(native);
495
517
  return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
@@ -620,7 +642,7 @@ export function sendPsmuxPayload(observe, sessionName, text, bracketedPaste) {
620
642
  beforeExecutionEffect(sessionName);
621
643
  const frame = nativeTargets.getStore();
622
644
  if (frame && (!frame.target || frame.session !== sessionName))
623
- throw nativeTargetUnavailable();
645
+ throw nativeTargetUnavailable("send_target_differs");
624
646
  if (frame)
625
647
  verifyNativeTarget(frame);
626
648
  const target = frame?.target;
@@ -668,7 +690,9 @@ export function pasteBufferBaseArgs() {
668
690
  export const TMUX_EMPTY_CONFIG = isWin ? "NUL" : "/dev/null";
669
691
  // A single POSIX command goes through the account's possibly non-login default-shell.
670
692
  export function paneCommandArgs(shell) {
671
- return isWin ? [shell] : ["/bin/sh", "-c", shell];
693
+ // A plain command name is exec'd so the pane's foreground is the requested shell: dash forks a lone -c command,
694
+ // and pane_current_command would then read "sh" (macOS /bin/sh already execs it).
695
+ return isWin ? [shell] : ["/bin/sh", "-c", /^[A-Za-z0-9_./+-]+$/u.test(shell) ? `exec ${shell}` : shell];
672
696
  }
673
697
  // tmux 3.2 で new-session -e と、update-environment のワイルドカードが入った。
674
698
  function tmuxHasSessionEnvironmentFlags(version) {
@@ -761,16 +785,17 @@ export function tmuxNewSession(observe, name, launch, registered = []) {
761
785
  const result = runTmux(observe, undefined, ["new-session", "-d", "-s", name, ...printNative, ...launch.args, "-f", TMUX_EMPTY_CONFIG, launch.shell]);
762
786
  if (result.code === 0) {
763
787
  if (pinned) {
788
+ let receipt;
764
789
  try {
765
- const receipt = parseNativeSessionReceipt(result.stdout);
766
- if (receipt.session_id !== name)
767
- throw nativeTargetUnavailable();
768
- if (witness)
769
- witness.target = receipt;
790
+ receipt = parseNativeSessionReceipt(result.stdout);
770
791
  }
771
792
  catch {
772
- throw nativeTargetUnavailable();
793
+ throw nativeTargetUnavailable(receiptUnparsed(result));
773
794
  }
795
+ if (receipt.session_id !== name)
796
+ throw nativeTargetUnavailable("receipt_name_differs");
797
+ if (witness)
798
+ witness.target = receipt;
774
799
  }
775
800
  // Existing psmux 3.3.8 registry protection must run before identity reads can trigger registry reaping.
776
801
  openPsmuxServerToDesktop(name);
@@ -778,7 +803,7 @@ export function tmuxNewSession(observe, name, launch, registered = []) {
778
803
  if (guarded && (result.code === 0 || result.stdout))
779
804
  captureExecutionCreatedNative(result.stdout);
780
805
  if (pinned && (result.code === 0 || result.stdout))
781
- captureNativeSessionReceipt(result.stdout);
806
+ captureNativeSessionReceipt(result);
782
807
  return result;
783
808
  }
784
809
  const env = sessionCallerEnvironment();
@@ -809,7 +834,7 @@ export function tmuxNewSession(observe, name, launch, registered = []) {
809
834
  if (guarded && (r.code === 0 || r.stdout))
810
835
  captureExecutionCreatedNative(r.stdout);
811
836
  if (pinned && (r.code === 0 || r.stdout))
812
- captureNativeSessionReceipt(r.stdout);
837
+ captureNativeSessionReceipt(r);
813
838
  if (r.code !== 0) {
814
839
  // 途中の命令が失敗すると、後続の命令は実行されない。差し替えた設定を戻す。
815
840
  runTmux(false, undefined, ["set-option", "-gu", "update-environment"]);
package/docs/DESIGN.md CHANGED
@@ -169,7 +169,7 @@ Claude Codeの入力待ちは、起動時の見出しが取得範囲から流れ
169
169
 
170
170
  ## Agent model
171
171
 
172
- POSIXのpane作成は要求したshellを直接実行するargvを渡し、サービス用アカウントのログイン不可shellへ仲介させない(ADR 0136)。WindowsのPowerShell/psmux経路は従来どおり。
172
+ POSIXのpane作成は要求したshellを直接実行するargvを渡し、サービス用アカウントのログイン不可shellへ仲介させない(ADR 0136)。単語だけのshell名は`/bin/sh -c 'exec <shell>'`で置き換え、paneの前面を要求したshellにする(dashは単独の-c命令をforkし、前面が`sh`に見える)。POSIXのPowerShellは行編集の開始前に打たれた文を壊すので、`pty_open`は最初のpromptで行頭からcursorが動くまで最大10秒待つ。WindowsのPowerShell/psmux経路は従来どおり。
173
173
 
174
174
  AntigravityのTUI+公式hook、発話位置とexecutionNumによる完了相関は[ADR 0135](https://github.com/kitepon/aiterm-mcp/blob/main/docs/adr/0135-antigravity-native-harness.md)を正とする。
175
175
 
@@ -386,6 +386,7 @@ PowerShellは`$PSHOME`を展開し、POSIX系はどちらも展開しない。PO
386
386
  `env`のPATHだけを受け取り、処理は`/bin/sh`で行う。profileの出力やfish等の文法差をMCPのstdoutへ持ち込まない。
387
387
  WindowsはユーザーのPATHで`aiterm-mcp`と`aiterm-wait`をそのまま呼ぶ。起動、hook、transcript、multiplexerは現地のAitermが所有し、
388
388
  呼び出し側は結果を返すだけにする。現地にポートは開けない。
389
+ MCP要求の`_meta`は現地へ不透明なまま渡し、現地resultの`_meta`も変更せず返す。親配送などのローカル投影を加える時も、現地metadataを保持する。
389
390
 
390
391
  接続先はtool引数で毎回受け取り、Aitermは一覧も既定値も持たない(オーナー裁定 2026-09-26。管理まで持つと重くなるため)。
391
392
  配送記録には、パスフレーズ本文を除いた接続情報だけを残す。平文のパスフレーズはMCP processのメモリにだけ置き、
package/docs/RELEASE.md CHANGED
@@ -5,14 +5,16 @@ Aitermのreleaseはこのrepositoryが所有する。`.github/workflows/product-
5
5
 
6
6
  ## CIの範囲
7
7
 
8
- - push/pull request: 共通実装・CI自身・未分類の変更は`macos-native`、`linux-workstation`、`windows-native`を選ぶ。
8
+ - push/pull request: 共通実装・CI自身・未分類の変更は`macos-hosted`、`linux-workstation`、`windows-native`を選ぶ。
9
9
  Windows固有ファイル(`src/windows-powershell.ts`、`src/psmux-send-worker.ts`、`test/windows-*.test.mjs`)だけの変更は
10
10
  LinuxとWindowsを選ぶ。共通変更が混ざっても対象OSを落とさない。試験は依存graphから選び、依存を確定できない変更だけ全テストへ広げる。
11
11
  - 版番号だけの変更はJSONの実差分で識別し、Linuxでbuildと配布metadata・pack・文書確認を行う。依存や実行設定の変更は省略しない。
12
12
  文書だけなら文書検査、実装と文書の混在なら関連試験と文書検査を行う。
13
13
  - 手動実行の`test_files`へ既存試験fileのJSON配列を渡すと、指定OSでその試験だけを実行する。空欄は従来の全試験。
14
14
  選択実行のjob名は`selected`で、同headの全試験成功の再利用対象にしない。
15
+ - `macos-hosted`は公開repositoryで利用できるGitHub-hosted `macos-latest` runnerを使う。AitermのCI/buildはOwnerのMacでは実行しない。`linux-workstation`と`windows-native`はfactory runnerを使う。
15
16
  - 週1回の定期実行(月曜 03:00 JST)と`test_files`未指定の手動実行は、指定された環境で全テストを回す。定期実行の対象は3環境である。
17
+ - macOS terminal runtimeのrelease buildもGitHub-hosted `macos-latest` runnerで行う。
16
18
  - pushは、同じcommitの全テスト(手動実行か定期実行)がもう通っている環境を流さない。枝で手動実行を通してからmainへ早送りすると、
17
19
  mainのpushは変更分類と関門だけで終わる。通っている環境が一部の時は、残りの環境だけを流す。GitHubへ聞けない時は、選んだ環境を全部流す。
18
20
  同じcommitのpush・pull requestの成功は、試験を絞っている事があるので数えない(ADR 0115)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.70.4",
3
+ "version": "0.70.5",
4
4
  "mcpName": "io.github.kitepon/aiterm-mcp",
5
5
  "description": "Persistent terminal MCP with one harness-based launcher for Claude Code, Codex CLI, Grok CLI, Cursor Agent CLI, and Antigravity CLI, plus durable PTYs for SSH, containers, and REPLs.",
6
6
  "keywords": [