aiterm-mcp 0.61.19 → 0.61.21

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
@@ -16,6 +16,13 @@ import * as path from "node:path";
16
16
  import { createHash, randomBytes } from "node:crypto";
17
17
  import { fileURLToPath } from "node:url";
18
18
  import * as rtk from "./rtk.js";
19
+ import { manageClaudeAgentGoal, manageGrokAgentGoal } from "./agent-goal-native-result.js";
20
+ import { grokCurrentSessionOwner, readFreshGrokGoal, clearGrokGoal, grokGoalClearReady } from './harnesses/grok-goal.js';
21
+ import { nativeGoalClickBytes } from './agent-goal-ui.js';
22
+ import { readClaudeGoalDialog, clearClaudeGoal, setClaudeGoalObjective, claudeCurrentSessionOwner } from "./harnesses/claude-goal.js";
23
+ import { AgentGoalNotIssuedError, manageAgentGoal } from "./agent-goal.js";
24
+ import { withCodexGoal } from "./harnesses/codex-goal.js";
25
+ import { createCodexGoalObjective, editCodexGoalObjective, submitCodexGoalCommand } from "./harnesses/codex-goal-editor.js";
19
26
  import { closeExpectedExecution, parseExecutionNativeSessions, executionNativeBindingSchema } from "./execution-close.js";
20
27
  import { executionLaunchSchema, executionPointSchema } from "./execution-contract.js";
21
28
  import { withExecutionInterruptEffectScope, bindExecutionNativeTarget, beforeExecutionEffect, bindExecutionCreatedLaunch, executionCreatedNativeBinding, hasExecutionCreationScope, assertExecutionContext, withExecutionPreparation, captureExecutionSendBoundary, readExecutionSendBoundary, executionManagementCloseTarget, withExecutionNativeAdmission } from "./execution-effect.js";
@@ -24,7 +31,7 @@ import { readExecutionParentProcess } from "./execution-parent-process.js";
24
31
  import { isCursorMcpClient } from "aiterm-steer-delivery";
25
32
  import { paneTokenHint } from "./harnesses/pane-tokens.js";
26
33
  import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
27
- import { readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, processElapsedSeconds } from "./process-runtime.js";
34
+ import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, processElapsedSeconds } from "./process-runtime.js";
28
35
  import { liveNodeExecutable } from "./live-node.js";
29
36
  import { AitermError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
30
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";
@@ -35,7 +42,7 @@ import { catalogUnavailable } from "./model-catalog.js";
35
42
  import { FastModeError, fastModeFailure } from "./fast-mode.js";
36
43
  import { readFileOrNull, restoreJsonSetting, withUserConfigLock } from "./user-config.js";
37
44
  import { isDeepStrictEqual } from "node:util";
38
- import { grokAuthPlan, grokAuthStatus, grokAuthPane, GROK_MODEL_DEFAULTS, realGrokHome, resolveAndValidateGrokAuth, assertGrokModelAvailable, grokModelChoices, grokModelFromFooter, grokFooterModelName, grokModelDefaultsFromBody, restoreGrokModelDefaults, grokEventsTranscript, latestGrokCompletion, grokTurnSettled, observeGrokDone, buildGrokAgentCmd, grokAgentArgv, grokLaunchNote, grokEnvTokens, grokEnvEntries, grokTuiReady, grokPaneObservation, GROK_INTERRUPT_KEY, grokRateLimitDialog, grokPromptAwaitingAccept, grokUnacceptedPromptRestored, grokStartupAction, grokFooterHasConfiguration, grokTranscriptText, createGrokAgentMetadata, } from "./harnesses/grok.js";
45
+ 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";
39
46
  import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexRunningTurn, codexInterruptionRecord, observeCodexDone, buildCodexAgentCmd, codexAgentArgv, codexLaunchNote, codexPaneObservation, CODEX_INTERRUPT_KEY, codexHelperProcess, codexRateLimitModelSwitchDialog, codexApprovalDialog, codexStartupAction, codexModelChoice, codexEffortChoice, codexMoreReasoningChoice, codexTranscriptText, createCodexAgentMetadata, codexModelChoices, codexFastCommandOffered, codexFooterShowsFast, codexServiceTierNotices, restoreCodexDefaults, restoreCodexDefaultInFile, } from "./harnesses/codex.js";
40
47
  import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, OPERATION_ID_RE, CLAUDE_RESULT_MAX_BYTES, CLAUDE_EFFORTS, agentManagedClaudeSettingsPath, agentClaudeResultPath, agentClaudeOperationPath, agentClaudeApprovalReceiptPath, agentClaudeDispatchReceiptPath, validateOperationId, readClaudeResultText, assertClaudeAuthenticationReady, claudeModelChoices, claudeConfigDir, claudeFastIndicatorShown, claudeFastResult, buildClaudeAgentCmd, claudeAgentArgv, claudeLaunchNote, claudePaneObservation, CLAUDE_INTERRUPT_KEY, claudeUsageLimit, claudeLiveSelectMenu, claudeModelPicker, claudeModelPickerRow, claudeModelSwitchConfirm, claudeModelSwitchResult, claudeStartupAction, createClaudeAgentMetadata, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, } from "./harnesses/claude.js";
