aiterm-mcp 0.62.6 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js CHANGED
@@ -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") ||
@@ -539,6 +566,8 @@ function autoName() {
539
566
  const r = tmux("list-sessions", "-F", "#{session_name}");
540
567
  const existing = new Set(r.code === 0 ? r.stdout.split(/\s+/).filter(Boolean) : []);
541
568
  let i = 1;
569
+ for (const name of savedAgentSessionNames())
570
+ existing.add(name);
542
571
  while (existing.has(`t${i}`))
543
572
  i++;
544
573
  return `t${i}`;
@@ -709,7 +738,20 @@ function rtkRewrite(text) {
709
738
  // Windows native pane の既定 shell 解決。裸の "bash" は PATH 上で System32 の
710
739
  // WSL launcher (bash.exe) に解決されてしまうため、Git for Windows の bash.exe を
711
740
  // 明示解決する(WSL 非依存の裁定に従う)。AITERM_BASH で上書き可。
741
+ function assertNoDormantSession(name) {
742
+ if (!name)
743
+ return;
744
+ assertSessionName(name);
745
+ const saved = tryLoadAgentMetadata(name);
746
+ if (saved && (readAgentLifecycle(saved) || agentDormantState(saved)))
747
+ throw new AitermError("AGENT_RESUME_REQUIRED: 保存した会話席はagent_launchまたはpty_sendで再開してください。", 2);
748
+ }
712
749
  export function openSession(name, shell = "bash", envVars = []) {
750
+ assertExecutionContext(name);
751
+ assertNoDormantSession(name);
752
+ return openSessionInternal(name, shell, envVars, false);
753
+ }
754
+ function openSessionInternal(name, shell, envVars, preserveAgentState) {
713
755
  assertExecutionContext(name);
714
756
  shell = resolveWinPaneShell(shell);
715
757
  for (const key of envVars) {
@@ -745,8 +787,6 @@ export function openSession(name, shell = "bash", envVars = []) {
745
787
  const launch = sessionEnvironmentLaunch(shell, environment);
746
788
  const r = tmuxNewSession(true, nm, launch, environment.map(entry => entry.slice(0, entry.indexOf("="))));
747
789
  if (r.code === 0) {
748
- // Windowsで、画面の無いlogon(ssh・service)で立てた本体の控えを、画面のある側のpsmuxに消させない(psmux 3.3.8)。
749
- openPsmuxServerToDesktop(nm);
750
790
  if (launch.register_after_start)
751
791
  for (const entry of environment) {
752
792
  const at = entry.indexOf("=");
@@ -783,7 +823,8 @@ export function openSession(name, shell = "bash", envVars = []) {
783
823
  /* noop */
784
824
  }
785
825
  }
786
- cleanupAgentState(nm);
826
+ if (!preserveAgentState)
827
+ cleanupAgentState(nm);
787
828
  // pipe-pane の引数は tmux 内部の /bin/sh -c で再解釈される(argv ではない)。パスは単一引用符で包み、
788
829
  // パス自身の ' は '\'' イディオムでエスケープする(名前は検証済みだが、Windows ユーザー名 O'Brien 等が
789
830
  // 一時パスに ' を持ち込み redirect を壊すのを防ぐ。空白対策も兼ねる)。
@@ -893,116 +934,118 @@ export function send(name, text, o = {}) {
893
934
  throw new AitermError("aiterm相関付きClaude agent sessionへの通常送信はturn境界を失うため拒否します。" +
894
935
  "pty_send(forceなし=自動dispatch)を使うか、通常対話へ切り替えるならsessionをcloseしてpty_openから手動起動し直してください。", 2);
895
936
  }
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 */
937
+ return withAgentNativeOperation(name, true, () => {
938
+ o.beforePtyWrite?.();
939
+ writeLastcmd(name, o.launchShell ? atomicShellMultiline(text, o.launchShell) : text);
940
+ if (o.rtk)
941
+ text = rtkRewrite(text);
942
+ const markId = o.mark ? randomBytes(16).toString("hex") : null;
943
+ if (markId !== null)
944
+ text = appendMarkSentinel(text, fg, markId);
945
+ assertSendTextSize(text, o.rtk || o.mark ? "変換後の送信文字列" : "送信文字列");
946
+ const reportedText = text;
947
+ // Agent composer paste is literal text even if native foreground metadata
948
+ // still reports the startup shell. Keep sanitization, but never encode TUI
949
+ // text as an executable shell command.
950
+ // Original text is validated above. OS queries, stale foreground handling
951
+ // and shell encoding belong to the runtime; common send supplies intent.
952
+ text = adaptShellSubmission(name, text, {
953
+ raw: o.raw, literalPaste: o.bracketedPaste, launchShell: o.launchShell, shell: fg,
954
+ });
955
+ if (o.mark) {
956
+ try {
957
+ fs.writeFileSync(markpath(name), markId);
958
+ }
959
+ catch {
960
+ throw new AitermError("完了印の送信IDを保存できません。文字列は送信していません。", 2);
961
+ }
928
962
  }
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);
963
+ else {
964
+ // 非 mark 送信は、未消化の古い mark 完了待ちを無効化する(前コマンドの sentinel を待ち続けない)。
965
+ try {
966
+ fs.unlinkSync(markpath(name));
967
+ }
968
+ catch {
969
+ /* noop */
938
970
  }
939
- return;
940
971
  }
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);
972
+ // POSIX tmuxはUTF-8安全な256byte pasteへ分割する。Windows psmuxは認証済み
973
+ // server commandでpayload全体を単一SendBytesへ変換し、別processとの交差を構造的に防ぐ。
974
+ const writePty = (payload, bracketedPaste, what) => {
975
+ if (isWin) {
976
+ o.beforePtyWrite?.();
977
+ const sent = sendPsmuxPayload(true, name, payload, bracketedPaste);
978
+ if (sent.code !== 0) {
979
+ throw new AitermError(`psmuxのPTY送信に失敗しました${what}: ${sent.stderr.trim() || `code=${sent.code}`}`, 2);
980
+ }
981
+ return;
957
982
  }
958
- const pasteArgs = pasteBufferBaseArgs();
959
- if (pasteSupportsNoSanitize)
960
- pasteArgs.push("-S");
961
- pasteArgs.push("-b", bufferName, "-t", name);
983
+ // tmuxの`paste-buffer -p`はchunkごとに包むため使わない。Claude Codeは貼り付け1回ごとに
984
+ // 画像pathを探すので、chunk境界でpathが切れて画像を落とし、行もずれた(2026-10-01、
985
+ // 画像4枚付きの約500byte)。全体を1回だけ包み、中身はchunkのまま流す。
986
+ const chunks = splitPtyText(bracketedPaste ? `\x1b[200~${payload}\x1b[201~` : payload);
987
+ const pasteSupportsNoSanitize = pasteBufferSupportsNoSanitizeFlag();
988
+ const bufferBase = `aiterm-${process.pid}-${randomBytes(8).toString("hex")}`;
989
+ for (let i = 0; i < chunks.length; i += 1) {
990
+ const bufferName = `${bufferBase}-${i}`;
991
+ const partial = i > 0
992
+ ? " 先行chunkはPTYに入力済みでEnterは未送信です。再送前に入力を確認・消去してください。"
993
+ : "";
994
+ const loaded = loadPtyBufferChunk(true, bufferName, chunks[i]);
995
+ if (loaded.code !== 0) {
996
+ tmuxCleanup("delete-buffer", "-b", bufferName);
997
+ throw new AitermError(`tmux bufferへの送信準備に失敗しました${what}` +
998
+ `(chunk ${i + 1}/${chunks.length}): ${loaded.stderr.trim() || `code=${loaded.code}`}.${partial}`, 2);
999
+ }
1000
+ const pasteArgs = pasteBufferBaseArgs();
1001
+ if (pasteSupportsNoSanitize)
1002
+ pasteArgs.push("-S");
1003
+ pasteArgs.push("-b", bufferName, "-t", name);
1004
+ try {
1005
+ o.beforePtyWrite?.();
1006
+ }
1007
+ catch (error) {
1008
+ tmuxCleanup("delete-buffer", "-b", bufferName);
1009
+ throw error;
1010
+ }
1011
+ const pasted = tmux(...pasteArgs);
1012
+ if (pasted.code !== 0) {
1013
+ tmuxCleanup("delete-buffer", "-b", bufferName);
1014
+ throw new AitermError(`tmux bufferのPTY送信に失敗しました${what}` +
1015
+ `(chunk ${i + 1}/${chunks.length}): ${pasted.stderr.trim() || `code=${pasted.code}`}.${partial}`, 2);
1016
+ }
1017
+ if (i + 1 < chunks.length) {
1018
+ pauseSync(PTY_PASTE_CHUNK_PAUSE_MS);
1019
+ }
1020
+ }
1021
+ };
1022
+ if (o.typedPreface !== undefined) {
1023
+ // 前置きは貼り付けの印なしで入れる。本文は続けて貼る。前置きだけが入って本文が失敗した時は、入力欄に前置きが残る。
1024
+ writePty(o.typedPreface, false, "(前置き)");
1025
+ pauseSync(PTY_PASTE_CHUNK_PAUSE_MS);
962
1026
  try {
963
- o.beforePtyWrite?.();
1027
+ writePty(text, !!o.bracketedPaste, "");
964
1028
  }
965
1029
  catch (error) {
966
- tmuxCleanup("delete-buffer", "-b", bufferName);
1030
+ if (error instanceof AitermError) {
1031
+ throw new AitermError(`${error.message} 前置きはPTYに入力済みでEnterは未送信です。再送前に入力を確認・消去してください。`, error.code);
1032
+ }
967
1033
  throw error;
968
1034
  }
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
1035
  }
979
- };
980
- if (o.typedPreface !== undefined) {
981
- // 前置きは貼り付けの印なしで入れる。本文は続けて貼る。前置きだけが入って本文が失敗した時は、入力欄に前置きが残る。
982
- writePty(o.typedPreface, false, "(前置き)");
983
- pauseSync(PTY_PASTE_CHUNK_PAUSE_MS);
984
- try {
1036
+ else
985
1037
  writePty(text, !!o.bracketedPaste, "");
986
- }
987
- catch (error) {
988
- if (error instanceof AitermError) {
989
- throw new AitermError(`${error.message} 前置きはPTYに入力済みでEnterは未送信です。再送前に入力を確認・消去してください。`, error.code);
1038
+ if (enter) {
1039
+ o.beforePtyWrite?.();
1040
+ const entered = tmux("send-keys", "-t", name, "Enter");
1041
+ if (entered.code !== 0) {
1042
+ throw new AitermError(`文字列はPTYに入力済みですがtmuxへEnterを送れませんでした: ` +
1043
+ `${entered.stderr.trim() || `code=${entered.code}`}。再送前に入力を確認・消去してください`, 2);
990
1044
  }
991
- throw error;
992
1045
  }
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
- }
1003
- }
1004
- // コードポイント数で数える(JS の .length は UTF-16 単位で絵文字等がズレる。Python は len()=コードポイント)。
1005
- return `sent ${[...reportedText].length} chars to ${name}` + (enter ? " (+Enter)" : "");
1046
+ // コードポイント数で数える(JS の .length は UTF-16 単位で絵文字等がズレる。Python は len()=コードポイント)。
1047
+ return `sent ${[...reportedText].length} chars to ${name}` + (enter ? " (+Enter)" : "");
1048
+ });
1006
1049
  }
1007
1050
  finally {
1008
1051
  releaseSendLock();
@@ -1016,6 +1059,16 @@ export function sendKey(name, key, o = {}) {
1016
1059
  * a launch/conversation identity, or permission to retry a failed delivery.
1017
1060
  */
1018
1061
  export function sendKeyResult(name, key, o = {}) {
1062
+ assertExecutionContext(name);
1063
+ assertSessionName(name);
1064
+ const k = KEYMAP[key.toLowerCase()] ?? key;
1065
+ if (!o.preserveAgentOperation && k !== "C-c" && isAgentSession(name) && managedClaudeOperation(name) !== undefined) {
1066
+ throw new AitermError("aiterm相関付きClaude agent sessionではturn相関を壊さないC-cだけをpty_keyで送れます。" +
1067
+ "他の対話操作はpty_send(自動dispatch)、終了はpty_closeを使ってください。", 2);
1068
+ }
1069
+ return withAgentNativeOperation(name, true, () => sendKeyResultInNative(name, key, o));
1070
+ }
1071
+ function sendKeyResultInNative(name, key, o) {
1019
1072
  assertExecutionContext(name);
1020
1073
  assertSessionName(name);
1021
1074
  if (!sessionExists(name))
@@ -1023,10 +1076,6 @@ export function sendKeyResult(name, key, o = {}) {
1023
1076
  const k = KEYMAP[key.toLowerCase()] ?? key;
1024
1077
  const receipt = () => ({ schema: "aiterm.pty-key-result.v1", session_id: name, key: k,
1025
1078
  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
1079
  const meta = tryLoadAgentMetadata(name);
1031
1080
  if (meta?.kind === "cursor" && k === "Enter") {
1032
1081
  send(name, CURSOR_SUBMIT_SEQUENCE, {
@@ -1047,9 +1096,9 @@ export function sendKeyResult(name, key, o = {}) {
1047
1096
  function readInterruptionTarget(name) {
1048
1097
  try {
1049
1098
  const files = fs.readdirSync(agentsDir()).filter(file => file.startsWith(name + ".") && file.endsWith(".agent.json"));
1050
- if (files.length !== 1)
1099
+ if (files.length === 0)
1051
1100
  return null;
1052
- const meta = JSON.parse(fs.readFileSync(path.join(agentsDir(), files[0]), "utf8"));
1101
+ const meta = JSON.parse(fs.readFileSync(path.join(agentsDir(), selectAgentMetadataFile(name, files)), "utf8"));
1053
1102
  return meta.aiterm_session === name && ["codex", "claude", "cursor", "grok", "antigravity"].includes(meta.kind)
1054
1103
  && typeof meta.launch_id === "string" && LAUNCH_ID_RE.test(meta.launch_id) ? { kind: meta.kind, launch_id: meta.launch_id } : null;
1055
1104
  }
@@ -1061,6 +1110,20 @@ function readInterruptionTarget(name) {
1061
1110
  * proof is required to send the harness's normal cancel key. The native session ID prevents a same-name
1062
1111
  * replacement from receiving the key. This never closes or clears a session. */
1063
1112
  export function interruptSessionNow(name, expectedLaunchId) {
1113
+ assertSessionName(name);
1114
+ const meta = tryLoadAgentMetadata(name);
1115
+ if (meta && agentDormantState(meta) === "hibernated") {
1116
+ const observed = observeSession(name);
1117
+ if (observed.state === "hibernated") {
1118
+ if (observed.launch_id !== meta.launch_id || expectedLaunchId && expectedLaunchId !== meta.launch_id)
1119
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
1120
+ return { session_id: name, outcome: "idle" };
1121
+ }
1122
+ }
1123
+ // The stop button must remain immediate, including during a normal send.
1124
+ return withAgentNativeOperation(name, false, () => interruptSessionNowInNative(name, expectedLaunchId));
1125
+ }
1126
+ function interruptSessionNowInNative(name, expectedLaunchId) {
1064
1127
  assertSessionName(name);
1065
1128
  const listing = observeExecutionNativeSessions();
1066
1129
  if (listing.state !== "known")
@@ -1369,6 +1432,9 @@ export function utf8SafeSliceStart(buf) {
1369
1432
  return buf.subarray(start);
1370
1433
  }
1371
1434
  export async function readOutput(name, o = {}) {
1435
+ return withAgentNativeOperation(name, false, () => readOutputInNative(name, o));
1436
+ }
1437
+ async function readOutputInNative(name, o) {
1372
1438
  assertSessionName(name);
1373
1439
  const timeout = o.timeout ?? DEFAULT_TIMEOUT;
1374
1440
  if (!sessionExists(name) && !fs.existsSync(logpath(name)))
@@ -1547,7 +1613,7 @@ export function startupProcessShapes(identities, rows) {
1547
1613
  // harnessは起動の足場(MCP、language server)を自分で立て直す。控えた後に立て直されると、控えに無いprocessとして残る。
1548
1614
  // 控えの物が終了していて、同じ親の下に同じargvで立ったprocessは、その立て直しとして数えない。
1549
1615
  // 親も立て直されている時は、立て直された親の下を見る。終了した控え1つにつき、数えないのは1つまで。
1550
- export function postStartupProcessCount(kind, activityRows, rows, startup, shapes = []) {
1616
+ export function postStartupProcessCount(kind, activityRows, rows, startup, shapes = [], harness) {
1551
1617
  const byPid = new Map(rows.map(row => [row.pid, row]));
1552
1618
  const relayChild = (row) => {
1553
1619
  const parent = parentProcess(row, byPid);
@@ -1563,7 +1629,8 @@ export function postStartupProcessCount(kind, activityRows, rows, startup, shape
1563
1629
  };
1564
1630
  const present = new Set(activityRows.map(processKey));
1565
1631
  const added = new Map(activityRows
1566
- .filter(row => !startup.has(processKey(row)) && !(kind === "codex" && codexHelperProcess(row.command)) && !relayChild(row) && !ownProbe(row))
1632
+ .filter(row => !startup.has(processKey(row)) && !(kind === "codex" && codexHelperProcess(row.command))
1633
+ && !(kind === "claude" && macKeepAwakeProcess(row, harness)) && !relayChild(row) && !ownProbe(row))
1567
1634
  .map(row => [processKey(row), row]));
1568
1635
  const gone = shapes.filter(shape => startup.has(shape.identity) && !present.has(shape.identity));
1569
1636
  const replacedBy = new Map();
@@ -1585,6 +1652,81 @@ export function postStartupProcessCount(kind, activityRows, rows, startup, shape
1585
1652
  }
1586
1653
  return added.size;
1587
1654
  }
1655
+ function emptySessionObservation(name, exists) {
1656
+ return {
1657
+ schema: "aiterm.pty-observe-result.v1", session_id: name, observed_at: new Date().toISOString(),
1658
+ exists, harness: null, launch_id: null, state: "missing", reason: "session_missing",
1659
+ pane_alive: false, harness_alive: null, pane_process: null, harness_process: null, process_identity: null,
1660
+ token_hint: null, pending_child_deliveries: null,
1661
+ activity: { cursor: null, output_changed: null, cpu_seconds: null, cpu_delta_seconds: null, cpu_delta_complete: null,
1662
+ background_cpu_seconds: null, background_cpu_delta_seconds: null, background_cpu_delta_complete: null,
1663
+ post_startup_process_count: null },
1664
+ };
1665
+ }
1666
+ function agentDormantState(meta) {
1667
+ const lifecycle = readAgentLifecycle(meta);
1668
+ const origin = lifecycle ?? (meta.resumed_from ? readAgentLifecycle({ aiterm_session: meta.aiterm_session, launch_id: meta.resumed_from }) : null);
1669
+ if (origin && origin.socket !== SOCK)
1670
+ return null;
1671
+ const attempt = readAgentResumeAttempt(meta);
1672
+ if (attempt)
1673
+ return attempt.state === "ready" ? "unknown" : attempt.state;
1674
+ if (lifecycle)
1675
+ return lifecycle.state;
1676
+ if (meta.resumed_from) {
1677
+ const previous = readAgentResumeAttempt({ aiterm_session: meta.aiterm_session, launch_id: meta.resumed_from });
1678
+ if (!previous || previous.next_launch_id !== meta.launch_id)
1679
+ return "unknown";
1680
+ if (previous.state !== "ready")
1681
+ return previous.state;
1682
+ }
1683
+ return null;
1684
+ }
1685
+ export function observeSession(name, cursor) {
1686
+ assertSessionName(name);
1687
+ const meta = tryLoadAgentMetadata(name);
1688
+ if (!meta) {
1689
+ isAgentSession(name);
1690
+ return observeNativeSession(name, cursor);
1691
+ }
1692
+ const state = agentDormantState(meta);
1693
+ if (!state)
1694
+ return observeNativeSession(name, cursor);
1695
+ if (cursor !== undefined)
1696
+ decodeActivityCursor(cursor, name);
1697
+ const result = emptySessionObservation(name, true);
1698
+ result.harness = agentHarness(meta.kind);
1699
+ result.launch_id = meta.launch_id;
1700
+ result.state = "unknown";
1701
+ result.reason = `agent_${state}`;
1702
+ result.pane_alive = null;
1703
+ const native = listNativeSessionsResult().sessions.some(row => row.session_id === name);
1704
+ if (state !== "hibernated" || native) {
1705
+ if (native && state === "hibernated")
1706
+ result.reason = "resume_native_conflict";
1707
+ return result;
1708
+ }
1709
+ try {
1710
+ confirmedAgentResumeRecipe(meta, readAgentLifecycle(meta));
1711
+ }
1712
+ catch {
1713
+ result.reason = "resume_unconfirmed";
1714
+ return result;
1715
+ }
1716
+ // Discard the old pane's cursor; hibernation proves absence, not an activity delta.
1717
+ if (!isDeepStrictEqual(loadAgentMetadata(name), meta) || agentDormantState(meta) !== "hibernated"
1718
+ || listNativeSessionsResult().sessions.some(row => row.session_id === name))
1719
+ return result;
1720
+ result.state = "hibernated";
1721
+ result.reason = "idle_timeout";
1722
+ result.pane_alive = false;
1723
+ result.harness_alive = false;
1724
+ result.pending_child_deliveries = 0;
1725
+ result.activity.cpu_seconds = 0;
1726
+ result.activity.background_cpu_seconds = 0;
1727
+ result.activity.post_startup_process_count = 0;
1728
+ return result;
1729
+ }
1588
1730
  /** Native absence before the owned launcher returns does not prove CLI exit. */
1589
1731
  export function absentHarnessAlive(meta, platform = process.platform) {
1590
1732
  if (platform === "win32" && meta.windows_launch_exit_tracked === true) {
@@ -1600,7 +1742,7 @@ export function absentHarnessAlive(meta, platform = process.platform) {
1600
1742
  // Input admission needs the same native ownership proof, without activity capture or child-delivery scans.
1601
1743
  function observeSessionNative(name) {
1602
1744
  assertSessionName(name);
1603
- const listed = listSessionsResult().sessions.find(session => session.session_id === name);
1745
+ const listed = listNativeSessionsResult().sessions.find(session => session.session_id === name);
1604
1746
  const result = {
1605
1747
  schema: "aiterm.pty-observe-result.v1", session_id: name, observed_at: new Date().toISOString(),
1606
1748
  exists: !!listed, harness: null, launch_id: null, state: "missing", reason: "session_missing",
@@ -1662,7 +1804,7 @@ function observeSessionNative(name) {
1662
1804
  }
1663
1805
  return { result, native: { rows, root, subtree, meta, agent } };
1664
1806
  }
1665
- export function observeSession(name, cursor) {
1807
+ function observeNativeSession(name, cursor) {
1666
1808
  assertSessionName(name);
1667
1809
  const previous = cursor === undefined ? null : decodeActivityCursor(cursor, name);
1668
1810
  const { result, native } = observeSessionNative(name);
@@ -1707,7 +1849,7 @@ export function observeSession(name, cursor) {
1707
1849
  background_cpu_delta_seconds: comparable ? Object.entries(backgroundCpu).reduce((sum, [identity, cpu]) => sum + cpu - (previous.background_processes[identity] ?? 0), 0) : null,
1708
1850
  background_cpu_delta_complete: comparable ? Object.keys(previous.background_processes).every(identity => identity in backgroundCpu) : null,
1709
1851
  post_startup_process_count: startup
1710
- ? postStartupProcessCount(meta.kind, activityRows, rows, startup, meta.startup_process_shapes) : null,
1852
+ ? postStartupProcessCount(meta.kind, activityRows, rows, startup, meta.startup_process_shapes, agent) : null,
1711
1853
  };
1712
1854
  return result;
1713
1855
  }
@@ -1721,6 +1863,222 @@ export function observeSessionGeneration(name) {
1721
1863
  return { schema: "aiterm.pty-observe-result.v1", session_id: name, exists,
1722
1864
  launch_id: exists ? tryLoadAgentMetadata(name)?.launch_id ?? null : null };
1723
1865
  }
1866
+ /** Internal lifecycle worker; not an MCP input route and never creates an effect scope. */
1867
+ export async function checkAgentIdle(expectedInput, expectedAnchor) {
1868
+ const expected = executionLaunchSchema.parse(expectedInput), name = expected.session_id;
1869
+ assertExecutionContext(name);
1870
+ assertExecutionResumeSupported();
1871
+ const minutes = idleMinutes();
1872
+ let captured = null;
1873
+ let pinned = null;
1874
+ let root = null;
1875
+ let recipeDigest = null;
1876
+ let configurationScreen = null;
1877
+ let configurationStartedAt = 0;
1878
+ let initialNative = null;
1879
+ let preparation = null;
1880
+ let effectIssued = false;
1881
+ const metadata = () => {
1882
+ assertExecutionContext(name);
1883
+ const meta = loadAgentMetadata(name);
1884
+ if (meta.launch_id !== expected.launch_id)
1885
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
1886
+ if (captured && (!isDeepStrictEqual(meta.execution_native, captured.execution_native) || meta.kind !== captured.kind
1887
+ || meta.vendor_session_id !== captured.vendor_session_id || meta.agent_executable !== captured.agent_executable
1888
+ || meta.cwd !== captured.cwd || meta.model !== captured.model || meta.fast !== captured.fast))
1889
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
1890
+ return meta;
1891
+ };
1892
+ const native = () => {
1893
+ const sessions = observeExecutionNativeSessions();
1894
+ if (sessions.state !== "known")
1895
+ throw new Error("native_session_unconfirmed");
1896
+ const current = sessions.sessions.find(item => item.session_id === name);
1897
+ if (!current)
1898
+ return null;
1899
+ 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}");
1900
+ const fields = pane.stdout.trim().split("\t"), pid = Number(fields[0]), attached = Number(fields[1]);
1901
+ if (pane.code !== 0 || fields.length !== 4 || !Number.isSafeInteger(pid) || pid < 1
1902
+ || !/^\d+$/.test(fields[1]) || !Number.isSafeInteger(attached))
1903
+ throw new Error("native_pane_unconfirmed");
1904
+ if (pinned && (current.native_id !== pinned.native_id || pid !== pinned.pane_pid))
1905
+ throw new Error("native_pane_replaced");
1906
+ return { native_id: current.native_id, pane_pid: pid, attached: attached > 0,
1907
+ window_activity_at: /^\d+$/.test(fields[2]) ? Number(fields[2]) * 1000 : null,
1908
+ last_attached_at: /^\d+$/.test(fields[3]) ? Number(fields[3]) * 1000 : null };
1909
+ };
1910
+ const snapshot = () => {
1911
+ const meta = metadata();
1912
+ captured ??= meta;
1913
+ const receipt = readAgentResumeNative(meta);
1914
+ if (initialNative && !isDeepStrictEqual(receipt, initialNative))
1915
+ throw new Error("native_creation_changed");
1916
+ initialNative ??= receipt;
1917
+ if (receipt && !effectIssued)
1918
+ verifyAgentResumeNative(meta, receipt);
1919
+ if (meta.kind === "codex" && readAgentResumeTemplate(meta)?.state === "confirmed")
1920
+ bindCodexTranscriptSession(meta);
1921
+ const recipe = refreshAgentResumeRecipe(meta);
1922
+ const digest = recipe && agentResumeRecipeDigest(recipe);
1923
+ if (recipeDigest && digest !== recipeDigest)
1924
+ throw new Error("resume_recipe_changed");
1925
+ const lifecycle = readAgentLifecycle(meta);
1926
+ if (lifecycle && !preparation)
1927
+ throw new Error("lifecycle_already_recorded");
1928
+ if (preparation && (!lifecycle || lifecycle.state !== "stopping" || lifecycle.anchor !== preparation.anchor
1929
+ || lifecycle.recipe_digest !== preparation.recipe_digest || lifecycle.resume_proof_digest !== preparation.resume_proof_digest
1930
+ || lifecycle.socket !== preparation.socket))
1931
+ throw new Error("lifecycle_changed");
1932
+ if (preparation?.resume_proof_digest && codexResumeProofDigest(readCodexResumeProof(meta)) !== preparation.resume_proof_digest)
1933
+ throw new Error("resume_proof_changed");
1934
+ const live = observeNativeSession(name), slot = native();
1935
+ if (slot && live.pane_process) {
1936
+ if (slot.pane_pid !== live.pane_process.pid)
1937
+ throw new Error("pane_identity_changed");
1938
+ if (root && !isDeepStrictEqual(root, live.pane_process))
1939
+ throw new Error("pane_identity_changed");
1940
+ pinned ??= { native_id: slot.native_id, pane_pid: slot.pane_pid };
1941
+ root ??= live.pane_process;
1942
+ }
1943
+ if (!effectIssued && meta.execution_native && observeExecutionSessionGeneration(name).launch_id !== expected.launch_id)
1944
+ throw new Error("native_creator_unconfirmed");
1945
+ const done = latestAgentDoneEvent(meta);
1946
+ if (!effectIssued && done)
1947
+ recordAgentTurnEnd(meta, {
1948
+ ...done, at: Number.isFinite(Date.parse(done.at)) ? done.at : new Date().toISOString(),
1949
+ });
1950
+ const resumeReady = !!receipt && !!recipe && recipe.kind === meta.kind && recipe.vendor_session_id === meta.vendor_session_id
1951
+ && recipe.executable === meta.agent_executable && recipe.cwd === (meta.cwd ?? recipe.cwd)
1952
+ && recipe.model === meta.model && recipe.fast === meta.fast;
1953
+ if (resumeReady)
1954
+ recipeDigest ??= digest;
1955
+ const settled = meta.kind === "claude" ? done !== null && readClaudeOperationMarker(meta) === null
1956
+ : meta.kind === "codex" ? done?.turn_id != null && done.turn_id === codexCompletedTurnId(meta) : agentTurnSettled(meta);
1957
+ return { launch_id: meta.launch_id, created_at: meta.created_at, vendor_session_id: meta.vendor_session_id,
1958
+ resume_ready: resumeReady, native_configuration_confirmed: configurationScreen !== null
1959
+ && (effectIssued || (slot?.last_attached_at != null && slot.last_attached_at < configurationStartedAt
1960
+ && configurationScreen === captureScreen(name, AGENT_TUI_READY_LINES))), activity: readAgentActivity(meta), state: live.state, reason: live.reason,
1961
+ attached: slot?.attached ?? (effectIssued ? false : null), turn_settled: settled,
1962
+ pending_child_deliveries: live.pending_child_deliveries,
1963
+ post_startup_process_count: live.activity.post_startup_process_count,
1964
+ window_activity_at: slot?.window_activity_at ?? null };
1965
+ };
1966
+ return checkIdleSeat({
1967
+ exclusive: body => withAgentSendLock(name, async () => {
1968
+ try {
1969
+ const before = snapshot();
1970
+ if (decideIdleSeat(before, Date.now(), minutes, expectedAnchor).reason === "native_configuration_unconfirmed") {
1971
+ const meta = metadata(), recipe = refreshAgentResumeRecipe(meta);
1972
+ configurationStartedAt = Math.floor(Date.now() / 1000) * 1000;
1973
+ if (recipe && await inspectAgentIdleSettings(name, meta, recipe))
1974
+ configurationScreen = captureScreen(name, AGENT_TUI_READY_LINES);
1975
+ }
1976
+ }
1977
+ catch {
1978
+ configurationScreen = null;
1979
+ }
1980
+ return body();
1981
+ }, AGENT_SEND_UNSENT, false), now: Date.now, snapshot,
1982
+ begin: (_seat, anchor) => withExecutionPreparation(name, () => {
1983
+ const meta = metadata();
1984
+ if (!pinned || !root || !recipeDigest || readAgentLifecycle(meta))
1985
+ throw new Error("idle_preparation_unconfirmed");
1986
+ const proof = meta.kind === "codex" ? captureCodexResumeProof(meta) : null;
1987
+ preparation = { schema: "aiterm.agent-lifecycle.v1", launch_id: meta.launch_id, state: "stopping", socket: SOCK,
1988
+ at: new Date().toISOString(), anchor, native_id: pinned.native_id, pane: root, recipe_digest: recipeDigest,
1989
+ ...(proof ? { resume_proof_digest: codexResumeProofDigest(proof) } : {}) };
1990
+ writeAgentLifecycle(meta, preparation);
1991
+ }),
1992
+ stop: async (verify, didIssue) => {
1993
+ if (!root)
1994
+ throw new Error("pane_identity_unavailable");
1995
+ const stopped = await stopProcessTree(root, verify, {
1996
+ read: () => readRuntimeProcesses(true), now: () => performance.now(), pause: sleep,
1997
+ prepare: body => withExecutionPreparation(name, body),
1998
+ signal: (target, signal, group) => {
1999
+ beforeExecutionEffect(name);
2000
+ didIssue();
2001
+ effectIssued = true;
2002
+ signalRuntimeProcess(target, signal, group);
2003
+ },
2004
+ });
2005
+ if (!stopped)
2006
+ return false;
2007
+ return withExecutionPreparation(name, () => {
2008
+ metadata();
2009
+ verify();
2010
+ const remaining = native();
2011
+ if (remaining) {
2012
+ if (!initialNative)
2013
+ throw new Error("native_creation_unconfirmed");
2014
+ const proof = initialNative;
2015
+ withNativeSessionTarget(proof, () => verifyAgentResumeNative(metadata(), proof, expected.launch_id, true), () => {
2016
+ bindExecutionNativeTarget(name, remaining.native_id);
2017
+ beforeExecutionEffect(name);
2018
+ didIssue();
2019
+ effectIssued = true;
2020
+ if (tmux("kill-session", "-t", remaining.native_id).code !== 0)
2021
+ throw new Error("native_close_unconfirmed");
2022
+ }, true);
2023
+ }
2024
+ return native() === null;
2025
+ });
2026
+ },
2027
+ finish: (_seat, anchor) => withExecutionPreparation(name, () => {
2028
+ const meta = metadata(), current = readAgentLifecycle(meta);
2029
+ if (native() !== null || !current || current.state !== "stopping" || current.anchor !== anchor
2030
+ || current.recipe_digest !== recipeDigest || !preparation)
2031
+ throw new Error("idle_finish_unconfirmed");
2032
+ writeAgentLifecycle(meta, { ...preparation, state: "hibernated", at: new Date().toISOString() });
2033
+ }),
2034
+ cancel: (_seat, anchor) => withExecutionPreparation(name, () => cancelAgentStopping(metadata(), anchor)),
2035
+ record: result => {
2036
+ if (tryLoadAgentMetadata(name)?.launch_id === expected.launch_id)
2037
+ writeJson0600(agentMetadataPath(name, expected.launch_id).replace(/\.agent\.json$/, ".idle-check.json"), result);
2038
+ },
2039
+ }, expected.launch_id, minutes, expectedAnchor);
2040
+ }
2041
+ /** One clock tick; native completion is refreshed even when no parent is waiting for the turn. */
2042
+ export async function serviceAgentIdleClock(expectedInput, token) {
2043
+ const expected = executionLaunchSchema.parse(expectedInput), name = expected.session_id;
2044
+ assertExecutionContext(name);
2045
+ const clock = await withAgentSendLock(name, async () => {
2046
+ const meta = loadAgentMetadata(name);
2047
+ if (meta.launch_id !== expected.launch_id)
2048
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
2049
+ return readAgentIdleClock(meta);
2050
+ });
2051
+ if (token !== undefined && (clock?.token !== token || !isAgentIdleClockOwner(clock)))
2052
+ return { outcome: "skipped", reason: "superseded_timer", anchor: null, due_at: null, stalled: false };
2053
+ const result = await checkAgentIdle(expected, token === undefined ? undefined : clock?.anchor ?? undefined);
2054
+ await withAgentSendLock(name, async () => {
2055
+ const meta = loadAgentMetadata(name);
2056
+ if (meta.launch_id !== expected.launch_id)
2057
+ return;
2058
+ const deadline = idleClockDeadline(result, Date.now());
2059
+ if (deadline === null || readAgentLifecycle(meta) || !["claude", "codex"].includes(meta.kind)) {
2060
+ retireAgentIdleClock(meta, token);
2061
+ return;
2062
+ }
2063
+ await armAgentIdleClock(meta, result.anchor, deadline, token);
2064
+ });
2065
+ return result;
2066
+ }
2067
+ /** Only public list/launch entries sweep; internal observation must never recurse into an idle check. */
2068
+ export async function maintainAgentIdleClocks() {
2069
+ if (!AGENT_IDLE_ENABLED)
2070
+ return;
2071
+ for (const name of savedAgentSessionNames()) {
2072
+ try {
2073
+ const meta = loadAgentMetadata(name);
2074
+ if (["claude", "codex"].includes(meta.kind))
2075
+ requestAgentIdleClock(name, meta.launch_id);
2076
+ }
2077
+ catch {
2078
+ process.stderr.write("aiterm: idle_clock_sweep_unconfirmed\n");
2079
+ }
2080
+ }
2081
+ }
1724
2082
  /** Private guarded-runtime read. Legacy metadata without an original native
1725
2083
  * creator stamp remains a present but unverified generation, never enrolled
1726
2084
  * from a current same-name PID or cached vendor session.
@@ -1806,7 +2164,7 @@ function observeEmptyCreatedLaunch(target, alive) {
1806
2164
  export function observeExecutionParentProcess(name) {
1807
2165
  assertSessionName(name);
1808
2166
  return readExecutionParentProcess(name, {
1809
- present: () => listSessionsResult().sessions.some(session => session.session_id === name),
2167
+ present: () => listNativeSessionsResult().sessions.some(session => session.session_id === name),
1810
2168
  metadata: () => tryLoadAgentMetadata(name),
1811
2169
  pane: () => tmux("display-message", "-p", "-t", name, "#{pane_pid}\t#{pane_dead}"),
1812
2170
  processes: readRuntimeProcesses,
@@ -1819,7 +2177,7 @@ export function observeExecutionParentProcess(name) {
1819
2177
  const SESSION_LIST_EXITING_RETRY_MS = 500;
1820
2178
  const SESSION_LIST_EXITING_POLL_MS = 20;
1821
2179
  const SESSION_LIST_SERVER_EXITING_RE = /server exited unexpectedly/i;
1822
- export function listSessionsResult(envKeys = [], runTmux = tmux) {
2180
+ function listNativeSessionsResult(envKeys = [], runTmux = tmux) {
1823
2181
  for (const key of envKeys) {
1824
2182
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
1825
2183
  throw new AitermError("env_keysの環境変数名が不正です", 2);
@@ -1860,6 +2218,40 @@ export function listSessionsResult(envKeys = [], runTmux = tmux) {
1860
2218
  }
1861
2219
  return { schema: "aiterm.pty-list-result.v1", observed_at: new Date().toISOString(), sessions };
1862
2220
  }
2221
+ export function listSessionsResult(envKeys = [], runTmux = tmux) {
2222
+ const result = listNativeSessionsResult(envKeys, runTmux);
2223
+ const present = new Set(result.sessions.map(row => row.session_id));
2224
+ for (const name of savedAgentSessionNames()) {
2225
+ // A known native terminal remains present even when its ordinary agent record is invalid.
2226
+ const meta = present.has(name) ? tryLoadAgentMetadata(name) : loadAgentMetadata(name);
2227
+ if (!meta)
2228
+ continue;
2229
+ const state = agentDormantState(meta);
2230
+ if (!state)
2231
+ continue;
2232
+ const environment = Object.fromEntries(envKeys.map(key => [key, null]));
2233
+ let command = state;
2234
+ const recipe = readAgentResumeRecipe(meta);
2235
+ if (recipe?.kind === meta.kind && recipe.vendor_session_id === meta.vendor_session_id)
2236
+ for (const key of envKeys)
2237
+ environment[key] = recipe.environment[key] ?? null;
2238
+ if (state === "hibernated") {
2239
+ try {
2240
+ confirmedAgentResumeRecipe(meta, readAgentLifecycle(meta));
2241
+ }
2242
+ catch {
2243
+ command = "unknown";
2244
+ }
2245
+ }
2246
+ if (present.has(name)) {
2247
+ result.sessions.find(row => row.session_id === name).environment = environment;
2248
+ continue;
2249
+ }
2250
+ result.sessions.push({ session_id: name, launch_id: meta.launch_id, current_command: command, attached: false, width: 0, height: 0,
2251
+ harness: agentHarness(meta.kind), vendor_session_id: meta.vendor_session_id ?? null, environment });
2252
+ }
2253
+ return result;
2254
+ }
1863
2255
  export function listSessions(result = listSessionsResult()) {
1864
2256
  if (result.sessions.length) {
1865
2257
  return result.sessions
@@ -2003,26 +2395,62 @@ function letClaudeExitBeforeClose(name) {
2003
2395
  function closeSessionInternal(name, observeDependency = true, o = {}) {
2004
2396
  assertSessionName(name);
2005
2397
  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)]) {
2398
+ const finish = (native) => {
2399
+ if (native && o.letHarnessExit)
2400
+ letClaudeExitBeforeClose(name);
2401
+ const killed = native ? (observeDependency ? tmux : tmuxCleanup)("kill-session", "-t", name) : { code: 0, stderr: "" };
2402
+ if (executionManagementCloseTarget(name) && killed.code !== 0) {
2403
+ // Recovery must not erase the old launch metadata or report closed when
2404
+ // its one pinned native close failed. Keep the original send uncertainty.
2405
+ throw new AitermError(`tmux sessionを閉じられませんでした: ${killed.stderr.trim() || `code=${killed.code}`}`, 2);
2406
+ }
2407
+ const proof = isWin && native && meta ? readAgentResumeNative(meta) : null;
2408
+ if (proof && killed.code === 0) {
2409
+ // psmux acknowledges shutdown before its children release their executable and cwd handles.
2410
+ const deadline = performance.now() + SESSION_LIST_EXITING_RETRY_MS;
2411
+ while (isPidAlive(proof.server_pid)) {
2412
+ if (performance.now() >= deadline)
2413
+ throw new AitermError("native_close_unconfirmed: psmuxの終了を確認できません。", 2);
2414
+ pauseSync(SESSION_LIST_EXITING_POLL_MS);
2415
+ }
2416
+ }
2417
+ for (const p of [logpath(name), offsetpath(name), lastcmdpath(name), markpath(name), sendLockPath(name)]) {
2418
+ try {
2419
+ fs.unlinkSync(p);
2420
+ }
2421
+ catch {
2422
+ /* noop */
2423
+ }
2424
+ }
2425
+ cleanupAgentSendLock(name);
2426
+ cleanupAgentState(name);
2427
+ agentLaunchLines.delete(name);
2428
+ return `closed ${name}`;
2429
+ };
2430
+ const meta = tryLoadAgentMetadata(name), lifecycle = meta && readAgentLifecycle(meta);
2431
+ const native = meta && !lifecycle && readAgentResumeNative(meta) ? observeExecutionNativeSessions() : null;
2432
+ const absent = native?.state === "known" && !native.sessions.some(row => row.session_id === name);
2433
+ if (meta && (lifecycle || absent)) {
2434
+ if (lifecycle)
2435
+ assertExecutionResumeSupported();
2436
+ const unavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 休止席のclose対象を確認できません。", 2);
2437
+ // A logical close must never kill a new same-name native terminal.
2438
+ const token = tryCreateOwnedLock(agentSendLockPath(name));
2439
+ if (!token)
2440
+ throw unavailable();
2015
2441
  try {
2016
- fs.unlinkSync(p);
2442
+ const current = observeExecutionNativeSessions();
2443
+ if ((lifecycle && (lifecycle.state !== "hibernated" || lifecycle.socket !== SOCK)) || readAgentResumeAttempt(meta)
2444
+ || !isDeepStrictEqual(loadAgentMetadata(name), meta) || !isDeepStrictEqual(readAgentLifecycle(meta), lifecycle)
2445
+ || current.state !== "known" || current.sessions.some(row => row.session_id === name))
2446
+ throw unavailable();
2447
+ return finish(false);
2017
2448
  }
2018
- catch {
2019
- /* noop */
2449
+ finally {
2450
+ releaseOwnedLock(agentSendLockPath(name), token);
2020
2451
  }
2021
2452
  }
2022
- cleanupAgentSendLock(name);
2023
- cleanupAgentState(name);
2024
- agentLaunchLines.delete(name);
2025
- return `closed ${name}`;
2453
+ return meta ? withAgentResumeTarget(meta, () => finish(true), true) : finish(true);
2026
2454
  }
2027
2455
  export function closeSession(name) {
2028
2456
  assertExecutionContext(name);
@@ -2031,14 +2459,15 @@ export function closeSession(name) {
2031
2459
  /**
2032
2460
  * Durable caller向けのclose receipt。
2033
2461
  *
2034
- * closeSessionInternalのidempotent cleanupは維持し、呼出時点でtmux sessionが
2035
- * 存在したかだけを固定語彙で返す。MCP response loss後も同じsession IDで再試行すれば
2462
+ * closeSessionInternalのidempotent cleanupは維持し、呼出時点でtmux session
2463
+ * または休止した論理席が存在したかを固定語彙で返す。MCP response loss後も同じsession IDで再試行すれば
2036
2464
  * already_closedとなり、close完了を文字列解析なしで確定できる。
2037
2465
  */
2038
2466
  export function closeSessionResult(name) {
2039
2467
  assertExecutionContext(name);
2040
2468
  assertSessionName(name);
2041
- const existed = sessionExists(name);
2469
+ const meta = tryLoadAgentMetadata(name);
2470
+ const existed = sessionExists(name) || !!(meta && agentDormantState(meta));
2042
2471
  closeSessionInternal(name, true, { letHarnessExit: true });
2043
2472
  return {
2044
2473
  schema: "aiterm.pty-close-result.v1",
@@ -2241,6 +2670,11 @@ function createAgentLineageContext(kind, sessionId, seed) {
2241
2670
  };
2242
2671
  }
2243
2672
  export function runAgentApproval(options) {
2673
+ if (options.action === "respond")
2674
+ assertExecutionContext(options.session_id);
2675
+ return withAgentNativeOperation(options.session_id, options.action === "respond", () => runAgentApprovalInNative(options));
2676
+ }
2677
+ function runAgentApprovalInNative(options) {
2244
2678
  const { action, session_id: name, approval_choice: selected, observed_prompt_digest: expected } = options;
2245
2679
  if (action === "respond")
2246
2680
  assertExecutionContext(name);
@@ -2499,7 +2933,12 @@ function assertExpectedClaudeOperation(meta, expectedOperationId) {
2499
2933
  }
2500
2934
  return active;
2501
2935
  }
2502
- export function runClaudeApproval({ action, session_id: name, operation_id: operationIdInput, approval_choice: approvalChoice, observed_prompt_digest: observedPromptDigest, }) {
2936
+ export function runClaudeApproval(options) {
2937
+ if (options.action === "respond")
2938
+ assertExecutionContext(options.session_id);
2939
+ return withAgentNativeOperation(options.session_id, options.action === "respond", () => runClaudeApprovalInNative(options));
2940
+ }
2941
+ function runClaudeApprovalInNative({ action, session_id: name, operation_id: operationIdInput, approval_choice: approvalChoice, observed_prompt_digest: observedPromptDigest, }) {
2503
2942
  if (action === "respond")
2504
2943
  assertExecutionContext(name);
2505
2944
  assertSessionName(name);
@@ -2749,6 +3188,8 @@ function acquireSessionSendFileLock(name) {
2749
3188
  // 同じprocessの中は着いた順の待ち行列、別のprocessの間はfileで排他し、後の1通は前の1通が終わってから振り分け直す。
2750
3189
  const agentSendQueues = new Map();
2751
3190
  const agentSendHeld = new Set();
3191
+ const agentSendOwner = new AsyncLocalStorage();
3192
+ const activeAgentSendOwner = new Map();
2752
3193
  let agentSendLockWaitMs = AGENT_SEND_LOCK_WAIT_MS;
2753
3194
  export function __testSetAgentSendLockWaitMs(value) {
2754
3195
  if (value !== null && (!Number.isSafeInteger(value) || value < 0))
@@ -2898,7 +3339,40 @@ async function acquireAgentSendFileLock(name, deadline, waitMs, untouched = AGEN
2898
3339
  await sleep(AGENT_SEND_LOCK_POLL_MS);
2899
3340
  }
2900
3341
  }
2901
- async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT) {
3342
+ function withAgentNativeOperation(name, mutates, body) {
3343
+ assertSessionName(name);
3344
+ if (!isAgentSession(name))
3345
+ return body();
3346
+ const verified = hasVerifiedNativeSessionTarget(name), owner = activeAgentSendOwner.get(name);
3347
+ const owns = owner !== undefined ? agentSendOwner.getStore() === owner : verified && agentSendHeld.has(name);
3348
+ // An actual pinned creation/resume may inspect its TUI before publication is ready.
3349
+ if (verified && (!mutates || owns))
3350
+ return body();
3351
+ const unavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 席は休止・停止・復帰中、または他の入力処理中です。操作していません。", 2);
3352
+ const execute = () => {
3353
+ const meta = loadAgentMetadata(name);
3354
+ if (readAgentLifecycle(meta) || agentDormantState(meta))
3355
+ throw unavailable();
3356
+ return withAgentResumeTarget(meta, body);
3357
+ };
3358
+ if (!mutates || owns)
3359
+ return execute();
3360
+ const token = tryCreateOwnedLock(agentSendLockPath(name));
3361
+ if (!token)
3362
+ throw unavailable();
3363
+ const mine = Symbol(name);
3364
+ agentSendHeld.add(name);
3365
+ activeAgentSendOwner.set(name, mine);
3366
+ try {
3367
+ return agentSendOwner.run(mine, execute);
3368
+ }
3369
+ finally {
3370
+ activeAgentSendOwner.delete(name);
3371
+ agentSendHeld.delete(name);
3372
+ releaseOwnedLock(agentSendLockPath(name), token);
3373
+ }
3374
+ }
3375
+ async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT, pinResume = true) {
2902
3376
  const launchId = tryLoadAgentMetadata(name)?.launch_id;
2903
3377
  const waitMs = agentSendLockWaitMs;
2904
3378
  const deadline = performance.now() + waitMs;
@@ -2926,13 +3400,27 @@ async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT) {
2926
3400
  if (!myTurn)
2927
3401
  throw agentSendBusyError(name, null, waitMs, untouched);
2928
3402
  const release = await acquireAgentSendFileLock(name, deadline, waitMs, untouched);
3403
+ const mine = Symbol(name);
2929
3404
  agentSendHeld.add(name);
3405
+ activeAgentSendOwner.set(name, mine);
2930
3406
  try {
2931
- if (tryLoadAgentMetadata(name)?.launch_id !== launchId)
3407
+ const current = tryLoadAgentMetadata(name);
3408
+ const resumed = launchId && current?.resumed_from === launchId
3409
+ && readAgentResumeAttempt({ aiterm_session: name, launch_id: launchId })?.next_launch_id === current.launch_id;
3410
+ if (current?.launch_id !== launchId && !resumed)
2932
3411
  throw new ExecutionError("EXECUTION_STALE_GENERATION");
2933
- return await run();
3412
+ return await agentSendOwner.run(mine, async () => {
3413
+ const meta = pinResume ? tryLoadAgentMetadata(name) : null;
3414
+ if (meta && !readAgentLifecycle(meta)) {
3415
+ if (!fs.existsSync(SOCKDIR) && !meta.resumed_from)
3416
+ throw new AitermError(`agent session '${name}' の ${agentLabel(meta.kind)} TUI が入力受付状態になりません。文字列は送信していません。`, 2);
3417
+ return await withAgentResumeTarget(meta, run);
3418
+ }
3419
+ return await run();
3420
+ });
2934
3421
  }
2935
3422
  finally {
3423
+ activeAgentSendOwner.delete(name);
2936
3424
  agentSendHeld.delete(name);
2937
3425
  release();
2938
3426
  }
@@ -3017,14 +3505,14 @@ function loadAgentMetadata(name) {
3017
3505
  .readdirSync(dir)
3018
3506
  .filter((f) => f.startsWith(`${name}.`) && f.endsWith(".agent.json"));
3019
3507
  if (files.length === 0) {
3508
+ if (readAgentGeneration(name))
3509
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 現在の起動記録がありません。", 2);
3020
3510
  throw new AitermError(`session '${name}' は agent_done 管理セッションではありません。claude_agent/codex_agent 等の launcher で起動してください。`, 2);
3021
3511
  }
3022
- if (files.length !== 1) {
3023
- throw new AitermError(`session '${name}' の agent metadata が複数あります。閉じて起動し直してください。`, 2);
3024
- }
3512
+ const selectedFile = selectAgentMetadataFile(name, files);
3025
3513
  let raw;
3026
3514
  try {
3027
- raw = JSON.parse(fs.readFileSync(path.join(dir, files[0]), "utf8"));
3515
+ raw = JSON.parse(fs.readFileSync(path.join(dir, selectedFile), "utf8"));
3028
3516
  }
3029
3517
  catch (e) {
3030
3518
  throw new AitermError(`agent metadata を読めません: ${e.message}`, 2);
@@ -3036,6 +3524,11 @@ function loadAgentMetadata(name) {
3036
3524
  !LAUNCH_ID_RE.test(m.launch_id)) {
3037
3525
  throw new AitermError(`agent metadata が不正です: ${files[0]}`, 2);
3038
3526
  }
3527
+ const generation = readAgentGeneration(name);
3528
+ if (m.resumed_from !== undefined && (typeof m.resumed_from !== "string" || !LAUNCH_ID_RE.test(m.resumed_from)
3529
+ || generation?.launch_id !== m.launch_id || generation.previous_launch_id !== m.resumed_from))
3530
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰した起動世代が一致しません。", 2);
3531
+ const resumeFields = m.resumed_from === undefined ? {} : { resumed_from: m.resumed_from };
3039
3532
  const expectedEvent = agentEventPath(name, m.launch_id);
3040
3533
  if (m.event_file !== expectedEvent) {
3041
3534
  throw new AitermError("agent metadata の path が現在の secure state root と一致しません", 2);
@@ -3088,6 +3581,7 @@ function loadAgentMetadata(name) {
3088
3581
  typeof m.vendor_session_id !== "string" ||
3089
3582
  !UUID_RE.test(m.vendor_session_id) ||
3090
3583
  m.result_file !== expectedResult ||
3584
+ (m.claude_home !== undefined && (typeof m.claude_home !== "string" || !path.isAbsolute(m.claude_home))) ||
3091
3585
  ((launchOperationId === null) !== (launchRequestDigest === null)) ||
3092
3586
  (launchOperationId !== null && !OPERATION_ID_RE.test(launchOperationId)) ||
3093
3587
  (launchRequestDigest !== null && !OPERATION_ID_RE.test(launchRequestDigest))) {
@@ -3106,6 +3600,7 @@ function loadAgentMetadata(name) {
3106
3600
  ...deliveryFields,
3107
3601
  ...executableFields,
3108
3602
  ...fastFields,
3603
+ ...resumeFields,
3109
3604
  ...startupFields,
3110
3605
  launch_operation_id: launchOperationId,
3111
3606
  launch_request_digest: launchRequestDigest,
@@ -3113,6 +3608,7 @@ function loadAgentMetadata(name) {
3113
3608
  ...loadAgentLineageFields(m, true),
3114
3609
  node_platform: process.platform,
3115
3610
  claude_settings: expectedSettings,
3611
+ ...(m.claude_home === undefined ? {} : { claude_home: m.claude_home }),
3116
3612
  result_file: expectedResult,
3117
3613
  };
3118
3614
  }
@@ -3139,6 +3635,7 @@ function loadAgentMetadata(name) {
3139
3635
  ...deliveryFields,
3140
3636
  ...executableFields,
3141
3637
  ...fastFields,
3638
+ ...resumeFields,
3142
3639
  ...startupFields,
3143
3640
  hook_route: "shared_codex_home",
3144
3641
  completion_route: "codex_transcript",
@@ -3168,6 +3665,7 @@ function loadAgentMetadata(name) {
3168
3665
  ...deliveryFields,
3169
3666
  ...executableFields,
3170
3667
  ...fastFields,
3668
+ ...resumeFields,
3171
3669
  ...startupFields,
3172
3670
  hook_route: "shared_cursor_home",
3173
3671
  completion_route: "cursor_transcript",
@@ -3547,7 +4045,8 @@ export function readSeatTurns(sessionIds) {
3547
4045
  continue;
3548
4046
  let turn = null;
3549
4047
  try {
3550
- turn = codexSeatTurn(meta);
4048
+ const state = agentDormantState(meta);
4049
+ turn = state ? (state === "hibernated" && observeSession(name).state === "hibernated" ? { state: "idle" } : null) : codexSeatTurn(meta);
3551
4050
  }
3552
4051
  catch { /* 読めない席は、分からないまま返す */ }
3553
4052
  seats.push({ session_id: name, launch_id: meta.launch_id, harness: agentHarness(meta.kind),
@@ -3810,13 +4309,28 @@ export function detectAgentRateLimit(kind, aitermSession) {
3810
4309
  return claudeUsageLimit(captureScreen(aitermSession, 0))?.message ?? null;
3811
4310
  return null;
3812
4311
  }
3813
- // 外部waiterプロセス用の純リーダー観測。lock・PTY・metadata書込・dispatch状態には一切触れない。
4312
+ // 外部waiterは完了の時刻だけを追記し、lock・PTY・metadata束縛・dispatch状態には触れない。
3814
4313
  // Codex/Cursor/Grokは各harnessのtranscript、Claudeはevent fileを増分走査し、vendor_session_idのbind永続化を
3815
4314
  // 行わない(waiterは観測者であって所有者でない)。
3816
4315
  // steerを渡した時は、その差し込み(pty_sendの返りのsteer_id)を取った番の終わりを待つ(ADR 0122。steer-follow.ts)。
3817
4316
  export async function observeAgentDone(name, o = {}) {
3818
4317
  if (o.expected_launch_id && !fs.existsSync(agentMetadataPath(name, o.expected_launch_id)))
3819
4318
  throw new ExecutionError("EXECUTION_STALE_GENERATION");
4319
+ const result = await observeAgentDoneInternal(name, o);
4320
+ if ((result.outcome === "done" || result.outcome === "error") && result.at !== null) {
4321
+ try {
4322
+ recordAgentTurnEnd({ aiterm_session: name, launch_id: result.launch_id }, {
4323
+ ...result, at: Number.isFinite(Date.parse(result.at)) ? result.at : new Date().toISOString(),
4324
+ });
4325
+ requestAgentIdleClock(name, result.launch_id);
4326
+ }
4327
+ catch {
4328
+ process.stderr.write("aiterm: AGENT_ACTIVITY_UNCONFIRMED: 番の終了時刻を保存できません。完了結果は保持し、休止判定では記録を再確認してください。\n");
4329
+ }
4330
+ }
4331
+ return result;
4332
+ }
4333
+ async function observeAgentDoneInternal(name, o = {}) {
3820
4334
  const meta = loadAgentMetadata(name);
3821
4335
  if (o.expected_launch_id && meta.launch_id !== o.expected_launch_id)
3822
4336
  throw new ExecutionError("EXECUTION_STALE_GENERATION");
@@ -4106,6 +4620,7 @@ async function submitAgentComposerText(name, kind, body, o) {
4106
4620
  preserveAgentOperation: o.preserveAgentOperation,
4107
4621
  bracketedPaste: true,
4108
4622
  typedPreface: o.typedPreface,
4623
+ ...(o.inputMeta ? { beforePtyWrite: () => recordAgentInput(o.inputMeta) } : {}),
4109
4624
  });
4110
4625
  });
4111
4626
  if (kind === "cursor") {
@@ -4123,12 +4638,13 @@ async function submitAgentComposerText(name, kind, body, o) {
4123
4638
  sendKey(name, "Enter", { preserveAgentOperation: o.preserveAgentOperation });
4124
4639
  });
4125
4640
  }
4126
- async function sendAgentPromptText(name, text, kind) {
4641
+ async function sendAgentPromptText(name, text, kind, inputMeta) {
4127
4642
  // 起動時の文にも、包みになる長さなら出所の1行を包みの外へ出す(ADR 0116)。
4128
4643
  const prefaced = kind === undefined ? { body: text } : splitAgentPreface(kind, null, text, { defaultForWrapped: true });
4129
4644
  await submitAgentComposerText(name, kind, prefaced.body, {
4130
4645
  force: true, raw: false, typedPreface: prefaced.typedPreface, preserveAgentOperation: true,
4131
4646
  admission: "none", subject: "送信prompt",
4647
+ inputMeta,
4132
4648
  });
4133
4649
  }
4134
4650
  // 利用者が端末で済ませるしかない起動前の状態。reasonだけでは直し方が分からないので案内を添える。
@@ -4193,7 +4709,7 @@ async function prepareAgentInput(name, meta, options) {
4193
4709
  }
4194
4710
  if (!ready.ready)
4195
4711
  return { status: "blocked", reason: agentPaneObservation(meta.kind, ready.lastScreen).reason };
4196
- const live = observeSession(name);
4712
+ const live = observeNativeSession(name);
4197
4713
  if (live.harness_alive !== true || live.harness_process === null || live.state !== "idle")
4198
4714
  return { status: "blocked", reason: live.reason };
4199
4715
  // ここまでに居るprocessは起動時の足場(harness・MCP・起動時hook)。初手を送る前に控える。
@@ -4243,7 +4759,7 @@ async function sendInitialAgentPromptInLock(name, text, o) {
4243
4759
  reserveAnonymousClaudeTurn(meta);
4244
4760
  }
4245
4761
  setInitialDelivery(meta, { status: "submitted_unconfirmed", reason: "dispatch_in_progress", turn_started: null }, startOffset);
4246
- await sendAgentPromptText(name, promptText, meta.kind);
4762
+ await sendAgentPromptText(name, promptText, meta.kind, meta);
4247
4763
  setInitialPromptState(meta, "pending");
4248
4764
  }
4249
4765
  catch (e) {
@@ -4303,6 +4819,19 @@ async function sendInitialAgentPromptInLock(name, text, o) {
4303
4819
  }
4304
4820
  export function isAgentSession(name) {
4305
4821
  assertSessionName(name);
4822
+ const dir = existingAgentsDir();
4823
+ const files = dir ? fs.readdirSync(dir).filter(file => file.startsWith(`${name}.`)) : [];
4824
+ const lifecycle = files.some(file => /\.(?:lifecycle|resume-attempt)\.json$/.test(file))
4825
+ || files.some(file => file.endsWith(".resume-native.json")) && files.some(file => file.endsWith(".agent.json"));
4826
+ if (readAgentGeneration(name) || lifecycle) {
4827
+ try {
4828
+ loadAgentMetadata(name);
4829
+ }
4830
+ catch {
4831
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 保存した会話席の起動記録を確認できません。", 2);
4832
+ }
4833
+ return true;
4834
+ }
4306
4835
  return tryLoadAgentMetadata(name) !== null;
4307
4836
  }
4308
4837
  async function waitForScreenText(name, text, timeoutMs = 3_000) {
@@ -4349,8 +4878,8 @@ async function waitForGrokConfigurationResult(name, before, model, effort, timeo
4349
4878
  } while (performance.now() < deadline);
4350
4879
  throw new AitermError(`${agentLabel(loadAgentMetadata(name).kind)} の設定変更完了を確認できません`, 2);
4351
4880
  }
4352
- function sendMenuChoice(name, choice) {
4353
- const sent = tmux("send-keys", "-t", name, choice);
4881
+ function sendMenuChoice(name, ...choices) {
4882
+ const sent = tmux("send-keys", "-t", name, ...choices);
4354
4883
  if (sent.code !== 0) {
4355
4884
  throw new AitermError(`agent設定の選択を送れませんでした: ${sent.stderr.trim() || `code=${sent.code}`}`, 2);
4356
4885
  }
@@ -4457,7 +4986,7 @@ function readExecutionAuthMetadata(name) {
4457
4986
  }
4458
4987
  /** 一覧の取得失敗を端末の消失へ丸めず、正規PTY一覧で存在を確認する。 */
4459
4988
  function authSessionExists(name) {
4460
- return listSessionsResult().sessions.some(session => session.session_id === name);
4989
+ return listNativeSessionsResult().sessions.some(session => session.session_id === name);
4461
4990
  }
4462
4991
  function authSessionEnvironment(name, keys) {
4463
4992
  const env = { ...process.env };
@@ -4819,6 +5348,26 @@ export async function listAgentModels(kind, options = {}) {
4819
5348
  case "antigravity": return antigravityModelChoices(bin, cwd);
4820
5349
  }
4821
5350
  }
5351
+ async function inspectAgentIdleSettings(name, meta, expected) {
5352
+ if (!readAgentResumeNative(meta))
5353
+ return false;
5354
+ const live = observeNativeSession(name);
5355
+ if (live.state !== "idle" || live.reason !== "composer_ready" || live.harness_alive !== true)
5356
+ return false;
5357
+ return withAgentResumeTarget(meta, () => inspectIdleSettings(meta.kind, expected, {
5358
+ screen: () => captureScreen(name, AGENT_TUI_READY_LINES),
5359
+ command: text => sendAgentPromptText(name, text),
5360
+ text: text => { send(name, text, { enter: false, force: true, raw: true, mark: false, rtk: false, preserveAgentOperation: true }); },
5361
+ key: (...keys) => sendMenuChoice(name, ...keys),
5362
+ ready: async () => (await waitAgentTuiReady(name, meta, AGENT_TUI_READY_TIMEOUT_MS, { selectSteer: screen => isAgentTuiBusy(meta.kind, screen) })).ready,
5363
+ }));
5364
+ }
5365
+ export async function __testInspectAgentIdleSettings(name) {
5366
+ return withAgentSendLock(name, async () => {
5367
+ const meta = loadAgentMetadata(name), template = readAgentResumeTemplate(meta);
5368
+ return !!template && typeof meta.fast === "boolean" && inspectAgentIdleSettings(name, meta, { ...template, fast: meta.fast });
5369
+ });
5370
+ }
4822
5371
  const CLAUDE_MODEL_PICKER_TIMEOUT_MS = 8_000;
4823
5372
  const CLAUDE_MODEL_PICKER_KEY_TIMEOUT_MS = 1_500;
4824
5373
  const CLAUDE_MODEL_SWITCH_TIMEOUT_MS = 15_000;
@@ -5038,12 +5587,9 @@ function modelIsFastVariant(kind, model) {
5038
5587
  return /-fast$/.test(model);
5039
5588
  return false;
5040
5589
  }
5041
- function claudeUserSettingsPath() {
5042
- return path.join(claudeConfigDir(), "settings.json");
5043
- }
5044
5590
  /** Claude Codeの席のmodelがfastへ切り替えられるかを、一覧で確かめる。使えない時は断る。 */
5045
- async function assertClaudeFastSupported(bin, cwd, model, untouched) {
5046
- const catalog = await claudeModelChoices(bin, cwd);
5591
+ async function assertClaudeFastSupported(bin, cwd, model, untouched, env = process.env) {
5592
+ const catalog = await claudeModelChoices(bin, cwd, env);
5047
5593
  const key = model ?? "default";
5048
5594
  if (!catalog.fast_ids?.[key]) {
5049
5595
  throw new FastModeError("FAST_MODE_NOT_SUPPORTED", `Claude Code の ${key} はfastに対応していません(対応: ${Object.keys(catalog.fast_ids ?? {}).join(", ") || "なし"})。${untouched}`);
@@ -5051,8 +5597,8 @@ async function assertClaudeFastSupported(bin, cwd, model, untouched) {
5051
5597
  return catalog.fast_unavailable ?? null;
5052
5598
  }
5053
5599
  /** Codexの席のmodel(省略時は利用者のconfig、無ければ一覧の既定)がfastへ切り替えられるかを、一覧で確かめる。 */
5054
- async function assertCodexFastSupported(bin, codexHome, model, untouched) {
5055
- const catalog = await codexModelChoices(bin, true);
5600
+ async function assertCodexFastSupported(bin, codexHome, model, untouched, env = process.env) {
5601
+ const catalog = await codexModelChoices(bin, true, codexHome, env);
5056
5602
  const effective = model ?? readCodexConfigPins(path.join(codexHome, "config.toml")).model.value ?? catalog.default_model;
5057
5603
  if (!effective || !catalog.fast_ids?.[effective]) {
5058
5604
  throw new FastModeError("FAST_MODE_NOT_SUPPORTED", `Codex の ${effective ?? "(modelを特定できません)"} はfastに対応していません(対応: ${Object.keys(catalog.fast_ids ?? {}).join(", ") || "なし"})。${untouched}`);
@@ -5228,11 +5774,11 @@ async function switchClaudeFast(name, meta, target, verified = false) {
5228
5774
  if (meta.model === undefined) {
5229
5775
  throw new FastModeError("FAST_MODE_UNCONFIRMED", `この席のmodelが控えに無く(前の版のAitermが起こした席)、fastの対応を確かめられません。agent_configureへmodelも渡してください。${untouched}`);
5230
5776
  }
5231
- const unavailable = await assertClaudeFastSupported(bin, meta.cwd ?? process.cwd(), meta.model, untouched);
5777
+ const unavailable = await assertClaudeFastSupported(bin, meta.cwd ?? process.cwd(), meta.model, untouched, { ...process.env, CLAUDE_CONFIG_DIR: meta.claude_home ?? claudeConfigDir() });
5232
5778
  if (unavailable)
5233
5779
  throw new FastModeError("FAST_MODE_UNAVAILABLE", `${unavailable.message.replace(/^FAST_MODE_UNAVAILABLE: /, "")}${untouched}`);
5234
5780
  }
5235
- const settings = claudeUserSettingsPath();
5781
+ const settings = path.join(meta.claude_home ?? claudeConfigDir(), "settings.json");
5236
5782
  // Claude Codeは結果の行を出す前に、利用者の設定へ fastMode を書く(on は true、off は項目を消す)。切り替えの前の値へ戻す。
5237
5783
  const seen = await keepingUserDefaults(settings, (before) => { restoreJsonSetting(settings, before, "fastMode"); }, async () => {
5238
5784
  const beforeScreen = captureScreen(name, AGENT_TUI_READY_LINES);
@@ -5541,7 +6087,7 @@ async function applyLaunchFast(name, meta) {
5541
6087
  }
5542
6088
  }
5543
6089
  /** Goal operations share the existing seat admission and original launch ID. */
5544
- export async function agentGoal(input, origin = "automatic") {
6090
+ export async function agentGoal(input, origin = "automatic", expectedGoal) {
5545
6091
  assertSessionName(input.session_id);
5546
6092
  if (input.action !== "inspect")
5547
6093
  assertExecutionContext(input.session_id);
@@ -5563,7 +6109,7 @@ export async function agentGoal(input, origin = "automatic") {
5563
6109
  if (candidates.length !== 1 || tryLoadAgentMetadata(input.session_id)?.launch_id !== input.launch_id)
5564
6110
  return null;
5565
6111
  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,
6112
+ 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
6113
  native_process: processIdentity(candidates[0]) };
5568
6114
  };
5569
6115
  const goalUi = (target) => {
@@ -5585,7 +6131,7 @@ export async function agentGoal(input, origin = "automatic") {
5585
6131
  const generation = owner ? readLinuxProcessRegistrationIdentity(owner.pid) : null;
5586
6132
  let registration;
5587
6133
  try {
5588
- const file = path.join(claudeConfigDir(), "sessions", `${owner?.pid}.json`);
6134
+ const file = path.join(target.claude_home ?? claudeConfigDir(), "sessions", `${owner?.pid}.json`);
5589
6135
  const st = fs.lstatSync(file);
5590
6136
  if (!st.isFile() || st.isSymbolicLink() || st.size > 64 * 1024)
5591
6137
  throw new Error("native registration unavailable");
@@ -5727,7 +6273,9 @@ export async function agentGoal(input, origin = "automatic") {
5727
6273
  }),
5728
6274
  clear: target => clearClaudeGoal(goalUi(target)),
5729
6275
  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) => {
6276
+ const run = () => manageAgentGoal(input, { resolve,
6277
+ ...(expectedGoal ? { beforeMutation: (current) => JSON.stringify(current) === JSON.stringify(expectedGoal) } : {}),
6278
+ connect: (target, callback) => withCodexGoal(target, (request, supported, fields) => callback((method, params) => {
5731
6279
  if (method !== "thread/goal/set" && method !== "thread/goal/clear")
5732
6280
  return request(method, params);
5733
6281
  return withExecutionNativeAdmission(input.session_id, () => {
@@ -5763,6 +6311,9 @@ export async function pauseAgentGoalForStop(target) {
5763
6311
  return { status: "paused" };
5764
6312
  return { status: result.availability === "unsupported" || result.outcome === "unsupported" ? "unsupported" : result.outcome === "outcome_unknown" ? "outcome_unknown" : "unavailable", reason: result.reason };
5765
6313
  }
6314
+ function agentConfigureNotReady(name) {
6315
+ return new AitermError(`agent session '${name}' は入力待ちではありません。番またはgoalが継続する場合はgoalを停止または完了にしてから agent_configure してください。設定は変えていません。`, 2);
6316
+ }
5766
6317
  export async function configureAgent(name, opts) {
5767
6318
  let mayHaveChanged = false;
5768
6319
  const beforeChange = () => { mayHaveChanged = true; };
@@ -5782,18 +6333,65 @@ export async function configureAgent(name, opts) {
5782
6333
  }
5783
6334
  // 設定替えは席の入力欄へ命令を打つので、送信と同じ行列(ADR 0088)に並ぶ。替えている間に届いた文は、替え終えてから席へ入る(ADR 0120)。
5784
6335
  // 番が動いている席では、行列を持ったまま番の終わりを待たない(待つ間も、その席への差し込みを通す)。
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
- }
6336
+ const meta = loadAgentMetadata(name);
6337
+ const checkGeneration = () => {
6338
+ assertExecutionContext(name);
6339
+ if (tryLoadAgentMetadata(name)?.launch_id !== meta.launch_id || observeSessionGeneration(name).launch_id !== meta.launch_id)
6340
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
6341
+ };
6342
+ const configure = async () => {
6343
+ const deadline = performance.now() + AGENT_TUI_READY_TIMEOUT_MS;
6344
+ for (;;) {
6345
+ checkGeneration();
6346
+ const result = await withAgentSendLock(name, async () => {
6347
+ checkGeneration();
6348
+ const current = loadAgentMetadata(name), saved = readAgentResumeTemplate(current);
6349
+ if (readAgentLifecycle(current) || agentDormantState(current))
6350
+ throw new AitermError("AGENT_RESUME_REQUIRED: 設定を変える前に保存した会話席をagent_launchで再開してください。設定は変えていません。", 2);
6351
+ let invalidated = false;
6352
+ const result = await configureAgentInLock(name, model, effort, fast, () => {
6353
+ if (saved && !invalidated) {
6354
+ withExecutionPreparation(name, () => writeAgentResumeTemplate(current, { ...saved, state: "unconfirmed" }));
6355
+ invalidated = true;
6356
+ }
6357
+ beforeChange();
6358
+ });
6359
+ if (result && saved)
6360
+ withExecutionPreparation(name, () => finishAgentResumeConfiguration(loadAgentMetadata(name), saved, model, effort));
6361
+ return result;
6362
+ }, AGENT_CONFIGURE_UNCHANGED);
6363
+ if (result)
6364
+ return result;
6365
+ if (performance.now() >= deadline)
6366
+ throw agentConfigureNotReady(name);
6367
+ await sleep(AGENT_TUI_READY_POLL_MS);
6368
+ }
6369
+ };
6370
+ if (meta.kind !== "codex")
6371
+ return await configure();
6372
+ return await configureWithPausedGoal({
6373
+ goal: (action, expected) => {
6374
+ checkGeneration();
6375
+ return agentGoal({ session_id: name, launch_id: meta.launch_id, action,
6376
+ ...(meta.vendor_session_id ? { expected_thread_id: meta.vendor_session_id } : {}) }, "user", expected);
6377
+ },
6378
+ waitForTurnEnd: async () => {
6379
+ const deadline = performance.now() + 30 * 60_000;
6380
+ for (;;) {
6381
+ checkGeneration();
6382
+ if (codexTurnSettled(loadAgentMetadata(name)))
6383
+ return;
6384
+ if (performance.now() >= deadline)
6385
+ throw new AitermError("GOAL_CONFIGURE_TURN_END_UNCONFIRMED: 30分以内に現在の番の終了を確認できません。設定は変えていません。", 2);
6386
+ await sleep(AGENT_TUI_READY_POLL_MS);
6387
+ }
6388
+ },
6389
+ }, configure);
5794
6390
  }
5795
6391
  catch (error) {
5796
6392
  const failure = error instanceof Error ? error : new AitermError(String(error), 2);
6393
+ if (!mayHaveChanged && failure.message.includes("AGENT_SEND_BUSY") && !failure.message.includes("設定は変えていません。"))
6394
+ failure.message += " 設定は変えていません。";
5797
6395
  Object.assign(failure, { configurationFailure: { schema: "aiterm.agent-configure-error.v1", session_id: name,
5798
6396
  outcome: mayHaveChanged ? "outcome_unknown" : "not_applied", effect: mayHaveChanged ? "possible" : "not_started" } });
5799
6397
  throw failure;
@@ -5811,7 +6409,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
5811
6409
  if (codexRateLimitModelSwitch) {
5812
6410
  throw new AitermError(`CODEX_RATE_LIMIT_MODEL_SWITCH_RECOVERY_FAILED: ${codexPaneObservation(ready.lastScreen).reason}。設定変更は送信していません。`, 2);
5813
6411
  }
5814
- throw new AitermError(`agent session '${name}' は入力待ちではありません`, 2);
6412
+ throw agentConfigureNotReady(name);
5815
6413
  }
5816
6414
  const configured = () => ({
5817
6415
  schema: "aiterm.agent-configure-result.v1",
@@ -5878,7 +6476,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
5878
6476
  if (target === undefined) {
5879
6477
  throw new FastModeError("FAST_MODE_UNCONFIRMED", `この席のmodelが控えに無く(前の版のAitermが起こした席)、fastの対応を確かめられません。modelも渡してください。${untouched}`);
5880
6478
  }
5881
- const unavailable = await assertClaudeFastSupported(bin, meta.cwd ?? process.cwd(), target, untouched);
6479
+ const unavailable = await assertClaudeFastSupported(bin, meta.cwd ?? process.cwd(), target, untouched, { ...process.env, CLAUDE_CONFIG_DIR: meta.claude_home ?? claudeConfigDir() });
5882
6480
  if (unavailable)
5883
6481
  throw new FastModeError("FAST_MODE_UNAVAILABLE", `${unavailable.message.replace(/^FAST_MODE_UNAVAILABLE: /, "")}${untouched}`);
5884
6482
  }
@@ -6197,11 +6795,210 @@ async function assertCursorPromptNotHookBlocked(name) {
6197
6795
  await sleep(100);
6198
6796
  } while (performance.now() < deadline || (performance.now() < hookDeadline && cursorPromptHooksRunning(screen)));
6199
6797
  }
6798
+ /** Caller holds the ordinary send admission for the entire resume and submission. */
6799
+ function verifyAgentResumeNative(meta, native, expectedLaunch = meta.launch_id, allowExitedPane = false) {
6800
+ const unavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰したnative世代が置き換わっています。", 2);
6801
+ if (loadAgentMetadata(meta.aiterm_session).launch_id !== expectedLaunch
6802
+ || !isDeepStrictEqual(readAgentResumeNative(meta), native))
6803
+ throw unavailable();
6804
+ verifyCreatedNative(native, allowExitedPane);
6805
+ }
6806
+ function verifyCreatedNative(native, allowExitedPane = false) {
6807
+ const unavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 作成したnative端末が置き換わっています。", 2);
6808
+ const sessions = observeExecutionNativeSessions();
6809
+ if (sessions.state !== "known" || !sessions.sessions.some(row => row.session_id === native.session_id && row.native_id === native.native_id))
6810
+ throw unavailable();
6811
+ 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}");
6812
+ const fields = pane.stdout.trim().split("\t");
6813
+ const exited = allowExitedPane && fields[5] === "1";
6814
+ const [serverStarted, paneStarted] = processStartIdentities(exited ? [native.server_pid] : [native.server_pid, native.pane_pid], process.platform);
6815
+ // macOS tmux clears pane_pid after exit; only the explicit dead-pane close admits that absence.
6816
+ 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")
6817
+ || (fields[4] !== String(native.pane_pid) && !(exited && fields[4] === ""))
6818
+ || !["0", "1"].includes(fields[5]) || serverStarted !== native.server_started_identity
6819
+ || (!exited && paneStarted !== native.pane_started_identity))
6820
+ throw unavailable();
6821
+ }
6822
+ function withAgentResumeTarget(meta, body, allowExitedPane = false) {
6823
+ if (hasVerifiedNativeSessionTarget(meta.aiterm_session))
6824
+ return body();
6825
+ let native;
6826
+ try {
6827
+ native = readAgentResumeNative(meta);
6828
+ }
6829
+ catch {
6830
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰したnative本人性の記録を確認できません。", 2);
6831
+ }
6832
+ if (!native) {
6833
+ if (meta.resumed_from)
6834
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰したnative本人性の記録がありません。", 2);
6835
+ return body();
6836
+ }
6837
+ return withNativeSessionTarget(native, () => verifyAgentResumeNative(meta, native, meta.launch_id, allowExitedPane), body, allowExitedPane);
6838
+ }
6839
+ function confirmedAgentResumeRecipe(meta, lifecycle) {
6840
+ const unavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 保存した休止会話の再開情報を確認できません。", 2);
6841
+ const recipe = readAgentResumeRecipe(meta);
6842
+ if (lifecycle.socket !== SOCK || !recipe || recipe.launch_id !== meta.launch_id || recipe.kind !== meta.kind
6843
+ || recipe.vendor_session_id !== meta.vendor_session_id || lifecycle.recipe_digest !== agentResumeRecipeDigest(recipe)
6844
+ || recipe.model !== meta.model || recipe.fast !== meta.fast || recipe.cwd !== meta.cwd || recipe.executable !== meta.agent_executable
6845
+ || recipe.configuration_root !== (meta.kind === "codex" ? meta.codex_home : meta.claude_home ?? claudeConfigDir())
6846
+ || !recipe.model || !recipe.reasoning_effort || !isUsableAgentExecutableFile(recipe.executable)
6847
+ || !fs.statSync(recipe.cwd).isDirectory())
6848
+ throw unavailable();
6849
+ if (meta.kind === "claude" && !Object.hasOwn(recipe.environment, "CLAUDE_CONFIG_DIR"))
6850
+ throw unavailable();
6851
+ if (meta.kind === "codex" && (!lifecycle.resume_proof_digest
6852
+ || codexResumeProofDigest(readCodexResumeProof(meta)) !== lifecycle.resume_proof_digest))
6853
+ throw unavailable();
6854
+ return recipe;
6855
+ }
6856
+ async function resumeAgentInLock(name, readyTimeout = AGENT_TUI_READY_TIMEOUT_MS) {
6857
+ const previous = loadAgentMetadata(name), lifecycle = readAgentLifecycle(previous);
6858
+ const uncertain = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 前の復帰処理を確認できません。本文は送信していません。再送せず席の状態を確認してください。", 2);
6859
+ const ownAttempt = readAgentResumeAttempt(previous);
6860
+ if (!lifecycle) {
6861
+ if (previous.resumed_from) {
6862
+ const attempt = readAgentResumeAttempt({ aiterm_session: name, launch_id: previous.resumed_from });
6863
+ if (attempt?.state !== "ready" || attempt.next_launch_id !== previous.launch_id)
6864
+ throw uncertain();
6865
+ }
6866
+ if (ownAttempt)
6867
+ throw uncertain();
6868
+ return previous;
6869
+ }
6870
+ if (lifecycle.state !== "hibernated" || ownAttempt)
6871
+ throw uncertain();
6872
+ assertExecutionResumeSupported();
6873
+ const recipe = confirmedAgentResumeRecipe(previous, lifecycle);
6874
+ if (sessionExists(name))
6875
+ throw uncertain();
6876
+ const controlEnv = { ...process.env };
6877
+ for (const [key, value] of Object.entries(recipe.environment)) {
6878
+ if (value === null)
6879
+ delete controlEnv[key];
6880
+ else
6881
+ controlEnv[key] = value;
6882
+ }
6883
+ if (recipe.kind === "codex")
6884
+ controlEnv.CODEX_HOME = recipe.configuration_root;
6885
+ if (recipe.fast) {
6886
+ if (recipe.kind === "claude") {
6887
+ if (await assertClaudeFastSupported(recipe.executable, recipe.cwd, recipe.model, "本文は送信していません。", controlEnv))
6888
+ throw uncertain();
6889
+ }
6890
+ else
6891
+ await assertCodexFastSupported(recipe.executable, recipe.configuration_root, recipe.model, "本文は送信していません。", controlEnv);
6892
+ }
6893
+ const lineage = { agentRole: "subagent", parentSessionId: previous.parent_session_id,
6894
+ delegationDepth: previous.delegation_depth, lineage: previous.lineage, delegationAllowed: true };
6895
+ let next = null, attempt = null;
6896
+ let native = null, published = false;
6897
+ return withNativeSessionCreation(name, receipt => {
6898
+ const [server, pane] = processStartIdentities([receipt.server_pid, receipt.pane_pid], process.platform);
6899
+ if (!next || !server || !pane)
6900
+ throw uncertain();
6901
+ native = { schema: "aiterm.agent-resume-native.v1", launch_id: next.launch_id, ...receipt,
6902
+ server_started_identity: server, pane_started_identity: pane };
6903
+ writeAgentResumeNative(next, native);
6904
+ }, () => {
6905
+ if (!next || !native)
6906
+ throw uncertain();
6907
+ verifyAgentResumeNative(next, native, published ? next.launch_id : previous.launch_id);
6908
+ }, async () => {
6909
+ try {
6910
+ await withExecutionNativeAdmission(name, () => {
6911
+ if (!isDeepStrictEqual(loadAgentMetadata(name), previous) || sessionExists(name))
6912
+ throw uncertain();
6913
+ if (readAgentLifecycle(previous)?.state !== "hibernated"
6914
+ || agentResumeRecipeDigest(readAgentResumeRecipe(previous)) !== lifecycle.recipe_digest)
6915
+ throw uncertain();
6916
+ if (previous.kind === "codex" && codexResumeProofDigest(readCodexResumeProof(previous)) !== lifecycle.resume_proof_digest)
6917
+ throw uncertain();
6918
+ publishAgentGeneration(previous);
6919
+ next = previous.kind === "claude"
6920
+ ? createClaudeAgentMetadata(name, recipe.cwd, "none", null, null, lineage, recipe.model, recipe.reasoning_effort)
6921
+ : createCodexAgentMetadata(name, recipe.cwd, "none", { model: recipe.model, effort: recipe.reasoning_effort }, previous.write_scope, lineage);
6922
+ next.vendor_session_id = previous.vendor_session_id;
6923
+ next.resumed_from = previous.launch_id;
6924
+ next.launch_operation_id = previous.launch_operation_id;
6925
+ next.launch_request_digest = previous.launch_request_digest;
6926
+ next.model = recipe.model;
6927
+ next.fast = false;
6928
+ next.agent_executable = recipe.executable;
6929
+ if (isWin)
6930
+ next.windows_launch_exit_tracked = true;
6931
+ if (next.kind === "claude")
6932
+ next.claude_home = recipe.configuration_root;
6933
+ else
6934
+ next.codex_home = recipe.configuration_root;
6935
+ if (previous.write_scope !== undefined)
6936
+ next.write_scope = previous.write_scope;
6937
+ writeAgentMetadata(next);
6938
+ initializeAgentActivity(next);
6939
+ writeAgentResumeRecipe(next, { ...recipe, launch_id: next.launch_id });
6940
+ attempt = { schema: "aiterm.agent-resume-attempt.v1", launch_id: previous.launch_id, next_launch_id: next.launch_id,
6941
+ state: "resuming", at: new Date().toISOString(), recipe_digest: lifecycle.recipe_digest };
6942
+ writeAgentResumeAttempt(previous, attempt);
6943
+ const shell = isWin ? "pwsh" : "bash";
6944
+ openSessionInternal(name, shell, [], true);
6945
+ const environment = [...Object.entries(recipe.environment),
6946
+ ...(next.kind === "codex" ? [["CODEX_HOME", recipe.configuration_root]] : []), ...agentEnvEntries(next, name)];
6947
+ for (const [key, value] of environment) {
6948
+ const stored = value === null ? tmux("set-environment", isWin ? "-u" : "-r", "-t", name, key) : tmux("set-environment", "-t", name, key, value);
6949
+ if (stored.code !== 0)
6950
+ throw uncertain();
6951
+ }
6952
+ if (registerSessionEnvironment(true, name, [...(registeredSessionEnvironment(name) ?? []), ...Object.keys(recipe.environment)]).code !== 0)
6953
+ throw uncertain();
6954
+ const argv = next.kind === "claude" ? claudeResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next)
6955
+ : codexResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next, recipe.cwd);
6956
+ const full = isWin ? windowsAgentLaunchLine(recipe.cwd, environment, windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), { file: agentMetadataPath(name, next.launch_id) + ".launch-exited", launch_id: next.launch_id })
6957
+ : `cd ${shq(recipe.cwd)} && /usr/bin/env ${environment.filter(([, value]) => value === null).map(([key]) => `-u ${shq(key)}`).join(" ")} `
6958
+ + `${environment.filter(([, value]) => value !== null).map(([key, value]) => shq(`${key}=${value}`)).join(" ")} ${argv.map(shq).join(" ")}`;
6959
+ agentLaunchLines.set(name, atomicShellMultiline(full, shell));
6960
+ send(name, full, { enter: true, mark: false, force: true, rtk: false, raw: true, launchShell: shell, preserveAgentOperation: true });
6961
+ publishAgentGeneration(previous, next);
6962
+ published = true;
6963
+ });
6964
+ const resumed = next;
6965
+ const ready = await prepareAgentInput(name, resumed, { ready_timeout: readyTimeout });
6966
+ if (ready.status !== "ready")
6967
+ throw uncertain();
6968
+ // Launch argv pins standard speed; restore fast only after the native composer is ready.
6969
+ if (recipe.fast) {
6970
+ const failed = await applyLaunchFast(name, resumed);
6971
+ if (failed || resumed.fast !== true)
6972
+ throw uncertain();
6973
+ }
6974
+ if (loadAgentMetadata(name).launch_id !== resumed.launch_id)
6975
+ throw uncertain();
6976
+ writeAgentResumeTemplate(resumed, { schema: "aiterm.agent-resume-template.v1", launch_id: resumed.launch_id, state: "confirmed",
6977
+ kind: recipe.kind, executable: recipe.executable, cwd: recipe.cwd, configuration_root: recipe.configuration_root,
6978
+ model: recipe.model, reasoning_effort: recipe.reasoning_effort, environment: recipe.environment });
6979
+ writeAgentResumeRecipe(resumed, { ...recipe, launch_id: resumed.launch_id });
6980
+ writeAgentResumeAttempt(previous, { ...attempt, state: "ready", at: new Date().toISOString() });
6981
+ return resumed;
6982
+ }
6983
+ catch (error) {
6984
+ const issued = attempt;
6985
+ if (issued)
6986
+ try {
6987
+ writeAgentResumeAttempt(previous, { ...issued, state: "failed", at: new Date().toISOString() });
6988
+ }
6989
+ catch { /* resuming also blocks replay */ }
6990
+ throw new AitermError(`AGENT_RESUME_FAILED: 同じ会話への復帰を確認できません。本文は送信していません。再送せず席の状態を確認してください。${error instanceof ExecutionError ? ` ${error.code}` : ""}`, 2);
6991
+ }
6992
+ });
6993
+ }
6200
6994
  export async function dispatchAgentTurn(name, text, o = {}) {
6201
6995
  assertExecutionContext(name);
6202
6996
  assertSessionName(name);
6203
6997
  loadAgentMetadata(name);
6204
- return withAgentSendLock(name, () => dispatchAgentTurnInLock(name, text, o));
6998
+ return withAgentSendLock(name, async () => {
6999
+ const meta = await resumeAgentInLock(name, o.ready_timeout);
7000
+ return withAgentResumeTarget(meta, () => dispatchAgentTurnInLock(name, text, o));
7001
+ });
6205
7002
  }
6206
7003
  async function dispatchAgentTurnInLock(name, text, o, pendingSend) {
6207
7004
  const meta = loadAgentMetadata(name);
@@ -6293,6 +7090,7 @@ async function dispatchAgentTurnInLock(name, text, o, pendingSend) {
6293
7090
  await o.before_send?.({ session_id: name, launch_id: meta.launch_id, vendor: meta.kind,
6294
7091
  harness: agentHarness(meta.kind), event_cursor: startOffset, operation_id: operationId });
6295
7092
  await submitAgentComposerText(name, meta.kind, dispatchText, {
7093
+ inputMeta: meta,
6296
7094
  force: o.force, raw: o.raw, typedPreface: prefaced.typedPreface, preserveAgentOperation: meta.kind === "claude",
6297
7095
  admission: "native", subject: "送信prompt",
6298
7096
  ...(pendingSend ? { checkInput: (started) => assertAgentSendHarness(name, meta, started) } : {}),
@@ -6437,7 +7235,10 @@ export async function sendAgentMessage(name, text, o = {}) {
6437
7235
  // 前置きは、順番待ちにも入力受付の待ちにも入る前に確かめる(外れた時に待たせない)。
6438
7236
  if (o.preface != null)
6439
7237
  assertAgentPreface(o.preface);
6440
- return withAgentSendLock(name, () => sendAgentMessageInLock(name, text, o));
7238
+ return withAgentSendLock(name, async () => {
7239
+ const meta = await resumeAgentInLock(name);
7240
+ return withAgentResumeTarget(meta, () => sendAgentMessageInLock(name, text, o));
7241
+ });
6441
7242
  }
6442
7243
  async function sendAgentMessageInLock(name, text, o) {
6443
7244
  const meta = loadAgentMetadata(name);
@@ -6527,6 +7328,7 @@ async function steerRunningTurn(name, meta, text, o) {
6527
7328
  await submitAgentComposerText(name, meta.kind, text, {
6528
7329
  force: true, raw: o.raw, typedPreface: prefaced.typedPreface, preserveAgentOperation: meta.kind === "claude",
6529
7330
  admission: "native", subject: "差し込む文",
7331
+ inputMeta: meta,
6530
7332
  checkInput: started => assertAgentSendHarness(name, meta, started),
6531
7333
  });
6532
7334
  // GrokとCursorは実行中の送信を待ち行列へ入れる。そのままだと現在turnの完了後に別turnとして動き、
@@ -6809,6 +7611,7 @@ export function openAgent(kind, opts = {}) {
6809
7611
  * Public synchronous openAgent retains its existing immediate refusal contract.
6810
7612
  */
6811
7613
  function prepareAgentLaunch(kind, opts = {}) {
7614
+ assertNoDormantSession(opts.session_name);
6812
7615
  const label = agentLabel(kind);
6813
7616
  // 前提検証は session を作る前に全部済ませる(失敗の残骸 session を作らない)。
6814
7617
  // model/effort → bin → cwd の順: model/effort 検証は CLI 不在の端末でも同じ結果になる(テスト可能性)。
@@ -6946,121 +7749,184 @@ function prepareAgentLaunch(kind, opts = {}) {
6946
7749
  assertCursorModelAvailable(bin, cwd ?? process.cwd(), model, effort, cursorFast);
6947
7750
  }
6948
7751
  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);
7752
+ let initialNative = null;
7753
+ let initialLaunch = null, initialProof = null;
7754
+ let initialAdmission = null;
7755
+ const create = () => {
7756
+ let sid;
7757
+ let hint;
7758
+ // Windows launches use native PowerShell input; never type an owned CLI
7759
+ // command through MSYS interactive select/console-master input handling.
7760
+ const paneShell = isWin ? "pwsh" : "bash";
7761
+ try {
7762
+ [sid, hint] = openSession(opts.session_name ?? null, paneShell, envVars);
6961
7763
  }
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);
7764
+ catch (error) {
7765
+ if (launchOperationId !== null && sessionExists(opts.session_name)) {
7766
+ requireMatchingClaudeLaunch(opts.session_name, launchOperationId, launchRequestDigest);
7767
+ return existingAgentLaunchResult("claude", opts.session_name, model, effort);
6998
7768
  }
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;
7769
+ throw error;
7026
7770
  }
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 は空のまま残る=残骸を作らない。片付けてから元エラーを伝える。
7771
+ let launchNote = "";
7043
7772
  try {
7044
- closeSessionInternal(sid, false);
7773
+ const lineageContext = createAgentLineageContext(kind, sid, lineageSeed);
7774
+ if (hasExecutionCreationScope())
7775
+ beforeExecutionEffect(sid);
7776
+ const meta = withExecutionPreparation(sid, () => {
7777
+ const meta = agentDone
7778
+ ? kind === "claude"
7779
+ ? createClaudeAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", launchOperationId, launchRequestDigest, lineageContext, model, effort)
7780
+ : kind === "codex"
7781
+ ? createCodexAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", { model, effort }, writeScope, lineageContext)
7782
+ : kind === "antigravity"
7783
+ ? createAntigravityAgentMetadata(sid, cwd ?? process.cwd(), opts.prompt ? "pending" : "none", writeScope, lineageContext)
7784
+ : kind === "cursor"
7785
+ ? createCursorAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", writeScope, lineageContext)
7786
+ : createGrokAgentMetadata(kind, sid, cwd, opts.prompt ? "pending" : "none", grokAuthPath, writeScope, lineageContext)
7787
+ : null;
7788
+ if (meta) {
7789
+ // Metadata constructors publish their internally generated launch ID.
7790
+ // Stamp its exact native creator before binding and any later input.
7791
+ if (hasExecutionCreationScope())
7792
+ meta.execution_native = executionCreatedNativeBinding(sid);
7793
+ meta.agent_executable = bin;
7794
+ if (isWin && ["claude", "codex", "grok", "antigravity"].includes(kind))
7795
+ meta.windows_launch_exit_tracked = true;
7796
+ if (kind === "claude" || kind === "codex")
7797
+ meta.cwd = kind === "claude" ? fs.realpathSync(cwd ?? process.cwd()) : path.resolve(cwd ?? process.cwd());
7798
+ // 席は通常の速度で始まる(Claude Code・Codexは起動の引数で明示する)。fast版のmodel IDで起こした時だけtrue。
7799
+ meta.fast = opts.fast_state === true;
7800
+ meta.model = opts.base_model !== undefined ? opts.base_model : model;
7801
+ initializeAgentActivity(meta);
7802
+ // The new physical shell is already pinned by its actual create receipt.
7803
+ // Validate it before publishing metadata, then bind this internally
7804
+ // generated managed launch. Model arguments cannot select this ID.
7805
+ writeAgentMetadata(meta);
7806
+ if (initialNative) {
7807
+ const proof = { schema: "aiterm.agent-resume-native.v1", launch_id: meta.launch_id, ...initialNative };
7808
+ writeAgentResumeNative(meta, proof);
7809
+ initialLaunch = meta;
7810
+ initialProof = proof;
7811
+ }
7812
+ try {
7813
+ captureAgentResumeTemplate(meta, effort, envVars, kind === "claude" ? meta.claude_home : meta.codex_home);
7814
+ }
7815
+ catch {
7816
+ process.stderr.write("aiterm: resume_template_unconfirmed\n");
7817
+ }
7818
+ agentMetadataNegativeCache.delete(sid);
7819
+ }
7820
+ return meta;
7821
+ });
7822
+ if (meta && hasExecutionCreationScope())
7823
+ bindExecutionCreatedLaunch({ session_id: sid, launch_id: meta.launch_id });
7824
+ launchNote = buildAgentLaunchNote(kind, model, effort, meta);
7825
+ let full;
7826
+ if (paneShell === "pwsh") {
7827
+ const prompt = opts.prompt ?? null;
7828
+ const argv = kind === "claude" ? claudeAgentArgv(bin, model, effort, prompt, meta)
7829
+ : kind === "codex" ? codexAgentArgv(bin, model, effort, prompt, meta)
7830
+ : kind === "cursor" ? cursorAgentArgv(bin, model, effort, prompt, meta, cursorFast)
7831
+ : kind === "antigravity" ? antigravityAgentArgv(bin, model, effort, prompt)
7832
+ : grokAgentArgv(kind, bin, model, effort, prompt, meta);
7833
+ full = windowsAgentLaunchLine(cwd, [
7834
+ ...(meta?.kind === "grok" ? grokEnvEntries(meta) : []), ...agentEnvEntries(meta, sid, envVars),
7835
+ ], windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), meta?.windows_launch_exit_tracked ? { file: agentMetadataPath(sid, meta.launch_id) + ".launch-exited", launch_id: meta.launch_id } : undefined);
7836
+ }
7837
+ else {
7838
+ const cmd = buildAgentCmd(kind, binForCmd, model, effort, opts.prompt ?? null, meta, cursorFast);
7839
+ const envPrefix = agentEnvPrefix(meta, sid, envVars);
7840
+ const command = cwdForCmd ? `cd ${shq(cwdForCmd)} && ${envPrefix}${cmd}` : `${envPrefix}${cmd}`;
7841
+ // このpaneのbashはAitermが自分で選んだ。sub-agent instructionのLFを含む起動commandは、
7842
+ // 利用者のshell送信と同じknown-shell適合で1物理行にしてから打つ(sanitizeはしない)。
7843
+ // 対話shellの行編集が、埋め込みLFごとに1行ずつ受け付けて継続promptで繋ぐ形に依存しない。
7844
+ // agent TUIへの本文(bracketedPaste)は文字どおりのまま。argv・lineage・metadata・native
7845
+ // admission・receiptの契約は変えない。
7846
+ full = command;
7847
+ }
7848
+ if (meta)
7849
+ agentLaunchLines.set(sid, atomicShellMultiline(full, paneShell));
7850
+ // force:true はagent sessionへの手動介入を表す。起動コマンド自体はAitermが組み立てて、sanitizeせずに送る。
7851
+ send(sid, full, {
7852
+ enter: true,
7853
+ mark: false,
7854
+ force: true,
7855
+ rtk: false,
7856
+ raw: true,
7857
+ launchShell: paneShell,
7858
+ preserveAgentOperation: meta?.kind === "claude",
7859
+ ...(meta && opts.prompt ? { beforePtyWrite: () => recordAgentInput(meta) } : {}),
7860
+ });
7045
7861
  }
7046
- catch {
7047
- /* 片付け失敗より元エラーの伝達を優先 */
7862
+ catch (e) {
7863
+ const failure = e instanceof ExecutionError ? e : telemetryOwnedFailure("AITERM.VENDOR_LAUNCHER_FAILED", e);
7864
+ // 起動コマンドを投入できなかった session は空のまま残る=残骸を作らない。片付けてから元エラーを伝える。
7865
+ try {
7866
+ closeSessionInternal(sid, false);
7867
+ }
7868
+ catch {
7869
+ /* 片付け失敗より元エラーの伝達を優先 */
7870
+ }
7871
+ throw failure;
7872
+ }
7873
+ const launched = tryLoadAgentMetadata(sid);
7874
+ if (launched)
7875
+ requestAgentIdleClock(sid, launched.launch_id);
7876
+ const driveHint = agentDone
7877
+ ? `TUI の描画には数秒かかる。少し置いてから pty_read(${sid}, screen:true) で画面を読み、` +
7878
+ `turnはpty_send(${sid}, "...")で送る(自動で非ブロックdispatch。${autoDeliveryParent() ? `回答本文は${autoDeliveryParent()}親へ自動配送する` : "完了通知はaiterm-wait"})。中断はpty_key(${sid}, "C-c")、` +
7879
+ `Stopが来ない場合の解除はpty_close(${sid})を使う。`
7880
+ : `TUI の描画には数秒かかる。少し置いてから pty_read(${sid}, screen:true) で画面を読み、` +
7881
+ `pty_send(${sid}, "...") で入力・pty_key(${sid}, "Enter"/"Up"/"C-c" 等) で操作する(対話)。`;
7882
+ return [
7883
+ sid,
7884
+ `${label} を session ${sid} で起動した。${launchNote}${agentDone ? "agent_done 待機が有効。" : ""}` +
7885
+ `${agentDone ? " 通常のproject/user環境を共有し、aiterm所有の完了相関とsub-agent lineageだけを加算。" : ""}\n${hint}\n` +
7886
+ driveHint +
7887
+ `起動直後に増分 pty_read すると空/半描画になり得るので screen:true を使う。`,
7888
+ ];
7889
+ };
7890
+ if (hasExecutionCreationScope() || !agentDone || !["claude", "codex"].includes(kind))
7891
+ return create();
7892
+ try {
7893
+ return withNativeSessionCreation(opts.session_name ?? null, receipt => {
7894
+ const [server, pane] = processStartIdentities([receipt.server_pid, receipt.pane_pid], process.platform);
7895
+ if (!server || !pane)
7896
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 作成したnative本人性を取得できません。", 2);
7897
+ initialNative = { ...receipt, server_started_identity: server, pane_started_identity: pane };
7898
+ try {
7899
+ const token = tryCreateOwnedLock(agentSendLockPath(receipt.session_id));
7900
+ if (!token)
7901
+ throw agentSendBusyError(receipt.session_id, null, 0);
7902
+ initialAdmission = { name: receipt.session_id, token };
7903
+ agentSendHeld.add(receipt.session_id);
7904
+ // The old launch may have entered hibernation after the public precheck.
7905
+ assertNoDormantSession(receipt.session_id);
7906
+ }
7907
+ catch (error) {
7908
+ try {
7909
+ tmux("kill-session", "-t", receipt.session_id);
7910
+ }
7911
+ catch { /* Preserve old launch state and the original error. */ }
7912
+ throw error;
7913
+ }
7914
+ }, () => {
7915
+ if (!initialNative)
7916
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: native作成結果を確認できません。", 2);
7917
+ if (initialLaunch && initialProof)
7918
+ verifyAgentResumeNative(initialLaunch, initialProof);
7919
+ else
7920
+ verifyCreatedNative(initialNative);
7921
+ }, create);
7922
+ }
7923
+ finally {
7924
+ if (initialAdmission) {
7925
+ const { name, token } = initialAdmission;
7926
+ agentSendHeld.delete(name);
7927
+ releaseOwnedLock(agentSendLockPath(name), token);
7048
7928
  }
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
- ];
7929
+ }
7064
7930
  };
7065
7931
  }
7066
7932
  export class AgentLaunchPromptError extends AitermError {
@@ -7105,6 +7971,49 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
7105
7971
  if (opts.launch_operation_id != null && prompt !== null) {
7106
7972
  throw new AitermError("launch_operation_idはpromptなしのClaude相関launchだけで指定できます", 2);
7107
7973
  }
7974
+ if (opts.session_name) {
7975
+ assertSessionName(opts.session_name);
7976
+ const name = opts.session_name, saved = tryLoadAgentMetadata(name);
7977
+ if (saved && (readAgentLifecycle(saved) || agentDormantState(saved))) {
7978
+ return withAgentSendLock(name, async () => {
7979
+ const previous = loadAgentMetadata(name), lifecycle = readAgentLifecycle(previous);
7980
+ if (!isDeepStrictEqual(previous, saved) || lifecycle?.state !== "hibernated" || readAgentResumeAttempt(previous))
7981
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 保存した会話席の再開世代を確認できません。", 2);
7982
+ const recipe = confirmedAgentResumeRecipe(previous, lifecycle);
7983
+ if (kind !== previous.kind || sourceSessionId !== null
7984
+ || (opts.model != null && opts.model.trim() !== recipe.model)
7985
+ || (opts.reasoning_effort != null && opts.reasoning_effort.trim() !== recipe.reasoning_effort)
7986
+ || (opts.fast != null && opts.fast !== recipe.fast)
7987
+ || (opts.cwd != null && path.resolve(opts.cwd) !== recipe.cwd)
7988
+ || (opts.write_scope !== undefined && opts.write_scope !== previous.write_scope)
7989
+ || (opts.env_vars !== undefined && !isDeepStrictEqual([...new Set(opts.env_vars)].sort(), Object.keys(recipe.environment).sort())))
7990
+ throw new AitermError("AGENT_RESUME_CONFLICT: 同名の休止席は保存したharness・設定・project・明示envで再開します。変更は再開後に行ってください。", 2);
7991
+ if (opts.launch_operation_id != null)
7992
+ requireMatchingClaudeLaunch(name, validateOperationId(opts.launch_operation_id), claudeLaunchRequestDigest({ sessionName: name, model: opts.model ?? null, effort: opts.reasoning_effort ?? null,
7993
+ cwd: opts.cwd ?? null, agentDone: true }));
7994
+ const resumed = await resumeAgentInLock(name, opts.ready_timeout ?? undefined);
7995
+ return withAgentResumeTarget(resumed, async () => {
7996
+ const hint = `${agentLabel(kind)} を保存した同じ会話へ再開した。\n${attachHint(name)}`;
7997
+ const fastState = { fast: resumed.fast === true, fast_error: null };
7998
+ if (!prompt)
7999
+ return [name, hint, null, null,
8000
+ { status: "not_requested", reason: "not_requested", turn_started: false },
8001
+ { status: "ready", reason: "composer_ready" }, fastState];
8002
+ try {
8003
+ const initial = await sendInitialAgentPromptInLock(name, prompt, {
8004
+ ready_timeout: opts.ready_timeout ?? undefined, before_send: opts.before_send,
8005
+ });
8006
+ return [name, `${hint}\n${initial.text}`, initial.event_cursor, initial.submit_residue, initial.initial_prompt,
8007
+ { status: "ready", reason: "composer_ready" }, fastState];
8008
+ }
8009
+ catch (error) {
8010
+ const current = loadAgentMetadata(name);
8011
+ 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" });
8012
+ }
8013
+ });
8014
+ });
8015
+ }
8016
+ }
7108
8017
  // ファスト(ADR 0114)。設定の誤りは席を作る前に断る。fastへ出来ない訳がアカウントの都合なら、通常で起こして返りへ訳を入れる。
7109
8018
  const requestedModel = opts.model == null ? null : opts.model.trim() || null;
7110
8019
  const fastPlan = await planLaunchFast(kind, {