aiterm-mcp 0.70.8 → 0.70.9

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,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.70.9] - 2026-11-10
11
+
12
+ - All five harnesses can run on a terminal. `agent_launch` (and the per-harness launchers) with `terminal` now accepts `grok-cli`, `cursor-cli` and `antigravity-cli` beside `claude-code` and `codex-cli`, routed to the terminal's `agent_launch` the same way, with the seat-forward URL rewrite and header extraction unchanged. These three need Aiterm 0.70.9 on the terminal (`REMOTE_AITERM_TOO_OLD` before any private value is sent). `TERMINAL_HARNESS_UNSUPPORTED` stays only as a guard for a name outside the five.
13
+ - `remote_terminal_command` gains `cli_version`, `cli_install`, `cli_update` and `cli_auth_status`, each with a required `harness` (`claude-code`, `codex-cli`, `grok-cli`, `cursor-cli`, `antigravity-cli`; a missing or unknown one is `COMMAND_INVALID`; a terminal older than 0.70.9 is `REMOTE_AITERM_TOO_OLD`). The first three answer `{op, harness, exit_code, version, output_tail}` with each CLI's official installer and updater (Windows: PowerShell). `cli_auth_status` answers `{op, harness, logged_in}` and nothing else, from the same status commands Aiterm uses locally; an answer that is not clearly logged in or out is `AUTH_STATUS_UNCONFIRMED`, a missing CLI `CLI_NOT_INSTALLED`. `claude_version`, `claude_install` and `claude_update` stay as aliases for `claude-code` (their version is now also read from `~/.local/bin/claude` when it is not on PATH).
14
+ - A launch of a CLI that is not logged in is `AGENT_LAUNCH_NOT_STARTED` with `_meta["aiterm/launch_error"]` `code: "AGENT_AUTH_REQUIRED"` (`phase: "input"`, `effect: "not_started"`, `session_created: false`, `harness`) for Claude Code, Cursor and Antigravity, locally and on a terminal; Claude keeps its `CLAUDE_AUTH_NOT_AUTHENTICATED` structured answer beside it. Codex and Grok have no launch preflight.
15
+ - `agent_launch` accepts `append_system_prompt` and `mcp_config` for grok-cli, cursor-cli and antigravity-cli too (same shapes as claude-code and codex-cli: http servers `{type?: "http", url, headers}`, headers literal, a whole `${NAME}` or `Bearer ${NAME}`). Nothing is written to the project or to `~/.grok`, `~/.cursor`, `~/.gemini`: the files are 0600 (folders 0700) in Aiterm's launch state and are removed with the seat. Grok: the text is appended to the one `--rules` value after Aiterm's lineage text; the servers are a per-seat agent file passed as `--agent` (frontmatter `mcpServers:` list, empty body, so the default agent stays; Grok does not expand `${VAR}` in headers, so `Bearer ${NAME}` becomes `bearer_token_env_var` and any other `${NAME}` is resolved from the seat env into the 0600 file). Cursor: no system-prompt channel, so the text joins Aiterm's first-prompt block; the servers are a per-seat plugin folder passed as `--plugin-dir` (`${env:NAME}` references; the server runs as `plugin-aiterm-caller-<name>` beside a same-name user server). Antigravity: the servers are `<seat folder>/.agents/mcp_config.json` (values resolved, 0600) passed as `--add-dir`, with `trustedWorkspaces` added to `--settings`; the text prefixes the first prompt, so `append_system_prompt` needs a prompt. A shape a harness cannot say, or a `${NAME}` with no value at launch, is refused before the seat starts (`AGENT_LAUNCH_NOT_STARTED`, phase `input`).
16
+
10
17
  ## [0.70.8] - 2026-11-10
11
18
 
12
19
  - Windows forks (x64): `agent_launch.fork_from` now starts the fork with every write inside the project folder refused instead of answering `READONLY_UNENFORCEABLE`. A bundled helper (`native/write-ban/win32-x64/aiterm-write-ban.exe`, about 24 KB, built reproducibly with the Linux ones) runs the CLI under a restricted copy of the user's token with no privileges and an Aiterm marker SID. The project folder carries, once, an inheritable Deny ACE for that marker SID (plus OWNER RIGHTS = READ_CONTROL and WRITE_DAC, so the DACL cannot be rewritten). The ACEs affect no other process, so the main seat writes as before and nothing is cleaned up later. npm shims run through `pwsh -File`. Measured on fox: new file, append, delete, rename, attributes, Set-Acl, icacls, takeown, git and cmd redirects inside were refused; writes outside succeeded. `fork_of.write_ban.method` is `restricted-token`.
@@ -3221,7 +3228,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3221
3228
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3222
3229
  provenance.
3223
3230
 
3224
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.8...HEAD
3231
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.9...HEAD
3232
+ [0.70.9]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.8...v0.70.9
3225
3233
  [0.70.8]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.7...v0.70.8
3226
3234
  [0.70.7]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.6...v0.70.7
3227
3235
  [0.70.6]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.5...v0.70.6
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.8** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.9** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
219
219
 
220
220
  ### 更新と巻き戻し
221
221
 
@@ -762,6 +762,8 @@ Claudeをリンク経由の`cwd`から起動した場合も、実体パスに対
762
762
 
763
763
  Claudeの認証事前確認による起動拒否は従来のエラー文を保ち、`structuredContent`へ`schema:"aiterm.agent-launch-error.v1"`、`harness:"claude-code"`、`phase:"authentication_preflight"`、`effect:"not_issued"`、`session_created:false`を返す。`code`は`CLAUDE_AUTH_NOT_AUTHENTICATED`(公式statusが未認証)、`CLAUDE_AUTH_STATUS_UNCONFIRMED`(確認不能)を区別する。確認が5秒で終わらない時は拒否せず起動へ進み、未ログインならlogin画面で`vendor_onboarding_required`として止まる。`CLAUDE_AUTH_STATUS_TIMEOUT`は0.70.1より前の端末だけが返す。資格情報の故障原因やログイン期限切れは断定せず、公式status本文・stderrは返さない。
764
764
 
765
+ ログインしていないと確かめられたCLIは、起動前確認のあるClaude Code・Cursor・Antigravityで同じ形で起動を断る。`_meta["aiterm/launch_error"]`が`code:"AGENT_AUTH_REQUIRED"`・`phase:"input"`・`effect:"not_started"`・`session_created:false`・`harness`を持つ(本文は`AGENT_LAUNCH_NOT_STARTED: AGENT_AUTH_REQUIRED: ...`。Claudeは従来の本文と`structuredContent`も残す)。CodexとGrokには起動前確認が無く、各CLIのログイン画面で止まる。状態を読めなかった場合はこのcodeにしない。
766
+
765
767
  ### 別端末のagentを1回で起動する(`remote`)
766
768
 
767
769
  `agent_launch`に`remote`を付けると、SSHで入った別端末のAitermで同じ起動を行う。端末へ入る操作と現地のagentを起動する操作が1回で済み、親から見た完了の届き方はこの端末の子と同じになる。Linux・macOS・Windowsの端末へ同じ依頼を並行して投げる用途を想定している。
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.8** · 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.9** · 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
 
@@ -772,6 +772,8 @@ The selected harness CLI must be installed and authenticated. Use each product o
772
772
 
773
773
  Claude authentication preflight refusals retain the existing error text and add `structuredContent` with schema `aiterm.agent-launch-error.v1`, `harness:"claude-code"`, `phase:"authentication_preflight"`, `effect:"not_issued"`, and `session_created:false`. `code` distinguishes `CLAUDE_AUTH_NOT_AUTHENTICATED` and `CLAUDE_AUTH_STATUS_UNCONFIRMED`. A status check that does not finish in 5 seconds no longer refuses: the launch goes on, and a logged-out Claude stops at its login screen as `vendor_onboarding_required`. `CLAUDE_AUTH_STATUS_TIMEOUT` comes only from terminals older than 0.70.1. These describe the official status check, not the cause of a credential failure or a confirmed login expiry. Native status bodies and stderr are omitted.
774
774
 
775
+ A CLI that is positively not logged in refuses the launch the same way for Claude Code, Cursor and Antigravity (the harnesses with a launch preflight): `_meta["aiterm/launch_error"]` carries `code:"AGENT_AUTH_REQUIRED"`, `phase:"input"`, `effect:"not_started"`, `session_created:false` and the `harness`; the text is `AGENT_LAUNCH_NOT_STARTED: AGENT_AUTH_REQUIRED: ...` (Claude keeps its older text and structured answer beside it). Codex and Grok have no launch preflight and stop at their own login screen. A status check that cannot be read is not this code.
776
+
775
777
  Set `throughline_source_session` together with a non-empty mission in `prompt` to prepend
776
778
  Throughline's read-only handoff context. This optional route requires `throughline >= 0.9.0`,
777
779
  cannot be combined with `launch_operation_id`, and leaves the source session's database ownership
@@ -5,7 +5,9 @@ import { AitermError } from "./errors.js";
5
5
  import { executionNativeBindingSchema } from "./execution-close.js";
6
6
  import { OPERATION_ID_RE, agentManagedClaudeSettingsPath, agentClaudeResultPath, agentClaudeCallerPromptPath, agentClaudeCallerMcpPath } from "./harnesses/claude.js";
7
7
  import { agentCodexCallerPromptPath, agentCodexCallerMcpPath } from "./harnesses/codex.js";
8
- import { resolveAndValidateGrokAuth } from "./harnesses/grok.js";
8
+ import { resolveAndValidateGrokAuth, agentGrokCallerPromptPath, agentGrokCallerAgentPath } from "./harnesses/grok.js";
9
+ import { agentCursorCallerPromptPath, agentCursorCallerPluginDir } from "./harnesses/cursor.js";
10
+ import { agentAntigravityCallerPromptPath, agentAntigravityCallerDir } from "./harnesses/antigravity.js";
9
11
  import { assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, agentEventPath, agentLineageFields, LAUNCH_ID_RE, AGENT_LINEAGE_RE } from "./agent-shared.js";
10
12
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
11
13
  function normalizeInitialPromptState(v) {
@@ -134,6 +136,8 @@ export function loadAgentMetadata(name) {
134
136
  vendor_session_id: m.vendor_session_id ?? null, initial_prompt: normalizeInitialPromptState(m.initial_prompt),
135
137
  hook_route: "shared_antigravity_home", antigravity_home: m.antigravity_home, node_platform: process.platform,
136
138
  ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
139
+ ...(m.antigravity_caller_prompt_file === agentAntigravityCallerPromptPath(name) ? { antigravity_caller_prompt_file: m.antigravity_caller_prompt_file } : {}),
140
+ ...(m.antigravity_caller_mcp_dir === agentAntigravityCallerDir(name) ? { antigravity_caller_mcp_dir: m.antigravity_caller_mcp_dir } : {}),
137
141
  ...deliveryFields, ...executableFields, ...fastFields, ...startupFields, ...loadAgentLineageFields(m, true) };
138
142
  }
