aiterm-mcp 0.62.6 → 0.63.1

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
@@ -1,3 +1,6 @@
1
+ import { nativePaneTarget } from "./native-session.js";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { inspectIdleSettings } from "./harnesses/idle-settings.js";
1
4
  import { AGENT_TUI_READY_TIMEOUT_MS, AGENT_TUI_FIRST_DRAW_TIMEOUT_MS, AGENT_TUI_READY_POLL_MS, isAgentTuiReady, isAgentTuiBusy, isAgentTuiIdleReady, agentPaneObservation, waitAgentTuiReadyImpl, detectAgentSubmitResidueImpl, waitCursorPromptVisibleImpl, settleAgentDoneScreenImpl } from "./agent-screen-observation.js";
2
5
  export { launchEchoIsLastOnScreen, __testSetAgentTuiReadyStableSamples } from "./agent-screen-observation.js";
3
6
  import { parseClaudeOperationMarker } from "./claude-operation-marker.js";
@@ -22,34 +25,41 @@ import { nativeGoalClickBytes } from './agent-goal-ui.js';
22
25
  import { readClaudeGoalDialog, clearClaudeGoal, setClaudeGoalObjective, claudeCurrentSessionOwner } from "./harnesses/claude-goal.js";
23
26
  import { AgentGoalNotIssuedError, manageAgentGoal } from "./agent-goal.js";
24
27
  import { withCodexGoal } from "./harnesses/codex-goal.js";
28
+ import { configureWithPausedGoal } from "./configure-goal.js";
29
+ import { initializeAgentActivity, recordAgentInput, recordAgentTurnEnd, readAgentActivity } from "./agent-activity.js";
30
+ import { checkIdleSeat, decideIdleSeat, idleMinutes } from "./agent-idle.js";
31
+ import { AGENT_IDLE_ENABLED, armAgentIdleClock, idleClockDeadline, isAgentIdleClockOwner, requestAgentIdleClock } from "./agent-idle-clock.js";
32
+ import { stopProcessTree } from "./process-tree-stop.js";
33
+ import { captureAgentResumeTemplate, readAgentResumeTemplate, writeAgentResumeTemplate, finishAgentResumeConfiguration, refreshAgentResumeRecipe, readAgentIdleClock, retireAgentIdleClock, readAgentResumeRecipe, writeAgentResumeRecipe, agentResumeRecipeDigest, readAgentLifecycle, writeAgentLifecycle, cancelAgentStopping, readAgentResumeAttempt, writeAgentResumeAttempt, readAgentResumeNative, writeAgentResumeNative } from "./agent-lifecycle.js";
25
34
  import { createCodexGoalObjective, editCodexGoalObjective, submitCodexGoalCommand } from "./harnesses/codex-goal-editor.js";
26
35
  import { closeExpectedExecution, parseExecutionNativeSessions, executionNativeBindingSchema } from "./execution-close.js";
27
36
  import { executionLaunchSchema, executionPointSchema } from "./execution-contract.js";
28
- import { withExecutionInterruptEffectScope, bindExecutionNativeTarget, beforeExecutionEffect, bindExecutionCreatedLaunch, executionCreatedNativeBinding, hasExecutionCreationScope, assertExecutionContext, withExecutionPreparation, captureExecutionSendBoundary, readExecutionSendBoundary, executionManagementCloseTarget, withExecutionNativeAdmission } from "./execution-effect.js";
37
+ import { withExecutionInterruptEffectScope, bindExecutionNativeTarget, beforeExecutionEffect, bindExecutionCreatedLaunch, executionCreatedNativeBinding, hasExecutionCreationScope, assertExecutionContext, assertExecutionResumeSupported, withExecutionPreparation, captureExecutionSendBoundary, readExecutionSendBoundary, executionManagementCloseTarget, withExecutionNativeAdmission } from "./execution-effect.js";
29
38
  import { ExecutionError } from "./execution-wire.js";
30
39
  import { readExecutionParentProcess } from "./execution-parent-process.js";
31
40
  import { isCursorMcpClient } from "aiterm-steer-delivery";
32
41
  import { antigravityAuthChoiceKey, antigravityCurrentModel, antigravityStartupAction, antigravityAgentArgv, antigravityModelChoices, antigravityAuthStatus, antigravityAuthPane, antigravityTranscriptText, bindAntigravitySession, createAntigravityAgentMetadata, mergeAntigravityHooks } from "./harnesses/antigravity.js";
33
42
  import { paneTokenHint } from "./harnesses/pane-tokens.js";
34
43
  import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
35
- import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, processElapsedSeconds } from "./process-runtime.js";
44
+ import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
36
45
  import { liveNodeExecutable } from "./live-node.js";
37
46
  import { AitermError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.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";
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";
47
+ import { isWin, SOCKDIR, SOCK, tmuxCommand, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, } from "./tmux-runtime.js";
48
+ 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, readAgentGeneration, selectAgentMetadataFile, publishAgentGeneration, agentEventPath, agentMetadataPath, writeAgentMetadata, AGENT_EVENT_TAIL_BYTES, agentLabel, agentHarness, subagentInstruction, agentLineageFields, } from "./agent-shared.js";
40
49
  import { AuthResponseError, authUi, authPromptDigest, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
41
50
  import { processStartIdentity } from "./runtime-error-os.js";
51
+ import { processStartIdentities } from "./process-start.js";
42
52
  import { catalogUnavailable } from "./model-catalog.js";
43
53
  import { FastModeError, fastModeFailure } from "./fast-mode.js";
44
54
  import { readFileOrNull, restoreJsonSetting, withUserConfigLock } from "./user-config.js";
45
55
  import { isDeepStrictEqual } from "node:util";
46
56
  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";
47
- import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexRunningTurn, codexInterruptionRecord, observeCodexDone, buildCodexAgentCmd, codexAgentArgv, codexLaunchNote, codexPaneObservation, CODEX_INTERRUPT_KEY, codexHelperProcess, codexRateLimitModelSwitchDialog, codexApprovalDialog, codexStartupAction, codexModelChoice, codexModelChangeNotices, codexEffortChoice, codexCurrentEffort, codexMoreReasoningChoice, codexTranscriptText, createCodexAgentMetadata, codexModelChoices, codexFastCommandOffered, codexFooterShowsFast, codexServiceTierNotices, restoreCodexDefaults, restoreCodexDefaultInFile, } from "./harnesses/codex.js";
48
- 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";
57
+ import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, captureCodexResumeProof, readCodexResumeProof, codexResumeProofDigest, codexRunningTurn, codexInterruptionRecord, observeCodexDone, buildCodexAgentCmd, codexAgentArgv, codexResumeArgv, codexLaunchNote, codexPaneObservation, CODEX_INTERRUPT_KEY, codexHelperProcess, codexRateLimitModelSwitchDialog, codexApprovalDialog, codexStartupAction, codexModelChoice, codexModelChangeNotices, codexEffortChoice, codexCurrentEffort, codexMoreReasoningChoice, codexTranscriptText, createCodexAgentMetadata, codexModelChoices, codexFastCommandOffered, codexFooterShowsFast, codexServiceTierNotices, restoreCodexDefaults, restoreCodexDefaultInFile, } from "./harnesses/codex.js";
58
+ 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, claudeResumeArgv, claudeLaunchNote, claudePaneObservation, CLAUDE_INTERRUPT_KEY, claudeUsageLimit, claudeLiveSelectMenu, claudeModelPicker, claudeModelPickerRow, claudeModelSwitchConfirm, claudeModelSwitchResult, claudeStartupAction, createClaudeAgentMetadata, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, } from "./harnesses/claude.js";
49
59
  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";
50
60
  import { interimFromNow, readInterimWords, recordInterimBoundary } from "./interim-words.js";
51
61
  import { codexSeatTurn, grokSteerAcceptance, observeSteerDone, readSteerEntry, recordSteer } from "./steer-follow.js";
52
- import { resolveAgentBin, resolveThroughlineBin, runThroughlineHandoffContext, isWindowsNativeExecutable, agentBinForPaneShell, resolveWinPaneShell, windowsAgentArgv, windowsAgentLaunchLine } from "./agent-resolver.js";
62
+ import { resolveAgentBin, resolveThroughlineBin, runThroughlineHandoffContext, isWindowsNativeExecutable, isUsableAgentExecutableFile, agentBinForPaneShell, resolveWinPaneShell, windowsAgentArgv, windowsAgentLaunchLine } from "./agent-resolver.js";
53
63
  export { AitermError } from "./errors.js";
54
64
  export { tmuxSpawnEnv } from "./tmux-runtime.js";
55
65
  export { agentHarness } from "./agent-shared.js";
@@ -337,6 +347,13 @@ function existingAgentsDir() {
337
347
  return null;
338
348
  }
339
349
  }
