aiterm-mcp 0.61.24 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js CHANGED
@@ -29,12 +29,13 @@ import { withExecutionInterruptEffectScope, bindExecutionNativeTarget, beforeExe
29
29
  import { ExecutionError } from "./execution-wire.js";
30
30
  import { readExecutionParentProcess } from "./execution-parent-process.js";
31
31
  import { isCursorMcpClient } from "aiterm-steer-delivery";
32
+ import { antigravityAuthChoiceKey, antigravityCurrentModel, antigravityStartupAction, antigravityAgentArgv, antigravityModelChoices, antigravityAuthStatus, antigravityAuthPane, antigravityTranscriptText, bindAntigravitySession, createAntigravityAgentMetadata, mergeAntigravityHooks } from "./harnesses/antigravity.js";
32
33
  import { paneTokenHint } from "./harnesses/pane-tokens.js";
33
34
  import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
34
35
  import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, processElapsedSeconds } from "./process-runtime.js";
35
36
  import { liveNodeExecutable } from "./live-node.js";
36
37
  import { AitermError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
37
- import { isWin, SOCKDIR, SOCK, tmuxCommand, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, openPsmuxServerToDesktop, registeredSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, } from "./tmux-runtime.js";
38
+ import { isWin, SOCKDIR, SOCK, tmuxCommand, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, openPsmuxServerToDesktop, registeredSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, } from "./tmux-runtime.js";
38
39
  import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, createEmpty0600, shq, LAUNCH_ID_RE, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, assertSessionName, agentsDir, agentEventPath, agentMetadataPath, writeAgentMetadata, AGENT_EVENT_TAIL_BYTES, agentLabel, agentHarness, subagentInstruction, agentLineageFields, } from "./agent-shared.js";
