aiterm-mcp 0.70.5 → 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 +7 -1
- package/README.ja.md +1 -1
- package/README.md +1 -1
- package/dist/agent-metadata-reader.js +15 -0
- package/dist/core.js +74 -7
- package/dist/harnesses/claude.js +7 -1
- package/dist/harnesses/codex.js +22 -6
- package/dist/index.js +21 -2
- package/dist/tmux-runtime.js +21 -5
- package/dist/write-ban.js +70 -0
- package/docs/DESIGN.md +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,11 @@ 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
|
+
|
|
10
15
|
## [0.70.5] - 2026-11-10
|
|
11
16
|
|
|
12
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.
|
|
@@ -3189,7 +3194,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
|
|
|
3189
3194
|
`ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
|
|
3190
3195
|
provenance.
|
|
3191
3196
|
|
|
3192
|
-
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.
|
|
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
|
|
3193
3199
|
[0.70.5]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.4...v0.70.5
|
|
3194
3200
|
[0.70.4]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.3...v0.70.4
|
|
3195
3201
|
[0.70.3]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.2...v0.70.3
|
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.
|
|
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.
|
|
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,7 +65,7 @@ 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
71
|
import { interimFromNow, interimFromToken, readInterimWords, recordInterimBoundary } from "./interim-words.js";
|
|
@@ -775,6 +776,7 @@ function openSessionInternal(name, shell, envVars, preserveAgentState) {
|
|
|
775
776
|
break;
|
|
776
777
|
}
|
|
777
778
|
}
|
|
779
|
+
rememberPaneShell(nm, shell);
|
|
778
780
|
return [nm, attachHint(nm)];
|
|
779
781
|
});
|
|
780
782
|
}
|
|
@@ -6880,6 +6882,9 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
|
|
|
6880
6882
|
next.codex_home = recipe.configuration_root;
|
|
6881
6883
|
if (previous.write_scope !== undefined)
|
|
6882
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;
|
|
6883
6888
|
writeAgentMetadata(next);
|
|
6884
6889
|
initializeAgentActivity(next);
|
|
6885
6890
|
writeAgentResumeRecipe(next, { ...recipe, launch_id: next.launch_id });
|
|
@@ -6903,8 +6908,9 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot) {
|
|
|
6903
6908
|
if (registerSessionEnvironment(true, name, [...(registeredSessionEnvironment(name) ?? []), ...Object.keys(recipe.environment)]).code !== 0)
|
|
6904
6909
|
throw uncertain();
|
|
6905
6910
|
phase = "vendor_start";
|
|
6906
|
-
const argv = next.
|
|
6907
|
-
|
|
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))];
|
|
6908
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 })
|
|
6909
6915
|
: `cd ${shq(recipe.cwd)} && /usr/bin/env ${environment.filter(([, value]) => value === null).map(([key]) => `-u ${shq(key)}`).join(" ")} `
|
|
6910
6916
|
+ `${environment.filter(([, value]) => value !== null).map(([key, value]) => shq(`${key}=${value}`)).join(" ")} ${argv.map(shq).join(" ")}`;
|
|
@@ -7522,6 +7528,9 @@ function agentEnvEntries(meta, sid, envVars = []) {
|
|
|
7522
7528
|
["AITERM_AGENT_LINEAGE", meta.lineage ?? `host-root>${meta.kind}:${sid}`],
|
|
7523
7529
|
["AITERM_AGENT_DELEGATION_ALLOWED", meta.delegation_allowed === true ? "true" : "false"],
|
|
7524
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]] : []),
|
|
7525
7534
|
];
|
|
7526
7535
|
}
|
|
7527
7536
|
/** POSIX shellの起動行に前置する環境変数。Grokは自分の認証の正本と自動更新停止の値を、共通の一覧の前に置く。 */
|
|
@@ -7777,6 +7786,8 @@ function prepareAgentLaunch(kind, opts = {}) {
|
|
|
7777
7786
|
meta.agent_executable = bin;
|
|
7778
7787
|
if (meta.kind === "claude")
|
|
7779
7788
|
writeClaudeCallerFiles(meta, opts.append_system_prompt ?? null, opts.mcp_config ?? null);
|
|
7789
|
+
if (opts.fork_of)
|
|
7790
|
+
meta.fork_of = opts.fork_of;
|
|
7780
7791
|
if (isWin && ["claude", "codex", "grok", "antigravity"].includes(kind))
|
|
7781
7792
|
meta.windows_launch_exit_tracked = true;
|
|
7782
7793
|
if (kind === "claude" || kind === "codex")
|
|
@@ -7821,7 +7832,8 @@ function prepareAgentLaunch(kind, opts = {}) {
|
|
|
7821
7832
|
], windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), meta?.windows_launch_exit_tracked ? { file: agentMetadataPath(sid, meta.launch_id) + ".launch-exited", launch_id: meta.launch_id } : undefined);
|
|
7822
7833
|
}
|
|
7823
7834
|
else {
|
|
7824
|
-
const cmd =
|
|
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);
|
|
7825
7837
|
const envPrefix = (!claudeRoot ? "" : claudeRoot.selector === null ? "unset CLAUDE_CONFIG_DIR && "
|
|
7826
7838
|
: `CLAUDE_CONFIG_DIR=${shq(claudeRoot.selector)} `) + launchEnvSource(sid, agentEnvEntries(null, sid, envVars)) + agentEnvPrefix(meta, sid);
|
|
7827
7839
|
const command = cwdForCmd ? `cd ${shq(cwdForCmd)} && ${envPrefix}${cmd}` : `${envPrefix}${cmd}`;
|
|
@@ -7951,10 +7963,64 @@ export class AgentLaunchPromptError extends AitermError {
|
|
|
7951
7963
|
this.startup = startup;
|
|
7952
7964
|
}
|
|
7953
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
|
+
}
|
|
7954
8019
|
export async function openAgentWithInitialPrompt(kind, opts = {}) {
|
|
8020
|
+
const fork = opts.fork_from ? resolveForkSource(kind, opts.fork_from, opts) : null;
|
|
7955
8021
|
if (opts.configuration_root != null && kind !== "claude")
|
|
7956
8022
|
throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: configuration_rootはclaude-code harnessだけで使えます。", 2);
|
|
7957
|
-
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);
|
|
7958
8024
|
if (opts.session_name)
|
|
7959
8025
|
await withExecutionNativeAdmission(opts.session_name, () => assertExecutionContext(opts.session_name));
|
|
7960
8026
|
else
|
|
@@ -8059,7 +8125,7 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
|
|
|
8059
8125
|
// modelは呼び手の渡した形のまま渡す(空文字の断りはopenAgentがする)。Grokのfastだけ、fast版のIDへ替える。
|
|
8060
8126
|
model: fastPlan.model !== requestedModel ? fastPlan.model : opts.model ?? null,
|
|
8061
8127
|
reasoning_effort: opts.reasoning_effort ?? null,
|
|
8062
|
-
cwd: opts.cwd ?? null,
|
|
8128
|
+
cwd: fork ? fork.cwd : opts.cwd ?? null,
|
|
8063
8129
|
prompt: null,
|
|
8064
8130
|
agent_done: true,
|
|
8065
8131
|
launch_operation_id: opts.launch_operation_id ?? null,
|
|
@@ -8071,6 +8137,7 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
|
|
|
8071
8137
|
claude_root: claudeRoot,
|
|
8072
8138
|
append_system_prompt: opts.append_system_prompt ?? null,
|
|
8073
8139
|
mcp_config: opts.mcp_config ?? null,
|
|
8140
|
+
...(fork ? { fork_of: fork.fork_of } : {}),
|
|
8074
8141
|
};
|
|
8075
8142
|
// GrokとCursorは、起動の --model の値を利用者の既定へ書く(Cursorは版による)。起動の前後で、直前の値へ戻す。
|
|
8076
8143
|
const launch = () => {
|
package/dist/harnesses/claude.js
CHANGED
|
@@ -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
|
}
|
package/dist/harnesses/codex.js
CHANGED
|
@@ -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
|
-
|
|
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);
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { loadAgentMetadata } from "./agent-metadata-reader.js";
|
|
2
3
|
import { remoteInputDescription, remoteInputSchema, terminalArgumentDescription, terminalArgumentSchema } from "./remote-contract.js";
|
|
3
4
|
import { boundTerminalTarget, bindTerminalSession, terminalSeatGroups, ensureSeatForward, extractMcpHeaders, maintainSeatForwards, REMOTE_MINIMUM_VERSION, seatIngressPort, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
|
|
4
5
|
import { launchEnvValue } from "./private-env.js";
|
|
@@ -1218,9 +1219,16 @@ export function createAitermServer(options = {}) {
|
|
|
1218
1219
|
async function launchRemoteAgent(target, harness, args, extra, privateEnv) {
|
|
1219
1220
|
if (args.image && args.image.length > 0)
|
|
1220
1221
|
throw new core.AitermError("REMOTE_IMAGE_UNSUPPORTED: 別端末への画像添付には未対応です", 2);
|
|
1222
|
+
// An Aiterm without fork_from would drop it and start a writable seat (ADR 0140): check the version first.
|
|
1223
|
+
if (args.fork_from) {
|
|
1224
|
+
const version = (await callRemoteTool(target, "pty_list", {}, 60_000)).remote_version ?? "0.0.0";
|
|
1225
|
+
if (!versionAtLeast(version, FORK_MINIMUM_VERSION))
|
|
1226
|
+
throw new AitermError(`REMOTE_AITERM_TOO_OLD: the remote runs Aiterm ${version}; fork_from needs ${FORK_MINIMUM_VERSION} or later`, 2);
|
|
1227
|
+
}
|
|
1221
1228
|
const delivery = args.prompt || args.throughline_source_session ? await deliveryForRequest(extra, true) : null;
|
|
1222
1229
|
// A terminal's claude_agent takes append_system_prompt / mcp_config since 0.65.0; its agent_launch drops them until this release.
|
|
1223
|
-
|
|
1230
|
+
// claude_agent has no fork_from, so a fork always goes through agent_launch.
|
|
1231
|
+
const result = target.trusted_ref && harness === "claude-code" && !args.fork_from
|
|
1224
1232
|
? await callRemoteTool(target, "claude_agent", args, 600_000, privateEnv)
|
|
1225
1233
|
: await callRemoteTool(target, "agent_launch", { harness, ...args }, 600_000, privateEnv);
|
|
1226
1234
|
const structured = result.structuredContent;
|
|
@@ -1249,6 +1257,8 @@ export function createAitermServer(options = {}) {
|
|
|
1249
1257
|
...(result.isError && !unconfirmed ? { isError: true } : {}),
|
|
1250
1258
|
};
|
|
1251
1259
|
}
|
|
1260
|
+
/** First release whose agent_launch knows fork_from (ADR 0140). */
|
|
1261
|
+
const FORK_MINIMUM_VERSION = "0.70.6";
|
|
1252
1262
|
const terminalVersions = new Map();
|
|
1253
1263
|
/** A seat on a BellTeam terminal (remote-terminal.md "One launch path"). Same launch arguments plus terminal + cwd. */
|
|
1254
1264
|
async function launchTerminalAgent(harness, terminal, args, extra) {
|
|
@@ -1297,8 +1307,8 @@ export function createAitermServer(options = {}) {
|
|
|
1297
1307
|
}
|
|
1298
1308
|
}
|
|
1299
1309
|
async function launchAgent(kind, args, extra) {
|
|
1310
|
+
const { prompt, image, throughline_source_session, throughline_supplement_file, model, reasoning_effort, fast, env_vars, cwd, session_name, launch_operation_id, write_scope, trust_project, require_existing_resume, configuration_root, append_system_prompt, mcp_config, fork_from } = args;
|
|
1300
1311
|
const supportsWriteScope = kind !== "claude";
|
|
1301
|
-
const { prompt, image, throughline_source_session, throughline_supplement_file, model, reasoning_effort, fast, env_vars, cwd, session_name, launch_operation_id, write_scope, trust_project, require_existing_resume, configuration_root, append_system_prompt, mcp_config } = args;
|
|
1302
1312
|
let delivery = null;
|
|
1303
1313
|
try {
|
|
1304
1314
|
if (!supportsWriteScope && write_scope !== undefined) {
|
|
@@ -1330,7 +1340,9 @@ export function createAitermServer(options = {}) {
|
|
|
1330
1340
|
mcp_config,
|
|
1331
1341
|
launch_operation_id: launch_operation_id ?? undefined,
|
|
1332
1342
|
...(supportsWriteScope ? { write_scope } : {}),
|
|
1343
|
+
...(fork_from ? { fork_from } : {}),
|
|
1333
1344
|
});
|
|
1345
|
+
const forkOf = fork_from ? loadAgentMetadata(sid).fork_of : undefined;
|
|
1334
1346
|
const structured = {
|
|
1335
1347
|
schema: "aiterm.agent-launch-result.v1",
|
|
1336
1348
|
provider: kind,
|
|
@@ -1354,6 +1366,7 @@ export function createAitermServer(options = {}) {
|
|
|
1354
1366
|
: "declaration_only_unsupported",
|
|
1355
1367
|
}
|
|
1356
1368
|
: {}),
|
|
1369
|
+
...(forkOf ? { fork_of: { session_id: forkOf.session_id, vendor_session_id: forkOf.vendor_session_id, write_ban: forkOf.write_ban } } : {}),
|
|
1357
1370
|
};
|
|
1358
1371
|
// 開始未確認(submitted_unconfirmed)は誤りにしない。sessionは立ち、promptは入力欄を離れ、配送も登録済み。
|
|
1359
1372
|
// 誤りで返すとClaude Code親は受け口のhookを走らせず、子の回答が届かない(ADR 0093)。状態はinitial_promptと本文で伝える。
|
|
@@ -1486,6 +1499,10 @@ export function createAitermServer(options = {}) {
|
|
|
1486
1499
|
terminal: terminalArgumentSchema.optional().describe(terminalArgumentDescription),
|
|
1487
1500
|
append_system_prompt: z.string().min(1).optional().describe("claude-code only. Launch instructions added to the system prompt; kept in Aiterm state, not in the project or home. Never put secrets here"),
|
|
1488
1501
|
mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("claude-code only. Extra MCP servers for this seat. Secret header values: write ${NAME} and list NAME in env_vars"),
|
|
1502
|
+
fork_from: z.object({
|
|
1503
|
+
session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/).describe("The main Aiterm seat on the same machine (the terminal or remote when given)"),
|
|
1504
|
+
fork_id: z.string().min(1).max(200).optional().describe("Caller's fork ID, passed to the seat as THROUGHLINE_FORK_ID"),
|
|
1505
|
+
}).strict().optional().describe("claude-code and codex-cli. Start a disposable fork of that seat's latest saved conversation, in its cwd, with the main's tools and MCP. Every write inside that cwd (the project folder) is refused below the tools for the whole process tree (Linux Landlock, macOS sandbox-exec); everything else is allowed. Windows answers READONLY_UNENFORCEABLE. Requires a prompt; no write_scope. Close it after its answer"),
|
|
1489
1506
|
},
|
|
1490
1507
|
outputSchema: {
|
|
1491
1508
|
schema: z.literal("aiterm.agent-launch-result.v1"),
|
|
@@ -1507,6 +1524,8 @@ export function createAitermServer(options = {}) {
|
|
|
1507
1524
|
fast_error: fastModeFailureSchema.nullable().optional().describe("fastを頼まれたが、通常の速度で起こした時の訳"),
|
|
1508
1525
|
write_scope: z.string().optional(),
|
|
1509
1526
|
write_scope_enforcement: z.enum(["enforced_read_only", "declaration_only_unsupported"]).optional(),
|
|
1527
|
+
fork_of: z.object({ session_id: z.string(), vendor_session_id: z.string(),
|
|
1528
|
+
write_ban: z.object({ path: z.string(), method: z.enum(["landlock", "seatbelt"]) }) }).optional().describe("The seat this fork copies and the folder it cannot write"),
|
|
1510
1529
|
},
|
|
1511
1530
|
}, async ({ harness, remote, terminal, ...args }, extra) => {
|
|
1512
1531
|
if (harness !== "claude-code" && (args.append_system_prompt !== undefined || args.mcp_config !== undefined))
|
package/dist/tmux-runtime.js
CHANGED
|
@@ -927,6 +927,14 @@ export function markShellCommand(foreground, screen, platform = process.platform
|
|
|
927
927
|
}
|
|
928
928
|
return foreground;
|
|
929
929
|
}
|
|
930
|
+
// Windows: the shell that last showed its prompt in each pane (seeded with the shell the pane was opened with).
|
|
931
|
+
// psmux's foreground name can be stale (pwsh for a Git Bash pane), so input typed while a command runs, or before the
|
|
932
|
+
// first prompt, would get the wrong dialect; the shell that reads it is the one whose prompt was last seen.
|
|
933
|
+
const windowsPromptShells = new Map();
|
|
934
|
+
export function rememberPaneShell(name, shell) {
|
|
935
|
+
if (isWin)
|
|
936
|
+
windowsPromptShells.set(name, normalizePaneCommand(shell));
|
|
937
|
+
}
|
|
930
938
|
/** The runtime owns platform foreground queries and shell-dialect reconciliation. */
|
|
931
939
|
export function paneShellForSubmission(name) {
|
|
932
940
|
const r = tmuxCommand(true, "display-message", "-p", "-t", name, "#{pane_current_command}");
|
|
@@ -935,12 +943,20 @@ export function paneShellForSubmission(name) {
|
|
|
935
943
|
return foreground;
|
|
936
944
|
const screen = tmuxCommand(true, "capture-pane", "-p", "-J", "-t", name, "-S", "-4");
|
|
937
945
|
const text = screen.code === 0 ? screen.stdout : "";
|
|
938
|
-
|
|
939
|
-
if (
|
|
946
|
+
let selected = markShellCommand(foreground, text);
|
|
947
|
+
if (isWin && selected === foreground && selected !== "bash" && /(?:^|\n)\$\s*$/u.test(text.trimEnd())) {
|
|
948
|
+
const width = tmuxCommand(true, "display-message", "-p", "-t", name, "#{pane_width}");
|
|
949
|
+
const columns = width.code === 0 && /^\d+\s*$/u.test(width.stdout) ? Number(width.stdout.trim()) : undefined;
|
|
950
|
+
selected = markShellCommand(foreground, text, "win32", columns);
|
|
951
|
+
}
|
|
952
|
+
if (!isWin)
|
|
953
|
+
return selected;
|
|
954
|
+
const current = text.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, "").trimEnd();
|
|
955
|
+
if (/(?:^|\n)PS [^\r\n]*>$/u.test(current) || /(?:^|\n)\$$/u.test(current)) {
|
|
956
|
+
windowsPromptShells.set(name, selected);
|
|
940
957
|
return selected;
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
return markShellCommand(foreground, text, "win32", columns);
|
|
958
|
+
}
|
|
959
|
+
return windowsPromptShells.get(name) ?? selected;
|
|
944
960
|
}
|
|
945
961
|
/** Common send code supplies intent; the runtime decides whether/how to encode it. */
|
|
946
962
|
export function adaptShellSubmission(name, text, options = {}) {
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Fork write-ban (ADR 0140): every write inside one folder is refused below the tools, for the whole CLI process tree.
|
|
2
|
+
// Everything else (reads, commands, network, MCP, writes elsewhere) is untouched.
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import * as fs from "node:fs";
|
|
5
|
+
import * as path from "node:path";
|
|
6
|
+
import { AitermError } from "./errors.js";
|
|
7
|
+
// Linux: Landlock, unprivileged (works in standard Docker, where bwrap cannot create a namespace).
|
|
8
|
+
// Handles only write-type rights and grants them on every sibling along / -> the folder, so only the folder
|
|
9
|
+
// (and new entries directly in its ancestors) is unwritable. Fails closed: exit 126 before the CLI starts.
|
|
10
|
+
const LANDLOCK_PY = `import ctypes,os,sys,struct
|
|
11
|
+
a=sys.argv[1:];probe=a[0]=='--probe'
|
|
12
|
+
if probe:a=a[1:]
|
|
13
|
+
P=os.path.realpath(a[0]);L=ctypes.CDLL(None,use_errno=True)
|
|
14
|
+
def c(r,w):
|
|
15
|
+
if r<0:
|
|
16
|
+
sys.stderr.write('aiterm write-ban: %s: %s\\n'%(w,os.strerror(ctypes.get_errno())));sys.exit(126)
|
|
17
|
+
return r
|
|
18
|
+
abi=c(L.syscall(444,None,0,1),'landlock unavailable')
|
|
19
|
+
D=0
|
|
20
|
+
for b in (1,4,5,6,7,8,9,10,11,12,13,14):D|=1<<b
|
|
21
|
+
if abi<2:D&=~(1<<13)
|
|
22
|
+
if abi<3:D&=~(1<<14)
|
|
23
|
+
F=D&((1<<1)|(1<<14));A=struct.pack('QQQ',D,0,0)
|
|
24
|
+
fd=c(L.syscall(444,ctypes.c_char_p(A),ctypes.c_size_t(len(A)),0),'create_ruleset')
|
|
25
|
+
def g(p):
|
|
26
|
+
try:q=os.open(p,os.O_PATH|os.O_CLOEXEC)
|
|
27
|
+
except OSError:return
|
|
28
|
+
try:c(L.syscall(445,fd,1,ctypes.c_char_p(struct.pack('=Qi',D if os.path.isdir(p) else F,q)),0),'add_rule '+p)
|
|
29
|
+
finally:os.close(q)
|
|
30
|
+
cur='/'
|
|
31
|
+
for part in P.strip('/').split('/'):
|
|
32
|
+
for e in os.listdir(cur):
|
|
33
|
+
if e!=part:g(os.path.join(cur,e))
|
|
34
|
+
cur=os.path.join(cur,part)
|
|
35
|
+
c(L.prctl(38,1,0,0,0),'no_new_privs')
|
|
36
|
+
c(L.syscall(446,fd,0),'restrict_self')
|
|
37
|
+
if probe:print('landlock',abi);sys.exit(0)
|
|
38
|
+
cmd=a[a.index('--')+1:];os.execvp(cmd[0],cmd)
|
|
39
|
+
`;
|
|
40
|
+
const LANDLOCK_LAUNCHER = `import base64;exec(base64.b64decode('${Buffer.from(LANDLOCK_PY).toString("base64")}'))`;
|
|
41
|
+
function seatbeltProfile(folder) {
|
|
42
|
+
return `(version 1)(allow default)(deny file-write* (subpath "${folder.replace(/[\\"]/g, "\\$&")}"))`;
|
|
43
|
+
}
|
|
44
|
+
/** argv placed before the CLI's own argv. The CLI is exec'd, so its PID and process name stay the seat's. */
|
|
45
|
+
export function writeBanPrefix(ban) {
|
|
46
|
+
return ban.method === "landlock"
|
|
47
|
+
? ["python3", "-c", LANDLOCK_LAUNCHER, ban.path, "--"]
|
|
48
|
+
: ["/usr/bin/sandbox-exec", "-p", seatbeltProfile(ban.path)];
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Prove on this machine that the ban can be applied before any seat starts. Without proof the fork is refused:
|
|
52
|
+
* starting it would let it write the project (the one thing the Owner forbade).
|
|
53
|
+
*/
|
|
54
|
+
export function probeWriteBan(folder, platform = process.platform) {
|
|
55
|
+
const unenforceable = (why) => new AitermError(`READONLY_UNENFORCEABLE: the project write-ban cannot be applied here: ${why}`, 2);
|
|
56
|
+
if (platform === "win32")
|
|
57
|
+
throw unenforceable("Windows has no same-user folder write-ban yet");
|
|
58
|
+
if (!path.isAbsolute(folder) || !fs.existsSync(folder))
|
|
59
|
+
throw unenforceable(`folder ${folder} does not exist`);
|
|
60
|
+
const real = fs.realpathSync(folder);
|
|
61
|
+
if (real === path.parse(real).root)
|
|
62
|
+
throw unenforceable("the folder is the filesystem root");
|
|
63
|
+
const ban = { path: real, method: platform === "darwin" ? "seatbelt" : "landlock" };
|
|
64
|
+
const [bin, ...args] = writeBanPrefix(ban);
|
|
65
|
+
const probe = ban.method === "landlock" ? [args[0], args[1], "--probe", real] : [...args, "/usr/bin/true"];
|
|
66
|
+
const r = spawnSync(bin, probe, { encoding: "utf8", timeout: 10_000 });
|
|
67
|
+
if (r.status !== 0)
|
|
68
|
+
throw unenforceable((r.stderr || r.error?.message || `exit ${r.status}`).trim().split("\n").pop() ?? "probe failed");
|
|
69
|
+
return ban;
|
|
70
|
+
}
|
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)。単語だけのshell名は`/bin/sh -c 'exec <shell>'`で置き換え、paneの前面を要求したshellにする(dashは単独の-c命令をforkし、前面が`sh`に見える)。POSIXのPowerShellは行編集の開始前に打たれた文を壊すので、`pty_open`は最初のpromptで行頭からcursorが動くまで最大10秒待つ。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経路は従来どおり。WindowsではpsmuxのFG名が古いまま(Git Bashのpaneでpwsh)返ることがあるため、送信の方言は見えているpromptで決め、promptが見えない時(命令の実行中や最初のpromptの前)は、そのpaneで最後にpromptを見たshell(最初はpaneを開いたshell)を使う(ADR 0136追補)。
|
|
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
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiterm-mcp",
|
|
3
|
-
"version": "0.70.
|
|
3
|
+
"version": "0.70.6",
|
|
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": [
|