350
+ function savedAgentSessionNames() {
351
+ const dir = existingAgentsDir();
352
+ return dir ? [...new Set(fs.readdirSync(dir).flatMap(file => {
353
+ const match = /^([A-Za-z0-9_-]{1,64})\.[a-f0-9]{32}\.agent\.json$/.exec(file);
354
+ return match ? [match[1]] : [];
355
+ }))] : [];
356
+ }
340
357
  function cleanupAgentState(name) {
341
358
  assertSessionName(name);
342
359
  agentMetadataNegativeCache.delete(name);
@@ -351,8 +368,18 @@ function cleanupAgentState(name) {
351
368
  const p = path.join(dir, f);
352
369
  try {
353
370
  if (f.endsWith(".agent.json") ||
371
+ f.endsWith(".active-launch.json") ||
354
372
  f.endsWith(".launch-exited") ||
355
373
  f.endsWith(".events.jsonl") ||
374
+ f.endsWith(".activity.jsonl") ||
375
+ f.endsWith(".resume.json") ||
376
+ f.endsWith(".resume-attempt.json") ||
377
+ f.endsWith(".resume-native.json") ||
378
+ f.endsWith(".resume-template.json") ||
379
+ f.endsWith(".codex-resume.json") ||
380
+ f.endsWith(".lifecycle.json") ||
381
+ f.endsWith(".idle-check.json") ||
382
+ f.endsWith(".idle-clock.json") ||
356
383
  f.endsWith(".wait.lock") ||
357
384
  f.endsWith(".claude-settings.json") ||
358
385
  f.endsWith(".claude-mcp.json") ||
@@ -445,15 +472,19 @@ function estimateTokens(s) {
445
472
  return Math.ceil(s.length / 4.0);
446
473
  }
447
474
  export function stripControl(text) {
475
+ // OSC/DCS等の本文内のCRを、印字された進捗断片として扱わない。
476
+ text = text.replace(ANSI_RE, sequence => sequence.startsWith("\x1b[") ? sequence : "");
448
477
  text = text.replace(/\r\n/g, "\n"); // CRLF 正規化
449
478
  const out = [];
450
- for (let line of text.split("\n")) {
451
- if (line.includes("\r")) {
452
- const parts = line.split("\r");
453
- line = parts[parts.length - 1]; // 行中の\rは進捗上書き=最終状態だけ残す
479
+ for (const line of text.split("\n")) {
480
+ let visibleLine = "";
481
+ for (const part of line.split("\r")) {
482
+ const visible = part.replace(ANSI_RE, "").replace(CTRL_RE, "");
483
+ // CRとcursor表示切替だけでは、既に印字した結果や完了印を消さない。
484
+ if (visible !== "" || /\x1b\[[0-2]?K/.test(part))
485
+ visibleLine = visible;
454
486
  }
455
- line = line.replace(ANSI_RE, "").replace(CTRL_RE, "");
456
- out.push(line.replace(/\s+$/, "")); // rstrip
487
+ out.push(visibleLine.replace(/\s+$/, "")); // rstrip
457
488
  }
458
489
  return out.join("\n");
459
490
  }
@@ -539,6 +570,8 @@ function autoName() {
539
570
  const r = tmux("list-sessions", "-F", "#{session_name}");
540
571
  const existing = new Set(r.code === 0 ? r.stdout.split(/\s+/).filter(Boolean) : []);
541
572
  let i = 1;
573
+ for (const name of savedAgentSessionNames())
574
+ existing.add(name);
542
575
  while (existing.has(`t${i}`))
543
576
  i++;
544
577
  return `t${i}`;
@@ -709,7 +742,20 @@ function rtkRewrite(text) {
709
742
  // Windows native pane の既定 shell 解決。裸の "bash" は PATH 上で System32 の
710
743
  // WSL launcher (bash.exe) に解決されてしまうため、Git for Windows の bash.exe を
711
744
  // 明示解決する(WSL 非依存の裁定に従う)。AITERM_BASH で上書き可。
745
+ function assertNoDormantSession(name) {
746
+ if (!name)
747
+ return;
748
+ assertSessionName(name);
749
+ const saved = tryLoadAgentMetadata(name);
750
+ if (saved && (readAgentLifecycle(saved) || agentDormantState(saved)))
751
+ throw new AitermError("AGENT_RESUME_REQUIRED: 保存した会話席はagent_launchまたはpty_sendで再開してください。", 2);
752
+ }
712
753
  export function openSession(name, shell = "bash", envVars = []) {
754
+ assertExecutionContext(name);
755
+ assertNoDormantSession(name);
756
+ return openSessionInternal(name, shell, envVars, false);
757
+ }
758
+ function openSessionInternal(name, shell, envVars, preserveAgentState) {
713
759
  assertExecutionContext(name);
714
760
  shell = resolveWinPaneShell(shell);
715
761
  for (const key of envVars) {
@@ -745,8 +791,6 @@ export function openSession(name, shell = "bash", envVars = []) {
745
791
  const launch = sessionEnvironmentLaunch(shell, environment);
746
792
  const r = tmuxNewSession(true, nm, launch, environment.map(entry => entry.slice(0, entry.indexOf("="))));
747
793
  if (r.code === 0) {
748
- // Windowsで、画面の無いlogon(ssh・service)で立てた本体の控えを、画面のある側のpsmuxに消させない(psmux 3.3.8)。
749
- openPsmuxServerToDesktop(nm);
750
794
  if (launch.register_after_start)
751
795
  for (const entry of environment) {
752
796
  const at = entry.indexOf("=");
@@ -783,7 +827,8 @@ export function openSession(name, shell = "bash", envVars = []) {
783
827
  /* noop */
784
828
  }
785
829
  }
786
- cleanupAgentState(nm);
830
+ if (!preserveAgentState)
831
+ cleanupAgentState(nm);
787
832
  // pipe-pane の引数は tmux 内部の /bin/sh -c で再解釈される(argv ではない)。パスは単一引用符で包み、
788
833
  // パス自身の ' は '\'' イディオムでエスケープする(名前は検証済みだが、Windows ユーザー名 O'Brien 等が
789
834
  // 一時パスに ' を持ち込み redirect を壊すのを防ぐ。空白対策も兼ねる)。
@@ -893,116 +938,118 @@ export function send(name, text, o = {}) {
893
938
  throw new AitermError("aiterm相関付きClaude agent sessionへの通常送信はturn境界を失うため拒否します。" +
894
939
  "pty_send(forceなし=自動dispatch)を使うか、通常対話へ切り替えるならsessionをcloseしてpty_openから手動起動し直してください。", 2);
895
940
  }
896
- o.beforePtyWrite?.();
897
- writeLastcmd(name, o.launchShell ? atomicShellMultiline(text, o.launchShell) : text);
898
- if (o.rtk)
899
- text = rtkRewrite(text);
900
- const markId = o.mark ? randomBytes(16).toString("hex") : null;
901
- if (markId !== null)
902
- text = appendMarkSentinel(text, fg, markId);
903
- assertSendTextSize(text, o.rtk || o.mark ? "変換後の送信文字列" : "送信文字列");
904
- const reportedText = text;
905
- // Agent composer paste is literal text even if native foreground metadata
906
- // still reports the startup shell. Keep sanitization, but never encode TUI
907
- // text as an executable shell command.
908
- // Original text is validated above. OS queries, stale foreground handling
909
- // and shell encoding belong to the runtime; common send supplies intent.
910
- text = adaptShellSubmission(name, text, {
911
- raw: o.raw, literalPaste: o.bracketedPaste, launchShell: o.launchShell, shell: fg,
912
- });
913
- if (o.mark) {
914
- try {
915
- fs.writeFileSync(markpath(name), markId);
916
- }
917
- catch {
918
- throw new AitermError("完了印の送信IDを保存できません。文字列は送信していません。", 2);
919
- }
920
- }
921
- else {
922
- // 非 mark 送信は、未消化の古い mark 完了待ちを無効化する(前コマンドの sentinel を待ち続けない)。
923
- try {
924
- fs.unlinkSync(markpath(name));
925
- }
926
- catch {
927
- /* noop */
941
+ return withAgentNativeOperation(name, true, () => {
942
+ o.beforePtyWrite?.();
943
+ writeLastcmd(name, o.launchShell ? atomicShellMultiline(text, o.launchShell) : text);
944
+ if (o.rtk)
945
+ text = rtkRewrite(text);
946
+ const markId = o.mark ? randomBytes(16).toString("hex") : null;
947
+ if (markId !== null)
948
+ text = appendMarkSentinel(text, fg, markId);
949
+ assertSendTextSize(text, o.rtk || o.mark ? "変換後の送信文字列" : "送信文字列");
950
+ const reportedText = text;
951
+ // Agent composer paste is literal text even if native foreground metadata
952
+ // still reports the startup shell. Keep sanitization, but never encode TUI
953
+ // text as an executable shell command.
954
+ // Original text is validated above. OS queries, stale foreground handling
955
+ // and shell encoding belong to the runtime; common send supplies intent.
956
+ text = adaptShellSubmission(name, text, {
957
+ raw: o.raw, literalPaste: o.bracketedPaste, launchShell: o.launchShell, shell: fg,
958
+ });
959
+ if (o.mark) {
960
+ try {
961
+ fs.writeFileSync(markpath(name), markId);
962
+ }
963
+ catch {
964
+ throw new AitermError("完了印の送信IDを保存できません。文字列は送信していません。", 2);
965
+ }
928
966
  }
929
- }
930
- // POSIX tmuxはUTF-8安全な256byte pasteへ分割する。Windows psmuxは認証済み
931
- // server commandでpayload全体を単一SendBytesへ変換し、別processとの交差を構造的に防ぐ。
932
- const writePty = (payload, bracketedPaste, what) => {
933
- if (isWin) {
934
- o.beforePtyWrite?.();
935
- const sent = sendPsmuxPayload(true, name, payload, bracketedPaste);
936
- if (sent.code !== 0) {
937
- throw new AitermError(`psmuxのPTY送信に失敗しました${what}: ${sent.stderr.trim() || `code=${sent.code}`}`, 2);
967
+ else {
968
+ // 非 mark 送信は、未消化の古い mark 完了待ちを無効化する(前コマンドの sentinel を待ち続けない)。
969
+ try {
970
+ fs.unlinkSync(markpath(name));
971
+ }
972
+ catch {
973
+ /* noop */
938
974
  }
939
- return;
940
975
  }
941
- // tmuxの`paste-buffer -p`はchunkごとに包むため使わない。Claude Codeは貼り付け1回ごとに
942
- // 画像pathを探すので、chunk境界でpathが切れて画像を落とし、行もずれた(2026-10-01、
943
- // 画像4枚付きの約500byte)。全体を1回だけ包み、中身はchunkのまま流す。
944
- const chunks = splitPtyText(bracketedPaste ? `\x1b[200~${payload}\x1b[201~` : payload);
945
- const pasteSupportsNoSanitize = pasteBufferSupportsNoSanitizeFlag();
946
- const bufferBase = `aiterm-${process.pid}-${randomBytes(8).toString("hex")}`;
947
- for (let i = 0; i < chunks.length; i += 1) {
948
- const bufferName = `${bufferBase}-${i}`;
949
- const partial = i > 0
950
- ? " 先行chunkはPTYに入力済みでEnterは未送信です。再送前に入力を確認・消去してください。"
951
- : "";
952
- const loaded = loadPtyBufferChunk(true, bufferName, chunks[i]);
953
- if (loaded.code !== 0) {
954
- tmuxCleanup("delete-buffer", "-b", bufferName);
955
- throw new AitermError(`tmux bufferへの送信準備に失敗しました${what}` +
956
- `(chunk ${i + 1}/${chunks.length}): ${loaded.stderr.trim() || `code=${loaded.code}`}.${partial}`, 2);
976
+ // POSIX tmuxはUTF-8安全な256byte pasteへ分割する。Windows psmuxは認証済み
977
+ // server commandでpayload全体を単一SendBytesへ変換し、別processとの交差を構造的に防ぐ。
978
+ const writePty = (payload, bracketedPaste, what) => {
979
+ if (isWin) {
980
+ o.beforePtyWrite?.();
981
+ const sent = sendPsmuxPayload(true, name, payload, bracketedPaste);
982
+ if (sent.code !== 0) {
983
+ throw new AitermError(`psmuxのPTY送信に失敗しました${what}: ${sent.stderr.trim() || `code=${sent.code}`}`, 2);
984
+ }
985
+ return;
957
986
  }
958
- const pasteArgs = pasteBufferBaseArgs();
959
- if (pasteSupportsNoSanitize)
960
- pasteArgs.push("-S");
961
- pasteArgs.push("-b", bufferName, "-t", name);
987
+ // tmuxの`paste-buffer -p`はchunkごとに包むため使わない。Claude Codeは貼り付け1回ごとに
988
+ // 画像pathを探すので、chunk境界でpathが切れて画像を落とし、行もずれた(2026-10-01、
989
+ // 画像4枚付きの約500byte)。全体を1回だけ包み、中身はchunkのまま流す。
990
+ const chunks = splitPtyText(bracketedPaste ? `\x1b[200~${payload}\x1b[201~` : payload);
991
+ const pasteSupportsNoSanitize = pasteBufferSupportsNoSanitizeFlag();
992
+ const bufferBase = `aiterm-${process.pid}-${randomBytes(8).toString("hex")}`;
993
+ for (let i = 0; i < chunks.length; i += 1) {
994
+ const bufferName = `${bufferBase}-${i}`;
995
+ const partial = i > 0
996
+ ? " 先行chunkはPTYに入力済みでEnterは未送信です。再送前に入力を確認・消去してください。"
997
+ : "";
998
+ const loaded = loadPtyBufferChunk(true, bufferName, chunks[i]);
999
+ if (loaded.code !== 0) {
1000
+ tmuxCleanup("delete-buffer", "-b", bufferName);
1001
+ throw new AitermError(`tmux bufferへの送信準備に失敗しました${what}` +
1002
+ `(chunk ${i + 1}/${chunks.length}): ${loaded.stderr.trim() || `code=${loaded.code}`}.${partial}`, 2);
1003
+ }
1004
+ const pasteArgs = pasteBufferBaseArgs();
1005
+ if (pasteSupportsNoSanitize)
1006
+ pasteArgs.push("-S");
1007
+ pasteArgs.push("-b", bufferName, "-t", name);
1008
+ try {
1009
+ o.beforePtyWrite?.();
1010
+ }
1011
+ catch (error) {
1012
+ tmuxCleanup("delete-buffer", "-b", bufferName);
1013
+ throw error;
1014
+ }
1015
+ const pasted = tmux(...pasteArgs);
1016
+ if (pasted.code !== 0) {
1017
+ tmuxCleanup("delete-buffer", "-b", bufferName);
1018
+ throw new AitermError(`tmux bufferのPTY送信に失敗しました${what}` +
1019
+ `(chunk ${i + 1}/${chunks.length}): ${pasted.stderr.trim() || `code=${pasted.code}`}.${partial}`, 2);
1020
+ }
1021
+ if (i + 1 < chunks.length) {
1022
+ pauseSync(PTY_PASTE_CHUNK_PAUSE_MS);
1023
+ }
1024
+ }
1025
+ };
1026
+ if (o.typedPreface !== undefined) {
1027
+ // 前置きは貼り付けの印なしで入れる。本文は続けて貼る。前置きだけが入って本文が失敗した時は、入力欄に前置きが残る。
1028
+ writePty(o.typedPreface, false, "(前置き)");
1029
+ pauseSync(PTY_PASTE_CHUNK_PAUSE_MS);
962
1030
  try {
963
- o.beforePtyWrite?.();
1031
+ writePty(text, !!o.bracketedPaste, "");
964
1032
  }
965
1033
  catch (error) {
966
- tmuxCleanup("delete-buffer", "-b", bufferName);
1034
+ if (error instanceof AitermError) {
1035
+ throw new AitermError(`${error.message} 前置きはPTYに入力済みでEnterは未送信です。再送前に入力を確認・消去してください。`, error.code);
1036
+ }
967
1037
  throw error;
968
1038
  }
969
- const pasted = tmux(...pasteArgs);
970
- if (pasted.code !== 0) {
971
- tmuxCleanup("delete-buffer", "-b", bufferName);
972
- throw new AitermError(`tmux bufferのPTY送信に失敗しました${what}` +
973
- `(chunk ${i + 1}/${chunks.length}): ${pasted.stderr.trim() || `code=${pasted.code}`}.${partial}`, 2);
974
- }
975
- if (i + 1 < chunks.length) {
976
- pauseSync(PTY_PASTE_CHUNK_PAUSE_MS);
977
- }
978
1039
  }
979
- };
980
- if (o.typedPreface !== undefined) {
981
- // 前置きは貼り付けの印なしで入れる。本文は続けて貼る。前置きだけが入って本文が失敗した時は、入力欄に前置きが残る。
982
- writePty(o.typedPreface, false, "(前置き)");
983
- pauseSync(PTY_PASTE_CHUNK_PAUSE_MS);
984
- try {
1040
+ else
985
1041
  writePty(text, !!o.bracketedPaste, "");
986
- }
987
- catch (error) {
988
- if (error instanceof AitermError) {
989
- throw new AitermError(`${error.message} 前置きはPTYに入力済みでEnterは未送信です。再送前に入力を確認・消去してください。`, error.code);
1042
+ if (enter) {
1043
+ o.beforePtyWrite?.();
1044
+ const entered = tmux("send-keys", "-t", name, "Enter");
1045
+ if (entered.code !== 0) {
1046
+ throw new AitermError(`文字列はPTYに入力済みですがtmuxへEnterを送れませんでした: ` +
1047
+ `${entered.stderr.trim() || `code=${entered.code}`}。再送前に入力を確認・消去してください`, 2);
990
1048
  }
991
- throw error;
992
- }
993
- }
994
- else
995
- writePty(text, !!o.bracketedPaste, "");
996
- if (enter) {
997
- o.beforePtyWrite?.();
998
- const entered = tmux("send-keys", "-t", name, "Enter");
999
- if (entered.code !== 0) {
1000
- throw new AitermError(`文字列はPTYに入力済みですがtmuxへEnterを送れませんでした: ` +
1001
- `${entered.stderr.trim() || `code=${entered.code}`}。再送前に入力を確認・消去してください`, 2);
1002
1049
  }
1003
- }
1004
- // コードポイント数で数える(JS の .length は UTF-16 単位で絵文字等がズレる。Python は len()=コードポイント)。
1005
- return `sent ${[...reportedText].length} chars to ${name}` + (enter ? " (+Enter)" : "");
1050
+ // コードポイント数で数える(JS の .length は UTF-16 単位で絵文字等がズレる。Python は len()=コードポイント)。
1051
+ return `sent ${[...reportedText].length} chars to ${name}` + (enter ? " (+Enter)" : "");
1052
+ });
1006
1053
  }
1007
1054
  finally {
1008
1055
  releaseSendLock();
@@ -1016,6 +1063,16 @@ export function sendKey(name, key, o = {}) {
1016
1063
  * a launch/conversation identity, or permission to retry a failed delivery.
1017
1064
  */
1018
1065
  export function sendKeyResult(name, key, o = {}) {
1066
+ assertExecutionContext(name);
1067
+ assertSessionName(name);
1068
+ const k = KEYMAP[key.toLowerCase()] ?? key;
1069
+ if (!o.preserveAgentOperation && k !== "C-c" && isAgentSession(name) && managedClaudeOperation(name) !== undefined) {
1070
+ throw new AitermError("aiterm相関付きClaude agent sessionではturn相関を壊さないC-cだけをpty_keyで送れます。" +
1071
+ "他の対話操作はpty_send(自動dispatch)、終了はpty_closeを使ってください。", 2);
1072
+ }
1073
+ return withAgentNativeOperation(name, true, () => sendKeyResultInNative(name, key, o));
1074
+ }
1075
+ function sendKeyResultInNative(name, key, o) {
1019
1076
  assertExecutionContext(name);
1020
1077
  assertSessionName(name);
1021
1078
  if (!sessionExists(name))
@@ -1023,10 +1080,6 @@ export function sendKeyResult(name, key, o = {}) {
1023
1080
  const k = KEYMAP[key.toLowerCase()] ?? key;
1024
1081
  const receipt = () => ({ schema: "aiterm.pty-key-result.v1", session_id: name, key: k,
1025
1082
  outcome: "accepted", interruption: "unconfirmed", session_preserved: "unconfirmed" });
1026
- if (!o.preserveAgentOperation && managedClaudeOperation(name) !== undefined && k !== "C-c") {
1027
- throw new AitermError("aiterm相関付きClaude agent sessionではturn相関を壊さないC-cだけをpty_keyで送れます。" +
1028
- "他の対話操作はpty_send(自動dispatch)、終了はpty_closeを使ってください。", 2);
1029
- }
1030
1083
  const meta = tryLoadAgentMetadata(name);
1031
1084
  if (meta?.kind === "cursor" && k === "Enter") {
1032
1085
  send(name, CURSOR_SUBMIT_SEQUENCE, {
@@ -1047,9 +1100,9 @@ export function sendKeyResult(name, key, o = {}) {
1047
1100
  function readInterruptionTarget(name) {
1048
1101
  try {
1049
1102
  const files = fs.readdirSync(agentsDir()).filter(file => file.startsWith(name + ".") && file.endsWith(".agent.json"));
1050
- if (files.length !== 1)
1103
+ if (files.length === 0)
1051
1104
  return null;
1052
- const meta = JSON.parse(fs.readFileSync(path.join(agentsDir(), files[0]), "utf8"));
1105
+ const meta = JSON.parse(fs.readFileSync(path.join(agentsDir(), selectAgentMetadataFile(name, files)), "utf8"));
1053
1106
  return meta.aiterm_session === name && ["codex", "claude", "cursor", "grok", "antigravity"].includes(meta.kind)
1054
1107
  && typeof meta.launch_id === "string" && LAUNCH_ID_RE.test(meta.launch_id) ? { kind: meta.kind, launch_id: meta.launch_id } : null;
1055
1108
  }
@@ -1061,6 +1114,20 @@ function readInterruptionTarget(name) {
1061
1114
  * proof is required to send the harness's normal cancel key. The native session ID prevents a same-name
1062
1115
  * replacement from receiving the key. This never closes or clears a session. */
1063
1116
  export function interruptSessionNow(name, expectedLaunchId) {
1117
+ assertSessionName(name);
1118
+ const meta = tryLoadAgentMetadata(name);
1119
+ if (meta && agentDormantState(meta) === "hibernated") {
1120
+ const observed = observeSession(name);
1121
+ if (observed.state === "hibernated") {
1122
+ if (observed.launch_id !== meta.launch_id || expectedLaunchId && expectedLaunchId !== meta.launch_id)
1123
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
1124
+ return { session_id: name, outcome: "idle" };
1125
+ }
1126
+ }
1127
+ // The stop button must remain immediate, including during a normal send.
1128
+ return withAgentNativeOperation(name, false, () => interruptSessionNowInNative(name, expectedLaunchId));
1129
+ }
1130
+ function interruptSessionNowInNative(name, expectedLaunchId) {
1064
1131
  assertSessionName(name);
1065
1132
  const listing = observeExecutionNativeSessions();
1066
1133
  if (listing.state !== "known")
@@ -1369,6 +1436,9 @@ export function utf8SafeSliceStart(buf) {
1369
1436
  return buf.subarray(start);
1370
1437
  }
1371
1438
  export async function readOutput(name, o = {}) {
1439
+ return withAgentNativeOperation(name, false, () => readOutputInNative(name, o));
1440
+ }
1441
+ async function readOutputInNative(name, o) {
1372
1442
  assertSessionName(name);
1373
1443
  const timeout = o.timeout ?? DEFAULT_TIMEOUT;
1374
1444
  if (!sessionExists(name) && !fs.existsSync(logpath(name)))
@@ -1547,7 +1617,7 @@ export function startupProcessShapes(identities, rows) {
1547
1617
  // harnessは起動の足場(MCP、language server)を自分で立て直す。控えた後に立て直されると、控えに無いprocessとして残る。
1548
1618
  // 控えの物が終了していて、同じ親の下に同じargvで立ったprocessは、その立て直しとして数えない。
1549
1619
  // 親も立て直されている時は、立て直された親の下を見る。終了した控え1つにつき、数えないのは1つまで。
1550
- export function postStartupProcessCount(kind, activityRows, rows, startup, shapes = []) {
1620
+ export function postStartupProcessCount(kind, activityRows, rows, startup, shapes = [], harness) {
1551
1621
  const byPid = new Map(rows.map(row => [row.pid, row]));
1552
1622
  const relayChild = (row) => {
1553
1623
  const parent = parentProcess(row, byPid);
@@ -1563,7 +1633,8 @@ export function postStartupProcessCount(kind, activityRows, rows, startup, shape
1563
1633
  };
1564
1634
  const present = new Set(activityRows.map(processKey));
1565
1635
  const added = new Map(activityRows
1566
- .filter(row => !startup.has(processKey(row)) && !(kind === "codex" && codexHelperProcess(row.command)) && !relayChild(row) && !ownProbe(row))
1636
+ .filter(row => !startup.has(processKey(row)) && !(kind === "codex" && codexHelperProcess(row.command))
1637
+ && !(kind === "claude" && macKeepAwakeProcess(row, harness)) && !relayChild(row) && !ownProbe(row))
1567
1638
  .map(row => [processKey(row), row]));
1568
1639
  const gone = shapes.filter(shape => startup.has(shape.identity) && !present.has(shape.identity));
1569
1640
  const replacedBy = new Map();
@@ -1585,6 +1656,81 @@ export function postStartupProcessCount(kind, activityRows, rows, startup, shape
1585
1656
  }
1586
1657
  return added.size;
1587
1658
  }
1659
+ function emptySessionObservation(name, exists) {
1660
+ return {
1661
+ schema: "aiterm.pty-observe-result.v1", session_id: name, observed_at: new Date().toISOString(),
1662
+ exists, harness: null, launch_id: null, state: "missing", reason: "session_missing",
1663
+ pane_alive: false, harness_alive: null, pane_process: null, harness_process: null, process_identity: null,
1664
+ token_hint: null, pending_child_deliveries: null,
1665
+ activity: { cursor: null, output_changed: null, cpu_seconds: null, cpu_delta_seconds: null, cpu_delta_complete: null,
1666
+ background_cpu_seconds: null, background_cpu_delta_seconds: null, background_cpu_delta_complete: null,
1667
+ post_startup_process_count: null },
1668
+ };
1669
+ }
1670
+ function agentDormantState(meta) {
1671
+ const lifecycle = readAgentLifecycle(meta);
1672
+ const origin = lifecycle ?? (meta.resumed_from ? readAgentLifecycle({ aiterm_session: meta.aiterm_session, launch_id: meta.resumed_from }) : null);
1673
+ if (origin && origin.socket !== SOCK)
1674
+ return null;
1675
+ const attempt = readAgentResumeAttempt(meta);
1676
+ if (attempt)
1677
+ return attempt.state === "ready" ? "unknown" : attempt.state;
1678
+ if (lifecycle)
1679
+ return lifecycle.state;
1680
+ if (meta.resumed_from) {
1681
+ const previous = readAgentResumeAttempt({ aiterm_session: meta.aiterm_session, launch_id: meta.resumed_from });
1682
+ if (!previous || previous.next_launch_id !== meta.launch_id)
1683
+ return "unknown";
1684
+ if (previous.state !== "ready")
1685
+ return previous.state;
1686
+ }
1687
+ return null;
1688
+ }
1689
+ export function observeSession(name, cursor) {
1690
+ assertSessionName(name);
1691
+ const meta = tryLoadAgentMetadata(name);
1692
+ if (!meta) {
1693
+ isAgentSession(name);
1694
+ return observeNativeSession(name, cursor);
1695
+ }
1696
+ const state = agentDormantState(meta);
1697
+ if (!state)
1698
+ return observeNativeSession(name, cursor);
1699
+ if (cursor !== undefined)
1700
+ decodeActivityCursor(cursor, name);
1701
+ const result = emptySessionObservation(name, true);
1702
+ result.harness = agentHarness(meta.kind);
1703
+ result.launch_id = meta.launch_id;
1704
+ result.state = "unknown";
1705
+ result.reason = `agent_${state}`;
1706
+ result.pane_alive = null;
1707
+ const native = listNativeSessionsResult().sessions.some(row => row.session_id === name);
1708
+ if (state !== "hibernated" || native) {
1709
+ if (native && state === "hibernated")
1710
+ result.reason = "resume_native_conflict";
1711
+ return result;
1712
+ }
1713
+ try {
1714
+ confirmedAgentResumeRecipe(meta, readAgentLifecycle(meta));
1715
+ }
1716
+ catch {
1717
+ result.reason = "resume_unconfirmed";
1718
+ return result;
1719
+ }
1720
+ // Discard the old pane's cursor; hibernation proves absence, not an activity delta.
1721
+ if (!isDeepStrictEqual(loadAgentMetadata(name), meta) || agentDormantState(meta) !== "hibernated"
1722
+ || listNativeSessionsResult().sessions.some(row => row.session_id === name))
1723
+ return result;
1724
+ result.state = "hibernated";
1725
+ result.reason = "idle_timeout";
1726
+ result.pane_alive = false;
1727
+ result.harness_alive = false;
1728
+ result.pending_child_deliveries = 0;
1729
+ result.activity.cpu_seconds = 0;
1730
+ result.activity.background_cpu_seconds = 0;
1731
+ result.activity.post_startup_process_count = 0;
1732
+ return result;
1733
+ }
1588
1734
  /** Native absence before the owned launcher returns does not prove CLI exit. */
1589
1735
  export function absentHarnessAlive(meta, platform = process.platform) {
1590
1736
  if (platform === "win32" && meta.windows_launch_exit_tracked === true) {
@@ -1600,7 +1746,7 @@ export function absentHarnessAlive(meta, platform = process.platform) {
1600
1746
  // Input admission needs the same native ownership proof, without activity capture or child-delivery scans.
1601
1747
  function observeSessionNative(name) {
1602
1748
  assertSessionName(name);
1603
- const listed = listSessionsResult().sessions.find(session => session.session_id === name);
1749
+ const listed = listNativeSessionsResult().sessions.find(session => session.session_id === name);
1604
1750
  const result = {
1605
1751
  schema: "aiterm.pty-observe-result.v1", session_id: name, observed_at: new Date().toISOString(),
1606
1752
  exists: !!listed, harness: null, launch_id: null, state: "missing", reason: "session_missing",
@@ -1662,7 +1808,7 @@ function observeSessionNative(name) {
1662
1808
  }
1663
1809
  return { result, native: { rows, root, subtree, meta, agent } };
1664
1810
  }
1665
- export function observeSession(name, cursor) {
1811
+ function observeNativeSession(name, cursor) {
1666
1812
  assertSessionName(name);
1667
1813
  const previous = cursor === undefined ? null : decodeActivityCursor(cursor, name);
1668
1814
  const { result, native } = observeSessionNative(name);
@@ -1707,7 +1853,7 @@ export function observeSession(name, cursor) {
1707
1853
  background_cpu_delta_seconds: comparable ? Object.entries(backgroundCpu).reduce((sum, [identity, cpu]) => sum + cpu - (previous.background_processes[identity] ?? 0), 0) : null,
1708
1854
  background_cpu_delta_complete: comparable ? Object.keys(previous.background_processes).every(identity => identity in backgroundCpu) : null,
1709
1855
  post_startup_process_count: startup
1710
- ? postStartupProcessCount(meta.kind, activityRows, rows, startup, meta.startup_process_shapes) : null,
1856
+ ? postStartupProcessCount(meta.kind, activityRows, rows, startup, meta.startup_process_shapes, agent) : null,
1711
1857
  };
1712
1858
  return result;
1713
1859
  }
@@ -1721,6 +1867,222 @@ export function observeSessionGeneration(name) {
1721
1867
  return { schema: "aiterm.pty-observe-result.v1", session_id: name, exists,
1722
1868
  launch_id: exists ? tryLoadAgentMetadata(name)?.launch_id ?? null : null };
1723
1869
  }
1870
+ /** Internal lifecycle worker; not an MCP input route and never creates an effect scope. */
1871
+ export async function checkAgentIdle(expectedInput, expectedAnchor) {
1872
+ const expected = executionLaunchSchema.parse(expectedInput), name = expected.session_id;
1873
+ assertExecutionContext(name);
1874
+ assertExecutionResumeSupported();
1875
+ const minutes = idleMinutes();
1876
+ let captured = null;
1877
+ let pinned = null;
1878
+ let root = null;
1879
+ let recipeDigest = null;
1880
+ let configurationScreen = null;
1881
+ let configurationStartedAt = 0;
1882
+ let initialNative = null;
1883
+ let preparation = null;
1884
+ let effectIssued = false;
1885
+ const metadata = () => {
1886
+ assertExecutionContext(name);
1887
+ const meta = loadAgentMetadata(name);
1888
+ if (meta.launch_id !== expected.launch_id)
1889
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
1890
+ if (captured && (!isDeepStrictEqual(meta.execution_native, captured.execution_native) || meta.kind !== captured.kind
1891
+ || meta.vendor_session_id !== captured.vendor_session_id || meta.agent_executable !== captured.agent_executable
1892
+ || meta.cwd !== captured.cwd || meta.model !== captured.model || meta.fast !== captured.fast))
1893
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
1894
+ return meta;
1895
+ };
1896
+ const native = () => {
1897
+ const sessions = observeExecutionNativeSessions();
1898
+ if (sessions.state !== "known")
1899
+ throw new Error("native_session_unconfirmed");
1900
+ const current = sessions.sessions.find(item => item.session_id === name);
1901
+ if (!current)
1902
+ return null;
1903
+ const pane = tmux("display-message", "-p", "-t", isWin ? `=${name}:` : current.native_id, "#{pane_pid}\t#{session_attached}\t#{window_activity}\t#{?session_last_attached,#{session_last_attached},0}");
1904
+ const fields = pane.stdout.trim().split("\t"), pid = Number(fields[0]), attached = Number(fields[1]);
1905
+ if (pane.code !== 0 || fields.length !== 4 || !Number.isSafeInteger(pid) || pid < 1
1906
+ || !/^\d+$/.test(fields[1]) || !Number.isSafeInteger(attached))
1907
+ throw new Error("native_pane_unconfirmed");
1908
+ if (pinned && (current.native_id !== pinned.native_id || pid !== pinned.pane_pid))
1909
+ throw new Error("native_pane_replaced");
1910
+ return { native_id: current.native_id, pane_pid: pid, attached: attached > 0,
1911
+ window_activity_at: /^\d+$/.test(fields[2]) ? Number(fields[2]) * 1000 : null,
1912
+ last_attached_at: /^\d+$/.test(fields[3]) ? Number(fields[3]) * 1000 : null };
1913
+ };
1914
+ const snapshot = () => {
1915
+ const meta = metadata();
1916
+ captured ??= meta;
1917
+ const receipt = readAgentResumeNative(meta);
1918
+ if (initialNative && !isDeepStrictEqual(receipt, initialNative))
1919
+ throw new Error("native_creation_changed");
1920
+ initialNative ??= receipt;
1921
+ if (receipt && !effectIssued)
1922
+ verifyAgentResumeNative(meta, receipt);
1923
+ if (meta.kind === "codex" && readAgentResumeTemplate(meta)?.state === "confirmed")
1924
+ bindCodexTranscriptSession(meta);
1925
+ const recipe = refreshAgentResumeRecipe(meta);
1926
+ const digest = recipe && agentResumeRecipeDigest(recipe);
1927
+ if (recipeDigest && digest !== recipeDigest)
1928
+ throw new Error("resume_recipe_changed");
1929
+ const lifecycle = readAgentLifecycle(meta);
1930
+ if (lifecycle && !preparation)
1931
+ throw new Error("lifecycle_already_recorded");
1932
+ if (preparation && (!lifecycle || lifecycle.state !== "stopping" || lifecycle.anchor !== preparation.anchor
1933
+ || lifecycle.recipe_digest !== preparation.recipe_digest || lifecycle.resume_proof_digest !== preparation.resume_proof_digest
1934
+ || lifecycle.socket !== preparation.socket))
1935
+ throw new Error("lifecycle_changed");
1936
+ if (preparation?.resume_proof_digest && codexResumeProofDigest(readCodexResumeProof(meta)) !== preparation.resume_proof_digest)
1937
+ throw new Error("resume_proof_changed");
1938
+ const live = observeNativeSession(name), slot = native();
1939
+ if (slot && live.pane_process) {
1940
+ if (slot.pane_pid !== live.pane_process.pid)
1941
+ throw new Error("pane_identity_changed");
1942
+ if (root && !isDeepStrictEqual(root, live.pane_process))
1943
+ throw new Error("pane_identity_changed");
1944
+ pinned ??= { native_id: slot.native_id, pane_pid: slot.pane_pid };
1945
+ root ??= live.pane_process;
1946
+ }
1947
+ if (!effectIssued && meta.execution_native && observeExecutionSessionGeneration(name).launch_id !== expected.launch_id)
1948
+ throw new Error("native_creator_unconfirmed");
1949
+ const done = latestAgentDoneEvent(meta);
1950
+ if (!effectIssued && done)
1951
+ recordAgentTurnEnd(meta, {
1952
+ ...done, at: Number.isFinite(Date.parse(done.at)) ? done.at : new Date().toISOString(),
1953
+ });
1954
+ const resumeReady = !!receipt && !!recipe && recipe.kind === meta.kind && recipe.vendor_session_id === meta.vendor_session_id
1955
+ && recipe.executable === meta.agent_executable && recipe.cwd === (meta.cwd ?? recipe.cwd)
1956
+ && recipe.model === meta.model && recipe.fast === meta.fast;
1957
+ if (resumeReady)
1958
+ recipeDigest ??= digest;
1959
+ const settled = meta.kind === "claude" ? done !== null && readClaudeOperationMarker(meta) === null
1960
+ : meta.kind === "codex" ? done?.turn_id != null && done.turn_id === codexCompletedTurnId(meta) : agentTurnSettled(meta);
1961
+ return { launch_id: meta.launch_id, created_at: meta.created_at, vendor_session_id: meta.vendor_session_id,
1962
+ resume_ready: resumeReady, native_configuration_confirmed: configurationScreen !== null
1963
+ && (effectIssued || (slot?.last_attached_at != null && slot.last_attached_at < configurationStartedAt
1964
+ && configurationScreen === captureScreen(name, AGENT_TUI_READY_LINES))), activity: readAgentActivity(meta), state: live.state, reason: live.reason,
1965
+ attached: slot?.attached ?? (effectIssued ? false : null), turn_settled: settled,
1966
+ pending_child_deliveries: live.pending_child_deliveries,
1967
+ post_startup_process_count: live.activity.post_startup_process_count,
1968
+ window_activity_at: slot?.window_activity_at ?? null };
1969
+ };
1970
+ return checkIdleSeat({
1971
+ exclusive: body => withAgentSendLock(name, async () => {
1972
+ try {
1973
+ const before = snapshot();
1974
+ if (decideIdleSeat(before, Date.now(), minutes, expectedAnchor).reason === "native_configuration_unconfirmed") {
1975
+ const meta = metadata(), recipe = refreshAgentResumeRecipe(meta);
1976
+ configurationStartedAt = Math.floor(Date.now() / 1000) * 1000;
1977
+ if (recipe && await inspectAgentIdleSettings(name, meta, recipe))
1978
+ configurationScreen = captureScreen(name, AGENT_TUI_READY_LINES);
1979
+ }
1980
+ }
1981
+ catch {
1982
+ configurationScreen = null;
1983
+ }
1984
+ return body();
1985
+ }, AGENT_SEND_UNSENT, false), now: Date.now, snapshot,
1986
+ begin: (_seat, anchor) => withExecutionPreparation(name, () => {
1987
+ const meta = metadata();
1988
+ if (!pinned || !root || !recipeDigest || readAgentLifecycle(meta))
1989
+ throw new Error("idle_preparation_unconfirmed");
1990
+ const proof = meta.kind === "codex" ? captureCodexResumeProof(meta) : null;
1991
+ preparation = { schema: "aiterm.agent-lifecycle.v1", launch_id: meta.launch_id, state: "stopping", socket: SOCK,
1992
+ at: new Date().toISOString(), anchor, native_id: pinned.native_id, pane: root, recipe_digest: recipeDigest,
1993
+ ...(proof ? { resume_proof_digest: codexResumeProofDigest(proof) } : {}) };
1994
+ writeAgentLifecycle(meta, preparation);
1995
+ }),
1996
+ stop: async (verify, didIssue) => {
1997
+ if (!root)
1998
+ throw new Error("pane_identity_unavailable");
1999
+ const stopped = await stopProcessTree(root, verify, {
2000
+ read: () => readRuntimeProcesses(true), now: () => performance.now(), pause: sleep,
2001
+ prepare: body => withExecutionPreparation(name, body),
2002
+ signal: (target, signal, group) => {
2003
+ beforeExecutionEffect(name);
2004
+ didIssue();
2005
+ effectIssued = true;
2006
+ signalRuntimeProcess(target, signal, group);
2007
+ },
2008
+ });
2009
+ if (!stopped)
2010
+ return false;
2011
+ return withExecutionPreparation(name, () => {
2012
+ metadata();
2013
+ verify();
2014
+ const remaining = native();
2015
+ if (remaining) {
2016
+ if (!initialNative)
2017
+ throw new Error("native_creation_unconfirmed");
2018
+ const proof = initialNative;
2019
+ withNativeSessionTarget(proof, () => verifyAgentResumeNative(metadata(), proof, expected.launch_id, true), () => {
2020
+ bindExecutionNativeTarget(name, remaining.native_id);
2021
+ beforeExecutionEffect(name);
2022
+ didIssue();
2023
+ effectIssued = true;
2024
+ if (tmux("kill-session", "-t", remaining.native_id).code !== 0)
2025
+ throw new Error("native_close_unconfirmed");
2026
+ }, true);
2027
+ }
2028
+ return native() === null;
2029
+ });
2030
+ },
2031
+ finish: (_seat, anchor) => withExecutionPreparation(name, () => {
2032
+ const meta = metadata(), current = readAgentLifecycle(meta);
2033
+ if (native() !== null || !current || current.state !== "stopping" || current.anchor !== anchor
2034
+ || current.recipe_digest !== recipeDigest || !preparation)
2035
+ throw new Error("idle_finish_unconfirmed");
2036
+ writeAgentLifecycle(meta, { ...preparation, state: "hibernated", at: new Date().toISOString() });
2037
+ }),
2038
+ cancel: (_seat, anchor) => withExecutionPreparation(name, () => cancelAgentStopping(metadata(), anchor)),
2039
+ record: result => {
2040
+ if (tryLoadAgentMetadata(name)?.launch_id === expected.launch_id)
2041
+ writeJson0600(agentMetadataPath(name, expected.launch_id).replace(/\.agent\.json$/, ".idle-check.json"), result);
2042
+ },
2043
+ }, expected.launch_id, minutes, expectedAnchor);
2044
+ }
2045
+ /** One clock tick; native completion is refreshed even when no parent is waiting for the turn. */
2046
+ export async function serviceAgentIdleClock(expectedInput, token) {
2047
+ const expected = executionLaunchSchema.parse(expectedInput), name = expected.session_id;
2048
+ assertExecutionContext(name);
2049
+ const clock = await withAgentSendLock(name, async () => {
2050
+ const meta = loadAgentMetadata(name);
2051
+ if (meta.launch_id !== expected.launch_id)
2052
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
2053
+ return readAgentIdleClock(meta);
2054
+ });
2055
+ if (token !== undefined && (clock?.token !== token || !isAgentIdleClockOwner(clock)))
2056
+ return { outcome: "skipped", reason: "superseded_timer", anchor: null, due_at: null, stalled: false };
2057
+ const result = await checkAgentIdle(expected, token === undefined ? undefined : clock?.anchor ?? undefined);
2058
+ await withAgentSendLock(name, async () => {
2059
+ const meta = loadAgentMetadata(name);
2060
+ if (meta.launch_id !== expected.launch_id)
2061
+ return;
2062
+ const deadline = idleClockDeadline(result, Date.now());
2063
+ if (deadline === null || readAgentLifecycle(meta) || !["claude", "codex"].includes(meta.kind)) {
2064
+ retireAgentIdleClock(meta, token);
2065
+ return;
2066
+ }
2067
+ await armAgentIdleClock(meta, result.anchor, deadline, token);
2068
+ });
2069
+ return result;
2070
+ }
2071
+ /** Only public list/launch entries sweep; internal observation must never recurse into an idle check. */
2072
+ export async function maintainAgentIdleClocks() {
2073
+ if (!AGENT_IDLE_ENABLED)
2074
+ return;
2075
+ for (const name of savedAgentSessionNames()) {
2076
+ try {
2077
+ const meta = loadAgentMetadata(name);
2078
+ if (["claude", "codex"].includes(meta.kind))
2079
+ requestAgentIdleClock(name, meta.launch_id);
2080
+ }
2081
+ catch {
2082
+ process.stderr.write("aiterm: idle_clock_sweep_unconfirmed\n");
2083
+ }
2084
+ }
2085
+ }
1724
2086
  /** Private guarded-runtime read. Legacy metadata without an original native
1725
2087
  * creator stamp remains a present but unverified generation, never enrolled
1726
2088
  * from a current same-name PID or cached vendor session.
@@ -1806,7 +2168,7 @@ function observeEmptyCreatedLaunch(target, alive) {
1806
2168
  export function observeExecutionParentProcess(name) {
1807
2169
  assertSessionName(name);
1808
2170
  return readExecutionParentProcess(name, {
1809
- present: () => listSessionsResult().sessions.some(session => session.session_id === name),
2171
+ present: () => listNativeSessionsResult().sessions.some(session => session.session_id === name),
1810
2172
  metadata: () => tryLoadAgentMetadata(name),
1811
2173
  pane: () => tmux("display-message", "-p", "-t", name, "#{pane_pid}\t#{pane_dead}"),
1812
2174
  processes: readRuntimeProcesses,
@@ -1819,7 +2181,7 @@ export function observeExecutionParentProcess(name) {
1819
2181
  const SESSION_LIST_EXITING_RETRY_MS = 500;
1820
2182
  const SESSION_LIST_EXITING_POLL_MS = 20;
1821
2183
  const SESSION_LIST_SERVER_EXITING_RE = /server exited unexpectedly/i;
1822
- export function listSessionsResult(envKeys = [], runTmux = tmux) {
2184
+ function listNativeSessionsResult(envKeys = [], runTmux = tmux) {
1823
2185
  for (const key of envKeys) {
1824
2186
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
1825
2187
  throw new AitermError("env_keysの環境変数名が不正です", 2);
@@ -1860,6 +2222,40 @@ export function listSessionsResult(envKeys = [], runTmux = tmux) {
1860
2222
  }
1861
2223
  return { schema: "aiterm.pty-list-result.v1", observed_at: new Date().toISOString(), sessions };
1862
2224
  }
2225
+ export function listSessionsResult(envKeys = [], runTmux = tmux) {
2226
+ const result = listNativeSessionsResult(envKeys, runTmux);
2227
+ const present = new Set(result.sessions.map(row => row.session_id));
2228
+ for (const name of savedAgentSessionNames()) {
2229
+ // A known native terminal remains present even when its ordinary agent record is invalid.
2230
+ const meta = present.has(name) ? tryLoadAgentMetadata(name) : loadAgentMetadata(name);
2231
+ if (!meta)
2232
+ continue;
2233
+ const state = agentDormantState(meta);
2234
+ if (!state)
2235
+ continue;
2236
+ const environment = Object.fromEntries(envKeys.map(key => [key, null]));
2237
+ let command = state;
2238
+ const recipe = readAgentResumeRecipe(meta);
2239
+ if (recipe?.kind === meta.kind && recipe.vendor_session_id === meta.vendor_session_id)
2240
+ for (const key of envKeys)
2241
+ environment[key] = recipe.environment[key] ?? null;
2242
+ if (state === "hibernated") {
2243
+ try {
2244
+ confirmedAgentResumeRecipe(meta, readAgentLifecycle(meta));
2245
+ }
2246
+ catch {
2247
+ command = "unknown";
2248
+ }
2249
+ }
2250
+ if (present.has(name)) {
2251
+ result.sessions.find(row => row.session_id === name).environment = environment;
2252
+ continue;
2253
+ }
2254
+ result.sessions.push({ session_id: name, launch_id: meta.launch_id, current_command: command, attached: false, width: 0, height: 0,
2255
+ harness: agentHarness(meta.kind), vendor_session_id: meta.vendor_session_id ?? null, environment });
2256
+ }
2257
+ return result;
2258
+ }
1863
2259
  export function listSessions(result = listSessionsResult()) {
1864
2260
  if (result.sessions.length) {
1865
2261
  return result.sessions
@@ -2003,26 +2399,62 @@ function letClaudeExitBeforeClose(name) {
2003
2399
  function closeSessionInternal(name, observeDependency = true, o = {}) {
2004
2400
  assertSessionName(name);
2005
2401
  assertSessionClosable(name);
2006
- if (o.letHarnessExit)
2007
- letClaudeExitBeforeClose(name);
2008
- const killed = (observeDependency ? tmux : tmuxCleanup)("kill-session", "-t", name);
2009
- if (executionManagementCloseTarget(name) && killed.code !== 0) {
2010
- // Recovery must not erase the old launch metadata or report closed when
2011
- // its one pinned native close failed. Keep the original send uncertainty.
2012
- throw new AitermError(`tmux sessionを閉じられませんでした: ${killed.stderr.trim() || `code=${killed.code}`}`, 2);
2013
- }
2014
- for (const p of [logpath(name), offsetpath(name), lastcmdpath(name), markpath(name), sendLockPath(name)]) {
2402
+ const finish = (native) => {
2403
+ if (native && o.letHarnessExit)
2404
+ letClaudeExitBeforeClose(name);
2405
+ const killed = native ? (observeDependency ? tmux : tmuxCleanup)("kill-session", "-t", name) : { code: 0, stderr: "" };
2406
+ if (executionManagementCloseTarget(name) && killed.code !== 0) {
2407
+ // Recovery must not erase the old launch metadata or report closed when
2408
+ // its one pinned native close failed. Keep the original send uncertainty.
2409
+ throw new AitermError(`tmux sessionを閉じられませんでした: ${killed.stderr.trim() || `code=${killed.code}`}`, 2);
2410
+ }
2411
+ const proof = isWin && native && meta ? readAgentResumeNative(meta) : null;
2412
+ if (proof && killed.code === 0) {
2413
+ // psmux acknowledges shutdown before its children release their executable and cwd handles.
2414
+ const deadline = performance.now() + SESSION_LIST_EXITING_RETRY_MS;
2415
+ while (isPidAlive(proof.server_pid)) {
2416
+ if (performance.now() >= deadline)
2417
+ throw new AitermError("native_close_unconfirmed: psmuxの終了を確認できません。", 2);
2418
+ pauseSync(SESSION_LIST_EXITING_POLL_MS);
2419
+ }
2420
+ }
2421
+ for (const p of [logpath(name), offsetpath(name), lastcmdpath(name), markpath(name), sendLockPath(name)]) {
2422
+ try {
2423
+ fs.unlinkSync(p);
2424
+ }
2425
+ catch {
2426
+ /* noop */
2427
+ }
2428
+ }
2429
+ cleanupAgentSendLock(name);
2430
+ cleanupAgentState(name);
2431
+ agentLaunchLines.delete(name);
2432
+ return `closed ${name}`;
2433
+ };
2434
+ const meta = tryLoadAgentMetadata(name), lifecycle = meta && readAgentLifecycle(meta);
2435
+ const native = meta && !lifecycle && readAgentResumeNative(meta) ? observeExecutionNativeSessions() : null;
2436
+ const absent = native?.state === "known" && !native.sessions.some(row => row.session_id === name);
2437
+ if (meta && (lifecycle || absent)) {
2438
+ if (lifecycle)
2439
+ assertExecutionResumeSupported();
2440
+ const unavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 休止席のclose対象を確認できません。", 2);
2441
+ // A logical close must never kill a new same-name native terminal.
2442
+ const token = tryCreateOwnedLock(agentSendLockPath(name));
2443
+ if (!token)
2444
+ throw unavailable();
2015
2445
  try {
2016
- fs.unlinkSync(p);
2446
+ const current = observeExecutionNativeSessions();
2447
+ if ((lifecycle && (lifecycle.state !== "hibernated" || lifecycle.socket !== SOCK)) || readAgentResumeAttempt(meta)
2448
+ || !isDeepStrictEqual(loadAgentMetadata(name), meta) || !isDeepStrictEqual(readAgentLifecycle(meta), lifecycle)
2449
+ || current.state !== "known" || current.sessions.some(row => row.session_id === name))
2450
+ throw unavailable();
2451
+ return finish(false);
2017
2452
  }
2018
- catch {
2019
- /* noop */
2453
+ finally {
2454
+ releaseOwnedLock(agentSendLockPath(name), token);
2020
2455
  }
2021
2456
  }
2022
- cleanupAgentSendLock(name);
2023
- cleanupAgentState(name);
2024
- agentLaunchLines.delete(name);
2025
- return `closed ${name}`;
2457
+ return meta ? withAgentResumeTarget(meta, () => finish(true), true) : finish(true);
2026
2458
  }
2027
2459
  export function closeSession(name) {
2028
2460
  assertExecutionContext(name);
@@ -2031,14 +2463,15 @@ export function closeSession(name) {
2031
2463
  /**
2032
2464
  * Durable caller向けのclose receipt。
2033
2465
  *
2034
- * closeSessionInternalのidempotent cleanupは維持し、呼出時点でtmux sessionが
2035
- * 存在したかだけを固定語彙で返す。MCP response loss後も同じsession IDで再試行すれば
2466
+ * closeSessionInternalのidempotent cleanupは維持し、呼出時点でtmux session
2467
+ * または休止した論理席が存在したかを固定語彙で返す。MCP response loss後も同じsession IDで再試行すれば
2036
2468
  * already_closedとなり、close完了を文字列解析なしで確定できる。
2037
2469
  */
2038
2470
  export function closeSessionResult(name) {
2039
2471
  assertExecutionContext(name);
2040
2472
  assertSessionName(name);
2041
- const existed = sessionExists(name);
2473
+ const meta = tryLoadAgentMetadata(name);
2474
+ const existed = sessionExists(name) || !!(meta && agentDormantState(meta));
2042
2475
  closeSessionInternal(name, true, { letHarnessExit: true });
2043
2476
  return {
2044
2477
  schema: "aiterm.pty-close-result.v1",
@@ -2241,6 +2674,11 @@ function createAgentLineageContext(kind, sessionId, seed) {
2241
2674
  };
2242
2675
  }
2243
2676
  export function runAgentApproval(options) {
2677
+ if (options.action === "respond")
2678
+ assertExecutionContext(options.session_id);
2679
+ return withAgentNativeOperation(options.session_id, options.action === "respond", () => runAgentApprovalInNative(options));
2680
+ }
2681
+ function runAgentApprovalInNative(options) {
2244
2682
  const { action, session_id: name, approval_choice: selected, observed_prompt_digest: expected } = options;
2245
2683
  if (action === "respond")
2246
2684
  assertExecutionContext(name);
@@ -2499,7 +2937,12 @@ function assertExpectedClaudeOperation(meta, expectedOperationId) {
2499
2937
  }
2500
2938
  return active;
2501
2939
  }
2502
- export function runClaudeApproval({ action, session_id: name, operation_id: operationIdInput, approval_choice: approvalChoice, observed_prompt_digest: observedPromptDigest, }) {
2940
+ export function runClaudeApproval(options) {
2941
+ if (options.action === "respond")
2942
+ assertExecutionContext(options.session_id);
2943
+ return withAgentNativeOperation(options.session_id, options.action === "respond", () => runClaudeApprovalInNative(options));
2944
+ }
2945
+ function runClaudeApprovalInNative({ action, session_id: name, operation_id: operationIdInput, approval_choice: approvalChoice, observed_prompt_digest: observedPromptDigest, }) {
2503
2946
  if (action === "respond")
2504
2947
  assertExecutionContext(name);
2505
2948
  assertSessionName(name);
@@ -2749,6 +3192,8 @@ function acquireSessionSendFileLock(name) {
2749
3192
  // 同じprocessの中は着いた順の待ち行列、別のprocessの間はfileで排他し、後の1通は前の1通が終わってから振り分け直す。
2750
3193
  const agentSendQueues = new Map();
2751
3194
  const agentSendHeld = new Set();
3195
+ const agentSendOwner = new AsyncLocalStorage();
3196
+ const activeAgentSendOwner = new Map();
2752
3197
  let agentSendLockWaitMs = AGENT_SEND_LOCK_WAIT_MS;
2753
3198
  export function __testSetAgentSendLockWaitMs(value) {
2754
3199
  if (value !== null && (!Number.isSafeInteger(value) || value < 0))
@@ -2898,7 +3343,40 @@ async function acquireAgentSendFileLock(name, deadline, waitMs, untouched = AGEN
2898
3343
  await sleep(AGENT_SEND_LOCK_POLL_MS);
2899
3344
  }
2900
3345
  }
2901
- async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT) {
3346
+ function withAgentNativeOperation(name, mutates, body) {
3347
+ assertSessionName(name);
3348
+ if (!isAgentSession(name))
3349
+ return body();
3350
+ const verified = hasVerifiedNativeSessionTarget(name), owner = activeAgentSendOwner.get(name);
3351
+ const owns = owner !== undefined ? agentSendOwner.getStore() === owner : verified && agentSendHeld.has(name);
3352
+ // An actual pinned creation/resume may inspect its TUI before publication is ready.
3353
+ if (verified && (!mutates || owns))
3354
+ return body();
3355
+ const unavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 席は休止・停止・復帰中、または他の入力処理中です。操作していません。", 2);
3356
+ const execute = () => {
3357
+ const meta = loadAgentMetadata(name);
3358
+ if (readAgentLifecycle(meta) || agentDormantState(meta))
3359
+ throw unavailable();
3360
+ return withAgentResumeTarget(meta, body);
3361
+ };
3362
+ if (!mutates || owns)
3363
+ return execute();
3364
+ const token = tryCreateOwnedLock(agentSendLockPath(name));
3365
+ if (!token)
3366
+ throw unavailable();
3367
+ const mine = Symbol(name);
3368
+ agentSendHeld.add(name);
3369
+ activeAgentSendOwner.set(name, mine);
3370
+ try {
3371
+ return agentSendOwner.run(mine, execute);
3372
+ }
3373
+ finally {
3374
+ activeAgentSendOwner.delete(name);
3375
+ agentSendHeld.delete(name);
3376
+ releaseOwnedLock(agentSendLockPath(name), token);
3377
+ }
3378
+ }
3379
+ async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT, pinResume = true) {
2902
3380
  const launchId = tryLoadAgentMetadata(name)?.launch_id;
2903
3381
  const waitMs = agentSendLockWaitMs;
2904
3382
  const deadline = performance.now() + waitMs;
@@ -2926,13 +3404,27 @@ async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT) {
2926
3404
  if (!myTurn)
2927
3405
  throw agentSendBusyError(name, null, waitMs, untouched);
2928
3406
  const release = await acquireAgentSendFileLock(name, deadline, waitMs, untouched);
3407
+ const mine = Symbol(name);
2929
3408
  agentSendHeld.add(name);
3409
+ activeAgentSendOwner.set(name, mine);
2930
3410
  try {
2931
- if (tryLoadAgentMetadata(name)?.launch_id !== launchId)
3411
+ const current = tryLoadAgentMetadata(name);
3412
+ const resumed = launchId && current?.resumed_from === launchId
3413
+ && readAgentResumeAttempt({ aiterm_session: name, launch_id: launchId })?.next_launch_id === current.launch_id;
3414
+ if (current?.launch_id !== launchId && !resumed)
2932
3415
  throw new ExecutionError("EXECUTION_STALE_GENERATION");
2933
- return await run();
3416
+ return await agentSendOwner.run(mine, async () => {
3417
+ const meta = pinResume ? tryLoadAgentMetadata(name) : null;
3418
+ if (meta && !readAgentLifecycle(meta)) {
3419
+ if (!fs.existsSync(SOCKDIR) && !meta.resumed_from)
3420
+ throw new AitermError(`agent session '${name}' の ${agentLabel(meta.kind)} TUI が入力受付状態になりません。文字列は送信していません。`, 2);
3421
+ return await withAgentResumeTarget(meta, run);
3422
+ }
3423
+ return await run();
3424
+ });
2934
3425
  }
2935
3426
  finally {
3427
+ activeAgentSendOwner.delete(name);
2936
3428
  agentSendHeld.delete(name);
2937
3429
  release();
2938
3430
  }
@@ -3017,14 +3509,14 @@ function loadAgentMetadata(name) {
3017
3509
  .readdirSync(dir)
3018
3510
  .filter((f) => f.startsWith(`${name}.`) && f.endsWith(".agent.json"));
3019
3511
  if (files.length === 0) {
3512
+ if (readAgentGeneration(name))
3513
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 現在の起動記録がありません。", 2);
3020
3514
  throw new AitermError(`session '${name}' は agent_done 管理セッションではありません。claude_agent/codex_agent 等の launcher で起動してください。`, 2);
3021
3515
  }
3022
- if (files.length !== 1) {
3023
- throw new AitermError(`session '${name}' の agent metadata が複数あります。閉じて起動し直してください。`, 2);
3024
- }
3516
+ const selectedFile = selectAgentMetadataFile(name, files);
3025
3517
  let raw;
3026
3518
  try {
3027
- raw = JSON.parse(fs.readFileSync(path.join(dir, files[0]), "utf8"));
3519
+ raw = JSON.parse(fs.readFileSync(path.join(dir, selectedFile), "utf8"));
3028
3520
  }
3029
3521
  catch (e) {
3030
3522
  throw new AitermError(`agent metadata を読めません: ${e.message}`, 2);
@@ -3036,6 +3528,11 @@ function loadAgentMetadata(name) {
3036
3528
  !LAUNCH_ID_RE.test(m.launch_id)) {
3037
3529
  throw new AitermError(`agent metadata が不正です: ${files[0]}`, 2);
3038
3530
  }
3531
+ const generation = readAgentGeneration(name);
3532
+ if (m.resumed_from !== undefined && (typeof m.resumed_from !== "string" || !LAUNCH_ID_RE.test(m.resumed_from)
3533
+ || generation?.launch_id !== m.launch_id || generation.previous_launch_id !== m.resumed_from))
3534
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰した起動世代が一致しません。", 2);
3535
+ const resumeFields = m.resumed_from === undefined ? {} : { resumed_from: m.resumed_from };
3039
3536
  const expectedEvent = agentEventPath(name, m.launch_id);
3040
3537
  if (m.event_file !== expectedEvent) {
3041
3538
  throw new AitermError("agent metadata の path が現在の secure state root と一致しません", 2);
@@ -3088,6 +3585,7 @@ function loadAgentMetadata(name) {
3088
3585
  typeof m.vendor_session_id !== "string" ||
3089
3586
  !UUID_RE.test(m.vendor_session_id) ||
3090
3587
  m.result_file !== expectedResult ||
3588
+ (m.claude_home !== undefined && (typeof m.claude_home !== "string" || !path.isAbsolute(m.claude_home))) ||
3091
3589
  ((launchOperationId === null) !== (launchRequestDigest === null)) ||
3092
3590
  (launchOperationId !== null && !OPERATION_ID_RE.test(launchOperationId)) ||
3093
3591
  (launchRequestDigest !== null && !OPERATION_ID_RE.test(launchRequestDigest))) {
@@ -3106,6 +3604,7 @@ function loadAgentMetadata(name) {
3106
3604
  ...deliveryFields,
3107
3605
  ...executableFields,
3108
3606
  ...fastFields,
3607
+ ...resumeFields,
3109
3608
  ...startupFields,
3110
3609
  launch_operation_id: launchOperationId,
3111
3610
  launch_request_digest: launchRequestDigest,
@@ -3113,6 +3612,7 @@ function loadAgentMetadata(name) {
3113
3612
  ...loadAgentLineageFields(m, true),
3114
3613
  node_platform: process.platform,
3115
3614
  claude_settings: expectedSettings,
3615
+ ...(m.claude_home === undefined ? {} : { claude_home: m.claude_home }),
3116
3616
  result_file: expectedResult,
3117
3617
  };
3118
3618
  }
@@ -3139,6 +3639,7 @@ function loadAgentMetadata(name) {
3139
3639
  ...deliveryFields,
3140
3640
  ...executableFields,
3141
3641
  ...fastFields,
3642
+ ...resumeFields,
3142
3643
  ...startupFields,
3143
3644
  hook_route: "shared_codex_home",
3144
3645
  completion_route: "codex_transcript",
@@ -3168,6 +3669,7 @@ function loadAgentMetadata(name) {
3168
3669
  ...deliveryFields,
3169
3670
  ...executableFields,
3170
3671
  ...fastFields,
3672
+ ...resumeFields,
3171
3673
  ...startupFields,
3172
3674
  hook_route: "shared_cursor_home",
3173
3675
  completion_route: "cursor_transcript",
@@ -3547,7 +4049,8 @@ export function readSeatTurns(sessionIds) {
3547
4049
  continue;
3548
4050
  let turn = null;
3549
4051
  try {
3550
- turn = codexSeatTurn(meta);
4052
+ const state = agentDormantState(meta);
4053
+ turn = state ? (state === "hibernated" && observeSession(name).state === "hibernated" ? { state: "idle" } : null) : codexSeatTurn(meta);
3551
4054
  }
3552
4055
  catch { /* 読めない席は、分からないまま返す */ }
3553
4056
  seats.push({ session_id: name, launch_id: meta.launch_id, harness: agentHarness(meta.kind),
@@ -3810,13 +4313,28 @@ export function detectAgentRateLimit(kind, aitermSession) {
3810
4313
  return claudeUsageLimit(captureScreen(aitermSession, 0))?.message ?? null;
3811
4314
  return null;
3812
4315
  }
3813
- // 外部waiterプロセス用の純リーダー観測。lock・PTY・metadata書込・dispatch状態には一切触れない。
4316
+ // 外部waiterは完了の時刻だけを追記し、lock・PTY・metadata束縛・dispatch状態には触れない。
3814
4317
  // Codex/Cursor/Grokは各harnessのtranscript、Claudeはevent fileを増分走査し、vendor_session_idのbind永続化を
3815
4318
  // 行わない(waiterは観測者であって所有者でない)。
3816
4319
  // steerを渡した時は、その差し込み(pty_sendの返りのsteer_id)を取った番の終わりを待つ(ADR 0122。steer-follow.ts)。
3817
4320
  export async function observeAgentDone(name, o = {}) {
3818
4321
  if (o.expected_launch_id && !fs.existsSync(agentMetadataPath(name, o.expected_launch_id)))
3819
4322
  throw new ExecutionError("EXECUTION_STALE_GENERATION");
4323
+ const result = await observeAgentDoneInternal(name, o);
4324
+ if ((result.outcome === "done" || result.outcome === "error") && result.at !== null) {
4325
+ try {
4326
+ recordAgentTurnEnd({ aiterm_session: name, launch_id: result.launch_id }, {
4327
+ ...result, at: Number.isFinite(Date.parse(result.at)) ? result.at : new Date().toISOString(),
4328
+ });
4329
+ requestAgentIdleClock(name, result.launch_id);
4330
+ }
4331
+ catch {
4332
+ process.stderr.write("aiterm: AGENT_ACTIVITY_UNCONFIRMED: 番の終了時刻を保存できません。完了結果は保持し、休止判定では記録を再確認してください。\n");
4333
+ }
4334
+ }
4335
+ return result;
4336
+ }
4337
+ async function observeAgentDoneInternal(name, o = {}) {
3820
4338
  const meta = loadAgentMetadata(name);
3821
4339
  if (o.expected_launch_id && meta.launch_id !== o.expected_launch_id)
3822
4340
  throw new ExecutionError("EXECUTION_STALE_GENERATION");
@@ -4106,6 +4624,7 @@ async function submitAgentComposerText(name, kind, body, o) {
4106
4624
  preserveAgentOperation: o.preserveAgentOperation,
4107
4625
  bracketedPaste: true,
4108
4626
  typedPreface: o.typedPreface,
4627
+ ...(o.inputMeta ? { beforePtyWrite: () => recordAgentInput(o.inputMeta) } : {}),
4109
4628
  });
4110
4629
  });
4111
4630
  if (kind === "cursor") {
@@ -4123,12 +4642,13 @@ async function submitAgentComposerText(name, kind, body, o) {
4123
4642
  sendKey(name, "Enter", { preserveAgentOperation: o.preserveAgentOperation });
4124
4643
  });
4125
4644
  }
4126
- async function sendAgentPromptText(name, text, kind) {
4645
+ async function sendAgentPromptText(name, text, kind, inputMeta) {
4127
4646
  // 起動時の文にも、包みになる長さなら出所の1行を包みの外へ出す(ADR 0116)。
4128
4647
  const prefaced = kind === undefined ? { body: text } : splitAgentPreface(kind, null, text, { defaultForWrapped: true });
4129
4648
  await submitAgentComposerText(name, kind, prefaced.body, {
4130
4649
  force: true, raw: false, typedPreface: prefaced.typedPreface, preserveAgentOperation: true,
4131
4650
  admission: "none", subject: "送信prompt",
4651
+ inputMeta,
4132
4652
  });
4133
4653
  }
4134
4654
  // 利用者が端末で済ませるしかない起動前の状態。reasonだけでは直し方が分からないので案内を添える。
@@ -4193,7 +4713,7 @@ async function prepareAgentInput(name, meta, options) {
4193
4713
  }
4194
4714
  if (!ready.ready)
4195
4715
  return { status: "blocked", reason: agentPaneObservation(meta.kind, ready.lastScreen).reason };
4196
- const live = observeSession(name);
4716
+ const live = observeNativeSession(name);
4197
4717
  if (live.harness_alive !== true || live.harness_process === null || live.state !== "idle")
4198
4718
  return { status: "blocked", reason: live.reason };
4199
4719
  // ここまでに居るprocessは起動時の足場(harness・MCP・起動時hook)。初手を送る前に控える。
@@ -4243,7 +4763,7 @@ async function sendInitialAgentPromptInLock(name, text, o) {
4243
4763
  reserveAnonymousClaudeTurn(meta);
4244
4764
  }
4245
4765
  setInitialDelivery(meta, { status: "submitted_unconfirmed", reason: "dispatch_in_progress", turn_started: null }, startOffset);
4246
- await sendAgentPromptText(name, promptText, meta.kind);
4766
+ await sendAgentPromptText(name, promptText, meta.kind, meta);
4247
4767
  setInitialPromptState(meta, "pending");
4248
4768
  }
4249
4769
  catch (e) {
@@ -4303,6 +4823,19 @@ async function sendInitialAgentPromptInLock(name, text, o) {
4303
4823
  }
4304
4824
  export function isAgentSession(name) {
4305
4825
  assertSessionName(name);
4826
+ const dir = existingAgentsDir();
4827
+ const files = dir ? fs.readdirSync(dir).filter(file => file.startsWith(`${name}.`)) : [];
4828
+ const lifecycle = files.some(file => /\.(?:lifecycle|resume-attempt)\.json$/.test(file))
4829
+ || files.some(file => file.endsWith(".resume-native.json")) && files.some(file => file.endsWith(".agent.json"));
4830
+ if (readAgentGeneration(name) || lifecycle) {
4831
+ try {
4832
+ loadAgentMetadata(name);
4833
+ }
4834
+ catch {
4835
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 保存した会話席の起動記録を確認できません。", 2);
4836
+ }
4837
+ return true;
4838
+ }
4306
4839
  return tryLoadAgentMetadata(name) !== null;
4307
4840
  }
4308
4841
  async function waitForScreenText(name, text, timeoutMs = 3_000) {
@@ -4349,8 +4882,8 @@ async function waitForGrokConfigurationResult(name, before, model, effort, timeo
4349
4882
  } while (performance.now() < deadline);
4350
4883
  throw new AitermError(`${agentLabel(loadAgentMetadata(name).kind)} の設定変更完了を確認できません`, 2);
4351
4884
  }
4352
- function sendMenuChoice(name, choice) {
4353
- const sent = tmux("send-keys", "-t", name, choice);
4885
+ function sendMenuChoice(name, ...choices) {
4886
+ const sent = tmux("send-keys", "-t", name, ...choices);
4354
4887
  if (sent.code !== 0) {
4355
4888
  throw new AitermError(`agent設定の選択を送れませんでした: ${sent.stderr.trim() || `code=${sent.code}`}`, 2);
4356
4889
  }
@@ -4457,7 +4990,7 @@ function readExecutionAuthMetadata(name) {
4457
4990
  }
4458
4991
  /** 一覧の取得失敗を端末の消失へ丸めず、正規PTY一覧で存在を確認する。 */
4459
4992
  function authSessionExists(name) {
4460
- return listSessionsResult().sessions.some(session => session.session_id === name);
4993
+ return listNativeSessionsResult().sessions.some(session => session.session_id === name);
4461
4994
  }
4462
4995
  function authSessionEnvironment(name, keys) {
4463
4996
  const env = { ...process.env };
@@ -4819,6 +5352,26 @@ export async function listAgentModels(kind, options = {}) {
4819
5352
  case "antigravity": return antigravityModelChoices(bin, cwd);
4820
5353
  }
4821
5354
  }
5355
+ async function inspectAgentIdleSettings(name, meta, expected) {
5356
+ if (!readAgentResumeNative(meta))
5357
+ return false;
5358
+ const live = observeNativeSession(name);
5359
+ if (live.state !== "idle" || live.reason !== "composer_ready" || live.harness_alive !== true)
5360
+ return false;
5361
+ return withAgentResumeTarget(meta, () => inspectIdleSettings(meta.kind, expected, {
5362
+ screen: () => captureScreen(name, AGENT_TUI_READY_LINES),
5363
+ command: text => sendAgentPromptText(name, text),
5364
+ text: text => { send(name, text, { enter: false, force: true, raw: true, mark: false, rtk: false, preserveAgentOperation: true }); },
5365
+ key: (...keys) => sendMenuChoice(name, ...keys),
5366
+ ready: async () => (await waitAgentTuiReady(name, meta, AGENT_TUI_READY_TIMEOUT_MS, { selectSteer: screen => isAgentTuiBusy(meta.kind, screen) })).ready,
5367
+ }));
5368
+ }
5369
+ export async function __testInspectAgentIdleSettings(name) {
5370
+ return withAgentSendLock(name, async () => {
5371
+ const meta = loadAgentMetadata(name), template = readAgentResumeTemplate(meta);
5372
+ return !!template && typeof meta.fast === "boolean" && inspectAgentIdleSettings(name, meta, { ...template, fast: meta.fast });
5373
+ });
5374
+ }
4822
5375
  const CLAUDE_MODEL_PICKER_TIMEOUT_MS = 8_000;
4823
5376
  const CLAUDE_MODEL_PICKER_KEY_TIMEOUT_MS = 1_500;
4824
5377
  const CLAUDE_MODEL_SWITCH_TIMEOUT_MS = 15_000;
@@ -5038,12 +5591,9 @@ function modelIsFastVariant(kind, model) {
5038
5591
  return /-fast$/.test(model);
5039
5592
  return false;
5040
5593
  }
5041
- function claudeUserSettingsPath() {
5042
- return path.join(claudeConfigDir(), "settings.json");
5043
- }
5044
5594
  /** Claude Codeの席のmodelがfastへ切り替えられるかを、一覧で確かめる。使えない時は断る。 */
5045
- async function assertClaudeFastSupported(bin, cwd, model, untouched) {
5046
- const catalog = await claudeModelChoices(bin, cwd);
5595
+ async function assertClaudeFastSupported(bin, cwd, model, untouched, env = process.env) {
5596
+ const catalog = await claudeModelChoices(bin, cwd, env);
5047
5597
  const key = model ?? "default";
5048
5598
  if (!catalog.fast_ids?.[key]) {
5049
5599
  throw new FastModeError("FAST_MODE_NOT_SUPPORTED", `Claude Code の ${key} はfastに対応していません(対応: ${Object.keys(catalog.fast_ids ?? {}).join(", ") || "なし"})。${untouched}`);
@@ -5051,8 +5601,8 @@ async function assertClaudeFastSupported(bin, cwd, model, untouched) {
5051
5601
  return catalog.fast_unavailable ?? null;
5052
5602
  }
5053
5603
  /** Codexの席のmodel(省略時は利用者のconfig、無ければ一覧の既定)がfastへ切り替えられるかを、一覧で確かめる。 */
5054
- async function assertCodexFastSupported(bin, codexHome, model, untouched) {
5055
- const catalog = await codexModelChoices(bin, true);
5604
+ async function assertCodexFastSupported(bin, codexHome, model, untouched, env = process.env) {
5605
+ const catalog = await codexModelChoices(bin, true, codexHome, env);
5056
5606
  const effective = model ?? readCodexConfigPins(path.join(codexHome, "config.toml")).model.value ?? catalog.default_model;
5057
5607
  if (!effective || !catalog.fast_ids?.[effective]) {
5058
5608
  throw new FastModeError("FAST_MODE_NOT_SUPPORTED", `Codex の ${effective ?? "(modelを特定できません)"} はfastに対応していません(対応: ${Object.keys(catalog.fast_ids ?? {}).join(", ") || "なし"})。${untouched}`);
@@ -5228,11 +5778,11 @@ async function switchClaudeFast(name, meta, target, verified = false) {
5228
5778
  if (meta.model === undefined) {
5229
5779
  throw new FastModeError("FAST_MODE_UNCONFIRMED", `この席のmodelが控えに無く(前の版のAitermが起こした席)、fastの対応を確かめられません。agent_configureへmodelも渡してください。${untouched}`);
5230
5780
  }
5231
- const unavailable = await assertClaudeFastSupported(bin, meta.cwd ?? process.cwd(), meta.model, untouched);
5781
+ const unavailable = await assertClaudeFastSupported(bin, meta.cwd ?? process.cwd(), meta.model, untouched, { ...process.env, CLAUDE_CONFIG_DIR: meta.claude_home ?? claudeConfigDir() });
5232
5782
  if (unavailable)
5233
5783
  throw new FastModeError("FAST_MODE_UNAVAILABLE", `${unavailable.message.replace(/^FAST_MODE_UNAVAILABLE: /, "")}${untouched}`);
5234
5784
  }
5235
- const settings = claudeUserSettingsPath();
5785
+ const settings = path.join(meta.claude_home ?? claudeConfigDir(), "settings.json");
5236
5786
  // Claude Codeは結果の行を出す前に、利用者の設定へ fastMode を書く(on は true、off は項目を消す)。切り替えの前の値へ戻す。
5237
5787
  const seen = await keepingUserDefaults(settings, (before) => { restoreJsonSetting(settings, before, "fastMode"); }, async () => {
5238
5788
  const beforeScreen = captureScreen(name, AGENT_TUI_READY_LINES);
@@ -5541,7 +6091,7 @@ async function applyLaunchFast(name, meta) {
5541
6091
  }
5542
6092
  }
5543
6093
  /** Goal operations share the existing seat admission and original launch ID. */
5544
- export async function agentGoal(input, origin = "automatic") {
6094
+ export async function agentGoal(input, origin = "automatic", expectedGoal) {
5545
6095
  assertSessionName(input.session_id);
5546
6096
  if (input.action !== "inspect")
5547
6097
  assertExecutionContext(input.session_id);
@@ -5563,7 +6113,7 @@ export async function agentGoal(input, origin = "automatic") {
5563
6113
  if (candidates.length !== 1 || tryLoadAgentMetadata(input.session_id)?.launch_id !== input.launch_id)
5564
6114
  return null;
5565
6115
  return { session_id: input.session_id, launch_id: meta.launch_id, harness: agentHarness(meta.kind),
5566
- 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,
6116
+ vendor_session_id: meta.vendor_session_id, codex_home: meta.codex_home, claude_home: meta.claude_home, grok_home: meta.grok_home, cwd: meta.cwd ?? process.cwd(), executable: meta.agent_executable,
5567
6117
  native_process: processIdentity(candidates[0]) };
5568
6118
  };
5569
6119
  const goalUi = (target) => {
@@ -5585,7 +6135,7 @@ export async function agentGoal(input, origin = "automatic") {
5585
6135
  const generation = owner ? readLinuxProcessRegistrationIdentity(owner.pid) : null;
5586
6136
  let registration;
5587
6137
  try {
5588
- const file = path.join(claudeConfigDir(), "sessions", `${owner?.pid}.json`);
6138
+ const file = path.join(target.claude_home ?? claudeConfigDir(), "sessions", `${owner?.pid}.json`);
5589
6139
  const st = fs.lstatSync(file);
5590
6140
  if (!st.isFile() || st.isSymbolicLink() || st.size > 64 * 1024)
5591
6141
  throw new Error("native registration unavailable");
@@ -5727,7 +6277,9 @@ export async function agentGoal(input, origin = "automatic") {
5727
6277
  }),
5728
6278
  clear: target => clearClaudeGoal(goalUi(target)),
5729
6279
  setObjective: (target, objective) => setClaudeGoalObjective(goalUi(target), objective), }, origin));
5730
- const run = () => manageAgentGoal(input, { resolve, connect: (target, callback) => withCodexGoal(target, (request, supported, fields) => callback((method, params) => {
6280
+ const run = () => manageAgentGoal(input, { resolve,
6281
+ ...(expectedGoal ? { beforeMutation: (current) => JSON.stringify(current) === JSON.stringify(expectedGoal) } : {}),
6282
+ connect: (target, callback) => withCodexGoal(target, (request, supported, fields) => callback((method, params) => {
5731
6283
  if (method !== "thread/goal/set" && method !== "thread/goal/clear")
5732
6284
  return request(method, params);
5733
6285
  return withExecutionNativeAdmission(input.session_id, () => {
@@ -5763,6 +6315,9 @@ export async function pauseAgentGoalForStop(target) {
5763
6315
  return { status: "paused" };
5764
6316
  return { status: result.availability === "unsupported" || result.outcome === "unsupported" ? "unsupported" : result.outcome === "outcome_unknown" ? "outcome_unknown" : "unavailable", reason: result.reason };
5765
6317
  }
6318
+ function agentConfigureNotReady(name) {
6319
+ return new AitermError(`agent session '${name}' は入力待ちではありません。番またはgoalが継続する場合はgoalを停止または完了にしてから agent_configure してください。設定は変えていません。`, 2);
6320
+ }
5766
6321
  export async function configureAgent(name, opts) {
5767
6322
  let mayHaveChanged = false;
5768
6323
  const beforeChange = () => { mayHaveChanged = true; };
@@ -5782,18 +6337,65 @@ export async function configureAgent(name, opts) {
5782
6337
  }
5783
6338
  // 設定替えは席の入力欄へ命令を打つので、送信と同じ行列(ADR 0088)に並ぶ。替えている間に届いた文は、替え終えてから席へ入る(ADR 0120)。
5784
6339
  // 番が動いている席では、行列を持ったまま番の終わりを待たない(待つ間も、その席への差し込みを通す)。
5785
- const deadline = performance.now() + AGENT_TUI_READY_TIMEOUT_MS;
5786
- for (;;) {
5787
- const result = await withAgentSendLock(name, () => configureAgentInLock(name, model, effort, fast, beforeChange), AGENT_CONFIGURE_UNCHANGED);
5788
- if (result)
5789
- return result;
5790
- if (performance.now() >= deadline)
5791
- throw new AitermError(`agent session '${name}' は入力待ちではありません`, 2);
5792
- await sleep(AGENT_TUI_READY_POLL_MS);
5793
- }
6340
+ const meta = loadAgentMetadata(name);
6341
+ const checkGeneration = () => {
6342
+ assertExecutionContext(name);
6343
+ if (tryLoadAgentMetadata(name)?.launch_id !== meta.launch_id || observeSessionGeneration(name).launch_id !== meta.launch_id)
6344
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
6345
+ };
6346
+ const configure = async () => {
6347
+ const deadline = performance.now() + AGENT_TUI_READY_TIMEOUT_MS;
6348
+ for (;;) {
6349
+ checkGeneration();
6350
+ const result = await withAgentSendLock(name, async () => {
6351
+ checkGeneration();
6352
+ const current = loadAgentMetadata(name), saved = readAgentResumeTemplate(current);
6353
+ if (readAgentLifecycle(current) || agentDormantState(current))
6354
+ throw new AitermError("AGENT_RESUME_REQUIRED: 設定を変える前に保存した会話席をagent_launchで再開してください。設定は変えていません。", 2);
6355
+ let invalidated = false;
6356
+ const result = await configureAgentInLock(name, model, effort, fast, () => {
6357
+ if (saved && !invalidated) {
6358
+ withExecutionPreparation(name, () => writeAgentResumeTemplate(current, { ...saved, state: "unconfirmed" }));
6359
+ invalidated = true;
6360
+ }
6361
+ beforeChange();
6362
+ });
6363
+ if (result && saved)
6364
+ withExecutionPreparation(name, () => finishAgentResumeConfiguration(loadAgentMetadata(name), saved, model, effort));
6365
+ return result;
6366
+ }, AGENT_CONFIGURE_UNCHANGED);
6367
+ if (result)
6368
+ return result;
6369
+ if (performance.now() >= deadline)
6370
+ throw agentConfigureNotReady(name);
6371
+ await sleep(AGENT_TUI_READY_POLL_MS);
6372
+ }
6373
+ };
6374
+ if (meta.kind !== "codex")
6375
+ return await configure();
6376
+ return await configureWithPausedGoal({
6377
+ goal: (action, expected) => {
6378
+ checkGeneration();
6379
+ return agentGoal({ session_id: name, launch_id: meta.launch_id, action,
6380
+ ...(meta.vendor_session_id ? { expected_thread_id: meta.vendor_session_id } : {}) }, "user", expected);
6381
+ },
6382
+ waitForTurnEnd: async () => {
6383
+ const deadline = performance.now() + 30 * 60_000;
6384
+ for (;;) {
6385
+ checkGeneration();
6386
+ if (codexTurnSettled(loadAgentMetadata(name)))
6387
+ return;
6388
+ if (performance.now() >= deadline)
6389
+ throw new AitermError("GOAL_CONFIGURE_TURN_END_UNCONFIRMED: 30分以内に現在の番の終了を確認できません。設定は変えていません。", 2);
6390
+ await sleep(AGENT_TUI_READY_POLL_MS);
6391
+ }
6392
+ },
6393
+ }, configure);
5794
6394
  }
5795
6395
  catch (error) {
5796
6396
  const failure = error instanceof Error ? error : new AitermError(String(error), 2);
6397
+ if (!mayHaveChanged && failure.message.includes("AGENT_SEND_BUSY") && !failure.message.includes("設定は変えていません。"))
6398
+ failure.message += " 設定は変えていません。";
5797
6399
  Object.assign(failure, { configurationFailure: { schema: "aiterm.agent-configure-error.v1", session_id: name,
5798
6400
  outcome: mayHaveChanged ? "outcome_unknown" : "not_applied", effect: mayHaveChanged ? "possible" : "not_started" } });
5799
6401
  throw failure;
@@ -5811,7 +6413,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
5811
6413
  if (codexRateLimitModelSwitch) {
5812
6414
  throw new AitermError(`CODEX_RATE_LIMIT_MODEL_SWITCH_RECOVERY_FAILED: ${codexPaneObservation(ready.lastScreen).reason}。設定変更は送信していません。`, 2);
5813
6415
  }
5814
- throw new AitermError(`agent session '${name}' は入力待ちではありません`, 2);
6416
+ throw agentConfigureNotReady(name);
5815
6417
  }
5816
6418
  const configured = () => ({
5817
6419
  schema: "aiterm.agent-configure-result.v1",
@@ -5878,7 +6480,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
5878
6480
  if (target === undefined) {
5879
6481
  throw new FastModeError("FAST_MODE_UNCONFIRMED", `この席のmodelが控えに無く(前の版のAitermが起こした席)、fastの対応を確かめられません。modelも渡してください。${untouched}`);
5880
6482
  }
5881
- const unavailable = await assertClaudeFastSupported(bin, meta.cwd ?? process.cwd(), target, untouched);
6483
+ const unavailable = await assertClaudeFastSupported(bin, meta.cwd ?? process.cwd(), target, untouched, { ...process.env, CLAUDE_CONFIG_DIR: meta.claude_home ?? claudeConfigDir() });
5882
6484
  if (unavailable)
5883
6485
  throw new FastModeError("FAST_MODE_UNAVAILABLE", `${unavailable.message.replace(/^FAST_MODE_UNAVAILABLE: /, "")}${untouched}`);
5884
6486
  }
@@ -6197,11 +6799,210 @@ async function assertCursorPromptNotHookBlocked(name) {
6197
6799
  await sleep(100);
6198
6800
  } while (performance.now() < deadline || (performance.now() < hookDeadline && cursorPromptHooksRunning(screen)));
6199
6801
  }
6802
+ /** Caller holds the ordinary send admission for the entire resume and submission. */
6803
+ function verifyAgentResumeNative(meta, native, expectedLaunch = meta.launch_id, allowExitedPane = false) {
6804
+ const unavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰したnative世代が置き換わっています。", 2);
6805
+ if (loadAgentMetadata(meta.aiterm_session).launch_id !== expectedLaunch
6806
+ || !isDeepStrictEqual(readAgentResumeNative(meta), native))
6807
+ throw unavailable();
6808
+ verifyCreatedNative(native, allowExitedPane);
6809
+ }
6810
+ function verifyCreatedNative(native, allowExitedPane = false) {
6811
+ const unavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 作成したnative端末が置き換わっています。", 2);
6812
+ const sessions = observeExecutionNativeSessions();
6813
+ if (sessions.state !== "known" || !sessions.sessions.some(row => row.session_id === native.session_id && row.native_id === native.native_id))
6814
+ throw unavailable();
6815
+ const pane = tmux("display-message", "-p", "-t", nativePaneTarget(native), "#{session_id}\t#{session_name}\t#{pid}\t#{pane_id}\t#{pane_pid}\t#{pane_dead}");
6816
+ const fields = pane.stdout.trim().split("\t");
6817
+ const exited = allowExitedPane && fields[5] === "1";
6818
+ const [serverStarted, paneStarted] = processStartIdentities(exited ? [native.server_pid] : [native.server_pid, native.pane_pid], process.platform);
6819
+ // macOS tmux clears pane_pid after exit; only the explicit dead-pane close admits that absence.
6820
+ if (pane.code !== 0 || fields.length !== 6 || fields.slice(0, 4).join("\t") !== [native.native_id, native.session_id, native.server_pid, native.pane_id].join("\t")
6821
+ || (fields[4] !== String(native.pane_pid) && !(exited && fields[4] === ""))
6822
+ || !["0", "1"].includes(fields[5]) || serverStarted !== native.server_started_identity
6823
+ || (!exited && paneStarted !== native.pane_started_identity))
6824
+ throw unavailable();
6825
+ }
6826
+ function withAgentResumeTarget(meta, body, allowExitedPane = false) {
6827
+ if (hasVerifiedNativeSessionTarget(meta.aiterm_session))
6828
+ return body();
6829
+ let native;
6830
+ try {
6831
+ native = readAgentResumeNative(meta);
6832
+ }
6833
+ catch {
6834
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰したnative本人性の記録を確認できません。", 2);
6835
+ }
6836
+ if (!native) {
6837
+ if (meta.resumed_from)
6838
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰したnative本人性の記録がありません。", 2);
6839
+ return body();
6840
+ }
6841
+ return withNativeSessionTarget(native, () => verifyAgentResumeNative(meta, native, meta.launch_id, allowExitedPane), body, allowExitedPane);
6842
+ }
6843
+ function confirmedAgentResumeRecipe(meta, lifecycle) {
6844
+ const unavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 保存した休止会話の再開情報を確認できません。", 2);
6845
+ const recipe = readAgentResumeRecipe(meta);
6846
+ if (lifecycle.socket !== SOCK || !recipe || recipe.launch_id !== meta.launch_id || recipe.kind !== meta.kind
6847
+ || recipe.vendor_session_id !== meta.vendor_session_id || lifecycle.recipe_digest !== agentResumeRecipeDigest(recipe)
6848
+ || recipe.model !== meta.model || recipe.fast !== meta.fast || recipe.cwd !== meta.cwd || recipe.executable !== meta.agent_executable
6849
+ || recipe.configuration_root !== (meta.kind === "codex" ? meta.codex_home : meta.claude_home ?? claudeConfigDir())
6850
+ || !recipe.model || !recipe.reasoning_effort || !isUsableAgentExecutableFile(recipe.executable)
6851
+ || !fs.statSync(recipe.cwd).isDirectory())
6852
+ throw unavailable();
6853
+ if (meta.kind === "claude" && !Object.hasOwn(recipe.environment, "CLAUDE_CONFIG_DIR"))
6854
+ throw unavailable();
6855
+ if (meta.kind === "codex" && (!lifecycle.resume_proof_digest
6856
+ || codexResumeProofDigest(readCodexResumeProof(meta)) !== lifecycle.resume_proof_digest))
6857
+ throw unavailable();
6858
+ return recipe;
6859
+ }
6860
+ async function resumeAgentInLock(name, readyTimeout = AGENT_TUI_READY_TIMEOUT_MS) {
6861
+ const previous = loadAgentMetadata(name), lifecycle = readAgentLifecycle(previous);
6862
+ const uncertain = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 前の復帰処理を確認できません。本文は送信していません。再送せず席の状態を確認してください。", 2);
6863
+ const ownAttempt = readAgentResumeAttempt(previous);
6864
+ if (!lifecycle) {
6865
+ if (previous.resumed_from) {
6866
+ const attempt = readAgentResumeAttempt({ aiterm_session: name, launch_id: previous.resumed_from });
6867
+ if (attempt?.state !== "ready" || attempt.next_launch_id !== previous.launch_id)
6868
+ throw uncertain();
6869
+ }
6870
+ if (ownAttempt)
6871
+ throw uncertain();
6872
+ return previous;
6873
+ }
6874
+ if (lifecycle.state !== "hibernated" || ownAttempt)
6875
+ throw uncertain();
6876
+ assertExecutionResumeSupported();
6877
+ const recipe = confirmedAgentResumeRecipe(previous, lifecycle);
6878
+ if (sessionExists(name))
6879
+ throw uncertain();
6880
+ const controlEnv = { ...process.env };
6881
+ for (const [key, value] of Object.entries(recipe.environment)) {
6882
+ if (value === null)
6883
+ delete controlEnv[key];
6884
+ else
6885
+ controlEnv[key] = value;
6886
+ }
6887
+ if (recipe.kind === "codex")
6888
+ controlEnv.CODEX_HOME = recipe.configuration_root;
6889
+ if (recipe.fast) {
6890
+ if (recipe.kind === "claude") {
6891
+ if (await assertClaudeFastSupported(recipe.executable, recipe.cwd, recipe.model, "本文は送信していません。", controlEnv))
6892
+ throw uncertain();
6893
+ }
6894
+ else
6895
+ await assertCodexFastSupported(recipe.executable, recipe.configuration_root, recipe.model, "本文は送信していません。", controlEnv);
6896
+ }
6897
+ const lineage = { agentRole: "subagent", parentSessionId: previous.parent_session_id,
6898
+ delegationDepth: previous.delegation_depth, lineage: previous.lineage, delegationAllowed: true };
6899
+ let next = null, attempt = null;
6900
+ let native = null, published = false;
6901
+ return withNativeSessionCreation(name, receipt => {
6902
+ const [server, pane] = processStartIdentities([receipt.server_pid, receipt.pane_pid], process.platform);
6903
+ if (!next || !server || !pane)
6904
+ throw uncertain();
6905
+ native = { schema: "aiterm.agent-resume-native.v1", launch_id: next.launch_id, ...receipt,
6906
+ server_started_identity: server, pane_started_identity: pane };
6907
+ writeAgentResumeNative(next, native);
6908
+ }, () => {
6909
+ if (!next || !native)
6910
+ throw uncertain();
6911
+ verifyAgentResumeNative(next, native, published ? next.launch_id : previous.launch_id);
6912
+ }, async () => {
6913
+ try {
6914
+ await withExecutionNativeAdmission(name, () => {
6915
+ if (!isDeepStrictEqual(loadAgentMetadata(name), previous) || sessionExists(name))
6916
+ throw uncertain();
6917
+ if (readAgentLifecycle(previous)?.state !== "hibernated"
6918
+ || agentResumeRecipeDigest(readAgentResumeRecipe(previous)) !== lifecycle.recipe_digest)
6919
+ throw uncertain();
6920
+ if (previous.kind === "codex" && codexResumeProofDigest(readCodexResumeProof(previous)) !== lifecycle.resume_proof_digest)
6921
+ throw uncertain();
6922
+ publishAgentGeneration(previous);
6923
+ next = previous.kind === "claude"
6924
+ ? createClaudeAgentMetadata(name, recipe.cwd, "none", null, null, lineage, recipe.model, recipe.reasoning_effort)
6925
+ : createCodexAgentMetadata(name, recipe.cwd, "none", { model: recipe.model, effort: recipe.reasoning_effort }, previous.write_scope, lineage);
6926
+ next.vendor_session_id = previous.vendor_session_id;
6927
+ next.resumed_from = previous.launch_id;
6928
+ next.launch_operation_id = previous.launch_operation_id;
6929
+ next.launch_request_digest = previous.launch_request_digest;
6930
+ next.model = recipe.model;
6931
+ next.fast = false;
6932
+ next.agent_executable = recipe.executable;
6933
+ if (isWin)
6934
+ next.windows_launch_exit_tracked = true;
6935
+ if (next.kind === "claude")
6936
+ next.claude_home = recipe.configuration_root;
6937
+ else
6938
+ next.codex_home = recipe.configuration_root;
6939
+ if (previous.write_scope !== undefined)
6940
+ next.write_scope = previous.write_scope;
6941
+ writeAgentMetadata(next);
6942
+ initializeAgentActivity(next);
6943
+ writeAgentResumeRecipe(next, { ...recipe, launch_id: next.launch_id });
6944
+ attempt = { schema: "aiterm.agent-resume-attempt.v1", launch_id: previous.launch_id, next_launch_id: next.launch_id,
6945
+ state: "resuming", at: new Date().toISOString(), recipe_digest: lifecycle.recipe_digest };
6946
+ writeAgentResumeAttempt(previous, attempt);
6947
+ const shell = isWin ? "pwsh" : "bash";
6948
+ openSessionInternal(name, shell, [], true);
6949
+ const environment = [...Object.entries(recipe.environment),
6950
+ ...(next.kind === "codex" ? [["CODEX_HOME", recipe.configuration_root]] : []), ...agentEnvEntries(next, name)];
6951
+ for (const [key, value] of environment) {
6952
+ const stored = value === null ? tmux("set-environment", isWin ? "-u" : "-r", "-t", name, key) : tmux("set-environment", "-t", name, key, value);
6953
+ if (stored.code !== 0)
6954
+ throw uncertain();
6955
+ }
6956
+ if (registerSessionEnvironment(true, name, [...(registeredSessionEnvironment(name) ?? []), ...Object.keys(recipe.environment)]).code !== 0)
6957
+ throw uncertain();
6958
+ const argv = next.kind === "claude" ? claudeResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next)
6959
+ : codexResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next, recipe.cwd);
6960
+ const full = isWin ? windowsAgentLaunchLine(recipe.cwd, environment, windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), { file: agentMetadataPath(name, next.launch_id) + ".launch-exited", launch_id: next.launch_id })
6961
+ : `cd ${shq(recipe.cwd)} && /usr/bin/env ${environment.filter(([, value]) => value === null).map(([key]) => `-u ${shq(key)}`).join(" ")} `
6962
+ + `${environment.filter(([, value]) => value !== null).map(([key, value]) => shq(`${key}=${value}`)).join(" ")} ${argv.map(shq).join(" ")}`;
6963
+ agentLaunchLines.set(name, atomicShellMultiline(full, shell));
6964
+ send(name, full, { enter: true, mark: false, force: true, rtk: false, raw: true, launchShell: shell, preserveAgentOperation: true });
6965
+ publishAgentGeneration(previous, next);
6966
+ published = true;
6967
+ });
6968
+ const resumed = next;
6969
+ const ready = await prepareAgentInput(name, resumed, { ready_timeout: readyTimeout });
6970
+ if (ready.status !== "ready")
6971
+ throw uncertain();
6972
+ // Launch argv pins standard speed; restore fast only after the native composer is ready.
6973
+ if (recipe.fast) {
6974
+ const failed = await applyLaunchFast(name, resumed);
6975
+ if (failed || resumed.fast !== true)
6976
+ throw uncertain();
6977
+ }
6978
+ if (loadAgentMetadata(name).launch_id !== resumed.launch_id)
6979
+ throw uncertain();
6980
+ writeAgentResumeTemplate(resumed, { schema: "aiterm.agent-resume-template.v1", launch_id: resumed.launch_id, state: "confirmed",
6981
+ kind: recipe.kind, executable: recipe.executable, cwd: recipe.cwd, configuration_root: recipe.configuration_root,
6982
+ model: recipe.model, reasoning_effort: recipe.reasoning_effort, environment: recipe.environment });
6983
+ writeAgentResumeRecipe(resumed, { ...recipe, launch_id: resumed.launch_id });
6984
+ writeAgentResumeAttempt(previous, { ...attempt, state: "ready", at: new Date().toISOString() });
6985
+ return resumed;
6986
+ }
6987
+ catch (error) {
6988
+ const issued = attempt;
6989
+ if (issued)
6990
+ try {
6991
+ writeAgentResumeAttempt(previous, { ...issued, state: "failed", at: new Date().toISOString() });
6992
+ }
6993
+ catch { /* resuming also blocks replay */ }
6994
+ throw new AitermError(`AGENT_RESUME_FAILED: 同じ会話への復帰を確認できません。本文は送信していません。再送せず席の状態を確認してください。${error instanceof ExecutionError ? ` ${error.code}` : ""}`, 2);
6995
+ }
6996
+ });
6997
+ }
6200
6998
  export async function dispatchAgentTurn(name, text, o = {}) {
6201
6999
  assertExecutionContext(name);
6202
7000
  assertSessionName(name);
6203
7001
  loadAgentMetadata(name);
6204
- return withAgentSendLock(name, () => dispatchAgentTurnInLock(name, text, o));
7002
+ return withAgentSendLock(name, async () => {
7003
+ const meta = await resumeAgentInLock(name, o.ready_timeout);
7004
+ return withAgentResumeTarget(meta, () => dispatchAgentTurnInLock(name, text, o));
7005
+ });
6205
7006
  }
6206
7007
  async function dispatchAgentTurnInLock(name, text, o, pendingSend) {
6207
7008
  const meta = loadAgentMetadata(name);
@@ -6293,6 +7094,7 @@ async function dispatchAgentTurnInLock(name, text, o, pendingSend) {
6293
7094
  await o.before_send?.({ session_id: name, launch_id: meta.launch_id, vendor: meta.kind,
6294
7095
  harness: agentHarness(meta.kind), event_cursor: startOffset, operation_id: operationId });
6295
7096
  await submitAgentComposerText(name, meta.kind, dispatchText, {
7097
+ inputMeta: meta,
6296
7098
  force: o.force, raw: o.raw, typedPreface: prefaced.typedPreface, preserveAgentOperation: meta.kind === "claude",
6297
7099
  admission: "native", subject: "送信prompt",
6298
7100
  ...(pendingSend ? { checkInput: (started) => assertAgentSendHarness(name, meta, started) } : {}),
@@ -6437,7 +7239,10 @@ export async function sendAgentMessage(name, text, o = {}) {
6437
7239
  // 前置きは、順番待ちにも入力受付の待ちにも入る前に確かめる(外れた時に待たせない)。
6438
7240
  if (o.preface != null)
6439
7241
  assertAgentPreface(o.preface);
6440
- return withAgentSendLock(name, () => sendAgentMessageInLock(name, text, o));
7242
+ return withAgentSendLock(name, async () => {
7243
+ const meta = await resumeAgentInLock(name);
7244
+ return withAgentResumeTarget(meta, () => sendAgentMessageInLock(name, text, o));
7245
+ });
6441
7246
  }
6442
7247
  async function sendAgentMessageInLock(name, text, o) {
6443
7248
  const meta = loadAgentMetadata(name);
@@ -6527,6 +7332,7 @@ async function steerRunningTurn(name, meta, text, o) {
6527
7332
  await submitAgentComposerText(name, meta.kind, text, {
6528
7333
  force: true, raw: o.raw, typedPreface: prefaced.typedPreface, preserveAgentOperation: meta.kind === "claude",
6529
7334
  admission: "native", subject: "差し込む文",
7335
+ inputMeta: meta,
6530
7336
  checkInput: started => assertAgentSendHarness(name, meta, started),
6531
7337
  });
6532
7338
  // GrokとCursorは実行中の送信を待ち行列へ入れる。そのままだと現在turnの完了後に別turnとして動き、
@@ -6809,6 +7615,7 @@ export function openAgent(kind, opts = {}) {
6809
7615
  * Public synchronous openAgent retains its existing immediate refusal contract.
6810
7616
  */
6811
7617
  function prepareAgentLaunch(kind, opts = {}) {
7618
+ assertNoDormantSession(opts.session_name);
6812
7619
  const label = agentLabel(kind);
6813
7620
  // 前提検証は session を作る前に全部済ませる(失敗の残骸 session を作らない)。
6814
7621
  // model/effort → bin → cwd の順: model/effort 検証は CLI 不在の端末でも同じ結果になる(テスト可能性)。
@@ -6946,121 +7753,184 @@ function prepareAgentLaunch(kind, opts = {}) {
6946
7753
  assertCursorModelAvailable(bin, cwd ?? process.cwd(), model, effort, cursorFast);
6947
7754
  }
6948
7755
  return () => {
6949
- let sid;
6950
- let hint;
6951
- // Windows launches use native PowerShell input; never type an owned CLI
6952
- // command through MSYS interactive select/console-master input handling.
6953
- const paneShell = isWin ? "pwsh" : "bash";
6954
- try {
6955
- [sid, hint] = openSession(opts.session_name ?? null, paneShell, envVars);
6956
- }
6957
- catch (error) {
6958
- if (launchOperationId !== null && sessionExists(opts.session_name)) {
6959
- requireMatchingClaudeLaunch(opts.session_name, launchOperationId, launchRequestDigest);
6960
- return existingAgentLaunchResult("claude", opts.session_name, model, effort);
7756
+ let initialNative = null;
7757
+ let initialLaunch = null, initialProof = null;
7758
+ let initialAdmission = null;
7759
+ const create = () => {
7760
+ let sid;
7761
+ let hint;
7762
+ // Windows launches use native PowerShell input; never type an owned CLI
7763
+ // command through MSYS interactive select/console-master input handling.
7764
+ const paneShell = isWin ? "pwsh" : "bash";
7765
+ try {
7766
+ [sid, hint] = openSession(opts.session_name ?? null, paneShell, envVars);
6961
7767
  }
6962
- throw error;
6963
- }
6964
- let launchNote = "";
6965
- try {
6966
- const lineageContext = createAgentLineageContext(kind, sid, lineageSeed);
6967
- if (hasExecutionCreationScope())
6968
- beforeExecutionEffect(sid);
6969
- const meta = withExecutionPreparation(sid, () => {
6970
- const meta = agentDone
6971
- ? kind === "claude"
6972
- ? createClaudeAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", launchOperationId, launchRequestDigest, lineageContext, model, effort)
6973
- : kind === "codex"
6974
- ? createCodexAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", { model, effort }, writeScope, lineageContext)
6975
- : kind === "antigravity"
6976
- ? createAntigravityAgentMetadata(sid, cwd ?? process.cwd(), opts.prompt ? "pending" : "none", writeScope, lineageContext)
6977
- : kind === "cursor"
6978
- ? createCursorAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", writeScope, lineageContext)
6979
- : createGrokAgentMetadata(kind, sid, cwd, opts.prompt ? "pending" : "none", grokAuthPath, writeScope, lineageContext)
6980
- : null;
6981
- if (meta) {
6982
- // Metadata constructors publish their internally generated launch ID.
6983
- // Stamp its exact native creator before binding and any later input.
6984
- if (hasExecutionCreationScope())
6985
- meta.execution_native = executionCreatedNativeBinding(sid);
6986
- meta.agent_executable = bin;
6987
- // Cursor retains its existing unresolved native-process contract.
6988
- if (isWin && kind !== "cursor")
6989
- meta.windows_launch_exit_tracked = true;
6990
- // 席は通常の速度で始まる(Claude Code・Codexは起動の引数で明示する)。fast版のmodel IDで起こした時だけtrue。
6991
- meta.fast = opts.fast_state === true;
6992
- meta.model = opts.base_model !== undefined ? opts.base_model : model;
6993
- // The new physical shell is already pinned by its actual create receipt.
6994
- // Validate it before publishing metadata, then bind this internally
6995
- // generated managed launch. Model arguments cannot select this ID.
6996
- writeAgentMetadata(meta);
6997
- agentMetadataNegativeCache.delete(sid);
7768
+ catch (error) {
7769
+ if (launchOperationId !== null && sessionExists(opts.session_name)) {
7770
+ requireMatchingClaudeLaunch(opts.session_name, launchOperationId, launchRequestDigest);
7771
+ return existingAgentLaunchResult("claude", opts.session_name, model, effort);
6998
7772
  }
6999
- return meta;
7000
- });
7001
- if (meta && hasExecutionCreationScope())
7002
- bindExecutionCreatedLaunch({ session_id: sid, launch_id: meta.launch_id });
7003
- launchNote = buildAgentLaunchNote(kind, model, effort, meta);
7004
- let full;
7005
- if (paneShell === "pwsh") {
7006
- const prompt = opts.prompt ?? null;
7007
- const argv = kind === "claude" ? claudeAgentArgv(bin, model, effort, prompt, meta)
7008
- : kind === "codex" ? codexAgentArgv(bin, model, effort, prompt, meta)
7009
- : kind === "cursor" ? cursorAgentArgv(bin, model, effort, prompt, meta, cursorFast)
7010
- : kind === "antigravity" ? antigravityAgentArgv(bin, model, effort, prompt)
7011
- : grokAgentArgv(kind, bin, model, effort, prompt, meta);
7012
- full = windowsAgentLaunchLine(cwd, [
7013
- ...(meta?.kind === "grok" ? grokEnvEntries(meta) : []), ...agentEnvEntries(meta, sid, envVars),
7014
- ], windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), meta ? { file: agentMetadataPath(sid, meta.launch_id) + ".launch-exited", launch_id: meta.launch_id } : undefined);
7015
- }
7016
- else {
7017
- const cmd = buildAgentCmd(kind, binForCmd, model, effort, opts.prompt ?? null, meta, cursorFast);
7018
- const envPrefix = agentEnvPrefix(meta, sid, envVars);
7019
- const command = cwdForCmd ? `cd ${shq(cwdForCmd)} && ${envPrefix}${cmd}` : `${envPrefix}${cmd}`;
7020
- // このpaneのbashはAitermが自分で選んだ。sub-agent instructionのLFを含む起動commandは、
7021
- // 利用者のshell送信と同じknown-shell適合で1物理行にしてから打つ(sanitizeはしない)。
7022
- // 対話shellの行編集が、埋め込みLFごとに1行ずつ受け付けて継続promptで繋ぐ形に依存しない。
7023
- // agent TUIへの本文(bracketedPaste)は文字どおりのまま。argv・lineage・metadata・native
7024
- // admission・receiptの契約は変えない。
7025
- full = command;
7773
+ throw error;
7026
7774
  }
7027
- if (meta)
7028
- agentLaunchLines.set(sid, atomicShellMultiline(full, paneShell));
7029
- // force:true はagent sessionへの手動介入を表す。起動コマンド自体はAitermが組み立てて、sanitizeせずに送る。
7030
- send(sid, full, {
7031
- enter: true,
7032
- mark: false,
7033
- force: true,
7034
- rtk: false,
7035
- raw: true,
7036
- launchShell: paneShell,
7037
- preserveAgentOperation: meta?.kind === "claude",
7038
- });
7039
- }
7040
- catch (e) {
7041
- const failure = e instanceof ExecutionError ? e : telemetryOwnedFailure("AITERM.VENDOR_LAUNCHER_FAILED", e);
7042
- // 起動コマンドを投入できなかった session は空のまま残る=残骸を作らない。片付けてから元エラーを伝える。
7775
+ let launchNote = "";
7043
7776
  try {
7044
- closeSessionInternal(sid, false);
7777
+ const lineageContext = createAgentLineageContext(kind, sid, lineageSeed);
7778
+ if (hasExecutionCreationScope())
7779
+ beforeExecutionEffect(sid);
7780
+ const meta = withExecutionPreparation(sid, () => {
7781
+ const meta = agentDone
7782
+ ? kind === "claude"
7783
+ ? createClaudeAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", launchOperationId, launchRequestDigest, lineageContext, model, effort)
7784
+ : kind === "codex"
7785
+ ? createCodexAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", { model, effort }, writeScope, lineageContext)
7786
+ : kind === "antigravity"
7787
+ ? createAntigravityAgentMetadata(sid, cwd ?? process.cwd(), opts.prompt ? "pending" : "none", writeScope, lineageContext)
7788
+ : kind === "cursor"
7789
+ ? createCursorAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", writeScope, lineageContext)
7790
+ : createGrokAgentMetadata(kind, sid, cwd, opts.prompt ? "pending" : "none", grokAuthPath, writeScope, lineageContext)
7791
+ : null;
7792
+ if (meta) {
7793
+ // Metadata constructors publish their internally generated launch ID.
7794
+ // Stamp its exact native creator before binding and any later input.
7795
+ if (hasExecutionCreationScope())
7796
+ meta.execution_native = executionCreatedNativeBinding(sid);
7797
+ meta.agent_executable = bin;
7798
+ if (isWin && ["claude", "codex", "grok", "antigravity"].includes(kind))
7799
+ meta.windows_launch_exit_tracked = true;
7800
+ if (kind === "claude" || kind === "codex")
7801
+ meta.cwd = kind === "claude" ? fs.realpathSync(cwd ?? process.cwd()) : path.resolve(cwd ?? process.cwd());
7802
+ // 席は通常の速度で始まる(Claude Code・Codexは起動の引数で明示する)。fast版のmodel IDで起こした時だけtrue。
7803
+ meta.fast = opts.fast_state === true;
7804
+ meta.model = opts.base_model !== undefined ? opts.base_model : model;
7805
+ initializeAgentActivity(meta);
7806
+ // The new physical shell is already pinned by its actual create receipt.
7807
+ // Validate it before publishing metadata, then bind this internally
7808
+ // generated managed launch. Model arguments cannot select this ID.
7809
+ writeAgentMetadata(meta);
7810
+ if (initialNative) {
7811
+ const proof = { schema: "aiterm.agent-resume-native.v1", launch_id: meta.launch_id, ...initialNative };
7812
+ writeAgentResumeNative(meta, proof);
7813
+ initialLaunch = meta;
7814
+ initialProof = proof;
7815
+ }
7816
+ try {
7817
+ captureAgentResumeTemplate(meta, effort, envVars, kind === "claude" ? meta.claude_home : meta.codex_home);
7818
+ }
7819
+ catch {
7820
+ process.stderr.write("aiterm: resume_template_unconfirmed\n");
7821
+ }
7822
+ agentMetadataNegativeCache.delete(sid);
7823
+ }
7824
+ return meta;
7825
+ });
7826
+ if (meta && hasExecutionCreationScope())
7827
+ bindExecutionCreatedLaunch({ session_id: sid, launch_id: meta.launch_id });
7828
+ launchNote = buildAgentLaunchNote(kind, model, effort, meta);
7829
+ let full;
7830
+ if (paneShell === "pwsh") {
7831
+ const prompt = opts.prompt ?? null;
7832
+ const argv = kind === "claude" ? claudeAgentArgv(bin, model, effort, prompt, meta)
7833
+ : kind === "codex" ? codexAgentArgv(bin, model, effort, prompt, meta)
7834
+ : kind === "cursor" ? cursorAgentArgv(bin, model, effort, prompt, meta, cursorFast)
7835
+ : kind === "antigravity" ? antigravityAgentArgv(bin, model, effort, prompt)
7836
+ : grokAgentArgv(kind, bin, model, effort, prompt, meta);
7837
+ full = windowsAgentLaunchLine(cwd, [
7838
+ ...(meta?.kind === "grok" ? grokEnvEntries(meta) : []), ...agentEnvEntries(meta, sid, envVars),
7839
+ ], windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), meta?.windows_launch_exit_tracked ? { file: agentMetadataPath(sid, meta.launch_id) + ".launch-exited", launch_id: meta.launch_id } : undefined);
7840
+ }
7841
+ else {
7842
+ const cmd = buildAgentCmd(kind, binForCmd, model, effort, opts.prompt ?? null, meta, cursorFast);
7843
+ const envPrefix = agentEnvPrefix(meta, sid, envVars);
7844
+ const command = cwdForCmd ? `cd ${shq(cwdForCmd)} && ${envPrefix}${cmd}` : `${envPrefix}${cmd}`;
7845
+ // このpaneのbashはAitermが自分で選んだ。sub-agent instructionのLFを含む起動commandは、
7846
+ // 利用者のshell送信と同じknown-shell適合で1物理行にしてから打つ(sanitizeはしない)。
7847
+ // 対話shellの行編集が、埋め込みLFごとに1行ずつ受け付けて継続promptで繋ぐ形に依存しない。
7848
+ // agent TUIへの本文(bracketedPaste)は文字どおりのまま。argv・lineage・metadata・native
7849
+ // admission・receiptの契約は変えない。
7850
+ full = command;
7851
+ }
7852
+ if (meta)
7853
+ agentLaunchLines.set(sid, atomicShellMultiline(full, paneShell));
7854
+ // force:true はagent sessionへの手動介入を表す。起動コマンド自体はAitermが組み立てて、sanitizeせずに送る。
7855
+ send(sid, full, {
7856
+ enter: true,
7857
+ mark: false,
7858
+ force: true,
7859
+ rtk: false,
7860
+ raw: true,
7861
+ launchShell: paneShell,
7862
+ preserveAgentOperation: meta?.kind === "claude",
7863
+ ...(meta && opts.prompt ? { beforePtyWrite: () => recordAgentInput(meta) } : {}),
7864
+ });
7045
7865
  }
7046
- catch {
7047
- /* 片付け失敗より元エラーの伝達を優先 */
7866
+ catch (e) {
7867
+ const failure = e instanceof ExecutionError ? e : telemetryOwnedFailure("AITERM.VENDOR_LAUNCHER_FAILED", e);
7868
+ // 起動コマンドを投入できなかった session は空のまま残る=残骸を作らない。片付けてから元エラーを伝える。
7869
+ try {
7870
+ closeSessionInternal(sid, false);
7871
+ }
7872
+ catch {
7873
+ /* 片付け失敗より元エラーの伝達を優先 */
7874
+ }
7875
+ throw failure;
7876
+ }
7877
+ const launched = tryLoadAgentMetadata(sid);
7878
+ if (launched)
7879
+ requestAgentIdleClock(sid, launched.launch_id);
7880
+ const driveHint = agentDone
7881
+ ? `TUI の描画には数秒かかる。少し置いてから pty_read(${sid}, screen:true) で画面を読み、` +
7882
+ `turnはpty_send(${sid}, "...")で送る(自動で非ブロックdispatch。${autoDeliveryParent() ? `回答本文は${autoDeliveryParent()}親へ自動配送する` : "完了通知はaiterm-wait"})。中断はpty_key(${sid}, "C-c")、` +
7883
+ `Stopが来ない場合の解除はpty_close(${sid})を使う。`
7884
+ : `TUI の描画には数秒かかる。少し置いてから pty_read(${sid}, screen:true) で画面を読み、` +
7885
+ `pty_send(${sid}, "...") で入力・pty_key(${sid}, "Enter"/"Up"/"C-c" 等) で操作する(対話)。`;
7886
+ return [
7887
+ sid,
7888
+ `${label} を session ${sid} で起動した。${launchNote}${agentDone ? "agent_done 待機が有効。" : ""}` +
7889
+ `${agentDone ? " 通常のproject/user環境を共有し、aiterm所有の完了相関とsub-agent lineageだけを加算。" : ""}\n${hint}\n` +
7890
+ driveHint +
7891
+ `起動直後に増分 pty_read すると空/半描画になり得るので screen:true を使う。`,
7892
+ ];
7893
+ };
7894
+ if (hasExecutionCreationScope() || !agentDone || !["claude", "codex"].includes(kind))
7895
+ return create();
7896
+ try {
7897
+ return withNativeSessionCreation(opts.session_name ?? null, receipt => {
7898
+ const [server, pane] = processStartIdentities([receipt.server_pid, receipt.pane_pid], process.platform);
7899
+ if (!server || !pane)
7900
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 作成したnative本人性を取得できません。", 2);
7901
+ initialNative = { ...receipt, server_started_identity: server, pane_started_identity: pane };
7902
+ try {
7903
+ const token = tryCreateOwnedLock(agentSendLockPath(receipt.session_id));
7904
+ if (!token)
7905
+ throw agentSendBusyError(receipt.session_id, null, 0);
7906
+ initialAdmission = { name: receipt.session_id, token };
7907
+ agentSendHeld.add(receipt.session_id);
7908
+ // The old launch may have entered hibernation after the public precheck.
7909
+ assertNoDormantSession(receipt.session_id);
7910
+ }
7911
+ catch (error) {
7912
+ try {
7913
+ tmux("kill-session", "-t", receipt.session_id);
7914
+ }
7915
+ catch { /* Preserve old launch state and the original error. */ }
7916
+ throw error;
7917
+ }
7918
+ }, () => {
7919
+ if (!initialNative)
7920
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: native作成結果を確認できません。", 2);
7921
+ if (initialLaunch && initialProof)
7922
+ verifyAgentResumeNative(initialLaunch, initialProof);
7923
+ else
7924
+ verifyCreatedNative(initialNative);
7925
+ }, create);
7926
+ }
7927
+ finally {
7928
+ if (initialAdmission) {
7929
+ const { name, token } = initialAdmission;
7930
+ agentSendHeld.delete(name);
7931
+ releaseOwnedLock(agentSendLockPath(name), token);
7048
7932
  }
7049
- throw failure;
7050
- }
7051
- const driveHint = agentDone
7052
- ? `TUI の描画には数秒かかる。少し置いてから pty_read(${sid}, screen:true) で画面を読み、` +
7053
- `turnはpty_send(${sid}, "...")で送る(自動で非ブロックdispatch。${autoDeliveryParent() ? `回答本文は${autoDeliveryParent()}親へ自動配送する` : "完了通知はaiterm-wait"})。中断はpty_key(${sid}, "C-c")、` +
7054
- `Stopが来ない場合の解除はpty_close(${sid})を使う。`
7055
- : `TUI の描画には数秒かかる。少し置いてから pty_read(${sid}, screen:true) で画面を読み、` +
7056
- `pty_send(${sid}, "...") で入力・pty_key(${sid}, "Enter"/"Up"/"C-c" 等) で操作する(対話)。`;
7057
- return [
7058
- sid,
7059
- `${label} を session ${sid} で起動した。${launchNote}${agentDone ? "agent_done 待機が有効。" : ""}` +
7060
- `${agentDone ? " 通常のproject/user環境を共有し、aiterm所有の完了相関とsub-agent lineageだけを加算。" : ""}\n${hint}\n` +
7061
- driveHint +
7062
- `起動直後に増分 pty_read すると空/半描画になり得るので screen:true を使う。`,
7063
- ];
7933
+ }
7064
7934
  };
7065
7935
  }
7066
7936
  export class AgentLaunchPromptError extends AitermError {
@@ -7105,6 +7975,49 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
7105
7975
  if (opts.launch_operation_id != null && prompt !== null) {
7106
7976
  throw new AitermError("launch_operation_idはpromptなしのClaude相関launchだけで指定できます", 2);
7107
7977
  }
7978
+ if (opts.session_name) {
7979
+ assertSessionName(opts.session_name);
7980
+ const name = opts.session_name, saved = tryLoadAgentMetadata(name);
7981
+ if (saved && (readAgentLifecycle(saved) || agentDormantState(saved))) {
7982
+ return withAgentSendLock(name, async () => {
7983
+ const previous = loadAgentMetadata(name), lifecycle = readAgentLifecycle(previous);
7984
+ if (!isDeepStrictEqual(previous, saved) || lifecycle?.state !== "hibernated" || readAgentResumeAttempt(previous))
7985
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 保存した会話席の再開世代を確認できません。", 2);
7986
+ const recipe = confirmedAgentResumeRecipe(previous, lifecycle);
7987
+ if (kind !== previous.kind || sourceSessionId !== null
7988
+ || (opts.model != null && opts.model.trim() !== recipe.model)
7989
+ || (opts.reasoning_effort != null && opts.reasoning_effort.trim() !== recipe.reasoning_effort)
7990
+ || (opts.fast != null && opts.fast !== recipe.fast)
7991
+ || (opts.cwd != null && path.resolve(opts.cwd) !== recipe.cwd)
7992
+ || (opts.write_scope !== undefined && opts.write_scope !== previous.write_scope)
7993
+ || (opts.env_vars !== undefined && !isDeepStrictEqual([...new Set(opts.env_vars)].sort(), Object.keys(recipe.environment).sort())))
7994
+ throw new AitermError("AGENT_RESUME_CONFLICT: 同名の休止席は保存したharness・設定・project・明示envで再開します。変更は再開後に行ってください。", 2);
7995
+ if (opts.launch_operation_id != null)
7996
+ requireMatchingClaudeLaunch(name, validateOperationId(opts.launch_operation_id), claudeLaunchRequestDigest({ sessionName: name, model: opts.model ?? null, effort: opts.reasoning_effort ?? null,
7997
+ cwd: opts.cwd ?? null, agentDone: true }));
7998
+ const resumed = await resumeAgentInLock(name, opts.ready_timeout ?? undefined);
7999
+ return withAgentResumeTarget(resumed, async () => {
8000
+ const hint = `${agentLabel(kind)} を保存した同じ会話へ再開した。\n${attachHint(name)}`;
8001
+ const fastState = { fast: resumed.fast === true, fast_error: null };
8002
+ if (!prompt)
8003
+ return [name, hint, null, null,
8004
+ { status: "not_requested", reason: "not_requested", turn_started: false },
8005
+ { status: "ready", reason: "composer_ready" }, fastState];
8006
+ try {
8007
+ const initial = await sendInitialAgentPromptInLock(name, prompt, {
8008
+ ready_timeout: opts.ready_timeout ?? undefined, before_send: opts.before_send,
8009
+ });
8010
+ return [name, `${hint}\n${initial.text}`, initial.event_cursor, initial.submit_residue, initial.initial_prompt,
8011
+ { status: "ready", reason: "composer_ready" }, fastState];
8012
+ }
8013
+ catch (error) {
8014
+ const current = loadAgentMetadata(name);
8015
+ throw new AgentLaunchPromptError(`session_id: ${name}\n復帰後の初回promptの受理を確認できません。本文を再送しないでください。\n${error instanceof Error ? error.message : String(error)}`, error instanceof AitermError ? error.code : 1, name, current.initial_prompt_delivery ?? { status: "not_sent", reason: "startup_failed", turn_started: false }, current.initial_prompt_cursor ?? null, { status: "blocked", reason: "startup_failed" });
8016
+ }
8017
+ });
8018
+ });
8019
+ }
8020
+ }
7108
8021
  // ファスト(ADR 0114)。設定の誤りは席を作る前に断る。fastへ出来ない訳がアカウントの都合なら、通常で起こして返りへ訳を入れる。
7109
8022
  const requestedModel = opts.model == null ? null : opts.model.trim() || null;
7110
8023
  const fastPlan = await planLaunchFast(kind, {