39
40
  import { AuthResponseError, authUi, authPromptDigest, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
40
41
  import { processStartIdentity } from "./runtime-error-os.js";
@@ -135,6 +136,7 @@ const AGENT_FOREGROUND_RECOVERY_TIMEOUT_MS = 3_000;
135
136
  const AGENT_FOREGROUND_RECOVERY_POLL_MS = 200;
136
137
  // harness の実プロセスを command 行から見分ける。agent が起動した子(bash -lc、ssh、git 等)は agent ではない。
137
138
  const AGENT_COMMAND_PATTERNS = {
139
+ antigravity: /(^|[\s/])agy(?:\.exe)?([\s]|$)/,
138
140
  codex: /(^|[\s/])codex([\s]|$)/,
139
141
  claude: /(^|[\s/])claude([\s]|$)/,
140
142
  grok: /(^|[\s/])grok(-[^\s/]+)?([\s]|$)/,
@@ -355,6 +357,8 @@ function cleanupAgentState(name) {
355
357
  f.endsWith(".claude-mcp.json") ||
356
358
  f.endsWith(".claude-result.json") ||
357
359
  f.endsWith(".cursor-result.json") ||
360
+ f.endsWith(".antigravity-session.json") ||
361
+ /\.antigravity-result-\d+-\d+\.json$/.test(f) ||
358
362
  f.endsWith(".claude-operation.json") ||
359
363
  f.endsWith(".claude-approval.json") ||
360
364
  f.endsWith(".claude-dispatch") ||
@@ -1034,7 +1038,7 @@ function readInterruptionTarget(name) {
1034
1038
  if (files.length !== 1)
1035
1039
  return null;
1036
1040
  const meta = JSON.parse(fs.readFileSync(path.join(agentsDir(), files[0]), "utf8"));
1037
- return meta.aiterm_session === name && ["codex", "claude", "cursor", "grok"].includes(meta.kind)
1041
+ return meta.aiterm_session === name && ["codex", "claude", "cursor", "grok", "antigravity"].includes(meta.kind)
1038
1042
  && typeof meta.launch_id === "string" && LAUNCH_ID_RE.test(meta.launch_id) ? { kind: meta.kind, launch_id: meta.launch_id } : null;
1039
1043
  }
1040
1044
  catch {
@@ -1053,10 +1057,10 @@ export function interruptSessionNow(name, expectedLaunchId) {
1053
1057
  if (!native)
1054
1058
  return { session_id: name, outcome: "idle" };
1055
1059
  const meta = readInterruptionTarget(name);
1056
- if (!meta || !["codex", "claude", "cursor", "grok"].includes(meta.kind))
1060
+ if (!meta || !["codex", "claude", "cursor", "grok", "antigravity"].includes(meta.kind))
1057
1061
  throw new ExecutionError("EXECUTION_UNSUPPORTED");
1058
1062
  const key = meta.kind === "codex" ? CODEX_INTERRUPT_KEY : meta.kind === "claude" ? CLAUDE_INTERRUPT_KEY
1059
- : meta.kind === "cursor" ? CURSOR_INTERRUPT_KEY : GROK_INTERRUPT_KEY;
1063
+ : meta.kind === "cursor" ? CURSOR_INTERRUPT_KEY : meta.kind === "antigravity" ? "C-c" : GROK_INTERRUPT_KEY;
1060
1064
  // A normal Ctrl+C can quit an idle CLI. Use its existing immediate pane
1061
1065
  // observation, never repeated Ctrl+C or kill as an escalation.
1062
1066
  if (key === "C-c") {
@@ -2989,7 +2993,7 @@ function loadAgentMetadata(name) {
2989
2993
  throw new AitermError(`agent metadata を読めません: ${e.message}`, 2);
2990
2994
  }
2991
2995
  const m = raw;
2992
- if ((m.kind !== "claude" && m.kind !== "codex" && m.kind !== "grok" && m.kind !== "cursor") ||
2996
+ if ((m.kind !== "claude" && m.kind !== "codex" && m.kind !== "grok" && m.kind !== "cursor" && m.kind !== "antigravity") ||
2993
2997
  m.aiterm_session !== name ||
2994
2998
  typeof m.launch_id !== "string" ||
2995
2999
  !LAUNCH_ID_RE.test(m.launch_id)) {
@@ -3023,6 +3027,17 @@ function loadAgentMetadata(name) {
3023
3027
  ? { startup_process_shapes: m.startup_process_shapes } : {};
3024
3028
  const startupFields = Array.isArray(m.startup_processes) && m.startup_processes.every((identity) => typeof identity === "string")
3025
3029
  ? { startup_processes: m.startup_processes, ...startupShapes } : {};
3030
+ if (m.kind === "antigravity") {
3031
+ if (m.hook_route !== "shared_antigravity_home" || typeof m.antigravity_home !== "string" || !path.isAbsolute(m.antigravity_home)
3032
+ || (m.vendor_session_id != null && (typeof m.vendor_session_id !== "string" || !UUID_RE.test(m.vendor_session_id))))
3033
+ throw new AitermError("Antigravity metadataが不正です", 2);
3034
+ return { kind: "antigravity", aiterm_session: name, launch_id: m.launch_id, event_file: expectedEvent,
3035
+ cwd: typeof m.cwd === "string" ? m.cwd : null, created_at: typeof m.created_at === "string" ? m.created_at : "",
3036
+ vendor_session_id: m.vendor_session_id ?? null, initial_prompt: normalizeInitialPromptState(m.initial_prompt),
3037
+ hook_route: "shared_antigravity_home", antigravity_home: m.antigravity_home, node_platform: process.platform,
3038
+ ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
3039
+ ...deliveryFields, ...executableFields, ...fastFields, ...startupFields, ...loadAgentLineageFields(m, true) };
3040
+ }
3026
3041
  if (m.kind === "claude") {
3027
3042
  const expectedSettings = agentManagedClaudeSettingsPath(name, m.launch_id);
3028
3043
  const expectedResult = agentClaudeResultPath(name, m.launch_id);
@@ -3172,7 +3187,7 @@ function parseAgentDoneEvent(line, meta) {
3172
3187
  ev.vendor !== meta.kind ||
3173
3188
  ev.aiterm_session !== meta.aiterm_session ||
3174
3189
  ev.launch_id !== meta.launch_id ||
3175
- ev.done_status !== "turn_done") {
3190
+ (ev.done_status !== "turn_done" && !(meta.kind === "antigravity" && ev.done_status === "turn_error"))) {
3176
3191
  return { event: null, malformed: false };
3177
3192
  }
3178
3193
  if (meta.vendor_session_id && ev.vendor_session_id !== meta.vendor_session_id) {
@@ -3200,7 +3215,7 @@ function parseAgentDoneEvent(line, meta) {
3200
3215
  turn_id: typeof ev.turn_id === "string" ? ev.turn_id : null,
3201
3216
  operation_id: typeof ev.operation_id === "string" && OPERATION_ID_RE.test(ev.operation_id) ? ev.operation_id : null,
3202
3217
  reason: typeof ev.reason === "string" ? ev.reason : "Stop",
3203
- done_status: "turn_done",
3218
+ done_status: ev.done_status === "turn_error" ? "turn_error" : "turn_done",
3204
3219
  stop_hook_active: !!ev.stop_hook_active,
3205
3220
  result_digest: typeof ev.result_digest === "string" && /^[0-9a-f]{64}$/.test(ev.result_digest) ? ev.result_digest : undefined,
3206
3221
  result_bytes: Number.isInteger(ev.result_bytes) && ev.result_bytes >= 0 ? ev.result_bytes : undefined,
@@ -3365,6 +3380,10 @@ function completedClaudeOperationEvent(meta, operationId) {
3365
3380
  return match;
3366
3381
  }
3367
3382
  function recoverAgentHarnessSession(meta) {
3383
+ if (meta.kind === "antigravity") {
3384
+ bindAntigravitySession(meta);
3385
+ return;
3386
+ }
3368
3387
  if (meta.vendor_session_id)
3369
3388
  return;
3370
3389
  if (meta.kind === "codex") {
@@ -3537,6 +3556,11 @@ export async function readAgentTranscriptResult(name, o = {}) {
3537
3556
  transcriptUnavailable();
3538
3557
  text = readClaudeResultText(meta, done, operationId, transcriptUnavailable);
3539
3558
  }
3559
+ else if (meta.kind === "antigravity") {
3560
+ if (!done || done.done_status !== "turn_done")
3561
+ transcriptUnavailable();
3562
+ text = antigravityTranscriptText(meta, done);
3563
+ }
3540
3564
  else if (meta.kind === "cursor") {
3541
3565
  text = cursorTranscriptText(meta, readTranscriptLines, transcriptUnavailable);
3542
3566
  }
@@ -3847,7 +3871,9 @@ export async function observeAgentDone(name, o = {}) {
3847
3871
  throw new AitermError("agent event file に複数の vendor_session_id が混在しています。該当セッションを閉じて起動し直してください。", 2);
3848
3872
  }
3849
3873
  if (scanned.event)
3850
- return observation("done", scanned.event);
3874
+ return scanned.event.done_status === "turn_error"
3875
+ ? { ...observation("error", scanned.event), error: `Antigravity execution ended: ${scanned.event.reason}`, error_kind: scanned.event.reason }
3876
+ : observation("done", scanned.event);
3851
3877
  }
3852
3878
  if (transcriptFile && fs.existsSync(transcriptFile)) {
3853
3879
  const transcriptSize = safeStatSize(transcriptFile);
@@ -4077,7 +4103,7 @@ const STARTUP_SELECTION_MAX_SAMPLES = 30;
4077
4103
  async function waitStartupSelection(name, selected) {
4078
4104
  for (let i = 0; i < STARTUP_SELECTION_MAX_SAMPLES; i++) {
4079
4105
  const marker = captureScreen(name, AGENT_TUI_READY_LINES).split("\n").slice(-32)
4080
- .filter(line => /^\s*❯/u.test(line)).at(-1)?.trim() ?? "";
4106
+ .filter(line => /^\s*(?:❯|>)/u.test(line)).at(-1)?.trim() ?? "";
4081
4107
  if (selected.test(marker))
4082
4108
  return true;
4083
4109
  await sleep(STARTUP_SELECTION_POLL_MS);
@@ -4091,7 +4117,8 @@ async function prepareAgentInput(name, meta, options) {
4091
4117
  while (!ready.ready) {
4092
4118
  const action = meta.kind === "codex" ? codexStartupAction(ready.lastScreen, options.trust_project === true)
4093
4119
  : meta.kind === "claude" ? claudeStartupAction(ready.lastScreen, options.trust_project === true)
4094
- : meta.kind === "grok" ? grokStartupAction(ready.lastScreen, options.trust_project === true) : null;
4120
+ : meta.kind === "grok" ? grokStartupAction(ready.lastScreen, options.trust_project === true)
4121
+ : meta.kind === "antigravity" ? antigravityStartupAction(ready.lastScreen, options.trust_project === true, meta.cwd) : null;
4095
4122
  if (!action || handled.has(action.kind))
4096
4123
  break;
4097
4124
  handled.add(action.kind);
@@ -4318,6 +4345,7 @@ function authPlan(kind, phase) {
4318
4345
  case "codex": return codexAuthPlan();
4319
4346
  case "grok": return grokAuthPlan();
4320
4347
  case "cursor": return cursorAuthPlan();
4348
+ case "antigravity": return { args: [], env: [] };
4321
4349
  }
4322
4350
  }
4323
4351
  async function authStatus(kind, bin, cwd, env = process.env) {
@@ -4326,6 +4354,7 @@ async function authStatus(kind, bin, cwd, env = process.env) {
4326
4354
  case "codex": return await codexAuthStatus(bin, cwd, env);
4327
4355
  case "grok": return await grokAuthStatus(bin, cwd, env);
4328
4356
  case "cursor": return cursorAuthStatus(bin, cwd, env);
4357
+ case "antigravity": return antigravityAuthStatus(bin, cwd, env);
4329
4358
  }
4330
4359
  }
4331
4360
  function authPane(meta, screen) {
@@ -4334,6 +4363,7 @@ function authPane(meta, screen) {
4334
4363
  case "codex": return codexAuthPane(screen);
4335
4364
  case "grok": return grokAuthPane(screen);
4336
4365
  case "cursor": return cursorAuthPane(screen);
4366
+ case "antigravity": return antigravityAuthPane(screen);
4337
4367
  }
4338
4368
  }
4339
4369
  function loadAuthMetadata(name, kind) {
@@ -4369,7 +4399,7 @@ function loadAuthMetadata(name, kind) {
4369
4399
  function readExecutionAuthMetadata(name) {
4370
4400
  try {
4371
4401
  const raw = JSON.parse(fs.readFileSync(authMetadataPath(name), "utf8"));
4372
- if (!["claude", "codex", "grok", "cursor"].includes(raw?.kind))
4402
+ if (!["claude", "codex", "grok", "cursor", "antigravity"].includes(raw?.kind))
4373
4403
  return null;
4374
4404
  const meta = loadAuthMetadata(name, raw.kind), launch = executionLaunchSchema.shape.launch_id.safeParse(meta?.launch_id);
4375
4405
  const native = executionNativeBindingSchema.safeParse(meta?.execution_native);
@@ -4492,7 +4522,7 @@ async function respondAgentAuth(kind, options) {
4492
4522
  if (!current)
4493
4523
  throw new Error("native selection unknown");
4494
4524
  issued = true;
4495
- if (tmux("send-keys", "-t", binding.pane_id, current === answer.id ? "Enter" : "Down").code !== 0)
4525
+ if (tmux("send-keys", "-t", binding.pane_id, meta.kind === "antigravity" ? antigravityAuthChoiceKey(screen, answer.id) : current === answer.id ? "Enter" : "Down").code !== 0)
4496
4526
  throw new Error("native choice unconfirmed");
4497
4527
  if (current === answer.id)
4498
4528
  break;
@@ -4588,6 +4618,8 @@ export async function authenticateAgent(kind, options) {
4588
4618
  const bin = resolveAgentBin(kind);
4589
4619
  if (!bin)
4590
4620
  return result("failed", null, `${agentLabel(kind)}の公式CLIが見つかりません。`);
4621
+ if (kind === "antigravity" && options.relogin)
4622
+ return result("failed", null, "AGENT_AUTH_RELOGIN_UNSUPPORTED: Antigravityの再認証は公式TUIの /logout が必要で、共有の資格情報とcacheを消します。Aitermからは開始していません。");
4591
4623
  // reloginは今の状態を聞かない。状態を確認できない時(failed)でも、入り直しは始められる。
4592
4624
  const before = options.relogin ? { status: "unauthenticated", message: null } : await authStatus(kind, bin, cwd);
4593
4625
  if (before.status === "failed")
@@ -4694,7 +4726,7 @@ export async function authenticateAgent(kind, options) {
4694
4726
  meta.phase = "onboarding";
4695
4727
  writeJson0600(authMetadataPath(session), meta);
4696
4728
  });
4697
- const restarted = tmux("respawn-pane", "-k", "-t", session, resolveWinPaneShell("bash"));
4729
+ const restarted = tmux("respawn-pane", "-k", "-t", session, ...paneCommandArgs(resolveWinPaneShell("bash")));
4698
4730
  if (restarted.code !== 0)
4699
4731
  return result("failed", session, "公式CLIの初回案内を起動できません。");
4700
4732
  launchAuthProcess(session, meta);
@@ -4733,6 +4765,7 @@ export async function listAgentModels(kind, options = {}) {
4733
4765
  case "codex": return codexModelChoices(bin, options.include_hidden === true);
4734
4766
  case "grok": return grokModelChoices(bin, cwd);
4735
4767
  case "cursor": return cursorModelChoices(bin, cwd);
4768
+ case "antigravity": return antigravityModelChoices(bin, cwd);
4736
4769
  }
4737
4770
  }
4738
4771
  const CLAUDE_MODEL_PICKER_TIMEOUT_MS = 8_000;
@@ -5006,6 +5039,8 @@ async function planLaunchFast(kind, o) {
5006
5039
  assertCursorModelAvailable(bin, cwd, o.model, o.effort, true);
5007
5040
  return { ...plan, cursor_fast: true, state: true };
5008
5041
  }
5042
+ if (kind === "antigravity")
5043
+ throw new FastModeError("FAST_MODE_NOT_SUPPORTED", "Antigravity CLIに低遅延fast切替の公式契約はありません(/boostは別の実行方式です)。起動していません。");
5009
5044
  const base = o.model ?? GROK_MODEL_DEFAULTS[kind];
5010
5045
  const catalog = await grokCatalogForFast(bin, cwd, base);
5011
5046
  const fastId = catalog.fast_ids?.[base];
@@ -5116,6 +5151,12 @@ function recordAgentFast(meta, fast) {
5116
5151
  }
5117
5152
  /** 動いている席のfastを切り替える。返りは切り替えた後の状態。席は入力待ちである事(呼び手が確かめる)。 */
5118
5153
  async function switchAgentFast(name, meta, target, verified = false) {
5154
+ if (meta.kind === "antigravity") {
5155
+ if (target)
5156
+ throw new FastModeError("FAST_MODE_NOT_SUPPORTED", "Antigravity CLIに低遅延fast切替の公式契約はありません(/boostは別の実行方式です)");
5157
+ recordAgentFast(meta, false);
5158
+ return false;
5159
+ }
5119
5160
  const state = meta.kind === "claude" ? await switchClaudeFast(name, meta, target, verified)
5120
5161
  : meta.kind === "codex" ? await switchCodexFast(name, meta, target, verified)
5121
5162
  : meta.kind === "cursor" ? await switchCursorFast(name, meta, target)
@@ -5728,6 +5769,42 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
5728
5769
  writeAgentMetadata(meta);
5729
5770
  });
5730
5771
  };
5772
+ if (meta.kind === "antigravity") {
5773
+ if (fast === true)
5774
+ throw new FastModeError("FAST_MODE_NOT_SUPPORTED", "Antigravity CLIには低遅延fast切替がありません。設定は変えていません。");
5775
+ const bin = meta.agent_executable ?? resolveAgentBin(meta.kind);
5776
+ if (!bin)
5777
+ throw new AitermError("Antigravity CLIが見つかりません", 2);
5778
+ const catalog = antigravityModelChoices(bin, meta.cwd ?? process.cwd());
5779
+ const current = antigravityCurrentModel(captureScreen(name, AGENT_TUI_READY_LINES), catalog);
5780
+ if (!current)
5781
+ throw new AitermError("ANTIGRAVITY_CONFIGURATION_UNCONFIRMED: 席の現在modelを確認できません", 2);
5782
+ const requested = model ?? (effort ? current.replace(/-(low|medium|high|xhigh|max)$/, `-${effort}`) : current);
5783
+ const target = catalog.models.find(item => item.id === requested);
5784
+ if (!target || (effort && !target.efforts.includes(effort)))
5785
+ throw new AitermError("Antigravity modelとeffortの組み合わせがcatalogにありません。設定は変えていません。", 2);
5786
+ if (target.id !== current) {
5787
+ const config = path.join(meta.antigravity_home, "settings.json");
5788
+ await withUserConfigLock(config, async () => {
5789
+ const before = readFileOrNull(config) ?? Buffer.from("{}");
5790
+ try {
5791
+ beforeChange();
5792
+ await sendAgentPromptText(name, `/model ${target.id}`, meta.kind);
5793
+ const deadline = performance.now() + 10000;
5794
+ while (antigravityCurrentModel(captureScreen(name, AGENT_TUI_READY_LINES), catalog) !== target.id) {
5795
+ if (performance.now() >= deadline)
5796
+ throw new AitermError("ANTIGRAVITY_CONFIGURATION_UNCONFIRMED: 変更後のmodelを確認できません", 2);
5797
+ await sleep(100);
5798
+ }
5799
+ }
5800
+ finally {
5801
+ restoreJsonSetting(config, before, ["model"]);
5802
+ }
5803
+ });
5804
+ }
5805
+ withExecutionPreparation(name, () => { meta.model = target.id; meta.fast = false; writeAgentMetadata(meta); });
5806
+ return { ...configured(), model: target.id, reasoning_effort: target.default_effort };
5807
+ }
5731
5808
  // fast: true は、modelやeffortを替える前に対応を確かめる(断る時は何も変えない)。
5732
5809
  let fastVerified = false;
5733
5810
  if (fast === true && (meta.kind === "claude" || meta.kind === "codex")) {
@@ -6534,6 +6611,8 @@ function buildAgentCmd(kind, bin, model, effort, prompt, meta = null, cursorFast
6534
6611
  return buildCodexAgentCmd(bin, model, effort, prompt, meta);
6535
6612
  if (kind === "cursor")
6536
6613
  return buildCursorAgentCmd(bin, model, effort, prompt, meta, cursorFast);
6614
+ if (kind === "antigravity")
6615
+ return antigravityAgentArgv(bin, model, effort, prompt).map(shq).join(" ");
6537
6616
  return buildGrokAgentCmd(kind, bin, model, effort, prompt, meta);
6538
6617
  }
6539
6618
  /**
@@ -6582,6 +6661,8 @@ function buildAgentLaunchNote(kind, model, effort, meta) {
6582
6661
  return claudeLaunchNote(model, effort, meta);
6583
6662
  if (kind === "cursor")
6584
6663
  return cursorLaunchNote(model, effort, meta);
6664
+ if (kind === "antigravity")
6665
+ return `model=${model ?? "CLI既定"} effort=${effort ?? "CLI既定"}。`;
6585
6666
  if (kind !== "codex")
6586
6667
  return grokLaunchNote(kind, model, effort, meta);
6587
6668
  return codexLaunchNote(model, effort, meta);
@@ -6681,7 +6762,7 @@ function prepareAgentLaunch(kind, opts = {}) {
6681
6762
  ? "~/.local/bin/codex"
6682
6763
  : kind === "cursor"
6683
6764
  ? "~/.local/bin/cursor-agent"
6684
- : "~/.grok/bin/grok";
6765
+ : kind === "antigravity" ? "~/.local/bin/agy(WindowsはLOCALAPPDATA/agy/bin/agy.exe)" : "~/.grok/bin/grok";
6685
6766
  ownTelemetryFailure("AITERM.VENDOR_LAUNCHER_FAILED", new AitermError(`${label} の CLI が見つかりません(${where} か PATH が必要)`, 2), 2);
6686
6767
  }
6687
6768
  // cwd 検証(session を作る前に。cd 失敗はシェル内で静かに死に「起動した」と偽成功を返すため)。
@@ -6706,6 +6787,8 @@ function prepareAgentLaunch(kind, opts = {}) {
6706
6787
  }
6707
6788
  cwd = opts.cwd;
6708
6789
  }
6790
+ if (kind === "antigravity" && cwd === null)
6791
+ cwd = process.cwd();
6709
6792
  const launchRequestDigest = launchOperationId === null
6710
6793
  ? null
6711
6794
  : claudeLaunchRequestDigest({
@@ -6723,6 +6806,17 @@ function prepareAgentLaunch(kind, opts = {}) {
6723
6806
  assertClaudeAuthenticationReady(bin);
6724
6807
  if (kind === "cursor")
6725
6808
  assertCursorAuthenticationReady(bin);
6809
+ if (kind === "antigravity") {
6810
+ const auth = antigravityAuthStatus(bin, cwd ?? process.cwd());
6811
+ if (auth.status !== "authenticated")
6812
+ throw new AitermError(`ANTIGRAVITY_AUTH_REQUIRED: ${auth.message}`, 2);
6813
+ const catalog = antigravityModelChoices(bin, cwd ?? process.cwd());
6814
+ const selected = model ?? catalog.default_model;
6815
+ const choice = catalog.models.find(item => item.id === selected);
6816
+ if (!choice || (effort && !choice.efforts.includes(effort)))
6817
+ throw new AitermError("Antigravity modelとeffortの組み合わせがcatalogにありません", 2);
6818
+ mergeAntigravityHooks();
6819
+ }
6726
6820
  // Windows agent launches run in a native PowerShell pane. Accepted shebang
6727
6821
  // wrappers use noninteractive Git Bash in that pane; there is no WSL bridge.
6728
6822
  // 未検証リスク: npm グローバル導入の codex.cmd/.bat シムの対話 TUI 描画は実 Windows でしか確認
@@ -6774,9 +6868,11 @@ function prepareAgentLaunch(kind, opts = {}) {
6774
6868
  ? createClaudeAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", launchOperationId, launchRequestDigest, lineageContext, model, effort)
6775
6869
  : kind === "codex"
6776
6870
  ? createCodexAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", { model, effort }, writeScope, lineageContext)
6777
- : kind === "cursor"
6778
- ? createCursorAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", writeScope, lineageContext)
6779
- : createGrokAgentMetadata(kind, sid, cwd, opts.prompt ? "pending" : "none", grokAuthPath, writeScope, lineageContext)
6871
+ : kind === "antigravity"
6872
+ ? createAntigravityAgentMetadata(sid, cwd ?? process.cwd(), opts.prompt ? "pending" : "none", writeScope, lineageContext)
6873
+ : kind === "cursor"
6874
+ ? createCursorAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", writeScope, lineageContext)
6875
+ : createGrokAgentMetadata(kind, sid, cwd, opts.prompt ? "pending" : "none", grokAuthPath, writeScope, lineageContext)
6780
6876
  : null;
6781
6877
  if (meta) {
6782
6878
  // Metadata constructors publish their internally generated launch ID.
@@ -6804,7 +6900,8 @@ function prepareAgentLaunch(kind, opts = {}) {
6804
6900
  const argv = kind === "claude" ? claudeAgentArgv(bin, model, effort, prompt, meta)
6805
6901
  : kind === "codex" ? codexAgentArgv(bin, model, effort, prompt, meta)
6806
6902
  : kind === "cursor" ? cursorAgentArgv(bin, model, effort, prompt, meta, cursorFast)
6807
- : grokAgentArgv(kind, bin, model, effort, prompt, meta);
6903
+ : kind === "antigravity" ? antigravityAgentArgv(bin, model, effort, prompt)
6904
+ : grokAgentArgv(kind, bin, model, effort, prompt, meta);
6808
6905
  full = windowsAgentLaunchLine(cwd, [
6809
6906
  ...(meta?.kind === "grok" ? grokEnvEntries(meta) : []), ...agentEnvEntries(meta, sid, envVars),
6810
6907
  ], windowsAgentArgv(argv, () => resolveWinPaneShell("bash")));
@@ -31,7 +31,7 @@ export function requireParentEndpointEvidence(value) {
31
31
  }
32
32
  const snapshotSchema = z.object({
33
33
  schema: z.literal("aiterm.execution-parent-process.v1"), source: executionPointSchema,
34
- harness: z.enum(["codex-cli", "claude-code", "cursor-cli", "grok-cli"]), harness_process: identity,
34
+ harness: z.enum(["codex-cli", "claude-code", "cursor-cli", "grok-cli", "antigravity-cli"]), harness_process: identity,
35
35
  processes: z.array(identity.extend({ parent_pid: z.number().int().nonnegative() }).strict()),
36
36
  }).strict();
37
37
  const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
@@ -0,0 +1,257 @@
1
+ import { z } from "zod";
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import { randomBytes, createHash } from "node:crypto";
6
+ import { fileURLToPath } from "node:url";
7
+ import { isDeepStrictEqual } from "node:util";
8
+ import { AitermError } from "../errors.js";
9
+ import { checkedCatalog, catalogInvalid, catalogUnavailable } from "../model-catalog.js";
10
+ import { spawnAgentControlCommand } from "../agent-resolver.js";
11
+ import { liveNodeExecutable } from "../live-node.js";
12
+ import { powershellInvocation } from "../windows-powershell.js";
13
+ import { agentEventPath, agentLineageFields, agentsDir, createEmpty0600, readFileRange, safeStatSize, shq, writeAgentMetadata, writeJson0600 } from "../agent-shared.js";
14
+ import { authUrl } from "../agent-auth.js";
15
+ // agy 1.4.10 exposes effort-specific IDs; overriding an ID's effort is rejected by the CLI.
16
+ export function antigravityCatalog(stdout, selected) {
17
+ const rows = (text) => text.split(/\r?\n/).filter(line => line.trim()).map(line => {
18
+ const fields = line.split("\t");
19
+ if (fields.length !== 2 || !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(fields[0]) || !fields[1].trim()) {
20
+ throw catalogInvalid("Antigravity", "agy modelsのIDと表示名を確認できません");
21
+ }
22
+ return { id: fields[0], display_name: fields[1] };
23
+ });
24
+ const models = rows(stdout).map(model => {
25
+ const effort = /-(low|medium|high|xhigh|max)$/.exec(model.id)?.[1] ?? null;
26
+ return { ...model, efforts: effort ? [effort] : [], default_effort: effort, hidden: false, fast: false };
27
+ });
28
+ const current = rows(selected);
29
+ if (current.length !== 1)
30
+ throw catalogInvalid("Antigravity", "agy -p /modelの選択modelを確認できません");
31
+ return checkedCatalog("Antigravity", {
32
+ source: "agy models / agy -p /model", harness_version: null,
33
+ default_model: current[0].id, models, adapter_efforts: {},
34
+ });
35
+ }
36
+ export function realAntigravityHome() {
37
+ return path.join(process.env.HOME ?? os.homedir(), ".gemini", "antigravity-cli");
38
+ }
39
+ export function antigravityModelChoices(bin, cwd) {
40
+ const run = (args) => {
41
+ const r = spawnAgentControlCommand(bin, args, cwd, { cwd, env: process.env, encoding: "utf8", timeout: 30000, maxBuffer: 1024 * 1024, windowsHide: true });
42
+ if (r.error || r.status !== 0)
43
+ throw catalogUnavailable("Antigravity", r.error?.message ?? r.stderr?.trim() ?? `exit=${r.status}`);
44
+ return r.stdout;
45
+ };
46
+ const catalog = antigravityCatalog(run(["models"]), run(["-p", "/model"]));
47
+ catalog.harness_version = run(["--version"]).trim();
48
+ return catalog;
49
+ }
50
+ export function antigravityAuthStatus(bin, cwd, env = process.env) {
51
+ const r = spawnAgentControlCommand(bin, ["models"], cwd, { cwd, env, encoding: "utf8", timeout: 30000, maxBuffer: 1024 * 1024, windowsHide: true });
52
+ if (!r.error && r.status === 0 && /^\S+\t.+/m.test(r.stdout))
53
+ return { status: "authenticated", message: null };
54
+ if (/Please sign in to view available models/.test(r.stderr))
55
+ return { status: "unauthenticated", message: "Antigravity CLIのGoogleサインインが必要です" };
56
+ return { status: "failed", message: "Antigravity CLIの認証状態を確認できません" };
57
+ }
58
+ export function antigravityAuthPane(screen) {
59
+ const lines = screen.split("\n"), start = lines.findIndex(line => line.includes("https://accounts.google.com/"));
60
+ const urlLines = [];
61
+ if (start >= 0)
62
+ for (const line of lines.slice(start)) {
63
+ if (/^\s*─|After authenticating|authorization code/i.test(line))
64
+ break;
65
+ urlLines.push(line.trim());
66
+ }
67
+ const url = authUrl(urlLines.join(""), ["accounts.google.com"]);
68
+ const complete = /Do you trust the contents of this project\?/.test(screen)
69
+ || (/\? for shortcuts/.test(screen) && /^\s*>\s*$/m.test(screen));
70
+ const base = { url, user_code: null, input_required: false, message: null, onboarding_complete: complete };
71
+ if (complete)
72
+ return base;
73
+ if (/authorization code/i.test(screen)) {
74
+ const empty = lines.some(line => /^\s*authorization code(?:\.{3}|…)?\s*$/.test(line));
75
+ return { ...base, input_required: true, native_input: { kind: "authorization_code", empty },
76
+ ...(empty ? { ui: { stage: "paste_code", title: "Antigravityの認証コード", message: "公式ページで認証し、表示されたコードを入力してください。", input: "authorization_code", choices: [] } } : {}) };
77
+ }
78
+ const rows = [];
79
+ let title = "";
80
+ if (/Select login method:/.test(screen)) {
81
+ title = "Antigravityのログイン方法";
82
+ for (const line of lines) {
83
+ const m = /^\s*(>)?\s*([12])\. (Google OAuth|Use a Google Cloud project)\s*$/.exec(line);
84
+ if (m)
85
+ rows.push({ id: `option-${m[2]}`, label: m[3], selected: !!m[1] });
86
+ }
87
+ }
88
+ else if (/Choose your color scheme:/.test(screen)) {
89
+ title = "Antigravityの表示テーマ";
90
+ for (const line of lines) {
91
+ const m = /^\s*(>)?\s*(terminal|light|solarized light|colorblind-friendly light|dark|solarized dark|colorblind-friendly dark|tokyo night)\s*(?:│.*)?$/.exec(line);
92
+ if (m)
93
+ rows.push({ id: `option-${rows.length + 1}`, label: m[2], selected: !!m[1] });
94
+ }
95
+ }
96
+ else if (/Terms of Service & Data Use/.test(screen)) {
97
+ title = "Antigravityのデータ提供設定";
98
+ const checkbox = /^\s*(>)?\s*\[([ x])\] Yes, I agree/m.exec(screen);
99
+ if (!checkbox)
100
+ return base;
101
+ rows.push({ id: "option-1", label: `任意の会話データ提供を${checkbox[2] === "x" ? "オフ" : "オン"}にする`, selected: !!checkbox[1] });
102
+ rows.push({ id: "option-2", label: "前の画面へ戻る", selected: />\s*Previous/.test(screen) });
103
+ rows.push({ id: "option-3", label: "現在の設定で完了する", selected: />\s*Done/.test(screen) });
104
+ }
105
+ const selected = rows.filter(row => row.selected);
106
+ if (!rows.length || selected.length !== 1)
107
+ return base;
108
+ return { ...base, input_required: true, native_input: { kind: "choice", selected_id: selected[0].id },
109
+ ui: { stage: "select", title, message: "公式CLIの選択肢を選んでください。", input: "choice", choices: rows.map(({ id, label }) => ({ id, label })) } };
110
+ }
111
+ export function antigravityAuthChoiceKey(screen, target) {
112
+ const pane = antigravityAuthPane(screen);
113
+ if (pane.native_input?.kind !== "choice" || !pane.ui?.choices.some(item => item.id === target))
114
+ throw new AitermError("Antigravity認証の選択肢が変わりました", 2);
115
+ const current = pane.native_input.selected_id;
116
+ if (current === target)
117
+ return "Enter";
118
+ if (!/Terms of Service & Data Use/.test(screen))
119
+ return "Down";
120
+ if (current === "option-1")
121
+ return "Down";
122
+ if (target === "option-1")
123
+ return "Up";
124
+ return current === "option-2" ? "Right" : "Left";
125
+ }
126
+ export function antigravityPaneObservation(screen) {
127
+ if (/esc to dismiss/.test(screen))
128
+ return { state: "blocked", reason: "vendor_notice" };
129
+ if (/Select login method|authorization code|Choose your color scheme|Terms of Service|Do you trust|ask_permission|Always Allow|Allow for this session/i.test(screen))
130
+ return { state: "blocked", reason: "vendor_action_required" };
131
+ if (/(?:Generating|Working)(?:\.{3}|…)|esc to interrupt/i.test(screen))
132
+ return { state: "busy", reason: "vendor_generating" };
133
+ if (/\? for shortcuts/.test(screen) && /^\s*>\s*$/m.test(screen))
134
+ return { state: "idle", reason: "composer_ready" };
135
+ return { state: "unknown", reason: "vendor_state_unknown" };
136
+ }
137
+ export function antigravityStartupAction(screen, trust, cwd) {
138
+ if (/esc to dismiss/.test(screen))
139
+ return { kind: "antigravity_notice", keys: ["Escape"] };
140
+ const heading = screen.indexOf("Do you trust the contents of this project?");
141
+ const lines = heading < 0 ? [] : screen.slice(0, heading).trimEnd().split("\n");
142
+ const normalize = (value) => value.replace(/\\/g, "/");
143
+ const matches = cwd && lines.some((_, at) => normalize(lines.slice(at).map(line => line.trim()).join("")) === normalize(cwd));
144
+ if (trust && matches)
145
+ return { kind: "antigravity_trust", keys: ["Enter"], selected: /^>\s*Yes, I trust this folder/ };
146
+ return null;
147
+ }
148
+ export function antigravityCurrentModel(screen, catalog) {
149
+ const header = screen.split("\n").slice(0, 10).map(line => line.trim());
150
+ const footer = screen.split("\n").slice(-5).join("\n");
151
+ const matches = catalog.models.filter(model => model.display_name && (header.some(line => line.endsWith(model.display_name))
152
+ || (model.default_effort && footer.includes(`${model.display_name.replace(/ \((?:Low|Medium|High|Xhigh|Max)\)$/, "")} · ${model.default_effort}`))));
153
+ return matches.length === 1 ? matches[0].id : null;
154
+ }
155
+ export function antigravityHookFile(home = process.env.HOME ?? os.homedir()) {
156
+ return path.join(home, ".gemini", "config", "hooks.json");
157
+ }
158
+ export function mergeAntigravityHooks(file = antigravityHookFile(), node = liveNodeExecutable(), script = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "antigravity-hook.js")) {
159
+ const target = fs.existsSync(file) ? fs.realpathSync(file) : file;
160
+ let current = {};
161
+ if (fs.existsSync(target))
162
+ current = z.record(z.string(), z.unknown()).parse(JSON.parse(fs.readFileSync(target, "utf8")));
163
+ const previous = current["aiterm-native"];
164
+ if (previous && typeof previous === "object" && previous.enabled === false)
165
+ throw new AitermError("ANTIGRAVITY_HOOK_DISABLED: aiterm-native hookは利用者が無効にしています", 2);
166
+ const command = (event) => process.platform === "win32"
167
+ ? `pwsh.exe ${powershellInvocation(node, [script, event]).join(" ")}`
168
+ : [node, script, event].map(shq).join(" ");
169
+ const entry = { SessionStart: [{ type: "command", command: command("SessionStart"), timeout: 10 }], Stop: [{ type: "command", command: command("Stop"), timeout: 10 }] };
170
+ if (isDeepStrictEqual(current["aiterm-native"], entry))
171
+ return "unchanged";
172
+ fs.mkdirSync(path.dirname(target), { recursive: true });
173
+ if (fs.existsSync(target))
174
+ fs.copyFileSync(target, `${target}.aiterm-backup`);
175
+ writeJson0600(target, { ...current, "aiterm-native": entry });
176
+ if (!isDeepStrictEqual(JSON.parse(fs.readFileSync(target, "utf8"))["aiterm-native"], entry))
177
+ throw new AitermError("ANTIGRAVITY_HOOK_READBACK_FAILED", 2);
178
+ return "configured";
179
+ }
180
+ export function createAntigravityAgentMetadata(name, cwd, initial, writeScope, lineage) {
181
+ const launchId = randomBytes(16).toString("hex");
182
+ const meta = { kind: "antigravity", aiterm_session: name, launch_id: launchId, event_file: agentEventPath(name, launchId),
183
+ created_at: new Date().toISOString(), cwd, vendor_session_id: null, initial_prompt: initial,
184
+ hook_route: "shared_antigravity_home", antigravity_home: realAntigravityHome(), ...agentLineageFields(lineage),
185
+ ...(writeScope ? { write_scope: writeScope } : {}), node_platform: process.platform };
186
+ createEmpty0600(meta.event_file);
187
+ writeAgentMetadata(meta);
188
+ return meta;
189
+ }
190
+ export function antigravityAgentArgv(bin, model, effort, prompt) {
191
+ return [bin, "--dangerously-skip-permissions", "--settings", '{"queuedMessages":"send-immediately"}', ...(model ? ["--model", model] : []), ...(effort ? ["--effort", effort] : []), ...(prompt ? ["--prompt-interactive", prompt] : [])];
192
+ }
193
+ export function antigravityBindingFile(meta) {
194
+ return path.join(agentsDir(), `${meta.aiterm_session}.${meta.launch_id}.antigravity-session.json`);
195
+ }
196
+ const bindingSchema = z.object({ conversation_id: z.uuid(), transcript: z.string().min(1) }).strict();
197
+ export function antigravityBinding(meta) {
198
+ const file = antigravityBindingFile(meta);
199
+ if (!fs.existsSync(file))
200
+ return null;
201
+ const result = bindingSchema.parse(JSON.parse(fs.readFileSync(file, "utf8")));
202
+ if (!meta.antigravity_home || !path.isAbsolute(result.transcript) || !path.relative(path.join(meta.antigravity_home, "brain", result.conversation_id), result.transcript).startsWith(".system_generated" + path.sep))
203
+ throw new AitermError("ANTIGRAVITY_BINDING_INVALID", 2);
204
+ return result;
205
+ }
206
+ export function bindAntigravitySession(meta) {
207
+ const binding = antigravityBinding(meta);
208
+ if (!binding)
209
+ return;
210
+ if (meta.vendor_session_id && meta.vendor_session_id !== binding.conversation_id)
211
+ throw new AitermError("ANTIGRAVITY_SESSION_MISMATCH", 2);
212
+ if (!meta.vendor_session_id) {
213
+ meta.vendor_session_id = binding.conversation_id;
214
+ writeAgentMetadata(meta);
215
+ }
216
+ }
217
+ export function antigravityResultPath(meta, turn) {
218
+ if (!/^\d{1,15}-\d{1,15}$/.test(turn))
219
+ throw new AitermError("ANTIGRAVITY_TURN_INVALID", 2);
220
+ return path.join(agentsDir(), `${meta.aiterm_session}.${meta.launch_id}.antigravity-result-${turn}.json`);
221
+ }
222
+ export function antigravityTranscriptText(meta, done) {
223
+ const body = z.object({ text: z.string(), conversation_id: z.uuid(), user_step: z.number().int().nonnegative(), execution: z.number().int().nonnegative() }).strict()
224
+ .parse(JSON.parse(fs.readFileSync(antigravityResultPath(meta, done.turn_id ?? ""), "utf8")));
225
+ if (body.conversation_id !== done.vendor_session_id || `${body.user_step}-${body.execution}` !== done.turn_id || Buffer.byteLength(body.text) !== done.result_bytes
226
+ || createHash("sha256").update(body.text).digest("hex") !== done.result_digest)
227
+ throw new AitermError("ANTIGRAVITY_RESULT_MISMATCH", 2);
228
+ return body.text;
229
+ }
230
+ export function antigravityTurn(file, requireAnswer) {
231
+ const size = safeStatSize(file), limit = 4 * 1024 * 1024;
232
+ if (!size)
233
+ throw new AitermError("ANTIGRAVITY_TRANSCRIPT_UNAVAILABLE", 2);
234
+ let text = readFileRange(file, Math.max(0, size - limit), size).toString("utf8");
235
+ if (size > limit)
236
+ text = text.slice(text.indexOf("\n") + 1);
237
+ const lines = text.split("\n");
238
+ if (lines.pop()?.trim())
239
+ throw new AitermError("ANTIGRAVITY_TRANSCRIPT_INCOMPLETE", 2);
240
+ let answer = null;
241
+ for (const line of lines.reverse()) {
242
+ if (!line.trim())
243
+ continue;
244
+ const row = JSON.parse(line);
245
+ if (row.type === "USER_INPUT") {
246
+ if (!Number.isSafeInteger(row.step_index) || row.step_index < 0 || (answer && answer.step <= row.step_index))
247
+ break;
248
+ if (requireAnswer && !answer)
249
+ break;
250
+ return { user_step: row.step_index, text: requireAnswer ? answer.text : "" };
251
+ }
252
+ if (!answer && row.type === "PLANNER_RESPONSE" && row.status === "DONE" && typeof row.content === "string"
253
+ && Number.isSafeInteger(row.step_index))
254
+ answer = { step: row.step_index, text: row.content };
255
+ }
256
+ throw new AitermError("ANTIGRAVITY_FINAL_RESPONSE_UNAVAILABLE", 2);
257
+ }