41
48
  import { cursorAuthPlan, cursorAuthStatus, cursorAuthPane, bindCursorTranscriptSession, cursorTurnBoundary, latestCursorCompletion, 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";
@@ -177,6 +184,28 @@ export function termiosIsCooked(sttyOutput) {
177
184
  const tokens = sttyOutput.split(/[\s;]+/);
178
185
  return tokens.includes("icanon") || tokens.includes("echo");
179
186
  }
187
+ /** Read-only ownership proof. A matching screen or another foreground CLI is
188
+ * not evidence that this original process owns the pane input. */
189
+ export function paneTtyInputOwnerReady(psOutput, expectedPid, expectedGroup, sttyOutput, agentPattern = AGENT_COMMAND_PATTERNS.codex) {
190
+ if (!Number.isSafeInteger(expectedPid) || expectedPid < 1 || !Number.isSafeInteger(expectedGroup) || expectedGroup < 1)
191
+ return false;
192
+ const rows = [];
193
+ for (const line of psOutput.split("\n").filter(value => value.trim())) {
194
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/u.exec(line);
195
+ if (!match)
196
+ return false;
197
+ rows.push({ pid: Number(match[1]), group: Number(match[2]), stat: match[3], command: match[4] });
198
+ }
199
+ const owners = rows.filter(row => row.pid === expectedPid);
200
+ if (owners.length !== 1 || owners[0].group !== expectedGroup || !owners[0].stat.includes("+")
201
+ || /[TtZ]/u.test(owners[0].stat) || rows.some(row => row.stat.includes("+") && row.group !== expectedGroup))
202
+ return false;
203
+ const state = classifyPaneTtyProcesses(rows.filter(row => row.group === expectedGroup)
204
+ .map(row => `${row.stat} ${row.command}`).join("\n"), agentPattern);
205
+ const flags = new Set(sttyOutput.split(/[\s;]+/u));
206
+ return state.agentPresent && state.agentForeground && !state.agentStopped
207
+ && flags.has("-icanon") && flags.has("-echo") && !termiosIsCooked(sttyOutput);
208
+ }
180
209
  function paneTtyOf(name) {
181
210
  const r = tmux("display-message", "-p", "-t", `=${name}:`, "#{pane_tty}");
182
211
  if (r.code !== 0)
@@ -849,6 +878,7 @@ export function send(name, text, o = {}) {
849
878
  throw new AitermError("aiterm相関付きClaude agent sessionへの通常送信はturn境界を失うため拒否します。" +
850
879
  "pty_send(forceなし=自動dispatch)を使うか、通常対話へ切り替えるならsessionをcloseしてpty_openから手動起動し直してください。", 2);
851
880
  }
881
+ o.beforePtyWrite?.();
852
882
  writeLastcmd(name, o.launchShell ? atomicShellMultiline(text, o.launchShell) : text);
853
883
  if (o.rtk)
854
884
  text = rtkRewrite(text);
@@ -885,6 +915,7 @@ export function send(name, text, o = {}) {
885
915
  // server commandでpayload全体を単一SendBytesへ変換し、別processとの交差を構造的に防ぐ。
886
916
  const writePty = (payload, bracketedPaste, what) => {
887
917
  if (isWin) {
918
+ o.beforePtyWrite?.();
888
919
  const sent = sendPsmuxPayload(true, name, payload, bracketedPaste);
889
920
  if (sent.code !== 0) {
890
921
  throw new AitermError(`psmuxのPTY送信に失敗しました${what}: ${sent.stderr.trim() || `code=${sent.code}`}`, 2);
@@ -912,6 +943,13 @@ export function send(name, text, o = {}) {
912
943
  if (pasteSupportsNoSanitize)
913
944
  pasteArgs.push("-S");
914
945
  pasteArgs.push("-b", bufferName, "-t", name);
946
+ try {
947
+ o.beforePtyWrite?.();
948
+ }
949
+ catch (error) {
950
+ tmuxCleanup("delete-buffer", "-b", bufferName);
951
+ throw error;
952
+ }
915
953
  const pasted = tmux(...pasteArgs);
916
954
  if (pasted.code !== 0) {
917
955
  tmuxCleanup("delete-buffer", "-b", bufferName);
@@ -940,6 +978,7 @@ export function send(name, text, o = {}) {
940
978
  else
941
979
  writePty(text, !!o.bracketedPaste, "");
942
980
  if (enter) {
981
+ o.beforePtyWrite?.();
943
982
  const entered = tmux("send-keys", "-t", name, "Enter");
944
983
  if (entered.code !== 0) {
945
984
  throw new AitermError(`文字列はPTYに入力済みですがtmuxへEnterを送れませんでした: ` +
@@ -4473,12 +4512,28 @@ async function respondAgentAuth(kind, options) {
4473
4512
  finally {
4474
4513
  release();
4475
4514
  }
4476
- await sleep(100);
4477
4515
  try {
4478
- const result = await authenticateAgent(kind, { action: "status", session_id: name });
4479
- if (result.auth_ui?.input === "authorization_code" && response.data.kind === "authorization_code")
4480
- throw new Error("native input consumption unconfirmed");
4481
- return result;
4516
+ const initialMeta = loadAuthMetadata(name, kind);
4517
+ const checkReadbackGeneration = (result) => {
4518
+ const current = loadAuthMetadata(name, kind);
4519
+ const stat = fs.lstatSync(authMetadataPath(name));
4520
+ const sameOnboardingLaunch = expected.data.launch_id !== null && initialMeta?.phase === "login" && current?.phase === "onboarding"
4521
+ && result?.status === "waiting" && result.auth_ui?.binding?.launch_id === expected.data.launch_id;
4522
+ if (!current || (current.launch_id ?? null) !== expected.data.launch_id
4523
+ || !sameOnboardingLaunch && !expected.data.metadata_identity.startsWith(`${stat.dev}:${stat.ino}:${stat.birthtimeMs}:`))
4524
+ throw new Error("native authentication generation changed");
4525
+ };
4526
+ const deadline = performance.now() + 3000;
4527
+ do {
4528
+ await sleep(100);
4529
+ checkReadbackGeneration();
4530
+ const result = await authenticateAgent(kind, { action: "status", session_id: name });
4531
+ checkReadbackGeneration(result);
4532
+ if (result.auth_ui?.input !== "authorization_code" || response.data.kind !== "authorization_code")
4533
+ return result;
4534
+ // Native input and its redraw are asynchronous; observe without submitting again.
4535
+ } while (performance.now() < deadline);
4536
+ throw new Error("native input consumption unconfirmed");
4482
4537
  }
4483
4538
  catch {
4484
4539
  throw new AuthResponseError("AGENT_AUTH_RESPONSE_UNKNOWN", "unknown", "入力後の状態を確認できません。自動再送しないでください。");
@@ -4581,19 +4636,52 @@ export async function authenticateAgent(kind, options) {
4581
4636
  meta = loaded;
4582
4637
  }
4583
4638
  const session = name;
4584
- const deadline = performance.now() + (options.action === "start" ? 3000 : 0);
4639
+ const exitDeadline = performance.now() + 3000;
4640
+ const deadline = options.action === "start" ? exitDeadline : performance.now();
4641
+ const originalStat = fs.lstatSync(authMetadataPath(session));
4642
+ let pendingExit = false;
4643
+ const pendingExitRefusal = () => {
4644
+ if (!pendingExit)
4645
+ return null;
4646
+ if (!authSessionExists(session))
4647
+ return result("failed", null, "認証sessionが失われました。元の終了状態は未確認です。");
4648
+ const current = loadAuthMetadata(session, kind);
4649
+ const stat = current && fs.lstatSync(authMetadataPath(session));
4650
+ return !current || !stat || (current.launch_id ?? null) !== (meta.launch_id ?? null)
4651
+ || stat.dev !== originalStat.dev || stat.ino !== originalStat.ino || stat.birthtimeMs !== originalStat.birthtimeMs
4652
+ ? result("failed", null, "認証sessionの世代が変わりました。元の終了状態は未確認です。") : null;
4653
+ };
4585
4654
  for (;;) {
4586
4655
  if (!authSessionExists(session))
4587
4656
  return result("failed", null, "認証sessionが失われました。agent_authのstartで開始してください。");
4588
- const observed = tmux("display-message", "-p", "-t", session, "#{pane_dead}\t#{pane_dead_status}");
4657
+ const beforeExitRead = pendingExitRefusal();
4658
+ if (beforeExitRead)
4659
+ return beforeExitRead;
4660
+ const observed = tmux("display-message", "-p", "-t", session, "#{pane_dead}\t#{pane_dead_status}\t#{pane_dead_signal}");
4589
4661
  if (observed.code !== 0)
4590
4662
  return result("failed", session, "認証processの終了状態を取得できません。");
4591
- const [dead, exit] = observed.stdout.trim().split("\t");
4663
+ const [dead, exit, signal] = observed.stdout.trim().split("\t");
4592
4664
  const pane = authPane(meta, stripControl(captureScreen(session, 0)));
4665
+ const afterExitRead = pendingExitRefusal();
4666
+ if (afterExitRead)
4667
+ return afterExitRead;
4668
+ if (pendingExit && dead === "0")
4669
+ return result("failed", null, "認証processが終了観測中に交代しました。元の終了状態は未確認です。");
4593
4670
  if (dead === "1") {
4671
+ // tmux can close the PTY before waitpid publishes either status or signal.
4672
+ if (!exit && !signal && performance.now() < exitDeadline) {
4673
+ pendingExit = true;
4674
+ await sleep(100);
4675
+ continue;
4676
+ }
4677
+ if (signal)
4678
+ return result("failed", session, `公式認証processがsignalで終了しました(signal=${/^[A-Z0-9]+$/.test(signal) ? signal : "unknown"})。`);
4594
4679
  if (exit !== "0")
4595
4680
  return result("failed", session, `公式認証processが失敗しました(exit=${/^\d+$/.test(exit ?? "") ? exit : "unknown"})。`);
4596
4681
  const checked = await authStatus(kind, meta.bin, meta.cwd, authSessionEnvironment(session, meta.env_vars));
4682
+ const afterOfficialStatus = pendingExitRefusal();
4683
+ if (afterOfficialStatus)
4684
+ return afterOfficialStatus;
4597
4685
  if (checked.status === "failed")
4598
4686
  return result("failed", session, checked.message);
4599
4687
  if (checked.status === "unauthenticated")
@@ -5339,6 +5427,219 @@ async function applyLaunchFast(name, meta) {
5339
5427
  };
5340
5428
  }
5341
5429
  }
5430
+ /** Goal operations share the existing seat admission and original launch ID. */
5431
+ export async function agentGoal(input, origin = "automatic") {
5432
+ assertSessionName(input.session_id);
5433
+ if (input.action !== "inspect")
5434
+ assertExecutionContext(input.session_id);
5435
+ const resolve = () => {
5436
+ const generation = observeSessionGeneration(input.session_id);
5437
+ const meta = tryLoadAgentMetadata(input.session_id);
5438
+ if (!generation.exists || generation.launch_id !== input.launch_id || meta?.launch_id !== input.launch_id)
5439
+ return null;
5440
+ const observed = observeSession(input.session_id);
5441
+ if (observed.launch_id !== input.launch_id || observed.harness_alive !== true || observed.harness_process === null)
5442
+ return null;
5443
+ return { session_id: input.session_id, launch_id: meta.launch_id, harness: agentHarness(meta.kind),
5444
+ vendor_session_id: meta.vendor_session_id, codex_home: meta.codex_home, grok_home: meta.grok_home, cwd: meta.cwd ?? process.cwd(), executable: meta.agent_executable,
5445
+ native_process: observed.harness_process };
5446
+ };
5447
+ const goalUi = (target) => {
5448
+ let inputStarted = false;
5449
+ let pinnedTty = null;
5450
+ const check = () => {
5451
+ const current = resolve();
5452
+ if (!current || current.vendor_session_id !== target.vendor_session_id
5453
+ || JSON.stringify(current.native_process) !== JSON.stringify(target.native_process))
5454
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
5455
+ const tty = paneTtyOf(input.session_id);
5456
+ const owner = target.native_process;
5457
+ const rejectOwner = (reason = "goal_input_owner_unavailable") => {
5458
+ if (!inputStarted)
5459
+ throw new AgentGoalNotIssuedError(reason);
5460
+ throw new Error("Goal input owner changed after input began");
5461
+ };
5462
+ if (target.harness === "claude-code") {
5463
+ const generation = owner ? readLinuxProcessRegistrationIdentity(owner.pid) : null;
5464
+ let registration;
5465
+ try {
5466
+ const file = path.join(claudeConfigDir(), "sessions", `${owner?.pid}.json`);
5467
+ const st = fs.lstatSync(file);
5468
+ if (!st.isFile() || st.isSymbolicLink() || st.size > 64 * 1024)
5469
+ throw new Error("native registration unavailable");
5470
+ registration = JSON.parse(fs.readFileSync(file, "utf8"));
5471
+ }
5472
+ catch {
5473
+ rejectOwner("goal_native_session_unavailable");
5474
+ }
5475
+ const ownership = generation && owner ? claudeCurrentSessionOwner(registration, { pid: owner.pid, sessionId: target.vendor_session_id, ...generation }) : "unavailable";
5476
+ if (ownership !== "match")
5477
+ rejectOwner(ownership === "mismatch" ? "goal_native_session_mismatch" : "goal_native_session_unavailable");
5478
+ }
5479
+ if (target.harness === 'grok-cli') {
5480
+ const identity = owner ? readLinuxProcessRegistrationIdentity(owner.pid) : null;
5481
+ let record;
5482
+ try {
5483
+ if (!target.grok_home)
5484
+ throw Error('native home unavailable');
5485
+ const file = path.join(target.grok_home, 'active_sessions.json'), st = fs.lstatSync(file);
5486
+ if (!st.isFile() || st.isSymbolicLink() || st.size > 1024 * 1024)
5487
+ throw Error('native registration unavailable');
5488
+ record = JSON.parse(fs.readFileSync(file, 'utf8'));
5489
+ }
5490
+ catch {
5491
+ rejectOwner('goal_native_session_unavailable');
5492
+ }
5493
+ const ownership = identity && owner ? grokCurrentSessionOwner(record, { pid: owner.pid, procStart: identity.procStart, sessionId: target.vendor_session_id, cwd: target.cwd }) : 'unavailable';
5494
+ if (ownership !== 'match')
5495
+ rejectOwner(ownership === 'mismatch' ? 'goal_native_session_mismatch' : 'goal_native_session_unavailable');
5496
+ }
5497
+ if (!tty || !owner?.process_group_id || pinnedTty !== null && pinnedTty !== tty)
5498
+ rejectOwner();
5499
+ const ps = spawnSync("/bin/ps", ["-t", tty.replace(/^\/dev\//u, ""), "-o", "pid=,pgid=,stat=,command="], { encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 5000 });
5500
+ const stty = spawnSync("/bin/stty", [process.platform === "linux" ? "-F" : "-f", tty, "-a"], { encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 5000 });
5501
+ if (ps.error || stty.error || ps.status !== 0 || stty.status !== 0 || paneTtyOf(input.session_id) !== tty
5502
+ || !paneTtyInputOwnerReady(ps.stdout, owner.pid, owner.process_group_id, stty.stdout, AGENT_COMMAND_PATTERNS[target.harness === "claude-code" ? "claude" : target.harness === 'grok-cli' ? 'grok' : "codex"]))
5503
+ rejectOwner();
5504
+ pinnedTty = tty;
5505
+ };
5506
+ const checkRow = (row, text) => {
5507
+ if (!Number.isSafeInteger(row) || row < 1 || row > 10000)
5508
+ throw new AgentGoalNotIssuedError('native_goal_ui_changed');
5509
+ const screen = tmux('capture-pane', '-e', '-p', '-J', '-t', input.session_id);
5510
+ if (screen.code !== 0 || screen.stdout.split('\n')[row - 1] !== text)
5511
+ throw new AgentGoalNotIssuedError('native_goal_ui_changed');
5512
+ };
5513
+ return {
5514
+ read() { check(); const value = tmux("capture-pane", "-e", "-p", "-J", "-t", input.session_id); if (value.code !== 0)
5515
+ throw new Error("Goal input observation unavailable"); return value.stdout; },
5516
+ async paste(text) {
5517
+ await withExecutionNativeAdmission(input.session_id, () => {
5518
+ check();
5519
+ send(input.session_id, text, { enter: false, force: true, mark: false, rtk: false, bracketedPaste: true, preserveAgentOperation: true,
5520
+ raw: true, beforePtyWrite: () => { check(); inputStarted = true; } });
5521
+ });
5522
+ },
5523
+ async keys(keys, expectedRow, confirm) {
5524
+ await withExecutionNativeAdmission(input.session_id, () => {
5525
+ check();
5526
+ if (expectedRow)
5527
+ checkRow(expectedRow.row, expectedRow.text);
5528
+ if (confirm) {
5529
+ const screen = tmux('capture-pane', '-e', '-p', '-J', '-t', input.session_id);
5530
+ if (screen.code !== 0 || !confirm(screen.stdout))
5531
+ throw new AgentGoalNotIssuedError('native_goal_ui_changed');
5532
+ }
5533
+ if (expectedRow || confirm)
5534
+ check();
5535
+ inputStarted = true;
5536
+ const sent = tmux("send-keys", "-t", input.session_id, ...keys);
5537
+ if (sent.code !== 0)
5538
+ throw new Error("Goal input key unconfirmed");
5539
+ });
5540
+ },
5541
+ async click(column, row, confirm) {
5542
+ await withExecutionNativeAdmission(input.session_id, () => {
5543
+ check();
5544
+ const size = tmux('display-message', '-p', '-t', input.session_id, '#{pane_width} #{pane_height}');
5545
+ if (size.code !== 0 || !/^\d+ \d+$/u.test(size.stdout.trim()))
5546
+ throw new AgentGoalNotIssuedError('native_goal_ui_changed');
5547
+ const [columns, rows] = size.stdout.trim().split(' ').map(Number);
5548
+ const bytes = nativeGoalClickBytes(column, row, columns, rows);
5549
+ const current = tmux('capture-pane', '-e', '-p', '-J', '-t', input.session_id);
5550
+ if (current.code !== 0 || !confirm(current.stdout))
5551
+ throw new AgentGoalNotIssuedError('native_goal_ui_changed');
5552
+ check();
5553
+ inputStarted = true;
5554
+ const sent = tmux('send-keys', '-t', input.session_id, '-H', ...Array.from(Buffer.from(bytes), byte => byte.toString(16).padStart(2, '0')));
5555
+ if (sent.code !== 0)
5556
+ throw new Error('Goal pointer input unconfirmed');
5557
+ });
5558
+ },
5559
+ pause: sleep,
5560
+ };
5561
+ };
5562
+ const grokPort = (target) => {
5563
+ const ui = goalUi(target);
5564
+ const read = (relative, optional = false) => {
5565
+ ui.read();
5566
+ const meta = tryLoadAgentMetadata(input.session_id);
5567
+ if (!meta || meta.launch_id !== target.launch_id || meta.vendor_session_id !== target.vendor_session_id)
5568
+ throw Error('generation_replaced');
5569
+ const directory = grokSessionDirectory(meta);
5570
+ if (!directory)
5571
+ throw Error('native session directory unavailable');
5572
+ const file = path.join(directory, relative);
5573
+ let st;
5574
+ try {
5575
+ st = fs.lstatSync(file);
5576
+ }
5577
+ catch (error) {
5578
+ if (optional && error.code === 'ENOENT')
5579
+ return null;
5580
+ throw error;
5581
+ }
5582
+ if (!st.isFile() || st.isSymbolicLink() || st.size > 4 * 1024 * 1024)
5583
+ throw Error('native state unavailable');
5584
+ return fs.readFileSync(file, 'utf8');
5585
+ };
5586
+ return { ui, rows: () => { const text = read('updates.jsonl', true); return text === null ? [] : text.split('\n').filter(line => line.trim()).map(line => JSON.parse(line)); }, state: () => { const text = read('goal/state.json', true); return text === null ? null : JSON.parse(text); } };
5587
+ };
5588
+ if (resolve()?.harness === 'grok-cli')
5589
+ return withAgentSendLock(input.session_id, () => manageGrokAgentGoal(input, { resolve,
5590
+ read: target => readFreshGrokGoal(target.vendor_session_id, grokPort(target)),
5591
+ canClear: target => grokGoalClearReady(grokPort(target).ui),
5592
+ clear: (target, before) => clearGrokGoal(target.vendor_session_id, before, grokPort(target)),
5593
+ }, origin));
5594
+ if (resolve()?.harness === "claude-code")
5595
+ return withAgentSendLock(input.session_id, () => manageClaudeAgentGoal(input, { resolve,
5596
+ read: target => readClaudeGoalDialog(target.vendor_session_id, goalUi(target), () => {
5597
+ const meta = tryLoadAgentMetadata(input.session_id);
5598
+ if (!meta || meta.launch_id !== target.launch_id || meta.vendor_session_id !== target.vendor_session_id)
5599
+ throw new Error("generation_replaced");
5600
+ const file = claudeSessionTranscriptPath(meta);
5601
+ if (!file || !fs.existsSync(file))
5602
+ return [];
5603
+ return readTranscriptLines(file).filter(line => line.trim()).map(line => JSON.parse(line));
5604
+ }),
5605
+ clear: target => clearClaudeGoal(goalUi(target)),
5606
+ setObjective: (target, objective) => setClaudeGoalObjective(goalUi(target), objective), }, origin));
5607
+ const run = () => manageAgentGoal(input, { resolve, connect: (target, callback) => withCodexGoal(target, (request, supported, fields) => callback((method, params) => {
5608
+ if (method !== "thread/goal/set" && method !== "thread/goal/clear")
5609
+ return request(method, params);
5610
+ return withExecutionNativeAdmission(input.session_id, () => {
5611
+ beforeExecutionEffect(input.session_id, () => {
5612
+ const current = resolve();
5613
+ if (!current || current.vendor_session_id !== target.vendor_session_id || current.codex_home !== target.codex_home
5614
+ || JSON.stringify(current.native_process) !== JSON.stringify(target.native_process))
5615
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
5616
+ });
5617
+ return request(method, params);
5618
+ });
5619
+ }, supported, fields), command => submitCodexGoalCommand(goalUi(target), command), (before, objective) => editCodexGoalObjective(goalUi(target), before, objective), objective => createCodexGoalObjective(goalUi(target), objective)) }, origin);
5620
+ return input.action === "inspect" ? run() : withAgentSendLock(input.session_id, run);
5621
+ }
5622
+ /** Whole-app stop uses native goal state, not the host's displayed snapshot. */
5623
+ export async function pauseAgentGoalForStop(target) {
5624
+ if (!target.launch_id)
5625
+ return { status: "unavailable", reason: "goal_launch_unavailable" };
5626
+ const input = { session_id: target.session_id, launch_id: target.launch_id };
5627
+ const before = await agentGoal({ ...input, action: "inspect" });
5628
+ if (before.availability !== "available")
5629
+ return { status: before.availability, reason: before.reason };
5630
+ if (before.goal === null)
5631
+ return { status: "no_goal" };
5632
+ if (before.schema === "aiterm.agent-goal-result.v2")
5633
+ return { status: "unsupported", reason: "native_goal_pause_unsupported" };
5634
+ if (before.goal?.status === "paused" || before.goal?.status === "complete")
5635
+ return { status: "already_inactive" };
5636
+ if (before.goal?.status !== "active")
5637
+ return { status: "unavailable", reason: "goal_not_explicitly_paused" };
5638
+ const result = await agentGoal({ ...input, action: "pause", expected_thread_id: before.binding.thread_id }, "user");
5639
+ if (result.outcome === "applied" && result.readback === "confirmed" && result.schema === "aiterm.agent-goal-result.v1" && result.goal?.status === "paused")
5640
+ return { status: "paused" };
5641
+ return { status: result.availability === "unsupported" || result.outcome === "unsupported" ? "unsupported" : result.outcome === "outcome_unknown" ? "outcome_unknown" : "unavailable", reason: result.reason };
5642
+ }
5342
5643
  export async function configureAgent(name, opts) {
5343
5644
  assertExecutionContext(name);
5344
5645
  assertSessionName(name);
@@ -37,7 +37,7 @@ export const executionRequestSchema = z.discriminatedUnion("kind", [
37
37
  process_started_identity: referenceId,
38
38
  request_id: z.union([referenceId, z.number().int().safe()]),
39
39
  tool: z.enum(["agent_launch", "claude_agent", "codex_agent", "grok_agent", "pty_open", "pty_send", "pty_key", "pty_close",
40
- "agent_configure", "agent_auth.start", "agent_auth.status", "agent_auth.cancel", "agent_approval.respond",
40
+ "agent_configure", "agent_goal", "agent_auth.start", "agent_auth.status", "agent_auth.cancel", "agent_approval.respond",
41
41
  "claude_approval.respond", "claude_turn.issue"]), target_session_id: sessionId }).strict(),
42
42
  ]);
43
43
  // Owner correction: interruption preserves the current session/launch and
@@ -15,6 +15,8 @@ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
15
15
  function routeFor(name, args) {
16
16
  if (reads.has(name))
17
17
  return null;
18
+ if (name === "agent_goal" && args.action === "inspect")
19
+ return null;
18
20
  if ((name === "agent_approval" || name === "claude_approval") && args.action === "inspect")
19
21
  return null;
20
22
  if (name === "claude_turn" && args.action === "recover")
@@ -177,7 +179,8 @@ export function createExecutionDispatcher(bindings) {
177
179
  const authInput = (route.tool === "pty_send" || route.tool === "pty_key") && !supplied
178
180
  && client === "bellteam" ? authGeneration(route.target) : null;
179
181
  const hostAuth = client === "bellteam" && !supplied && authOperation;
180
- const hostManagement = hostClose || hostLaunch || hostConfigure || hostAuth || !!authInput;
182
+ const hostGoal = client === "bellteam" && route.tool === "agent_goal" && !supplied;
183
+ const hostManagement = hostClose || hostLaunch || hostConfigure || hostGoal || hostAuth || !!authInput;
181
184
  if (args.remote !== undefined && args.remote !== null)
182
185
  throw new ExecutionError("EXECUTION_UNSUPPORTED");
183
186
  let reference = supplied;
@@ -5,12 +5,15 @@ import { executionLaunchSchema, unfinishedExecutionRelations } from "./execution
5
5
  const session = executionLaunchSchema.shape.session_id;
6
6
  export const immediateStopInputSchema = z.object({
7
7
  session_id: session.optional(), session_ids: z.array(session).min(1).optional(),
8
+ pause_goals: z.boolean().optional(),
8
9
  }).strict().refine(value => (value.session_id !== undefined) !== (value.session_ids !== undefined));
10
+ export const goalPauseStatusSchema = z.enum(["paused", "already_inactive", "no_goal", "unsupported", "unavailable", "outcome_unknown"]);
9
11
  export const immediateStopResultSchema = z.object({
10
12
  session_id: session.optional(), status: z.enum(["sent", "partial", "failed", "idle"]),
11
- targets: z.array(z.object({ session_id: session, status: z.enum(["sent", "failed", "idle"]), error: z.string().optional() }).strict()),
13
+ targets: z.array(z.object({ session_id: session, status: z.enum(["sent", "failed", "idle"]), error: z.string().optional(),
14
+ goal_pause: goalPauseStatusSchema.optional(), goal_error: z.string().optional() }).strict()),
12
15
  }).strict();
13
- export function interruptKnownSessions(input, dependencies) {
16
+ function stopPlan(input, dependencies) {
14
17
  const args = immediateStopInputSchema.parse(input), roots = [...new Set(args.session_ids ?? [args.session_id])];
15
18
  let relations = [], children = [], graphUnavailable = false;
16
19
  try {
@@ -23,18 +26,23 @@ export function interruptKnownSessions(input, dependencies) {
23
26
  graphUnavailable = true;
24
27
  }
25
28
  const ordered = [], visited = new Set(), sent = new Set();
29
+ const links = [];
26
30
  const visit = (name, launchId) => {
27
31
  const key = JSON.stringify([name, launchId]);
28
32
  if (visited.has(key))
29
33
  return;
30
34
  visited.add(key);
31
35
  for (const child of children)
32
- if (child.parent === name)
36
+ if (child.parent === name) {
37
+ links.push({ parent: name, child: child.child });
33
38
  visit(child.child);
39
+ }
34
40
  for (const edge of relations)
35
41
  if (edge.source?.launch.session_id === name
36
- && (!launchId || edge.source.launch.launch_id === launchId) && edge.target)
42
+ && (!launchId || edge.source.launch.launch_id === launchId) && edge.target) {
43
+ links.push({ parent: name, child: edge.target.launch.session_id });
37
44
  visit(edge.target.launch.session_id, edge.target.launch.launch_id);
45
+ }
38
46
  if (!sent.has(name)) {
39
47
  sent.add(name);
40
48
  ordered.push({ session_id: name, ...(launchId ? { launch_id: launchId } : {}) });
@@ -48,27 +56,72 @@ export function interruptKnownSessions(input, dependencies) {
48
56
  catch { /* still send to the explicitly requested current session */ }
49
57
  visit(name, launchId ?? undefined);
50
58
  }
51
- const targets = ordered.map(target => {
52
- try {
53
- const receipt = dependencies.sendKey(target.session_id, target.launch_id);
54
- if (receipt?.then) {
55
- void Promise.resolve(receipt).catch(() => undefined);
56
- throw new Error("async key sender");
57
- }
58
- if (receipt?.outcome === "idle" && receipt.session_id === target.session_id)
59
- return { session_id: target.session_id, status: "idle" };
60
- if (receipt?.outcome !== "accepted" || receipt.session_id !== target.session_id)
61
- throw new Error("missing key receipt");
62
- return { session_id: target.session_id, status: "sent",
63
- ...(graphUnavailable && roots.includes(target.session_id) ? { error: "RELATION_GRAPH_UNAVAILABLE" } : {}) };
64
- }
65
- catch (error) {
66
- const code = error?.code;
67
- return { session_id: target.session_id, status: "failed",
68
- error: typeof code === "string" && /^EXECUTION_[A-Z_]+$/.test(code) ? code : "KEY_SEND_FAILED" };
59
+ return { args, roots, ordered, links, graphUnavailable };
60
+ }
61
+ function sendStopTarget(target, plan, dependencies) {
62
+ try {
63
+ const receipt = dependencies.sendKey(target.session_id, target.launch_id);
64
+ if (receipt?.then) {
65
+ void Promise.resolve(receipt).catch(() => undefined);
66
+ throw new Error("async key sender");
69
67
  }
70
- });
68
+ if (receipt?.outcome === "idle" && receipt.session_id === target.session_id)
69
+ return { session_id: target.session_id, status: "idle" };
70
+ if (receipt?.outcome !== "accepted" || receipt.session_id !== target.session_id)
71
+ throw new Error("missing key receipt");
72
+ return { session_id: target.session_id, status: "sent",
73
+ ...(plan.graphUnavailable && plan.roots.includes(target.session_id) ? { error: "RELATION_GRAPH_UNAVAILABLE" } : {}) };
74
+ }
75
+ catch (error) {
76
+ const code = error?.code;
77
+ return { session_id: target.session_id, status: "failed",
78
+ error: typeof code === "string" && /^EXECUTION_[A-Z_]+$/.test(code) ? code : "KEY_SEND_FAILED" };
79
+ }
80
+ }
81
+ function finishStop(plan, targets) {
82
+ const { args, graphUnavailable } = plan;
71
83
  const successful = targets.filter(target => target.status !== "failed").length;
84
+ const goalsConfirmed = targets.every(target => target.goal_pause === undefined
85
+ || ["paused", "already_inactive", "no_goal"].includes(target.goal_pause));
72
86
  return immediateStopResultSchema.parse({ ...(args.session_id ? { session_id: args.session_id } : {}),
73
- status: successful === targets.length && !graphUnavailable ? (targets.every(target => target.status === "idle") ? "idle" : "sent") : successful ? "partial" : "failed", targets });
87
+ status: successful === targets.length && !graphUnavailable && goalsConfirmed ? (targets.every(target => target.status === "idle") ? "idle" : "sent") : successful ? "partial" : "failed", targets });
88
+ }
89
+ export function interruptKnownSessions(input, dependencies) {
90
+ const plan = stopPlan(input, dependencies);
91
+ if (plan.args.pause_goals)
92
+ throw new Error("GOAL_PAUSE_REQUIRES_TRUSTED_ASYNC_STOP");
93
+ return finishStop(plan, plan.ordered.map(target => sendStopTarget(target, plan, dependencies)));
94
+ }
95
+ /** Explicit whole-application stop only. Ordinary interruption stays synchronous.
96
+ * One existing relation snapshot and one key per target; no retries or store. */
97
+ export async function interruptKnownSessionsAndGoals(input, dependencies, origin) {
98
+ const plan = stopPlan(input, dependencies);
99
+ if (!plan.args.pause_goals)
100
+ return finishStop(plan, plan.ordered.map(target => sendStopTarget(target, plan, dependencies)));
101
+ if (origin !== "user")
102
+ throw new Error("GOAL_OWNER_ACTION_REQUIRED");
103
+ // A target waits only for its selected descendants. Independent roots do
104
+ // not inherit another root's native read/pause deadline. Existing DFS order
105
+ // breaks relation cycles; no new queue, identity, timer, or retry is added.
106
+ const positions = new Map(plan.ordered.map((target, index) => [target.session_id, index]));
107
+ const jobs = [];
108
+ for (const [index, target] of plan.ordered.entries()) {
109
+ const descendants = [...new Set(plan.links.filter(link => link.parent === target.session_id)
110
+ .map(link => positions.get(link.child)).filter((position) => position !== undefined && position < index))];
111
+ jobs.push((async () => {
112
+ await Promise.all(descendants.map(position => jobs[position]));
113
+ let pause;
114
+ try {
115
+ pause = await dependencies.pauseGoal(target);
116
+ pause.status = goalPauseStatusSchema.parse(pause.status);
117
+ }
118
+ catch {
119
+ pause = { status: "outcome_unknown", reason: "GOAL_PAUSE_UNCONFIRMED" };
120
+ }
121
+ // Preserve the explicit emergency key even when goal state is unavailable.
122
+ return { ...sendStopTarget(target, plan, dependencies), goal_pause: pause.status,
123
+ ...(pause.reason ? { goal_error: pause.reason } : {}) };
124
+ })());
125
+ }
126
+ return finishStop(plan, await Promise.all(jobs));
74
127
  }
@@ -8,7 +8,8 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
8
8
  import * as core from "./core.js";
9
9
  import { localParentWorkerRuntime, createExecutionParentWorker } from "./execution-parent-worker.js";
10
10
  import { createExecutionParticipant } from "./execution-participant.js";
11
- import { interruptKnownSessions } from "./execution-immediate-stop.js";
11
+ import { interruptKnownSessions, interruptKnownSessionsAndGoals } from "./execution-immediate-stop.js";
12
+ import { goalOriginFromHost } from "./agent-goal.js";
12
13
  import { registerExecutionTools } from "./execution-tools.js";
13
14
  import { AITERM_PROFILE } from "./steer-profile.js";
14
15
  import { EXECUTION_SOURCE_ENV_NAMES, EXECUTION_SCOPE_ENV_NAMES } from "./execution-runtime.js";
@@ -19,17 +20,20 @@ import { immediateStopInputSchema, immediateStopResultSchema } from "./execution
19
20
  /** Ordinary delivery and leaf-first cancel keys have no execution-store
20
21
  * registration, participant gate, shared transaction or graph write. */
21
22
  export function createNativeDeliveryServer(dependencies = {}) {
22
- const server = createAitermServer();
23
+ const server = createAitermServer({ goalOrigin: dependencies.goalOrigin });
23
24
  server.registerTool("agent_stop", {
24
25
  description: "指定sessionとその呼出先へ末端から通常の停止キーを送る。sentはキー送信結果であり終了の証明ではない。",
25
26
  inputSchema: immediateStopInputSchema.shape,
26
27
  outputSchema: immediateStopResultSchema.shape,
27
- }, async (args) => {
28
- const result = interruptKnownSessions(args, {
28
+ }, async (args, extra) => {
29
+ const stop = {
29
30
  children: dependencies.children ?? core.agentSessionChildren,
30
31
  currentLaunchId: dependencies.currentLaunchId ?? core.interruptionLaunchId,
31
32
  sendKey: dependencies.sendKey ?? core.interruptSessionNow,
32
- });
33
+ };
34
+ const result = args.pause_goals
35
+ ? await interruptKnownSessionsAndGoals(args, { ...stop, pauseGoal: dependencies.pauseGoal ?? core.pauseAgentGoalForStop }, dependencies.goalOrigin ? dependencies.goalOrigin(extra) : goalOriginFromHost(server.server.getClientVersion()?.name, extra._meta))
36
+ : interruptKnownSessions(args, stop);
33
37
  return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result };
34
38
  });
35
39
  return server;