139
143
  if (m.kind === "claude") {
@@ -242,6 +246,8 @@ export function loadAgentMetadata(name) {
242
246
  completion_route: "cursor_transcript",
243
247
  ...loadAgentLineageFields(m, true),
244
248
  node_platform: process.platform,
249
+ ...(m.cursor_caller_prompt_file === agentCursorCallerPromptPath(name) ? { cursor_caller_prompt_file: m.cursor_caller_prompt_file } : {}),
250
+ ...(m.cursor_caller_mcp_dir === agentCursorCallerPluginDir(name) ? { cursor_caller_mcp_dir: m.cursor_caller_mcp_dir } : {}),
245
251
  cursor_home: recordedHome,
246
252
  };
247
253
  }
@@ -279,6 +285,8 @@ export function loadAgentMetadata(name) {
279
285
  completion_route: "grok_transcript",
280
286
  ...loadAgentLineageFields(m, true),
281
287
  node_platform: process.platform,
288
+ ...(m.grok_caller_prompt_file === agentGrokCallerPromptPath(name) ? { grok_caller_prompt_file: m.grok_caller_prompt_file } : {}),
289
+ ...(m.grok_caller_mcp_file === agentGrokCallerAgentPath(name) ? { grok_caller_mcp_file: m.grok_caller_mcp_file } : {}),
282
290
  grok_home: recordedGrokHome,
283
291
  grok_auth_path: expectedAuthPath,
284
292
  };
package/dist/core.js CHANGED
@@ -26,6 +26,7 @@ import * as fs from "node:fs";
26
26
  import * as path from "node:path";
27
27
  import { createHash, randomBytes } from "node:crypto";
28
28
  import { launchEnvValue } from "./private-env.js";
29
+ import { assertCallerEnv } from "./harnesses/caller-mcp.js";
29
30
  import { fileURLToPath } from "node:url";
30
31
  import * as rtk from "./rtk.js";
31
32
  import { manageClaudeAgentGoal, manageGrokAgentGoal } from "./agent-goal-native-result.js";
