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/CHANGELOG.md CHANGED
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.70.6] - 2026-11-10
11
+
12
+ - `agent_launch` takes `fork_from: {session_id, fork_id?}` (claude-code, codex-cli). It starts a disposable fork of that seat's latest saved conversation, in the main's cwd and on the main's account, with the main's tools and MCP servers. Every write inside that cwd (the project folder) is refused below the tools for the whole CLI process tree. That covers file tools, shell redirects, git, sqlite and anything else. Everything outside the folder stays writable, and reads, commands, network and MCP are untouched. Linux uses Landlock (unprivileged; works in standard Docker, where bwrap-based sandboxes do not; needs python3). macOS uses `sandbox-exec`. Windows, and any machine where the ban cannot be proven before launch, answers `READONLY_UNENFORCEABLE`, and no seat is created. Claude forks with `--resume <main> --fork-session` under the seat's own session ID. The tools array equals the main's, and the first fork request read about 99% of the main's prompt cache. Codex forks with `codex fork <main>` and is bound by the rollout's `forked_from_id` plus the first input. The receipt adds `fork_of {session_id, vendor_session_id, write_ban {path, method}}`. The seat environment adds `THROUGHLINE_SESSION_KIND=fork`, `THROUGHLINE_PARENT_SESSION_ID` and `THROUGHLINE_FORK_ID`. A resumed fork keeps the ban. Remote and terminal forks need this release on the terminal (`REMOTE_AITERM_TOO_OLD` otherwise) and go through the terminal's `agent_launch`. Refusals: `FORK_INVALID`, `FORK_SOURCE_UNAVAILABLE`, `FORK_UNSUPPORTED`. ADR 0140.
13
+ - Windows: input sent while a command runs, or before a pane's first prompt, is typed in the dialect of the shell whose prompt the pane last showed (at first, the shell it was opened with), not in the dialect of psmux's foreground name. That name can be stale (`pwsh` for a Git Bash pane), and bash then read a PowerShell scriptblock (`syntax error near unexpected token [scriptblock]::Create`).
14
+
15
+ ## [0.70.5] - 2026-11-10
16
+
17
+ - 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.
18
+ - 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.
19
+ - A launch refused because a live session already has the name answers `SESSION_EXISTS: session '<name>' は既に存在します…`.
20
+ - 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.
21
+ - 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.
22
+ - `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.
23
+ - `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).
24
+ - 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.
25
+
10
26
  ## [0.70.4] - 2026-11-10
11
27
 
12
28
  - `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 +3194,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3178
3194
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3179
3195
  provenance.
3180
3196
 
3181
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.4...HEAD
3197
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.6...HEAD
3198
+ [0.70.6]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.5...v0.70.6
3199
+ [0.70.5]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.4...v0.70.5
3182
3200
  [0.70.4]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.3...v0.70.4
3183
3201
  [0.70.3]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.2...v0.70.3
3184
3202
  [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.6** · 動作対象は 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.6** · 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
 
@@ -49,6 +49,19 @@ function loadAgentLineageFields(m, required) {
49
49
  delegationAllowed: true,
50
50
  });
51
51
  }
52
+ /** A fork seat's source (ADR 0140). Malformed is refused: dropping it would resume the fork writable. */
53
+ function forkOfField(v) {
54
+ if (v === undefined)
55
+ return {};
56
+ if (!v || typeof v.session_id !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(v.session_id)
57
+ || typeof v.vendor_session_id !== "string" || !UUID_RE.test(v.vendor_session_id)
58
+ || (v.fork_id !== undefined && typeof v.fork_id !== "string") || (v.first_input !== undefined && typeof v.first_input !== "string")
59
+ || !v.write_ban || typeof v.write_ban.path !== "string" || !path.isAbsolute(v.write_ban.path)
60
+ || (v.write_ban.method !== "landlock" && v.write_ban.method !== "seatbelt"))
61
+ throw new AitermError("agent metadata fork_of が不正です", 2);
62
+ return { fork_of: { session_id: v.session_id, vendor_session_id: v.vendor_session_id, ...(v.fork_id === undefined ? {} : { fork_id: v.fork_id }),
63
+ write_ban: { path: v.write_ban.path, method: v.write_ban.method }, ...(v.first_input === undefined ? {} : { first_input: v.first_input }) } };
64
+ }
52
65
  export function loadAgentMetadata(name) {
53
66
  assertSessionName(name);
54
67
  const dir = agentsDir();
@@ -146,6 +159,7 @@ export function loadAgentMetadata(name) {
146
159
  created_at: typeof m.created_at === "string" ? m.created_at : "",
147
160
  cwd: typeof m.cwd === "string" ? m.cwd : null,
148
161
  ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
162
+ ...forkOfField(m.fork_of),
149
163
  vendor_session_id: m.vendor_session_id,
150
164
  initial_prompt: normalizeInitialPromptState(m.initial_prompt),
151
165
  ...deliveryFields,
@@ -183,6 +197,7 @@ export function loadAgentMetadata(name) {
183
197
  created_at: typeof m.created_at === "string" ? m.created_at : "",
184
198
  cwd: typeof m.cwd === "string" ? m.cwd : null,
185
199
  ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
200
+ ...forkOfField(m.fork_of),
186
201
  vendor_session_id: typeof m.vendor_session_id === "string" ? m.vendor_session_id : null,
187
202
  initial_prompt: normalizeInitialPromptState(m.initial_prompt),
188
203
  ...deliveryFields,
package/dist/core.js CHANGED
@@ -53,8 +53,9 @@ import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
53
53
  import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
54
54
  import { liveNodeExecutable } from "./live-node.js";
55
55
  import { resolveClaudeConfigurationRoot, withClaudeConfigRoot } from "./claude-config-root.js";
56
+ import { probeWriteBan, writeBanPrefix } from "./write-ban.js";
56
57
  import { AitermError, AgentResumeUnavailableError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
57
- import { isWin, SOCKDIR, SOCK, tmuxCommand, readOnlyTmuxList, PtyDiagnosticError, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, withNativeSessionSetupRollback, hasNativeSessionSetupRollback, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, } from "./tmux-runtime.js";
58
+ import { isWin, SOCKDIR, SOCK, tmuxCommand, readOnlyTmuxList, PtyDiagnosticError, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, withNativeSessionSetupRollback, hasNativeSessionSetupRollback, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, rememberPaneShell, } from "./tmux-runtime.js";
58
59
  import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, createEmpty0600, shq, LAUNCH_ID_RE, AGENT_LINEAGE_RE, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, publishAgentGeneration, agentMetadataPath, writeAgentMetadata, AGENT_EVENT_TAIL_BYTES, agentLabel, agentHarness, subagentInstruction, } from "./agent-shared.js";
59
60
  import { AuthResponseError, authUi, authPromptDigest, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
60
61
  import { processStartIdentity } from "./runtime-error-os.js";
@@ -64,10 +65,10 @@ import { FastModeError, fastModeFailure } from "./fast-mode.js";
64
65
  import { readFileOrNull, restoreJsonSetting, withUserConfigLock, restoreUserDefaults, keepingUserDefaults, USER_DEFAULT_SETTLE_MS } from "./user-config.js";
65
66
  import { isDeepStrictEqual } from "node:util";
66
67
  import { grokAuthPlan, grokAuthStatus, grokAuthPane, GROK_MODEL_DEFAULTS, realGrokHome, resolveAndValidateGrokAuth, assertGrokModelAvailable, grokModelChoices, grokModelFromFooter, grokFooterModelName, grokModelDefaultsFromBody, restoreGrokModelDefaults, grokEventsTranscript, grokSessionDirectory, latestGrokCompletion, grokTurnSettled, observeGrokDone, buildGrokAgentCmd, grokAgentArgv, grokLaunchNote, grokEnvTokens, grokEnvEntries, grokTuiReady, grokPaneObservation, GROK_INTERRUPT_KEY, grokRateLimitDialog, grokPromptAwaitingAccept, grokUnacceptedPromptRestored, grokStartupAction, grokFooterHasConfiguration, grokTranscriptText, createGrokAgentMetadata, } from "./harnesses/grok.js";
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
+ import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, codexWorkingResumeConfiguration, captureCodexRecoveryProof, captureCodexResumeProof, readCodexResumeProof, codexResumeProofDigest, codexRootTranscript, codexRolloutSessionId, 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
69
  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
70
  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";
71
+ import { interimFromNow, interimFromToken, readInterimWords, recordInterimBoundary } from "./interim-words.js";
71
72
  import { codexSeatTurn, grokSteerAcceptance, observeSteerDone, readSteerEntry, recordSteer } from "./steer-follow.js";
72
73
  import { resolveAgentBin, resolveThroughlineBin, runThroughlineHandoffContext, isWindowsNativeExecutable, isUsableAgentExecutableFile, agentBinForPaneShell, resolveWinPaneShell, windowsAgentArgv, windowsAgentLaunchLine } from "./agent-resolver.js";
73
74
  export { AitermError } from "./errors.js";
@@ -689,7 +690,7 @@ function openSessionInternal(name, shell, envVars, preserveAgentState) {
689
690
  throw new AitermError("openSession: 自動採番のリトライ上限(tmux new-session が重複以外で失敗し続けている可能性)", 2);
690
691
  if (sessionExists(nm)) {
691
692
  if (explicit)
692
- throw new AitermError(`session '${nm}' は既に存在します(list で確認)`, 2);
693
+ throw new AitermError(`SESSION_EXISTS: session '${nm}' は既に存在します(list で確認)`, 2);
693
694
  }
694
695
  else {
695
696
  const environment = [...banner, ...envVars.filter(key => key !== "AITERM_SESSION_ID" && launchEnvValue(key) !== undefined)
@@ -766,6 +767,16 @@ function openSessionInternal(name, shell, envVars, preserveAgentState) {
766
767
  catch (error) {
767
768
  ownTelemetryFailure("AITERM.PERSISTENCE_WRITE_FAILED", error);
768
769
  }
770
+ // PowerShell on POSIX garbles input typed before its line editor starts (bash keeps it as a line). Wait, bounded,
771
+ // until a prompt leaves the cursor off column 0; a pane that never shows one is returned as before.
772
+ if (process.platform !== "win32" && /^pwsh(?:-preview)?$/u.test(path.basename(shell))) {
773
+ for (const deadline = Date.now() + 10_000; Date.now() < deadline; pauseSync(100)) {
774
+ const cursor = tmux("display-message", "-p", "-t", nm, "#{cursor_x}");
775
+ if (cursor.code !== 0 || Number(cursor.stdout.trim()) > 0)
776
+ break;
777
+ }
778
+ }
779
+ rememberPaneShell(nm, shell);
769
780
  return [nm, attachHint(nm)];
770
781
  });
771
782
  }
@@ -3796,6 +3807,17 @@ function managedSeatTerminal(meta) {
3796
3807
  return null;
3797
3808
  }
3798
3809
  }
3810
+ /** Where a later self-started turn's words begin. Cursor rewrites its tail at turn start and Antigravity has no word reader: null. */
3811
+ function managedSpanStart(meta) {
3812
+ if (meta.kind !== "claude" && meta.kind !== "grok")
3813
+ return null;
3814
+ try {
3815
+ return interimFromToken(interimFromNow(meta, agentCompletionCursor(meta)));
3816
+ }
3817
+ catch {
3818
+ return null;
3819
+ }
3820
+ }
3799
3821
  function readManagedSeatTurn(meta) {
3800
3822
  const started = performance.now();
3801
3823
  const result = withManagedSpan(meta, file => {
@@ -3825,7 +3847,7 @@ function readManagedSeatTurn(meta) {
3825
3847
  || performance.now() - started >= 15_000)
3826
3848
  return null;
3827
3849
  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());
3850
+ return observeManagedSpan(file, binding, evidence, terminal, new Date().toISOString(), () => managedSpanStart(meta));
3829
3851
  });
3830
3852
  return performance.now() - started < 15_000 ? result : null;
3831
3853
  }
@@ -6860,6 +6882,9 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
6860
6882
  next.codex_home = recipe.configuration_root;
6861
6883
  if (previous.write_scope !== undefined)
6862
6884
  next.write_scope = previous.write_scope;
6885
+ // A resumed fork stays read-only (ADR 0140): argv and env derive from fork_of.
6886
+ if (previous.fork_of)
6887
+ next.fork_of = previous.fork_of;
6863
6888
  writeAgentMetadata(next);
6864
6889
  initializeAgentActivity(next);
6865
6890
  writeAgentResumeRecipe(next, { ...recipe, launch_id: next.launch_id });
@@ -6883,8 +6908,9 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
6883
6908
  if (registerSessionEnvironment(true, name, [...(registeredSessionEnvironment(name) ?? []), ...Object.keys(recipe.environment)]).code !== 0)
6884
6909
  throw uncertain();
6885
6910
  phase = "vendor_start";
6886
- const argv = next.kind === "claude" ? claudeResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next)
6887
- : codexResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next, recipe.cwd);
6911
+ const argv = [...(next.fork_of ? writeBanPrefix(next.fork_of.write_ban) : []),
6912
+ ...(next.kind === "claude" ? claudeResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next)
6913
+ : codexResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next, recipe.cwd))];
6888
6914
  const full = isWin ? windowsAgentLaunchLine(recipe.cwd, environment, windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), { file: agentMetadataPath(name, next.launch_id) + ".launch-exited", launch_id: next.launch_id })
6889
6915
  : `cd ${shq(recipe.cwd)} && /usr/bin/env ${environment.filter(([, value]) => value === null).map(([key]) => `-u ${shq(key)}`).join(" ")} `
6890
6916
  + `${environment.filter(([, value]) => value !== null).map(([key, value]) => shq(`${key}=${value}`)).join(" ")} ${argv.map(shq).join(" ")}`;
@@ -7502,6 +7528,9 @@ function agentEnvEntries(meta, sid, envVars = []) {
7502
7528
  ["AITERM_AGENT_LINEAGE", meta.lineage ?? `host-root>${meta.kind}:${sid}`],
7503
7529
  ["AITERM_AGENT_DELEGATION_ALLOWED", meta.delegation_allowed === true ? "true" : "false"],
7504
7530
  ["AITERM_STATE_BASE", runtimeStateBase()],
7531
+ // Fork marker for transcript readers (ADR 0140): set before the CLI starts, so every hook inherits it.
7532
+ ...(meta.fork_of ? [["THROUGHLINE_SESSION_KIND", "fork"], ["THROUGHLINE_PARENT_SESSION_ID", meta.fork_of.vendor_session_id],
7533
+ ["THROUGHLINE_FORK_ID", meta.fork_of.fork_id ?? sid]] : []),
7505
7534
  ];
7506
7535
  }
7507
7536
  /** POSIX shellの起動行に前置する環境変数。Grokは自分の認証の正本と自動更新停止の値を、共通の一覧の前に置く。 */
@@ -7757,6 +7786,8 @@ function prepareAgentLaunch(kind, opts = {}) {
7757
7786
  meta.agent_executable = bin;
7758
7787
  if (meta.kind === "claude")
7759
7788
  writeClaudeCallerFiles(meta, opts.append_system_prompt ?? null, opts.mcp_config ?? null);
7789
+ if (opts.fork_of)
7790
+ meta.fork_of = opts.fork_of;
7760
7791
  if (isWin && ["claude", "codex", "grok", "antigravity"].includes(kind))
7761
7792
  meta.windows_launch_exit_tracked = true;
7762
7793
  if (kind === "claude" || kind === "codex")
@@ -7801,7 +7832,8 @@ function prepareAgentLaunch(kind, opts = {}) {
7801
7832
  ], windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), meta?.windows_launch_exit_tracked ? { file: agentMetadataPath(sid, meta.launch_id) + ".launch-exited", launch_id: meta.launch_id } : undefined);
7802
7833
  }
7803
7834
  else {
7804
- const cmd = buildAgentCmd(kind, binForCmd, model, effort, opts.prompt ?? null, meta, cursorFast);
7835
+ const cmd = (meta?.fork_of ? writeBanPrefix(meta.fork_of.write_ban).map(shq).join(" ") + " " : "")
7836
+ + buildAgentCmd(kind, binForCmd, model, effort, opts.prompt ?? null, meta, cursorFast);
7805
7837
  const envPrefix = (!claudeRoot ? "" : claudeRoot.selector === null ? "unset CLAUDE_CONFIG_DIR && "
7806
7838
  : `CLAUDE_CONFIG_DIR=${shq(claudeRoot.selector)} `) + launchEnvSource(sid, agentEnvEntries(null, sid, envVars)) + agentEnvPrefix(meta, sid);
7807
7839
  const command = cwdForCmd ? `cd ${shq(cwdForCmd)} && ${envPrefix}${cmd}` : `${envPrefix}${cmd}`;
@@ -7884,6 +7916,9 @@ function prepareAgentLaunch(kind, opts = {}) {
7884
7916
  verifyCreatedNative(initialNative);
7885
7917
  }, create);
7886
7918
  }
7919
+ catch (error) {
7920
+ throw freshLaunchFailure(error, agentHarness(kind));
7921
+ }
7887
7922
  finally {
7888
7923
  if (initialAdmission) {
7889
7924
  const { name } = initialAdmission;
@@ -7892,6 +7927,29 @@ function prepareAgentLaunch(kind, opts = {}) {
7892
7927
  }
7893
7928
  };
7894
7929
  }
7930
+ /** remote-terminal.md R18: a fresh launch never answers the resume code. A setup failure whose session name a
7931
+ * complete listing proved absent, with no dormant record under it, left no seat. */
7932
+ function freshLaunchFailure(error, harness) {
7933
+ if (!(error instanceof AitermError))
7934
+ return error;
7935
+ const resume = "AGENT_RESUME_UNCONFIRMED: ";
7936
+ const cause = error.message.startsWith(resume) ? error.message.slice(resume.length) : error.message;
7937
+ let absent = error.nativeSessionAbsent !== undefined;
7938
+ if (absent)
7939
+ try {
7940
+ assertNoDormantSession(error.nativeSessionAbsent);
7941
+ }
7942
+ catch {
7943
+ absent = false;
7944
+ }
7945
+ if (absent) {
7946
+ error.message = `AGENT_LAUNCH_NOT_STARTED: 新しい端末を作成できませんでした。席は作られていません。${cause}`;
7947
+ error.launchNotStarted = { harness };
7948
+ }
7949
+ else if (cause !== error.message)
7950
+ error.message = `AGENT_LAUNCH_UNCONFIRMED: 新規起動の結果を確認できません。${cause}`;
7951
+ return error;
7952
+ }
7895
7953
  export class AgentLaunchPromptError extends AitermError {
7896
7954
  session_id;
7897
7955
  initial_prompt;
@@ -7905,10 +7963,64 @@ export class AgentLaunchPromptError extends AitermError {
7905
7963
  this.startup = startup;
7906
7964
  }
7907
7965
  }
7966
+ /** Whitespace-free head of a fork's first input; binds a forked Codex rollout, which has no launch marker (ADR 0140). */
7967
+ export function forkInputKey(text) {
7968
+ return (text ?? "").replace(/\s+/gu, "").slice(0, 2000);
7969
+ }
7970
+ /**
7971
+ * Source of a fork (ADR 0140): the main seat's saved conversation, cwd and (Claude) configuration root, plus the
7972
+ * project write-ban proven on this machine. Refusals name what they protect: a fork must never start able to write
7973
+ * the project, and never on another account or conversation.
7974
+ */
7975
+ export function resolveForkSource(kind, from, opts, probe = probeWriteBan) {
7976
+ if (kind !== "claude" && kind !== "codex")
7977
+ throw new AitermError("FORK_UNSUPPORTED: fork_from is available for claude-code and codex-cli (ADR 0140)", 2);
7978
+ if (!opts.prompt?.trim())
7979
+ throw new AitermError("FORK_INVALID: fork_from requires a prompt (the fork's first input)", 2);
7980
+ if (opts.write_scope !== undefined || opts.require_existing_resume || opts.throughline_source_session != null || opts.launch_operation_id != null
7981
+ || opts.configuration_root != null)
7982
+ throw new AitermError("FORK_INVALID: fork_from cannot be combined with write_scope, require_existing_resume, throughline_source_session, launch_operation_id or configuration_root", 2);
7983
+ if (opts.session_name && tryLoadAgentMetadata(opts.session_name))
7984
+ throw new AitermError(`FORK_INVALID: session_name ${opts.session_name} already names a seat`, 2);
7985
+ assertSessionName(from.session_id);
7986
+ const unavailable = (why) => new AitermError(`FORK_SOURCE_UNAVAILABLE: ${from.session_id}: ${why}`, 2);
7987
+ const main = tryLoadAgentMetadata(from.session_id);
7988
+ if (!main || main.kind !== kind || !main.cwd)
7989
+ throw unavailable("no managed seat of this harness");
7990
+ // Codex binds its conversation lazily and may switch it (/new): read the current one without writing the main's record.
7991
+ let rollout = null;
7992
+ try {
7993
+ rollout = main.kind === "codex" ? codexRootTranscript(main) : null;
7994
+ }
7995
+ catch {
7996
+ rollout = null;
7997
+ }
7998
+ const mainVendorId = main.kind === "codex" ? (rollout ? codexRolloutSessionId(main, rollout) : null) : main.vendor_session_id;
7999
+ if (!mainVendorId || (main.kind === "claude" ? !main.claude_home
8000
+ || !fs.existsSync(path.join(main.claude_home, "projects", claudeProjectSlug(main.cwd), `${mainVendorId}.jsonl`)) : !rollout))
8001
+ throw unavailable("the saved conversation file does not exist yet");
8002
+ if (opts.cwd != null && (!fs.existsSync(opts.cwd) || fs.realpathSync(opts.cwd) !== fs.realpathSync(main.cwd)))
8003
+ throw new AitermError("FORK_INVALID: a fork runs in its main seat's cwd; omit cwd", 2);
8004
+ // The main's cwd is the project folder the Owner forbade writing (ADR 0140).
8005
+ const write_ban = probe(main.cwd);
8006
+ let root;
8007
+ if (main.kind === "claude") {
8008
+ try {
8009
+ root = resolveClaudeConfigurationRoot(main.claude_home);
8010
+ }
8011
+ catch {
8012
+ throw unavailable("its configuration root is not an accepted root here");
8013
+ }
8014
+ }
8015
+ const first_input = kind === "codex" ? forkInputKey(opts.prompt) : undefined;
8016
+ return { fork_of: { session_id: from.session_id, vendor_session_id: mainVendorId, ...(from.fork_id ? { fork_id: from.fork_id } : {}),
8017
+ write_ban, ...(first_input ? { first_input } : {}) }, cwd: main.cwd, ...(root ? { root } : {}) };
8018
+ }
7908
8019
  export async function openAgentWithInitialPrompt(kind, opts = {}) {
8020
+ const fork = opts.fork_from ? resolveForkSource(kind, opts.fork_from, opts) : null;
7909
8021
  if (opts.configuration_root != null && kind !== "claude")
7910
8022
  throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: configuration_rootはclaude-code harnessだけで使えます。", 2);
7911
- const claudeRoot = opts.configuration_root == null ? undefined : resolveClaudeConfigurationRoot(opts.configuration_root);
8023
+ const claudeRoot = fork ? fork.root : opts.configuration_root == null ? undefined : resolveClaudeConfigurationRoot(opts.configuration_root);
7912
8024
  if (opts.session_name)
7913
8025
  await withExecutionNativeAdmission(opts.session_name, () => assertExecutionContext(opts.session_name));
7914
8026
  else
@@ -8013,7 +8125,7 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
8013
8125
  // modelは呼び手の渡した形のまま渡す(空文字の断りはopenAgentがする)。Grokのfastだけ、fast版のIDへ替える。
8014
8126
  model: fastPlan.model !== requestedModel ? fastPlan.model : opts.model ?? null,
8015
8127
  reasoning_effort: opts.reasoning_effort ?? null,
8016
- cwd: opts.cwd ?? null,
8128
+ cwd: fork ? fork.cwd : opts.cwd ?? null,
8017
8129
  prompt: null,
8018
8130
  agent_done: true,
8019
8131
  launch_operation_id: opts.launch_operation_id ?? null,
@@ -8025,6 +8137,7 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
8025
8137
  claude_root: claudeRoot,
8026
8138
  append_system_prompt: opts.append_system_prompt ?? null,
8027
8139
  mcp_config: opts.mcp_config ?? null,
8140
+ ...(fork ? { fork_of: fork.fork_of } : {}),
8028
8141
  };
8029
8142
  // GrokとCursorは、起動の --model の値を利用者の既定へ書く(Cursorは版による)。起動の前後で、直前の値へ戻す。
8030
8143
  const launch = () => {
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;
@@ -365,6 +365,9 @@ export function claudeAgentArgv(bin, model, effort, prompt, meta) {
365
365
  parts.push("--dangerously-skip-permissions", "--setting-sources", "user,project,local", "--settings", meta.claude_settings ?? "", "--session-id", meta.vendor_session_id ?? "", "--append-system-prompt", subagentInstruction(meta, CLAUDE_DELIVERY_NOTES));
366
366
  if (meta.claude_caller_prompt_file)
367
367
  parts.push("--append-system-prompt-file", meta.claude_caller_prompt_file);
368
+ // Fork (ADR 0140): the main's conversation under the seat's own --session-id; tools and MCP stay the main's.
369
+ if (meta.fork_of)
370
+ parts.push("--resume", meta.fork_of.vendor_session_id, "--fork-session");
368
371
  if (meta.claude_caller_mcp_file)
369
372
  parts.push("--mcp-config", meta.claude_caller_mcp_file);
370
373
  }
@@ -381,12 +384,15 @@ export function claudeResumeArgv(bin, model, effort, meta) {
381
384
  if (meta.kind !== "claude" || !meta.vendor_session_id || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(meta.vendor_session_id))
382
385
  throw new AitermError("AGENT_RESUME_UNSUPPORTED: Claudeの保存会話IDを確認できません。", 2);
383
386
  const argv = claudeAgentArgv(bin, model, effort, null, meta);
387
+ // A fork resumes its own conversation: drop `--resume <main> --fork-session`.
388
+ if (meta.fork_of)
389
+ argv.splice(argv.indexOf("--fork-session") - 2, 3);
384
390
  argv[argv.indexOf("--session-id")] = "--resume";
385
391
  return argv;
386
392
  }
387
393
  export function buildClaudeAgentCmd(bin, model, effort, prompt, meta) {
388
394
  const argv = claudeAgentArgv(bin, model, effort, prompt, meta);
389
- const values = new Set(["--setting-sources", "--settings", "--session-id", "--append-system-prompt", "--append-system-prompt-file", "--mcp-config", "--model", "--effort"]);
395
+ const values = new Set(["--setting-sources", "--settings", "--session-id", "--resume", "--append-system-prompt", "--append-system-prompt-file", "--mcp-config", "--model", "--effort"]);
390
396
  return argv.map((arg, index) => index === 0 || values.has(argv[index - 1]) || (prompt && index === argv.length - 1)
391
397
  ? shq(arg) : arg).join(" ");
392
398
  }
@@ -136,6 +136,12 @@ export function listCodexTranscripts(codexHome) {
136
136
  * - undecided: 書いている途中などで、まだ決められない。
137
137
  * forkedは、ほかの会話から派生した会話(session_metaのforked_from_id)か。派生は元の会話の文を写すので、印だけでは持ち主を決められない。
138
138
  */
139
+ /** A fork's rollout carries no launch marker; it is this launch's when it forks the recorded main and holds the first input (ADR 0140). */
140
+ function codexForkInputSeen(record, meta) {
141
+ const key = meta.fork_of?.first_input;
142
+ return !!key && record?.type === "response_item" && record?.payload?.type === "message" && record?.payload?.role === "user"
143
+ && Array.isArray(record?.payload?.content) && record.payload.content.some((item) => item?.type === "input_text" && typeof item?.text === "string" && item.text.replace(/\s+/gu, "").includes(key));
144
+ }
139
145
  function codexLaunchVerdict(file, meta) {
140
146
  const createdAt = Date.parse(meta.created_at);
141
147
  try {
@@ -169,7 +175,11 @@ function codexLaunchVerdict(file, meta) {
169
175
  if (!rootCli)
170
176
  return { verdict: "other", forked: false };
171
177
  forked = typeof record?.payload?.forked_from_id === "string" && record.payload.forked_from_id !== "";
178
+ if (meta.fork_of && record.payload.forked_from_id !== meta.fork_of.vendor_session_id)
179
+ return { verdict: "other", forked };
172
180
  }
181
+ if (rootCli && forked && codexForkInputSeen(record, meta))
182
+ return { verdict: "match", forked };
173
183
  if (record?.type === "turn_context")
174
184
  firstTurnContext = true;
175
185
  if (record?.type === "response_item" &&
@@ -180,9 +190,12 @@ function codexLaunchVerdict(file, meta) {
180
190
  typeof item?.text === "string" &&
181
191
  item.text.includes(marker));
182
192
  }
183
- if (rootCli && launchMarker)
193
+ if (rootCli && launchMarker && !meta.fork_of)
184
194
  return { verdict: "match", forked };
185
195
  }
196
+ // A fork of the recorded main stays undecided until its first input is written: "other" is memoized for good.
197
+ if (meta.fork_of && rootCli && forked)
198
+ return { verdict: "undecided", forked };
186
199
  return { verdict: rootCli && firstTurnContext ? "other" : "undecided", forked };
187
200
  }
188
201
  export function codexTranscriptMatchesLaunch(file, meta) {
@@ -248,7 +261,7 @@ export function codexBoundTranscript(meta) {
248
261
  return origin.file;
249
262
  const file = findLatestCodexTranscript(meta.codex_home, meta.vendor_session_id);
250
263
  if (origin && (!file || codexTranscriptSessionId(file) !== meta.vendor_session_id
251
- || codexLaunchVerdict(file, meta).verdict !== "match" || codexLaunchVerdict(file, meta).forked))
264
+ || codexLaunchVerdict(file, meta).verdict !== "match" || (codexLaunchVerdict(file, meta).forked && !meta.fork_of)))
252
265
  throw resumeProofUnavailable();
253
266
  return file;
254
267
  }
@@ -531,7 +544,7 @@ function codexNativeRootRecord(meta, requireBoundary) {
531
544
  const lines = readFileRange(file, 0, Math.min(safeStatSize(file), 1024 * 1024)).toString("utf8").split("\n");
532
545
  // The final split element may be incomplete. Never parse that fragment.
533
546
  lines.pop();
534
- let session = null, own = false, root = false;
547
+ let session = null, own = false, root = false, forkOwn = false;
535
548
  for (const line of lines) {
536
549
  if (!line.trim())
537
550
  continue;
@@ -544,7 +557,7 @@ function codexNativeRootRecord(meta, requireBoundary) {
544
557
  }
545
558
  if (record?.type === "session_meta") {
546
559
  if (session !== null || record.payload?.originator !== "codex-tui" || record.payload?.source !== "cli"
547
- || record.payload?.forked_from_id)
560
+ || (record.payload?.forked_from_id && record.payload.forked_from_id !== meta.fork_of?.vendor_session_id))
548
561
  return null;
549
562
  const id = record.payload?.id;
550
563
  if (typeof id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id)
@@ -557,6 +570,8 @@ function codexNativeRootRecord(meta, requireBoundary) {
557
570
  && Array.isArray(record.payload?.content))
558
571
  own ||= record.payload.content.some((item) => (item?.type === "input_text" || item?.type === "output_text") && typeof item.text === "string"
559
572
  && item.text.split(/\r?\n/).includes(marker));
573
+ if (meta.fork_of)
574
+ own = (forkOwn ||= codexForkInputSeen(record, meta));
560
575
  if (root && own && session)
561
576
  return session;
562
577
  }
@@ -881,7 +896,8 @@ export async function observeCodexDone(meta, timeout, requestedCursor, signal) {
881
896
  }
882
897
  }
883
898
  export function codexAgentArgv(bin, model, effort, prompt, meta) {
884
- const parts = [bin];
899
+ // A fork (ADR 0140) starts from the main's conversation; codexResumeArgv drops this pair again.
900
+ const parts = meta?.kind === "codex" && meta.fork_of ? [bin, "fork", meta.fork_of.vendor_session_id] : [bin];
885
901
  // `codex --help` で確認した実在フラグ。read-only 宣言だけはCLI sandboxへ落とし、
886
902
  // launcher自身が実効能力壁を作る。パス説明はCodex CLIに同等のallowlist引数がないため宣言のまま残す。
887
903
  if (meta?.kind === "codex" && meta.write_scope === "read-only")
@@ -909,7 +925,7 @@ export function codexResumeArgv(bin, model, effort, meta, cwd) {
909
925
  if (meta.kind !== "codex" || !meta.vendor_session_id || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(meta.vendor_session_id)
910
926
  || !path.isAbsolute(cwd) || cwd.includes("\0"))
911
927
  throw new AitermError("AGENT_RESUME_UNSUPPORTED: Codexの保存会話IDとcwdを確認できません。", 2);
912
- return [bin, "resume", meta.vendor_session_id, ...codexAgentArgv(bin, model, effort, null, meta).slice(1), "--cd", cwd];
928
+ return [bin, "resume", meta.vendor_session_id, ...codexAgentArgv(bin, model, effort, null, meta).slice(meta.fork_of ? 3 : 1), "--cd", cwd];
913
929
  }
914
930
  export function buildCodexAgentCmd(bin, model, effort, prompt, meta) {
915
931
  const argv = codexAgentArgv(bin, model, effort, prompt, meta);