@@ -47,16 +48,16 @@ import { withExecutionInterruptEffectScope, bindExecutionNativeTarget, beforeExe
47
48
  import { ExecutionError } from "./execution-wire.js";
48
49
  import { readExecutionParentProcess } from "./execution-parent-process.js";
49
50
  import { isCursorMcpClient } from "aiterm-steer-delivery";
50
- import { antigravityBinding, antigravityAuthChoiceKey, antigravityCurrentModel, antigravityStartupAction, antigravityAgentArgv, antigravityModelChoices, antigravityAuthStatus, antigravityAuthPane, antigravityTranscriptText, bindAntigravitySession, createAntigravityAgentMetadata, mergeAntigravityHooks } from "./harnesses/antigravity.js";
51
+ import { antigravityBinding, antigravityAuthChoiceKey, antigravityCurrentModel, antigravityStartupAction, antigravityAgentArgv, writeAntigravityCallerFiles, checkAntigravityCallerInput, antigravityPromptWithCaller, antigravityModelChoices, antigravityAuthStatus, antigravityAuthPane, antigravityTranscriptText, bindAntigravitySession, createAntigravityAgentMetadata, mergeAntigravityHooks } from "./harnesses/antigravity.js";
51
52
  import { paneTokenHint } from "./harnesses/pane-tokens.js";
52
53
  import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
53
54
  import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
54
55
  import { liveNodeExecutable } from "./live-node.js";
55
56
  import { resolveClaudeConfigurationRoot, withClaudeConfigRoot } from "./claude-config-root.js";
56
57
  import { probeWriteBan, writeBanPrefix, windowsWriteBanArgv } from "./write-ban.js";
57
- import { AitermError, AgentResumeUnavailableError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
58
+ import { AitermError, launchAuthRequired, launchInputRefusal, AgentResumeUnavailableError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
58
59
  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";
59
- import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, writeText0600, 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";
60
+ import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, writeText0600, 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, } from "./agent-shared.js";
60
61
  import { AuthResponseError, authUi, authPromptDigest, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
61
62
  import { processStartIdentity } from "./runtime-error-os.js";
62
63
  import { processStartIdentities } from "./process-start.js";
@@ -64,10 +65,10 @@ import { catalogUnavailable } from "./model-catalog.js";
64
65
  import { FastModeError, fastModeFailure } from "./fast-mode.js";
65
66
  import { readFileOrNull, restoreJsonSetting, withUserConfigLock, restoreUserDefaults, keepingUserDefaults, USER_DEFAULT_SETTLE_MS } from "./user-config.js";
66
67
  import { isDeepStrictEqual } from "node:util";
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";
68
+ import { grokAuthPlan, grokAuthStatus, grokAuthPane, GROK_MODEL_DEFAULTS, realGrokHome, resolveAndValidateGrokAuth, assertGrokModelAvailable, grokModelChoices, grokModelFromFooter, grokFooterModelName, grokModelDefaultsFromBody, restoreGrokModelDefaults, grokEventsTranscript, grokSessionDirectory, latestGrokCompletion, grokTurnSettled, observeGrokDone, buildGrokAgentCmd, grokAgentArgv, writeGrokCallerFiles, checkGrokCallerInput, grokLaunchNote, grokEnvTokens, grokEnvEntries, grokTuiReady, grokPaneObservation, GROK_INTERRUPT_KEY, grokRateLimitDialog, grokPromptAwaitingAccept, grokUnacceptedPromptRestored, grokStartupAction, grokFooterHasConfiguration, grokTranscriptText, createGrokAgentMetadata, } from "./harnesses/grok.js";
68
69
  import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, codexWorkingResumeConfiguration, captureCodexRecoveryProof, captureCodexResumeProof, readCodexResumeProof, codexResumeProofDigest, codexRootTranscript, codexRolloutSessionId, codexRunningTurn, codexInterruptionRecord, observeCodexDone, buildCodexAgentCmd, codexAgentArgv, codexResumeArgv, writeCodexCallerFiles, refuseCodexCallerInput, codexLaunchNote, codexPaneObservation, CODEX_INTERRUPT_KEY, codexHelperProcess, codexRateLimitModelSwitchDialog, codexApprovalDialog, codexStartupAction, codexModelChoice, codexEffortChoice, codexMoreReasoningChoice, codexTranscriptText, createCodexAgentMetadata, codexModelChoices, codexFastCommandOffered, codexFooterShowsFast, codexServiceTierNotices, restoreCodexDefaults, restoreCodexDefaultInFile, } from "./harnesses/codex.js";
69
70
  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";
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";
71
+ 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, cursorLineagePreface, writeCursorCallerFiles, checkCursorCallerInput, createCursorAgentMetadata, cursorLaunchNote, cursorEffortNavigation, cursorTuiReady, cursorPaneObservation, CURSOR_INTERRUPT_KEY, cursorPromptHooksRunning, cursorUsageLimit, CURSOR_SUBMIT_SEQUENCE, validateCursorModelEffort, } from "./harnesses/cursor.js";
71
72
  import { interimFromNow, interimFromToken, readInterimWords, recordInterimBoundary } from "./interim-words.js";
72
73
  import { codexSeatTurn, grokSteerAcceptance, observeSteerDone, readSteerEntry, recordSteer } from "./steer-follow.js";
73
74
  import { resolveAgentBin, resolveThroughlineBin, runThroughlineHandoffContext, isWindowsNativeExecutable, isUsableAgentExecutableFile, agentBinForPaneShell, resolveWinPaneShell, windowsAgentArgv, windowsAgentLaunchLine, windowsLaunchIndirection } from "./agent-resolver.js";
@@ -394,6 +395,10 @@ function cleanupAgentState(name) {
394
395
  f.endsWith(".claude-caller-mcp.json") ||
395
396
  f.endsWith(".codex-caller-prompt.md") ||
396
397
  f.endsWith(".codex-caller-mcp.json") ||
398
+ f.endsWith(".grok-caller-prompt.md") ||
399
+ f.endsWith(".grok-caller-agent.md") ||
400
+ f.endsWith(".cursor-caller-prompt.md") ||
401
+ f.endsWith(".antigravity-caller-prompt.md") ||
397
402
  f.endsWith(".launch-env") ||
398
403
  f.endsWith(".claude-result.json") ||
399
404
  f.endsWith(".cursor-result.json") ||
@@ -406,7 +411,7 @@ function cleanupAgentState(name) {
406
411
  f.endsWith(".steers.jsonl") ||
407
412
  f.endsWith(".auth.json"))
408
413
  fs.unlinkSync(p);
409
- else if (f.endsWith(".seat-span.d") || f.endsWith(".codex-home") || f.endsWith(".grok-home") || f.endsWith(".cursor-plugin") || f.endsWith(".home") || f.endsWith(".resume-restore.d")) {
414
+ else if (f.endsWith(".seat-span.d") || f.endsWith(".codex-home") || f.endsWith(".grok-home") || f.endsWith(".cursor-plugin") || f.endsWith(".antigravity-caller") || f.endsWith(".home") || f.endsWith(".resume-restore.d")) {
410
415
  fs.rmSync(p, { recursive: true, force: true });
411
416
  }
412
417
  }
@@ -4667,7 +4672,7 @@ async function sendInitialAgentPromptInLock(name, text, o) {
4667
4672
  startupBlockedHint(startup.reason), 2);
4668
4673
  }
4669
4674
  await o.after_ready?.(name, meta);
4670
- const promptText = meta.kind === "cursor" ? cursorPromptWithLineage(meta, text) : text;
4675
+ const promptText = meta.kind === "cursor" ? cursorPromptWithLineage(meta, text) : meta.kind === "antigravity" ? antigravityPromptWithCaller(meta, text) : text;
4671
4676
  const startOffset = agentCompletionCursor(meta);
4672
4677
  const inputId = meta.kind === "claude" ? randomBytes(16).toString("hex") : undefined;
4673
4678
  try {
@@ -7073,7 +7078,7 @@ async function dispatchAgentTurnInLock(name, text, o, pendingSend) {
7073
7078
  // 画面の確かめを飛ばす送信(force)と、加工なしの送信(raw)には、既定の前置きを打たない(打った文は入力欄がそのまま読む)。
7074
7079
  const prefaced = splitAgentPreface(meta.kind, o.preface, text, { defaultForWrapped: !o.force && !o.raw });
7075
7080
  const dispatchText = meta.kind === "cursor" && !meta.vendor_session_id
7076
- ? `${subagentInstruction(meta)}\n\n${prefaced.body}`
7081
+ ? `${cursorLineagePreface(meta)}\n\n${prefaced.body}`
7077
7082
  : prefaced.body;
7078
7083
  prepareSendText(dispatchText, { raw: o.raw });
7079
7084
  const inputId = meta.kind === "claude" ? randomBytes(16).toString("hex") : undefined;
@@ -7509,7 +7514,7 @@ function buildAgentCmd(kind, bin, model, effort, prompt, meta = null, cursorFast
7509
7514
  if (kind === "cursor")
7510
7515
  return buildCursorAgentCmd(bin, model, effort, prompt, meta, cursorFast);
7511
7516
  if (kind === "antigravity")
7512
- return antigravityAgentArgv(bin, model, effort, prompt).map(shq).join(" ");
7517
+ return antigravityAgentArgv(bin, model, effort, prompt, meta).map(shq).join(" ");
7513
7518
  return buildGrokAgentCmd(kind, bin, model, effort, prompt, meta);
7514
7519
  }
7515
7520
  /**
@@ -7723,6 +7728,8 @@ function prepareAgentLaunch(kind, opts = {}) {
7723
7728
  assertCursorAuthenticationReady(bin);
7724
7729
  if (kind === "antigravity") {
7725
7730
  const auth = antigravityAuthStatus(bin, cwd ?? process.cwd());
7731
+ if (auth.status === "unauthenticated")
7732
+ throw launchAuthRequired("antigravity-cli", `${auth.message}`);
7726
7733
  if (auth.status !== "authenticated")
7727
7734
  throw new AitermError(`ANTIGRAVITY_AUTH_REQUIRED: ${auth.message}`, 2);
7728
7735
  const catalog = antigravityModelChoices(bin, cwd ?? process.cwd());
@@ -7803,6 +7810,12 @@ function prepareAgentLaunch(kind, opts = {}) {
7803
7810
  writeClaudeCallerFiles(meta, opts.append_system_prompt ?? null, opts.mcp_config ?? null);
7804
7811
  if (meta.kind === "codex")
7805
7812
  writeCodexCallerFiles(meta, opts.append_system_prompt ?? null, opts.mcp_config ?? null);
7813
+ if (meta.kind === "grok" || meta.kind === "cursor" || meta.kind === "antigravity") {
7814
+ // The seat's own environment: what ${NAME} in a header resolves to (and what a harness reads at run time).
7815
+ const seatEnv = new Map(agentEnvEntries(meta, sid, envVars));
7816
+ const write = meta.kind === "grok" ? writeGrokCallerFiles : meta.kind === "cursor" ? writeCursorCallerFiles : writeAntigravityCallerFiles;
7817
+ write(meta, opts.append_system_prompt ?? null, opts.mcp_config ?? null, name => seatEnv.get(name));
7818
+ }
7806
7819
  if (opts.fork_of)
7807
7820
  meta.fork_of = opts.fork_of;
7808
7821
  if (isWin && ["claude", "codex", "grok", "antigravity"].includes(kind))
@@ -7842,7 +7855,7 @@ function prepareAgentLaunch(kind, opts = {}) {
7842
7855
  const argv = kind === "claude" ? claudeAgentArgv(bin, model, effort, prompt, meta)
7843
7856
  : kind === "codex" ? codexAgentArgv(bin, model, effort, prompt, meta)
7844
7857
  : kind === "cursor" ? cursorAgentArgv(bin, model, effort, prompt, meta, cursorFast)
7845
- : kind === "antigravity" ? antigravityAgentArgv(bin, model, effort, prompt)
7858
+ : kind === "antigravity" ? antigravityAgentArgv(bin, model, effort, prompt, meta)
7846
7859
  : grokAgentArgv(kind, bin, model, effort, prompt, meta);
7847
7860
  full = windowsAgentLaunchLine(cwd, [
7848
7861
  ...claudeRootEntries, ...(meta?.kind === "grok" ? grokEnvEntries(meta) : []), ...agentEnvEntries(meta, sid, envVars),
@@ -8035,10 +8048,27 @@ export function resolveForkSource(kind, from, opts, probe = probeWriteBan) {
8035
8048
  return { fork_of: { session_id: from.session_id, vendor_session_id: mainVendorId, ...(from.fork_id ? { fork_id: from.fork_id } : {}),
8036
8049
  write_ban, ...(first_input ? { first_input } : {}) }, cwd: main.cwd, ...(root ? { root } : {}) };
8037
8050
  }
8051
+ /** Caller launch fields refused from the arguments alone, before any session or file exists (phase "input"). */
8052
+ function refuseCallerInput(kind, opts) {
8053
+ if (kind === "codex")
8054
+ return refuseCodexCallerInput(opts.append_system_prompt, opts.mcp_config);
8055
+ if (kind !== "grok" && kind !== "cursor" && kind !== "antigravity")
8056
+ return;
8057
+ try {
8058
+ const servers = (kind === "grok" ? checkGrokCallerInput : kind === "cursor" ? checkCursorCallerInput : checkAntigravityCallerInput)(opts.append_system_prompt, opts.mcp_config);
8059
+ // Cursor puts the text in the seat's first dispatch whatever it is; agy's only channel is the launch prompt itself.
8060
+ if (kind === "antigravity" && opts.append_system_prompt != null && opts.prompt == null && opts.throughline_source_session == null)
8061
+ throw new AitermError("append_system_prompt needs a prompt for antigravity-cli (agy has no instruction channel; the text prefixes the first prompt)", 2);
8062
+ const envVars = opts.env_vars ?? [];
8063
+ assertCallerEnv(kind.toUpperCase(), servers, name => envVars.includes(name) ? launchEnvValue(name) : undefined, true);
8064
+ }
8065
+ catch (e) {
8066
+ throw e instanceof AitermError ? launchInputRefusal(agentHarness(kind), e.message) : e;
8067
+ }
8068
+ }
8038
8069
  export async function openAgentWithInitialPrompt(kind, opts = {}) {
8039
8070
  // Caller launch fields: refused from the arguments alone, before any session or file exists (phase "input").
8040
- if (kind === "codex")
8041
- refuseCodexCallerInput(opts.append_system_prompt, opts.mcp_config);
8071
+ refuseCallerInput(kind, opts);
8042
8072
  const fork = opts.fork_from ? resolveForkSource(kind, opts.fork_from, opts) : null;
8043
8073
  if (opts.configuration_root != null && kind !== "claude")
8044
8074
  throw new AitermError("AGENT_CONFIGURATION_ROOT_REJECTED: configuration_rootはclaude-code harnessだけで使えます。", 2);
package/dist/errors.js CHANGED
@@ -21,6 +21,12 @@ export function launchInputRefusal(harness, reason) {
21
21
  error.launchNotStarted = { harness, phase: "input" };
22
22
  return error;
23
23
  }
24
+ /** The harness CLI is not logged in; the launch is refused before any session exists (remote-terminal.md R18, code AGENT_AUTH_REQUIRED). */
25
+ export function launchAuthRequired(harness, reason) {
26
+ const error = new AitermError(`AGENT_LAUNCH_NOT_STARTED: AGENT_AUTH_REQUIRED: ${reason}`, 2);
27
+ error.launchNotStarted = { harness, phase: "input", code: "AGENT_AUTH_REQUIRED" };
28
+ return error;
29
+ }
24
30
  /** A harness authentication check refused launch before any session creation.
25
31
  * Keep the native CLI's status body and credential diagnostics out of the wire. */
26
32
  export class AgentAuthenticationPreflightError extends AitermError {
@@ -10,7 +10,8 @@ import { checkedCatalog, catalogInvalid, catalogUnavailable } from "../model-cat
10
10
  import { spawnAgentControlCommand } from "../agent-resolver.js";
11
11
  import { liveNodeExecutable } from "../live-node.js";
12
12
  import { powershellInvocation } from "../windows-powershell.js";
13
- import { agentEventPath, agentLineageFields, agentsDir, createEmpty0600, readFileRange, safeStatSize, shq, writeAgentMetadata, writeJson0600 } from "../agent-shared.js";
13
+ import { agentEventPath, agentLineageFields, agentsDir, assertSessionName, createEmpty0600, writeText0600, readFileRange, safeStatSize, shq, writeAgentMetadata, writeJson0600 } from "../agent-shared.js";
14
+ import { assertCallerEnv, checkCallerInput, readCallerText, resolveCallerHeader, writeCallerJson } from "./caller-mcp.js";
14
15
  import { authUrl } from "../agent-auth.js";
15
16
  // agy 1.4.10 exposes effort-specific IDs; overriding an ID's effort is rejected by the CLI.
16
17
  export function antigravityCatalog(stdout, selected) {
@@ -190,8 +191,52 @@ export function createAntigravityAgentMetadata(name, cwd, initial, writeScope, l
190
191
  writeAgentMetadata(meta);
191
192
  return meta;
192
193
  }
193
- export function antigravityAgentArgv(bin, model, effort, prompt) {
194
- return [bin, "--dangerously-skip-permissions", "--settings", '{"queuedMessages":"send-immediately"}', ...(model ? ["--model", model] : []), ...(effort ? ["--effort", effort] : []), ...(prompt ? ["--prompt-interactive", prompt] : [])];
194
+ // ---- Caller launch fields (launch-identity-input.md "Caller launch fields"). agy has no per-run instruction channel Aiterm could
195
+ // prove (the .agents/rules route was not confirmed), so the text prefixes the first prompt; the servers are .agents/mcp_config.json
196
+ // in a per-seat folder passed as --add-dir. Both live in Aiterm state (0600 files), never in ~/.gemini or the project.
197
+ export function agentAntigravityCallerPromptPath(name) {
198
+ assertSessionName(name);
199
+ return path.join(agentsDir(), `${name}.antigravity-caller-prompt.md`);
200
+ }
201
+ export function agentAntigravityCallerDir(name) {
202
+ assertSessionName(name);
203
+ return path.join(agentsDir(), `${name}.antigravity-caller`);
204
+ }
205
+ /** agy does not expand header references, so every ${NAME} is written as the seat's value. */
206
+ export function antigravityCallerMcpJson(servers, valueOf) {
207
+ return { mcpServers: Object.fromEntries(servers.map(server => [server.name, {
208
+ serverUrl: server.url,
209
+ ...(server.headers.length ? { headers: Object.fromEntries(server.headers.map(header => [header.name, resolveCallerHeader("ANTIGRAVITY", header, valueOf)])) } : {}),
210
+ }])) };
211
+ }
212
+ export function checkAntigravityCallerInput(prompt, mcp) {
213
+ return checkCallerInput("ANTIGRAVITY", prompt, mcp);
214
+ }
215
+ export function writeAntigravityCallerFiles(meta, prompt, mcp, valueOf) {
216
+ const servers = checkAntigravityCallerInput(prompt, mcp);
217
+ assertCallerEnv("ANTIGRAVITY", servers, valueOf);
218
+ if (prompt !== null) {
219
+ const file = agentAntigravityCallerPromptPath(meta.aiterm_session);
220
+ writeText0600(file, prompt);
221
+ meta.antigravity_caller_prompt_file = file;
222
+ }
223
+ if (mcp !== null) {
224
+ const dir = agentAntigravityCallerDir(meta.aiterm_session);
225
+ writeCallerJson(path.join(dir, ".agents", "mcp_config.json"), antigravityCallerMcpJson(servers, valueOf));
226
+ meta.antigravity_caller_mcp_dir = dir;
227
+ }
228
+ }
229
+ /** The first prompt with the caller's text in front (the seat's only instruction channel here). */
230
+ export function antigravityPromptWithCaller(meta, prompt) {
231
+ const caller = readCallerText(meta.antigravity_caller_prompt_file);
232
+ return caller === null ? prompt : `${caller}\n\n${prompt}`;
233
+ }
234
+ export function antigravityAgentArgv(bin, model, effort, prompt, meta) {
235
+ // The seat folder and the cwd are trusted by --settings, or agy asks and then writes settings.json in ~/.gemini.
236
+ const folder = meta?.antigravity_caller_mcp_dir;
237
+ const trusted = folder ? [...new Set([meta.cwd, meta.cwd && fs.existsSync(meta.cwd) ? fs.realpathSync(meta.cwd) : null, folder].filter((item) => !!item))] : [];
238
+ const settings = JSON.stringify({ queuedMessages: "send-immediately", ...(folder ? { trustedWorkspaces: trusted } : {}) });
239
+ return [bin, "--dangerously-skip-permissions", "--settings", settings, ...(folder ? ["--add-dir", folder] : []), ...(model ? ["--model", model] : []), ...(effort ? ["--effort", effort] : []), ...(prompt ? ["--prompt-interactive", prompt] : [])];
195
240
  }
196
241
  export function antigravityBindingFile(meta) {
197
242
  return path.join(agentsDir(), `${meta.aiterm_session}.${meta.launch_id}.antigravity-session.json`);
@@ -0,0 +1,94 @@
1
+ // Caller launch fields (launch-identity-input.md "Caller launch fields") shared by grok-cli, cursor-cli and antigravity-cli:
2
+ // one reading of `mcp_config` and the checks that decide, before any seat exists, whether a harness can carry it.
3
+ // Codex keeps its own copy of the same rules (codex.ts codexMcpOverrides) and error codes.
4
+ import * as fs from "node:fs";
5
+ import * as path from "node:path";
6
+ import { AitermError } from "../errors.js";
7
+ import { writeJson0600 } from "../agent-shared.js";
8
+ // The text travels in one argv element (Linux caps one at 128 KiB) or the typed first prompt.
9
+ export const CALLER_PROMPT_MAX = 64 * 1024;
10
+ const MCP_SERVER_NAME = /^[A-Za-z0-9_-]{1,64}$/;
11
+ const HEADER_NAME = /^[A-Za-z0-9-]{1,128}$/;
12
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
13
+ // Names every seat has whatever env_vars says (core.ts agentEnvEntries), known before the seat exists.
14
+ const SEAT_ENV_NAMES = new Set(["AITERM_SESSION_ID", "AITERM_AGENT_SESSION_ID", "AITERM_AGENT_LAUNCH_ID"]);
15
+ /** `mcp_config` -> servers. Refuses (<LABEL>_MCP_CONFIG_UNSUPPORTED) what an http server table with env-named headers cannot say. */
16
+ export function parseCallerMcp(mcp, label) {
17
+ const refuse = (message) => { throw new AitermError(`${label}_MCP_CONFIG_UNSUPPORTED: ${message}`, 2); };
18
+ const servers = mcp?.mcpServers;
19
+ if (!mcp || typeof mcp !== "object" || Object.keys(mcp).some(key => key !== "mcpServers") || !servers || typeof servers !== "object" || Array.isArray(servers))
20
+ return refuse("mcp_config must be {mcpServers: {...}}");
21
+ return Object.entries(servers).map(([name, server]) => {
22
+ if (!MCP_SERVER_NAME.test(name))
23
+ return refuse(`server name '${name}' must be letters, digits, '_' or '-'`);
24
+ const spec = server;
25
+ if (!spec || typeof spec !== "object" || Array.isArray(spec))
26
+ return refuse(`server '${name}' must be an object`);
27
+ if (Object.keys(spec).some(key => !["type", "url", "headers"].includes(key)))
28
+ return refuse(`server '${name}' may only have type, url and headers`);
29
+ if (spec.type !== undefined && spec.type !== "http")
30
+ return refuse(`server '${name}': only type 'http' is supported here (got '${String(spec.type)}')`);
31
+ let url = null;
32
+ try {
33
+ url = typeof spec.url === "string" ? new URL(spec.url) : null;
34
+ }
35
+ catch { /* refused below */ }
36
+ if (!url || (url.protocol !== "http:" && url.protocol !== "https:"))
37
+ return refuse(`server '${name}': url must be an http(s) URL`);
38
+ if (spec.headers !== undefined && (!spec.headers || typeof spec.headers !== "object" || Array.isArray(spec.headers)))
39
+ return refuse(`server '${name}': headers must be an object`);
40
+ const seen = new Set();
41
+ const headers = Object.entries((spec.headers ?? {})).map(([header, value]) => {
42
+ if (!HEADER_NAME.test(header) || typeof value !== "string")
43
+ return refuse(`server '${name}': header '${header}' must be a plain name with a string value`);
44
+ if (seen.has(header.toLowerCase()))
45
+ return refuse(`server '${name}': header '${header}' is given twice`);
46
+ seen.add(header.toLowerCase());
47
+ const bearer = header.toLowerCase() === "authorization" ? /^Bearer \$\{([^}]*)\}$/.exec(value)?.[1] : undefined;
48
+ const whole = /^\$\{([^}]*)\}$/.exec(value)?.[1];
49
+ if (bearer !== undefined || whole !== undefined) {
50
+ const envName = (bearer ?? whole);
51
+ if (!ENV_NAME.test(envName))
52
+ return refuse(`server '${name}': header '${header}' names an invalid environment variable`);
53
+ return { name: header, kind: bearer !== undefined ? "bearer" : "env", value: envName };
54
+ }
55
+ if (value.includes("${"))
56
+ return refuse(`server '${name}': header '${header}' mixes text with \${NAME}; only the whole value or 'Bearer \${NAME}' can be given`);
57
+ return { name: header, kind: "literal", value };
58
+ });
59
+ return { name, url: spec.url, headers };
60
+ });
61
+ }
62
+ /** The text and servers of a caller input, or the refusal. `null` mcp -> no servers. */
63
+ export function checkCallerInput(label, prompt, mcp) {
64
+ if (prompt != null && (!prompt.trim() || Buffer.byteLength(prompt, "utf8") > CALLER_PROMPT_MAX))
65
+ throw new AitermError(`append_system_prompt must be non-empty and at most 64 KiB for ${label.toLowerCase()}`, 2);
66
+ return mcp == null ? [] : parseCallerMcp(mcp, label);
67
+ }
68
+ /** Every `${NAME}` the servers name must have a value at launch, or the seat would start with an empty secret. */
69
+ export function assertCallerEnv(label, servers, valueOf, preStart = false) {
70
+ for (const server of servers)
71
+ for (const header of server.headers) {
72
+ if (header.kind === "literal")
73
+ continue;
74
+ if (valueOf(header.value) === undefined && !(preStart && SEAT_ENV_NAMES.has(header.value)))
75
+ throw new AitermError(`${label}_MCP_ENV_UNAVAILABLE: header '${header.name}' of server '${server.name}' uses \${${header.value}}, which has no value at launch; list ${header.value} in env_vars`, 2);
76
+ }
77
+ }
78
+ /** The header value with every `${NAME}` replaced by the seat's value (for a harness that does not expand them). */
79
+ export function resolveCallerHeader(label, header, valueOf) {
80
+ if (header.kind === "literal")
81
+ return header.value;
82
+ const value = valueOf(header.value);
83
+ if (value === undefined || value === "")
84
+ throw new AitermError(`${label}_MCP_ENV_UNAVAILABLE: \${${header.value}} has no value at launch`, 2);
85
+ return header.kind === "bearer" ? `Bearer ${value}` : value;
86
+ }
87
+ /** 0600 file inside a seat folder (created 0700) of Aiterm's launch state. */
88
+ export function writeCallerJson(file, value) {
89
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
90
+ writeJson0600(file, value);
91
+ }
92
+ export function readCallerText(file) {
93
+ return file ? fs.readFileSync(file, "utf8") : null;
94
+ }
@@ -5,11 +5,12 @@ import * as fs from "node:fs";
5
5
  import * as os from "node:os";
6
6
  import * as path from "node:path";
7
7
  import { randomBytes } from "node:crypto";
8
- import { AitermError } from "../errors.js";
8
+ import { AitermError, launchAuthRequired } from "../errors.js";
9
9
  import { spawnAgentControlCommand } from "../agent-resolver.js";
10
10
  import { checkedCatalog } from "../model-catalog.js";
11
11
  import { FastModeError } from "../fast-mode.js";
12
- import { AGENT_DONE_POLL_MS, CURSOR_SCREEN_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, agentEventPath, agentHarness, agentLineageFields, agentMetadataPath, createEmpty0600, readFileRange, safeStatSize, shq, sleep, subagentInstruction, writeAgentMetadata, writeScopeLaunchNote, } from "../agent-shared.js";
12
+ import { AGENT_DONE_POLL_MS, CURSOR_SCREEN_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, agentEventPath, agentHarness, agentLineageFields, agentMetadataPath, agentsDir, assertSessionName, createEmpty0600, readFileRange, safeStatSize, shq, sleep, subagentInstruction, writeAgentMetadata, writeScopeLaunchNote, writeText0600, } from "../agent-shared.js";
13
+ import { assertCallerEnv, checkCallerInput, readCallerText, writeCallerJson } from "./caller-mcp.js";
13
14
  const CURSOR_TRANSCRIPT_MATCH_MAX_BYTES = 1024 * 1024;
14
15
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
15
16
  // Cursor Agentはextended keyboard protocolを有効にするため、通常のtmux Enterではなく
@@ -508,12 +509,49 @@ export function assertCursorAuthenticationReady(bin) {
508
509
  if (result.error == null && result.status === 0 && !/not logged in|unauthenticated|sign in/i.test(output))
509
510
  return;
510
511
  if (/not logged in|unauthenticated|sign in/i.test(output)) {
511
- throw new AitermError("Cursor Agent CLIが未認証です。sessionは作成していません。通常端末で公式の `agent login` を一度だけ完了してください。", 2);
512
+ throw launchAuthRequired("cursor-cli", "Cursor Agent CLIが未認証です。sessionは作成していません。通常端末で公式の `agent login` を一度だけ完了してください。");
512
513
  }
513
514
  const timedOut = result.error && result.error.code === "ETIMEDOUT";
514
515
  throw new AitermError(`Cursor Agent CLIの認証状態を起動前に確認できません${timedOut ? "(5秒でtimeout)" : ""}。sessionは作成していません。` +
515
516
  "通常端末で `agent status` が成功することを確認してください。", 2);
516
517
  }
518
+ // ---- Caller launch fields (launch-identity-input.md "Caller launch fields"). Cursor has no per-run instruction channel, so the
519
+ // text joins Aiterm's first-prompt block; the servers are a per-seat plugin folder passed as --plugin-dir. Both live in Aiterm state.
520
+ export function agentCursorCallerPromptPath(name) {
521
+ assertSessionName(name);
522
+ return path.join(agentsDir(), `${name}.cursor-caller-prompt.md`);
523
+ }
524
+ /** The plugin folder's name becomes part of each server's name (plugin-aiterm-caller-<name>), so it is fixed under a per-seat parent. */
525
+ export function agentCursorCallerPluginDir(name) {
526
+ assertSessionName(name);
527
+ return path.join(agentsDir(), `${name}.cursor-plugin`, "aiterm-caller");
528
+ }
529
+ /** Cursor expands ${env:NAME} in headers from the seat's environment, so no secret value is written. */
530
+ export function cursorCallerMcpJson(servers) {
531
+ return { mcpServers: Object.fromEntries(servers.map(server => [server.name, {
532
+ url: server.url,
533
+ ...(server.headers.length ? { headers: Object.fromEntries(server.headers.map(header => [header.name,
534
+ header.kind === "bearer" ? `Bearer \${env:${header.value}}` : header.kind === "env" ? `\${env:${header.value}}` : header.value])) } : {}),
535
+ }])) };
536
+ }
537
+ export function checkCursorCallerInput(prompt, mcp) {
538
+ return checkCallerInput("CURSOR", prompt, mcp);
539
+ }
540
+ export function writeCursorCallerFiles(meta, prompt, mcp, valueOf) {
541
+ const servers = checkCursorCallerInput(prompt, mcp);
542
+ assertCallerEnv("CURSOR", servers, valueOf);
543
+ if (prompt !== null) {
544
+ const file = agentCursorCallerPromptPath(meta.aiterm_session);
545
+ writeText0600(file, prompt);
546
+ meta.cursor_caller_prompt_file = file;
547
+ }
548
+ if (mcp !== null) {
549
+ const dir = agentCursorCallerPluginDir(meta.aiterm_session);
550
+ writeCallerJson(path.join(dir, ".cursor-plugin", "plugin.json"), { name: "aiterm-caller", version: "1.0.0", description: "MCP servers Aiterm adds for this seat" });
551
+ writeCallerJson(path.join(dir, "mcp.json"), cursorCallerMcpJson(servers));
552
+ meta.cursor_caller_mcp_dir = dir;
553
+ }
554
+ }
517
555
  /** 起動argv(先頭が実行ファイル)。paneのshellに合わせた引用は呼び出し側が行う。 */
518
556
  export function cursorAgentArgv(bin, model, effort, prompt, meta, fast = false) {
519
557
  validateCursorModelEffort(model, effort);
@@ -524,6 +562,8 @@ export function cursorAgentArgv(bin, model, effort, prompt, meta, fast = false)
524
562
  // managed agentは人の対話承認を待てない。Cursor公式の無人運転フラグで
525
563
  // workspace・MCP server・各tool callの確認をadapter内に閉じ込める。
526
564
  parts.push("--force", "--approve-mcps", "--trust");
565
+ if (meta?.kind === "cursor" && meta.cursor_caller_mcp_dir)
566
+ parts.push("--plugin-dir", meta.cursor_caller_mcp_dir);
527
567
  if (meta?.kind === "cursor" && meta.write_scope === "read-only")
528
568
  parts.push("--mode", "ask");
529
569
  if (prompt)
@@ -533,7 +573,7 @@ export function cursorAgentArgv(bin, model, effort, prompt, meta, fast = false)
533
573
  export function buildCursorAgentCmd(bin, model, effort, prompt, meta, fast = false) {
534
574
  // 固定の語彙(--force、--mode ask等)は引用しない。実行ファイル、model、promptだけを引用する。
535
575
  const argv = cursorAgentArgv(bin, model, effort, prompt, meta, fast);
536
- return argv.map((part, index) => index === 0 || argv[index - 1] === "--model" || (prompt !== null && index === argv.length - 1) ? shq(part) : part).join(" ");
576
+ return argv.map((part, index) => index === 0 || argv[index - 1] === "--model" || argv[index - 1] === "--plugin-dir" || (prompt !== null && index === argv.length - 1) ? shq(part) : part).join(" ");
537
577
  }
538
578
  /**
539
579
  * Windows native paneのPowerShell 7で走らせる起動行。WindowsのCursor Agentは、Git Bash配下で起動すると
@@ -541,8 +581,13 @@ export function buildCursorAgentCmd(bin, model, effort, prompt, meta, fast = fal
541
581
  * Git Bash配下は全てprompt_historyだけ残りstore.dbが作られず、PowerShell 7 paneからは同じhookで通る)。
542
582
  */
543
583
  export { windowsAgentLaunchLine as cursorPwshLaunchLine, windowsAgentArgv as cursorPwshArgv } from "../agent-resolver.js";
584
+ /** Aiterm's lineage block, then the caller's text: the one block that precedes the first prompt (Cursor has no system channel). */
585
+ export function cursorLineagePreface(meta) {
586
+ const caller = readCallerText(meta.cursor_caller_prompt_file);
587
+ return caller === null ? subagentInstruction(meta) : `${subagentInstruction(meta)}\n\n${caller}`;
588
+ }
544
589
  export function cursorPromptWithLineage(meta, prompt) {
545
- return `${subagentInstruction(meta)}\n\n${prompt}`;
590
+ return `${cursorLineagePreface(meta)}\n\n${prompt}`;
546
591
  }
547
592
  export function cursorLaunchNote(model, effort, meta) {
548
593
  const effective = cursorModelArgument(model, effort);
@@ -9,8 +9,54 @@ import * as path from "node:path";
9
9
  import { randomBytes, randomUUID } from "node:crypto";
10
10
  import { AitermError } from "../errors.js";
11
11
  import { runAgentProtocolCommand, spawnAgentControlCommand } from "../agent-resolver.js";
12
+ import { assertCallerEnv, checkCallerInput, readCallerText, resolveCallerHeader } from "./caller-mcp.js";
12
13
  import { catalogInvalid, catalogUnavailable, checkedCatalog, findJsonLine, processSummary } from "../model-catalog.js";
13
- import { shq, subagentInstruction, writeScopeLaunchNote, safeStatSize, readFileRange, sleep, agentMetadataPath, writeAgentMetadata, agentEventPath, createEmpty0600, agentLineageFields, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, AGENT_TURN_BOUNDARY_TAIL_BYTES, readTailLinesNewestFirst, GROK_TRANSCRIPT_INCREMENT_MAX_BYTES, agentHarness, } from "../agent-shared.js";
14
+ import { shq, subagentInstruction, writeScopeLaunchNote, safeStatSize, readFileRange, sleep, agentMetadataPath, agentsDir, assertSessionName, writeAgentMetadata, writeText0600, agentEventPath, createEmpty0600, agentLineageFields, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, AGENT_TURN_BOUNDARY_TAIL_BYTES, readTailLinesNewestFirst, GROK_TRANSCRIPT_INCREMENT_MAX_BYTES, agentHarness, } from "../agent-shared.js";
15
+ // ---- Caller launch fields (launch-identity-input.md "Caller launch fields"). The text joins the one --rules value;
16
+ // the servers are a per-seat agent definition passed as --agent. Both files live in Aiterm state (0600), never in ~/.grok or the project.
17
+ export function agentGrokCallerPromptPath(name) {
18
+ assertSessionName(name);
19
+ return path.join(agentsDir(), `${name}.grok-caller-prompt.md`);
20
+ }
21
+ export function agentGrokCallerAgentPath(name) {
22
+ assertSessionName(name);
23
+ return path.join(agentsDir(), `${name}.grok-caller-agent.md`);
24
+ }
25
+ /** Grok does not expand ${VAR} in headers: 'Bearer ${NAME}' is bearer_token_env_var (read from the seat env at run time),
26
+ * any other ${NAME} is written as the seat's value. `mcpServers` must be a LIST of entries (a map keyed by name silently
27
+ * drops the whole file); the body stays empty so the default agent's prompt and tools are unchanged. YAML flow style is JSON. */
28
+ export function grokCallerAgentDefinition(servers, valueOf) {
29
+ const entries = servers.map(server => {
30
+ const headers = {};
31
+ let bearer;
32
+ for (const header of server.headers) {
33
+ if (header.kind === "bearer")
34
+ bearer = header.value;
35
+ else
36
+ headers[header.name] = resolveCallerHeader("GROK", header, valueOf);
37
+ }
38
+ return { name: server.name, type: "http", url: server.url, ...(Object.keys(headers).length ? { headers } : {}), ...(bearer ? { bearer_token_env_var: bearer } : {}) };
39
+ });
40
+ return `---\nname: aiterm-caller\ndescription: MCP servers Aiterm adds for this seat\nmcpServers: ${JSON.stringify(entries)}\n---\n`;
41
+ }
42
+ /** Pre-start check of the caller fields for a Grok launch (the servers, for the env check by the caller). */
43
+ export function checkGrokCallerInput(prompt, mcp) {
44
+ return checkCallerInput("GROK", prompt, mcp);
45
+ }
46
+ export function writeGrokCallerFiles(meta, prompt, mcp, valueOf) {
47
+ const servers = checkGrokCallerInput(prompt, mcp);
48
+ assertCallerEnv("GROK", servers, valueOf);
49
+ if (prompt !== null) {
50
+ const file = agentGrokCallerPromptPath(meta.aiterm_session);
51
+ writeText0600(file, prompt);
52
+ meta.grok_caller_prompt_file = file;
53
+ }
54
+ if (mcp !== null) {
55
+ const file = agentGrokCallerAgentPath(meta.aiterm_session);
56
+ writeText0600(file, grokCallerAgentDefinition(servers, valueOf));
57
+ meta.grok_caller_mcp_file = file;
58
+ }
59
+ }
14
60
  const GROK_MODELS_MAX_BYTES = 1024 * 1024;
15
61
  const GROK_MODELS_TIMEOUT_MS = 15_000;
16
62
  // grok CLI はモデル未指定だと端末側 default に従うため、ツール契約として既定 slug を固定する。
@@ -410,7 +456,10 @@ export function grokAgentArgv(kind, bin, model, effort, prompt, meta) {
410
456
  parts.push("--sandbox", "read-only", "--always-approve");
411
457
  }
412
458
  if (meta?.kind === "grok" && meta.hook_route === "shared_grok_home") {
413
- parts.push("--session-id", meta.vendor_session_id ?? "", "--rules", subagentInstruction(meta));
459
+ // Aiterm's lineage text stays first; the caller's text joins the same value (one --rules).
460
+ parts.push("--session-id", meta.vendor_session_id ?? "", "--rules", subagentInstruction(meta) + (meta.grok_caller_prompt_file ? `\n\n${readCallerText(meta.grok_caller_prompt_file)}` : ""));
461
+ if (meta.grok_caller_mcp_file)
462
+ parts.push("--agent", meta.grok_caller_mcp_file);
414
463
  }
415
464
  if (meta?.kind === "grok" && prompt)
416
465
  parts.push("--verbatim");
@@ -420,7 +469,7 @@ export function grokAgentArgv(kind, bin, model, effort, prompt, meta) {
420
469
  }
421
470
  export function buildGrokAgentCmd(kind, bin, model, effort, prompt, meta) {
422
471
  const argv = grokAgentArgv(kind, bin, model, effort, prompt, meta);
423
- const values = new Set(["--model", "--reasoning-effort", "--session-id", "--rules"]);
472
+ const values = new Set(["--model", "--reasoning-effort", "--session-id", "--rules", "--agent"]);
424
473
  return argv.map((arg, index) => index === 0 || values.has(argv[index - 1]) || (prompt && index === argv.length - 1)
425
474
  ? shq(arg) : arg).join(" ");
426
475
  }
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { loadAgentMetadata } from "./agent-metadata-reader.js";
3
3
  import { remoteInputDescription, remoteInputSchema, terminalArgumentDescription, terminalArgumentSchema } from "./remote-contract.js";
4
- import { boundTerminalTarget, bindTerminalSession, terminalSeatGroups, ensureSeatForward, extractMcpHeaders, maintainSeatForwards, REMOTE_MINIMUM_VERSION, seatIngressPort, checkTerminalPlatform, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
4
+ import { boundTerminalTarget, bindTerminalSession, terminalSeatGroups, ensureSeatForward, extractMcpHeaders, maintainSeatForwards, REMOTE_MINIMUM_VERSION, REMOTE_CLI_OPS_VERSION, seatIngressPort, checkTerminalPlatform, rewriteSeatMcpConfig, terminalRemoteTarget, unbindTerminalSession, versionAtLeast } from "./remote-terminal.js";
5
5
  import { terminalCwdFits } from "./remote-path.js";
6
6
  import { launchEnvValue } from "./private-env.js";
7
7
  import { AuthResponseError, authUiSchema, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
@@ -260,10 +260,11 @@ export function createAitermServer(options = {}) {
260
260
  content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
261
261
  structuredContent: { schema: "aiterm.agent-launch-error.v1", harness: "claude-code", code: e.reasonCode,
262
262
  phase: "authentication_preflight", effect: "not_issued", session_created: false, message: msg },
263
+ ...(e.reasonCode === "CLAUDE_AUTH_NOT_AUTHENTICATED" ? { _meta: launchNotStartedMeta("claude-code", "input", "AGENT_AUTH_REQUIRED") } : {}),
263
264
  };
264
265
  if (e instanceof AitermError && e.launchNotStarted)
265
266
  return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
266
- _meta: launchNotStartedMeta(e.launchNotStarted.harness, e.launchNotStarted.phase) };
267
+ _meta: launchNotStartedMeta(e.launchNotStarted.harness, e.launchNotStarted.phase, e.launchNotStarted.code) };
267
268
  return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true };
268
269
  }
269
270
  /**
@@ -1268,14 +1269,21 @@ export function createAitermServer(options = {}) {
1268
1269
  const FORK_MINIMUM_VERSION = "0.70.6";
1269
1270
  /** First release whose agent_launch takes append_system_prompt / mcp_config for codex-cli, and the first a terminal may run a Codex seat on. */
1270
1271
  const CODEX_REMOTE_MINIMUM_VERSION = "0.70.7";
1272
+ /** The oldest terminal Aiterm per harness: Grok, Cursor and Antigravity seats need 0.70.9 (checked before any private value is sent). */
1273
+ const TERMINAL_MINIMUM_VERSION = {
1274
+ "claude-code": REMOTE_MINIMUM_VERSION, "codex-cli": CODEX_REMOTE_MINIMUM_VERSION,
1275
+ "grok-cli": REMOTE_CLI_OPS_VERSION, "cursor-cli": REMOTE_CLI_OPS_VERSION, "antigravity-cli": REMOTE_CLI_OPS_VERSION,
1276
+ };
1271
1277
  const terminalVersions = new Map();
1272
1278
  /** A seat on a BellTeam terminal (remote-terminal.md "One launch path"). Same launch arguments plus terminal + cwd. */
1273
1279
  async function launchTerminalAgent(harness, terminal, args, extra) {
1274
1280
  try {
1275
1281
  if (args.remote)
1276
1282
  throw new AitermError("TERMINAL_INVALID: use terminal or remote, not both; for a registered terminal pass only terminal", 2);
1277
- if (harness !== "claude-code" && harness !== "codex-cli")
1278
- throw new AitermError(`TERMINAL_HARNESS_UNSUPPORTED: terminal seats support harnesses claude-code and codex-cli; ${harness} is not available on a terminal yet`, 2);
1283
+ const minimum = TERMINAL_MINIMUM_VERSION[harness];
1284
+ // Every real harness is routed since 0.70.9; this only guards a name outside the five.
1285
+ if (!minimum)
1286
+ throw new AitermError(`TERMINAL_HARNESS_UNSUPPORTED: ${harness} is not a harness a terminal can run`, 2);
1279
1287
  const cwdForm = "TERMINAL_INVALID: cwd is required with terminal: the absolute project folder on that terminal in its own form (a POSIX path starting with / on macOS and Linux, X:\\folder with backslashes on Windows; never launch locally and cd)";
1280
1288
  if (!terminalCwdFits(args.cwd, terminal.os))
1281
1289
  throw new AitermError(cwdForm, 2);
@@ -1291,7 +1299,6 @@ export function createAitermServer(options = {}) {
1291
1299
  version = (await callRemoteTool(target, "pty_list", {}, 60_000)).remote_version ?? "0.0.0";
1292
1300
  terminalVersions.set(target.trusted_ref, version);
1293
1301
  }
1294
- const minimum = harness === "codex-cli" ? CODEX_REMOTE_MINIMUM_VERSION : REMOTE_MINIMUM_VERSION;
1295
1302
  if (!versionAtLeast(version, minimum))
1296
1303
  throw new AitermError(`REMOTE_AITERM_TOO_OLD: the terminal runs Aiterm ${version}; ${minimum} or later is required (update Aiterm on the terminal)`, 2);
1297
1304
  const privateEnv = {};
@@ -1519,8 +1526,8 @@ export function createAitermServer(options = {}) {
1519
1526
  launch_operation_id: z.string().regex(/^sha256:[0-9a-f]{64}$/).optional().describe("Claude Codeのpromptなしexact replay相関だけで使用"),
1520
1527
  remote: remoteInputField,
1521
1528
  terminal: terminalArgumentSchema.optional().describe(terminalArgumentDescription),
1522
- append_system_prompt: z.string().min(1).optional().describe("claude-code and codex-cli only. Launch instructions added to the system prompt (Codex: appended to developer_instructions after Aiterm's marker, at most 64 KiB); kept in Aiterm state, not in the project or home. Never put secrets here"),
1523
- mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("claude-code and codex-cli only. Extra MCP servers for this seat. Secret header values: write ${NAME} and list NAME in env_vars. Codex takes only http servers {type?: \"http\", url, headers}: 'Authorization: Bearer ${NAME}' or a header whose whole value is ${NAME}; other shapes are refused before the seat starts"),
1529
+ append_system_prompt: z.string().min(1).optional().describe("Launch instructions added to the system prompt; kept in Aiterm state, not in the project or home. Never put secrets here. Codex: appended to developer_instructions after Aiterm's marker; Grok: appended to --rules; at most 64 KiB for both. Cursor and Antigravity have no system-prompt channel: the text goes in front of the first prompt (Antigravity needs a prompt; at most 64 KiB)"),
1530
+ mcp_config: z.object({ mcpServers: z.record(z.string(), z.unknown()) }).strict().optional().describe("Extra MCP servers for this seat. Secret header values: write ${NAME} and list NAME in env_vars. Codex, Grok, Cursor and Antigravity take only http servers {type?: \"http\", url, headers}: a literal header, 'Authorization: Bearer ${NAME}' or a header whose whole value is ${NAME}; other shapes, and a ${NAME} with no value at launch, are refused before the seat starts. Cursor runs a server as plugin-aiterm-caller-<name> beside a same-name user server; Grok and Antigravity replace a same-name user server for this seat"),
1524
1531
  fork_from: z.object({
1525
1532
  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)"),
1526
1533
  fork_id: z.string().min(1).max(200).optional().describe("Caller's fork ID, passed to the seat as THROUGHLINE_FORK_ID"),
@@ -1550,8 +1557,6 @@ export function createAitermServer(options = {}) {
1550
1557
  write_ban: z.object({ path: z.string(), method: z.enum(["landlock", "seatbelt", "restricted-token"]) }) }).optional().describe("The seat this fork copies and the folder it cannot write"),
1551
1558
  },
1552
1559
  }, async ({ harness, remote, terminal, ...args }, extra) => {
1553
- if (harness !== "claude-code" && harness !== "codex-cli" && (args.append_system_prompt !== undefined || args.mcp_config !== undefined))
1554
- return fail(launchInputRefusal(harness, `append_system_prompt and mcp_config are claude-code and codex-cli only; ${harness} cannot take them`));
1555
1560
  if (terminal)
1556
1561
  return launchTerminalAgent(harness, terminal, { ...args, ...(remote ? { remote } : {}) }, extra);
1557
1562
  if (remote && args.require_existing_resume)
@@ -59,6 +59,6 @@ export const terminalArgumentDescription = "Run this seat on another computer (a
59
59
  "CREDENTIAL_REQUIRED / CREDENTIAL_NOT_LOADED = this terminal's key comes from a credential handle that the registry must load first; never paste a key anywhere. " +
60
60
  "AUTH_FAILED = the terminal refused the key. UNREACHABLE = the terminal is offline; try later. CONNECTION_REFUSED = the terminal refused the SSH connection (SSH may be off there); try later. " +
61
61
  "REMOTE_AITERM_TOO_OLD = update Aiterm on the terminal. CWD_UNAVAILABLE = the folder does not exist there; do not pick another folder. " +
62
- "SEAT_FORWARD_UNAVAILABLE = the seat's MCP route back to this computer is not ready (launch again later), or the seat MCP URLs are not http://127.0.0.1:<one port>/api/seat-mcp. TERMINAL_HARNESS_UNSUPPORTED = use harness claude-code or codex-cli (codex-cli needs Aiterm 0.70.7 on the terminal). " +
62
+ "SEAT_FORWARD_UNAVAILABLE = the seat's MCP route back to this computer is not ready (launch again later), or the seat MCP URLs are not http://127.0.0.1:<one port>/api/seat-mcp. All five harnesses run on a terminal; REMOTE_AITERM_TOO_OLD names the Aiterm version the harness needs there (claude-code 0.65.0, codex-cli 0.70.7, grok-cli / cursor-cli / antigravity-cli 0.70.9). TERMINAL_HARNESS_UNSUPPORTED = the harness name is none of the five. AGENT_LAUNCH_NOT_STARTED with _meta aiterm/launch_error code AGENT_AUTH_REQUIRED = the CLI on the terminal is not logged in; the Owner logs it in there, then launch again. " +
63
63
  "TERMINAL_OS_MISMATCH = the terminal is not the operating system os says: the registry's os is wrong or the binding points at another machine; ask the terminal registry, do not retry. " +
64
64
  "TERMINAL_PLATFORM_UNSUPPORTED = the terminal is not a macOS, Linux or Windows system, so it cannot run seats.";
@@ -108,9 +108,9 @@ function serve() {
108
108
  }
109
109
  });
110
110
  server.registerTool("remote_terminal_command", {
111
- description: "Fixed operation on the terminal: Claude Code setup, or a path check / mkdir / read-only folder listing",
112
- inputSchema: { op: z.enum(REMOTE_COMMAND_OPS), path: z.string().optional() },
113
- }, guarded(({ op, path }) => bound().command(op, path)));
111
+ description: "Fixed operation on the terminal: a CLI's version / install / update / login state (cli_*, harness required), Claude Code setup (claude_*), or a path check / mkdir / read-only folder listing",
112
+ inputSchema: { op: z.enum(REMOTE_COMMAND_OPS), path: z.string().optional(), harness: z.string().optional() },
113
+ }, guarded(({ op, path, harness }) => bound().command(op, path, harness)));
114
114
  server.registerTool("remote_terminal_close", { description: "Close the bound connection and exit", inputSchema: {} }, guarded(async () => { const result = connection ? await connection.close() : { closed: true }; setTimeout(() => process.exit(0), 100); return result; }));
115
115
  server.connect(new StdioServerTransport()).catch(error => { console.error("aiterm-remote-terminal fatal:", error); process.exit(1); });
116
116
  }
@@ -264,19 +264,55 @@ export class SshStdioTransport {
264
264
  async close() { this.child?.kill(); }
265
265
  }
266
266
  export const REMOTE_SEAT_TOOLS = new Set(["agent_launch", "pty_send", "pty_observe", "pty_read", "pty_key", "claude_turn", "agent_stop", "pty_close"]);
267
- export const REMOTE_COMMAND_OPS = ["claude_version", "claude_install", "claude_update", "path_status", "make_dir", "list_dirs"];
268
- // Fixed operations per terminal shell (R21). Windows: the official PowerShell installer; a failure stops with exit 1 and its message.
269
- const COMMANDS = {
270
- claude_version: { posix: "claude --version 2>&1", windows: "claude --version 2>&1" },
271
- claude_install: { posix: "curl -fsSL https://claude.ai/install.sh | bash 2>&1",
272
- windows: "& { $ErrorActionPreference = 'Stop'; try { irm https://claude.ai/install.ps1 | iex } catch { $_.Exception.Message; exit 1 } } *>&1; exit 0" },
273
- claude_update: { posix: "claude update 2>&1", windows: "claude update 2>&1" },
274
- };
275
- // The official installers' place, which a login shell may not have on PATH yet.
276
- const CLAUDE_VERSION_AFTER_INSTALL = {
277
- posix: 'claude --version 2>&1 || "$HOME/.local/bin/claude" --version 2>&1',
278
- windows: "$p = (Get-Command claude -ErrorAction SilentlyContinue).Source; if (-not $p) { $p = Join-Path $env:USERPROFILE '.local\\bin\\claude.exe' }; & $p --version 2>&1",
267
+ export const REMOTE_COMMAND_OPS = ["claude_version", "claude_install", "claude_update", "path_status", "make_dir", "list_dirs",
268
+ "cli_version", "cli_install", "cli_update", "cli_auth_status"];
269
+ export const CLI_HARNESSES = ["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"];
270
+ const CLAUDE_ALIASES = { claude_version: "cli_version", claude_install: "cli_install", claude_update: "cli_update" };
271
+ const posixInstall = (url, shell = "bash") => `curl -fsSL ${url} | ${shell} 2>&1`;
272
+ // A failure stops with exit 1 and its message (the official installers are `irm | iex`).
273
+ const windowsInstall = (url) => `& { $ErrorActionPreference = 'Stop'; try { irm ${url} | iex } catch { $_.Exception.Message; exit 1 } } *>&1; exit 0`;
274
+ const readJson = (text) => { try {
275
+ return JSON.parse(text.trim());
276
+ }
277
+ catch {
278
+ return null;
279
+ } };
280
+ const CLI = {
281
+ "claude-code": { bin: "claude", posixDir: "$HOME/.local/bin", winPath: "Join-Path $env:USERPROFILE '.local\\bin\\claude.exe'",
282
+ install: { posix: posixInstall("https://claude.ai/install.sh"), windows: windowsInstall("https://claude.ai/install.ps1") },
283
+ auth: ["auth", "status", "--json"],
284
+ classify: (code, out) => { const j = readJson(out); return j?.loggedIn === false ? false : j?.loggedIn === true && code === 0 ? true : null; } },
285
+ "codex-cli": { bin: "codex", posixDir: "$HOME/.local/bin", winPath: "Join-Path $env:LOCALAPPDATA 'Programs\\OpenAI\\Codex\\bin\\codex.exe'",
286
+ install: { posix: posixInstall("https://chatgpt.com/codex/install.sh", "CODEX_NON_INTERACTIVE=true sh"), windows: windowsInstall("https://chatgpt.com/codex/install.ps1") },
287
+ auth: ["login", "status"],
288
+ classify: (code, out, err) => { const t = `${out}\n${err}`; return /Not logged in/i.test(t) ? false : code === 0 && /Logged in/i.test(t) ? true : null; } },
289
+ "grok-cli": { bin: "grok", posixDir: "$HOME/.grok/bin", winPath: "Join-Path $env:USERPROFILE '.grok\\bin\\grok.exe'",
290
+ install: { posix: posixInstall("https://x.ai/cli/install.sh"), windows: windowsInstall("https://x.ai/cli/install.ps1") },
291
+ auth: ["models"], recheckMs: 1500,
292
+ classify: (code, out, err) => { const t = `${out}\n${err}`; return /You are not authenticated|Not signed in/i.test(t) ? false : code === 0 && /Available models/i.test(t) ? true : null; } },
293
+ "cursor-cli": { bin: "cursor-agent", posixDir: "$HOME/.local/bin", winPath: "Join-Path $env:LOCALAPPDATA 'cursor-agent\\cursor-agent.cmd'",
294
+ install: { posix: "curl https://cursor.com/install -fsS | bash 2>&1", windows: "& { $ErrorActionPreference = 'Stop'; try { irm 'https://cursor.com/install?win32=true' | iex } catch { $_.Exception.Message; exit 1 } } *>&1; exit 0" },
295
+ auth: ["status"],
296
+ classify: (code, out, err) => {
297
+ const t = `${out}\n${err}`;
298
+ return /not logged in|unauthenticated|sign in/i.test(t) ? false : /unable to fetch user details/i.test(t) ? null : code === 0 ? true : null;
299
+ } },
300
+ "antigravity-cli": { bin: "agy", posixDir: "$HOME/.local/bin", winPath: "Join-Path $env:LOCALAPPDATA 'agy\\bin\\agy.exe'",
301
+ install: { posix: posixInstall("https://antigravity.google/cli/install.sh"), windows: windowsInstall("https://antigravity.google/cli/install.ps1") },
302
+ auth: ["models"],
303
+ classify: (code, out, err) => code === 0 && /^\S+\t.+/m.test(out) ? true : /Please sign in to view available models/.test(err) ? false : null },
279
304
  };
305
+ /** Version of a CLI: on PATH, else in its installer's place (a login shell may not have that on PATH yet). */
306
+ const cliVersionScript = (c) => ({
307
+ posix: `${c.bin} --version 2>&1 || "${c.posixDir}/${c.bin}" --version 2>&1`,
308
+ windows: `$p = (Get-Command ${c.bin} -ErrorAction SilentlyContinue).Source; if (-not $p) { $p = ${c.winPath} }; & $p --version 2>&1`,
309
+ });
310
+ const cliUpdateScript = (c) => ({ posix: `${c.bin} update 2>&1`, windows: `${c.bin} update 2>&1` });
311
+ /** Exit 127 when the CLI is in neither place, so "not installed" is told from "not logged in". */
312
+ const cliAuthScript = (c) => ({
313
+ posix: `b=$(command -v ${c.bin}) || b="${c.posixDir}/${c.bin}"; [ -x "$b" ] || exit 127; "$b" ${c.auth.join(" ")}`,
314
+ windows: `$p = (Get-Command ${c.bin} -ErrorAction SilentlyContinue).Source; if (-not $p) { $p = ${c.winPath}; if (-not (Test-Path -LiteralPath $p)) { exit 127 } }; & $p ${c.auth.join(" ")}`,
315
+ });
280
316
  /** The remote command the forward keeper holds: it ends exactly when ssh's stdin closes. */
281
317
  export function keeperCommand(shell) {
282
318
  return shell === "posix" ? "cat >/dev/null" : powershellForShell(shell, "[Console]::In.ReadToEnd() | Out-Null");
@@ -311,6 +347,8 @@ export const REMOTE_PATH_OPS_VERSION = "0.69.0";
311
347
  export const REMOTE_LIST_DIRS_VERSION = "0.70.0";
312
348
  // The first release whose terminal-side path operations know drive paths.
313
349
  export const REMOTE_WINDOWS_PATH_VERSION = "0.70.8";
350
+ // The first release of the harness-generic cli_* ops, and the first a terminal may run Grok, Cursor and Antigravity seats on.
351
+ export const REMOTE_CLI_OPS_VERSION = "0.70.9";
314
352
  export class RemoteTerminalConnection extends EventEmitter {
315
353
  b;
316
354
  dir;
@@ -492,23 +530,63 @@ export class RemoteTerminalConnection extends EventEmitter {
492
530
  throw new RemoteTerminalError("COMMAND_FAILED", "aiterm-wait returned no receipt");
493
531
  }
494
532
  }
495
- async command(op, targetPath) {
533
+ async command(op, targetPath, harness) {
534
+ if (harness !== undefined && !op.startsWith("cli_"))
535
+ throw new RemoteTerminalError("COMMAND_INVALID", `${op} takes no harness`);
496
536
  if (op === "path_status" || op === "make_dir")
497
537
  return this.pathCommand(op, targetPath);
498
538
  if (op === "list_dirs")
499
539
  return this.listDirs(targetPath);
500
540
  if (targetPath !== undefined)
501
541
  throw new RemoteTerminalError("COMMAND_INVALID", `${op} takes no path`);
502
- if (!Object.hasOwn(COMMANDS, op))
542
+ const alias = CLAUDE_ALIASES[op];
543
+ const cliOp = alias ?? op;
544
+ if (!cliOp.startsWith("cli_"))
503
545
  throw new RemoteTerminalError("COMMAND_UNSUPPORTED", "unknown op");
504
- const run = await this.exec(COMMANDS[op], op === "claude_version" ? 60_000 : 900_000);
546
+ const h = alias ? "claude-code" : harness;
547
+ if (!h || !Object.hasOwn(CLI, h))
548
+ throw new RemoteTerminalError("COMMAND_INVALID", `${op} needs harness: one of ${CLI_HARNESSES.join(", ")}`);
549
+ if (!alias && !versionAtLeast(this.remoteVersion, REMOTE_CLI_OPS_VERSION))
550
+ throw new RemoteTerminalError("REMOTE_AITERM_TOO_OLD", `the terminal runs Aiterm ${this.remoteVersion}; ${REMOTE_CLI_OPS_VERSION} or later is required (update Aiterm on the terminal)`);
551
+ const spec = CLI[h];
552
+ if (cliOp === "cli_auth_status")
553
+ return this.cliAuthStatus(h, spec);
554
+ const cell = this.shell === "posix" ? "posix" : "windows";
555
+ const installer = spec.install[cell];
556
+ if (cliOp === "cli_install" && installer === null)
557
+ throw new RemoteTerminalError("CLI_INSTALL_UNSUPPORTED", `no official one-line installer is known for ${h} on ${this.platform}`);
558
+ const script = cliOp === "cli_version" ? cliVersionScript(spec) : cliOp === "cli_update" ? cliUpdateScript(spec) : { posix: spec.install.posix ?? "", windows: spec.install.windows ?? "" };
559
+ const run = await this.exec(script, cliOp === "cli_version" ? 60_000 : 900_000);
505
560
  if (run.code === 255) {
506
561
  const f = classifySshFailure(run.stderr);
507
562
  throw new RemoteTerminalError(f.code, f.message, f.action);
508
563
  }
509
- const probe = op === "claude_version" ? run : await this.exec(CLAUDE_VERSION_AFTER_INSTALL, 60_000);
564
+ const probe = cliOp === "cli_version" ? run : await this.exec(cliVersionScript(spec), 60_000);
510
565
  const version = probe.code === 0 ? (/\d+\.\d+\.\d+\S*/.exec(probe.stdout)?.[0] ?? null) : null;
511
- return { op, exit_code: run.code, version, output_tail: run.stdout.slice(-2000) };
566
+ const result = { exit_code: run.code, version, output_tail: run.stdout.slice(-2000) };
567
+ return alias ? { op, ...result } : { op, harness: h, ...result };
568
+ }
569
+ /** The login state and nothing of the CLI's own answer: `{op, harness, logged_in}`. */
570
+ async cliAuthStatus(h, spec) {
571
+ const ask = async () => {
572
+ const r = await this.exec(cliAuthScript(spec), 60_000);
573
+ if (r.code === 255) {
574
+ const f = classifySshFailure(r.stderr);
575
+ throw new RemoteTerminalError(f.code, f.message, f.action);
576
+ }
577
+ if (r.code === 127)
578
+ throw new RemoteTerminalError("CLI_NOT_INSTALLED", `${h} is not installed on the terminal (neither on PATH nor in its installer's place)`);
579
+ return spec.classify(r.code, r.stdout, r.stderr);
580
+ };
581
+ let answer = await ask();
582
+ // A live login can answer "not authenticated" once while it refreshes an old token (grokAuthStatus asks again the same way).
583
+ if (answer === false && spec.recheckMs) {
584
+ await new Promise(resolve => setTimeout(resolve, spec.recheckMs));
585
+ answer = await ask();
586
+ }
587
+ if (answer === null)
588
+ throw new RemoteTerminalError("AUTH_STATUS_UNCONFIRMED", `the login state of ${h} could not be read from its status answer`);
589
+ return { op: "cli_auth_status", harness: h, logged_in: answer };
512
590
  }
513
591
  /** R15: the terminal's own fs answers; the path travels as base64 so no shell reads it. */
514
592
  async pathCommand(op, targetPath) {
@@ -5,7 +5,8 @@ const ACTIONS = {
5
5
  TARGET_INVALID: "起動の指定(端末の情報)が正しくありません。BellTeamの不具合の恐れがあります。",
6
6
  TERMINAL_OS_MISMATCH: "端末のOSが、登録されているOSと違います。別の機械を指している恐れがあり止めました。端末の登録(OS)を確かめてください。",
7
7
  TERMINAL_PLATFORM_UNSUPPORTED: "この端末のOSは、Mac・Linux・Windowsのどれとも確かめられず、席を起こせません。Mac、Linux、Windowsのどれかの端末を使ってください。",
8
- TERMINAL_HARNESS_UNSUPPORTED: "この端末で起こせるAIは、今はClaude CodeとCodexだけです。メンバーのAIをClaude CodeかCodexにしてください。",
8
+ TERMINAL_HARNESS_UNSUPPORTED: "このAIの種類は、端末では起こせません。BellTeamの不具合の恐れがあります。",
9
+ AGENT_AUTH_REQUIRED: "端末のこのAIにログインしていません。席は作られていません。端末でこのAIにログインしてから、起こし直してください。",
9
10
  REF_INVALID: "端末の登録が見つかりません。端末の登録を確かめてください。",
10
11
  BINDING_UNKNOWN: "端末の登録が見つかりません。端末の登録を確かめてください。",
11
12
  BINDING_STORE_UNREADABLE: "端末の登録を読めませんでした。端末の登録をやり直してください。",
@@ -27,7 +28,6 @@ const ACTIONS = {
27
28
  SEAT_FORWARD_UNAVAILABLE: "端末からBellTeamへ戻る通り道がまだ用意できていません。少し待ってから起こし直してください。",
28
29
  CWD_UNAVAILABLE: "端末に作業フォルダがありません。メンバーの作業フォルダを選び直すか、そのフォルダを作ってください。",
29
30
  AGENT_LAUNCH_NOT_STARTED: "席を作る途中で失敗しました。席は残っていません。もう一度起こし直します。",
30
- CLAUDE_AUTH_NOT_AUTHENTICATED: "端末のClaude Codeにログインしていません。端末でClaude Codeにログインしてください。",
31
31
  CLAUDE_AUTH_STATUS_UNCONFIRMED: "端末のClaude Codeのログイン状態を確かめられませんでした。少し待ってから起こし直してください。",
32
32
  CLAUDE_AUTH_STATUS_TIMEOUT: "端末のClaude Codeのログイン状態を時間内に確かめられませんでした。少し待ってから起こし直してください。",
33
33
  };
@@ -41,10 +41,9 @@ export function terminalLaunchAction(code) {
41
41
  export const LAUNCH_ERROR_META = "aiterm/launch_error";
42
42
  export const ERROR_CODE_META = "aiterm/error_code";
43
43
  /** R18 for a local launch: the fresh native creation left no seat (core.freshLaunchFailure). */
44
- export function launchNotStartedMeta(harness, phase = "native_create") {
45
- const code = "AGENT_LAUNCH_NOT_STARTED";
44
+ export function launchNotStartedMeta(harness, phase = "native_create", code = "AGENT_LAUNCH_NOT_STARTED") {
46
45
  return { [LAUNCH_ERROR_META]: { schema: "aiterm.agent-launch-error.v1", harness, code, phase,
47
- effect: "not_started", session_created: false, action: phase === "input" ? INPUT_ACTION : ACTIONS[code] } };
46
+ effect: "not_started", session_created: false, action: code === "AGENT_AUTH_REQUIRED" || phase !== "input" ? ACTIONS[code] : INPUT_ACTION } };
48
47
  }
49
48
  // phase "input": refused from the arguments alone; nothing was started, so launching again unchanged fails the same way.
50
49
  const INPUT_ACTION = "起動の指定(追加の指示かMCPの設定)をこのAIでは使えません。席は作られていません。指定を見直してください。";
@@ -65,7 +64,11 @@ export function withTerminalLaunchAction(result, harness = "claude-code") {
65
64
  const preflight = structured?.schema === "aiterm.agent-launch-error.v1";
66
65
  if (structured && !preflight)
67
66
  return result;
68
- const code = preflight ? structured.code : errorCode(result.content?.find((item) => item.type === "text")?.text ?? "");
67
+ const text = result.content?.find((item) => item.type === "text")?.text ?? "";
68
+ // "Not logged in" is one code for every harness (0.70.9). A terminal on 0.70.1-0.70.8 answers Claude's only as the structured preflight code.
69
+ if (preflight ? structured.code === "CLAUDE_AUTH_NOT_AUTHENTICATED" : /^(?:aiterm: )?AGENT_LAUNCH_NOT_STARTED: AGENT_AUTH_REQUIRED:/.test(text))
70
+ return { ...result, _meta: { ...result._meta, ...launchNotStartedMeta(preflight ? structured.harness : harness, "input", "AGENT_AUTH_REQUIRED") } };
71
+ const code = preflight ? structured.code : errorCode(text);
69
72
  const action = terminalLaunchAction(code);
70
73
  if (!action)
71
74
  return result;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.70.8",
3
+ "version": "0.70.9",
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": [