devez-vibe 1.10.21 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +73 -73
  3. package/bin/dvz.exe +0 -0
  4. package/bin/dvz.js +35 -35
  5. package/bridge/claude-agent-sdk-bridge.mjs +364 -35
  6. package/install-skills.mjs +11 -11
  7. package/package.json +50 -50
  8. package/prepare-search-deps.mjs +42 -42
  9. package/skills/insane-search/SKILL.md +36 -36
  10. package/skills/insane-search/engine/__main__.py +44 -44
  11. package/skills/insane-search/engine/executor.py +246 -246
  12. package/skills/insane-search/engine/fetch_chain.py +443 -443
  13. package/skills/insane-search/engine/network.py +108 -108
  14. package/skills/insane-search/engine/phase0.py +380 -380
  15. package/skills/insane-search/engine/session_input.py +120 -120
  16. package/skills/insane-search/engine/templates/invisible_playwright_fetch.py +57 -57
  17. package/skills/insane-search/engine/templates/nodriver_fetch.py +9 -9
  18. package/skills/insane-search/engine/templates/patchright_fetch.py +9 -9
  19. package/skills/insane-search/engine/templates/playwright_mobile_chrome.js +9 -9
  20. package/skills/insane-search/engine/templates/playwright_real_chrome.js +7 -7
  21. package/skills/insane-search/engine/templates/scrapling_fetch.py +46 -46
  22. package/skills/insane-search/engine/tests/test_smoke.py +8 -8
  23. package/skills/insane-search/engine/tests/test_t10_artifact_routes.py +126 -126
  24. package/skills/insane-search/engine/tests/test_t11_session_handoff.py +157 -157
  25. package/skills/insane-search/engine/tests/test_t5_pdfplumber.py +11 -11
  26. package/skills/insane-search/engine/tests/test_t7_browser_gate.py +3 -3
  27. package/skills/insane-search/engine/tests/test_t8_network_routes.py +207 -207
  28. package/skills/insane-search/engine/tests/test_t9_evidence_bundle.py +89 -89
  29. package/skills/insane-search/engine/tests/test_u5.py +9 -9
  30. package/skills/insane-search/engine/transport.py +94 -94
  31. package/skills/insane-search/engine/waf_profiles.yaml +38 -38
  32. package/skills/insane-search/references/cache-archive.md +13 -13
  33. package/skills/insane-search/references/media.md +14 -14
  34. package/skills/insane-search/references/playwright.md +27 -27
  35. package/skills/insane-search/references/research-evidence.md +36 -36
  36. package/skills/insane-search/references/session-handoff.md +26 -26
  37. package/skills/insane-search/tests/test_x_search.py +3 -3
  38. package/skills/luna-loop/agents/openai.yaml +7 -7
@@ -116,8 +116,12 @@ function hostRequest(method, params, signal, sessionId) {
116
116
  };
117
117
  if (signal?.aborted) return abort();
118
118
  signal?.addEventListener("abort", abort, { once: true });
119
+ const session = sessionId ? lookupSession(sessionId) : null;
120
+ // The host routes a card to the pane showing this conversation, not
121
+ // whichever one is in front.
122
+ if (session) params = { ...params, threadId: session.id };
119
123
  pendingHostRequests.set(id, {
120
- session: sessionId ? lookupSession(sessionId) : null,
124
+ session,
121
125
  resolve: (value) => {
122
126
  signal?.removeEventListener("abort", abort);
123
127
  resolve(value);
@@ -223,13 +227,14 @@ function applyClaudeExecutable(options, params) {
223
227
 
224
228
  // The SDK model list carries no window size, so the status line would stay
225
229
  // blank until a turn reports one — and a fresh session has no turn yet. Claude
226
- // defaults here stay unchanged; Haiku 5.5 has a native 1M window.
230
+ // defaults here stay unchanged. Fable 5.1 and the 5.5 models have a native 1M
231
+ // window, so Claude Code 2.1.311 lists them without the `[1m]` suffix.
227
232
  function claudeContextWindow(...names) {
228
233
  if (["1", "true"].includes(String(process.env.CLAUDE_CODE_DISABLE_1M_CONTEXT || "").toLowerCase())) {
229
234
  return 200_000;
230
235
  }
231
236
  const oneMillion = names.some((name) => String(name || "").includes("[1m]")
232
- || /claude-haiku-5-5(?:$|[-\[])/i.test(String(name || "")));
237
+ || /claude-(?:(?:haiku|sonnet|opus)-5-5|fable-5-1)(?:$|[-\[])/i.test(String(name || "")));
233
238
  return oneMillion ? 1_000_000 : 200_000;
234
239
  }
235
240
 
@@ -784,7 +789,7 @@ function subdirectories(dir) {
784
789
  // live at plugins/cache/<marketplace>/<plugin>/<version>, which is also where
785
790
  // the `<plugin>@<marketplace>` id the setting expects comes from.
786
791
  function styleShippingPlugins() {
787
- const root = join(homedir(), ".claude", "plugins", "cache");
792
+ const root = join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "plugins", "cache");
788
793
  const disabled = {};
789
794
  for (const marketplace of subdirectories(root)) {
790
795
  const marketplaceDir = join(root, marketplace);
@@ -798,7 +803,9 @@ function styleShippingPlugins() {
798
803
  return disabled;
799
804
  }
800
805
 
801
- function makeOptions(params, sessionId, resume) {
806
+ // `currentId` follows the live conversation id: /clear moves the same query to a
807
+ // new id with no alias back, so callbacks holding the start id lost the session.
808
+ function makeOptions(params, sessionId, resume, currentId = () => sessionId) {
802
809
  const options = {
803
810
  cwd: params.cwd || process.cwd(),
804
811
  includePartialMessages: true,
@@ -845,14 +852,14 @@ function makeOptions(params, sessionId, resume) {
845
852
  if (resume) options.resume = resume;
846
853
  else options.sessionId = sessionId;
847
854
  options.canUseTool = (toolName, input, permission) =>
848
- requestToolPermission(toolName, input, permission, sessionId);
855
+ requestToolPermission(toolName, input, permission, currentId());
849
856
  // Hooks run whatever the permission mode, so a read-only role turn holds even
850
857
  // under bypass. The policy itself arrives with each prompt.
851
858
  options.hooks = {
852
- PreToolUse: [{ hooks: [(input) => toolPolicyHook(sessionId, input)] }],
859
+ PreToolUse: [{ hooks: [(input) => toolPolicyHook(currentId(), input)] }],
853
860
  };
854
861
  if (process.platform === "win32" && z) {
855
- options.mcpServers = { [COMPUTER_SERVER]: computerServer(sessionId) };
862
+ options.mcpServers = { [COMPUTER_SERVER]: computerServer(currentId) };
856
863
  }
857
864
  return options;
858
865
  }
@@ -878,6 +885,27 @@ const MUTATING_SHELL_PATTERNS = [
878
885
  // A redirect into a file. `2>&1`, `>/dev/null`, `> nul`, `->` and `>=` pass.
879
886
  /(?:^|[^<>=-])>{1,2}(?!\s*(?:&|=|\/dev\/null\b|nul\b))/i,
880
887
  /\b(?:Set-Content|Add-Content|Out-File|Remove-Item|Move-Item|Copy-Item|New-Item|Rename-Item|Clear-Content|Set-ItemProperty|Export-Csv|Export-Clixml)\b/i,
888
+ // cmd verbs and PowerShell aliases. Only in command position: as plain words
889
+ // ("rg move src") they are searches, not writes.
890
+ /(?:^|[;&|(`]\s*)(?:del|erase|move|copy|ren|rename|md|rd|xcopy|robocopy|ni|ri|mi|cpi|rni|si|clc)\s/i,
891
+ /\bfind\b[^|;&\n]*\s-delete\b/,
892
+ // curl writes a file with -o/-O, alone or inside a flag cluster (-sSLo).
893
+ /\bcurl\b[^|;&\n]*\s(?:-[a-zA-Z]*[oO][a-zA-Z]*|--output|--remote-name)\b/,
894
+ /\bwget\b/,
895
+ /\s-OutFile\b/i,
896
+ // `git config` as the subcommand, writing: a key and a value, or a mutating
897
+ // flag or verb. A key alone reads, `get`/`list` read, and "config" in a path
898
+ // or pattern is not this.
899
+ /\bgit(?:\s+-[cC]\s+\S+|\s+--?[\w-]+(?:=\S+)?)*\s+config\b[^|;&\n]*\s(?:--unset\S*|--add|--replace-all|--rename-section|--remove-section|--edit|-e|set|unset|rename-section|remove-section|edit)\b/,
900
+ /\bgit(?:\s+-[cC]\s+\S+|\s+--?[\w-]+(?:=\S+)?)*\s+config(?:\s+--[\w-]+(?:=\S+)?|\s+--file\s+\S+|\s+-f\s+\S+)*\s+(?!-|get\b|list\b)[\w.-]+\s+(?!\d*>)[^\s|;&-]/,
901
+ // Inline interpreter code that writes: the interpreter in command position and
902
+ // the write inside its quoted code argument, so searching for these names
903
+ // (rg writeFileSync, `node -v && rg ...`) still reads. Best effort: an
904
+ // interpreter can always write in ways no pattern sees, so the role prompt
905
+ // remains the main guard.
906
+ /(?:^|[;&|(]\s*)(?:node|deno|bun)(?:\s+\S+)*?\s+(?:-e|--eval|-p|--print)\s+(["'])(?:(?!\1)[^\n])*\b(?:writeFileSync|writeFile|appendFileSync|appendFile|rmSync|unlinkSync|renameSync|mkdirSync|copyFileSync|cpSync)\b/,
907
+ /(?:^|[;&|(]\s*)(?:python3?|py)(?:\s+\S+)*?\s+-c\s+(["'])(?:(?!\1)[^\n])*(?:\bopen\([^)]*,\s*['"][wax+]|\b(?:os\.(?:remove|unlink|rename|replace|makedirs|mkdir|rmdir)|shutil\.(?:rmtree|move|copy\w*))\()/,
908
+ /\[(?:System\.)?IO\.(?:File|Directory)\]::(?:WriteAll\w+|AppendAll\w+|Delete|Move|Copy|CreateDirectory)\b/i,
881
909
  ];
882
910
 
883
911
  function pathWithin(cwd, root, target) {
@@ -1048,8 +1076,14 @@ async function requestToolPermission(toolName, input, permission, sessionId) {
1048
1076
  // decide that a human answer is needed. Forward every such request to the host;
1049
1077
  // auto-allowing the ordinary cases here would silently defeat default/auto mode.
1050
1078
  const planApproval = toolName === "ExitPlanMode";
1079
+ // A `setMode` suggestion would switch the CLI out of the verified auto mode
1080
+ // behind the bridge's back while the card read "Don't ask again". Rules and
1081
+ // directories still apply.
1082
+ const suggestions = Array.isArray(permission.suggestions)
1083
+ ? permission.suggestions.filter((suggestion) => suggestion?.type !== "setMode")
1084
+ : permission.suggestions;
1051
1085
  const persistentApprovalLabel = permission.suppressAlwaysAllowRule
1052
- ? "" : permissionSuggestionLabel(permission.suggestions);
1086
+ ? "" : permissionSuggestionLabel(suggestions);
1053
1087
  const common = {
1054
1088
  claudePermission: true,
1055
1089
  title: permission.title || permission.displayName,
@@ -1093,7 +1127,7 @@ async function requestToolPermission(toolName, input, permission, sessionId) {
1093
1127
  updatedInput: input,
1094
1128
  ...(!permission.suppressAlwaysAllowRule
1095
1129
  && (response?.decision === "acceptForSession" || response?.scope === "session")
1096
- ? { updatedPermissions: permission.suggestions }
1130
+ ? { updatedPermissions: suggestions }
1097
1131
  : {}),
1098
1132
  };
1099
1133
  }
@@ -1544,7 +1578,7 @@ async function performComputerAction(session, input, signal) {
1544
1578
  return computerResult("Clicked.");
1545
1579
  }
1546
1580
 
1547
- function computerServer(sessionId) {
1581
+ function computerServer(currentId) {
1548
1582
  const point = () => z.array(z.number().int()).length(2);
1549
1583
  return createSdkMcpServer({
1550
1584
  name: COMPUTER_SERVER,
@@ -1572,7 +1606,7 @@ function computerServer(sessionId) {
1572
1606
  repeat: z.number().int().min(1).max(100).optional().describe("Times to press the key"),
1573
1607
  display: z.number().int().min(1).optional().describe("screenshot only: the display to capture, 1 being the primary. Later actions use the display last captured"),
1574
1608
  },
1575
- (input, extra) => runComputerAction(sessionId, input, extra),
1609
+ (input, extra) => runComputerAction(currentId(), input, extra),
1576
1610
  { searchHint: "computer use desktop screen screenshot mouse click keyboard type" },
1577
1611
  )],
1578
1612
  });
@@ -1629,7 +1663,7 @@ function runClaudeCommand(params, args, deadlineMs = CLAUDE_COMMAND_TIMEOUT) {
1629
1663
  const output = Buffer.concat(stdout).toString("utf8").trim();
1630
1664
  const detail = Buffer.concat(stderr).toString("utf8").trim();
1631
1665
  if (code === 0) resolve(output);
1632
- else reject(Object.assign(new Error(detail || output || `Claude 명령이 종료 코드 ${code}로 실패했습니다.`), { exitCode: code }));
1666
+ else reject(Object.assign(new Error(detail || output || `Claude 명령이 종료 코드 ${code}로 실패했습니다.`), { exitCode: code, stdout: output }));
1633
1667
  });
1634
1668
  });
1635
1669
  }
@@ -2056,7 +2090,7 @@ async function createSession(params, resumeId) {
2056
2090
  computerDisplay: 0,
2057
2091
  };
2058
2092
  await ensureClaudeExecutableChoice(params);
2059
- const agentQuery = await startAgentQuery(queue, makeOptions(params, id, resumeId));
2093
+ const agentQuery = await startAgentQuery(queue, makeOptions(params, id, resumeId, () => session.id));
2060
2094
  session.query = agentQuery;
2061
2095
  sessions.set(id, session);
2062
2096
  const consumer = consume(session)
@@ -2138,7 +2172,10 @@ async function createSession(params, resumeId) {
2138
2172
  // 추가 입력·작업 통지의 후속 턴 예약은 살아 있는 작업의 증거가 아니다. 턴 중에
2139
2173
  // 흡수된 입력·통지는 CLI가 알려 주지 않아 예약이 끝없이 남으므로 전환을 막지 않는다.
2140
2174
  function sessionHasLiveWork(session) {
2175
+ // `runtimeActive`: the CLI is mid-run with no host turn yet (an automatic run
2176
+ // between its init and first frame); closing it then dropped that answer.
2141
2177
  return Boolean(session.initializing || session.promptStarting || session.queryRequests > 0 || session.turn
2178
+ || session.runtimeActive
2142
2179
  || session.pendingPrompts?.length || session.queue?.values?.length || session.usageLimitWait
2143
2180
  || session.subagents?.size || session.hiddenSubagentTasks?.size || session.ambientSubagentTasks?.size
2144
2181
  || [...pendingHostRequests.values()].some((request) => request.session === session));
@@ -2420,11 +2457,13 @@ async function processStreamEvent(session, message) {
2420
2457
  }
2421
2458
 
2422
2459
  function processAssistant(session, message) {
2423
- if (!session.turn) return;
2460
+ // A background agent keeps working after the turn closes; its row should still
2461
+ // show the tool it is on.
2424
2462
  if (message.parent_tool_use_id) {
2425
2463
  recordSubagentMessage(session, message);
2426
2464
  return;
2427
2465
  }
2466
+ if (!session.turn) return;
2428
2467
  session.lastContextUsage = tokenBreakdown(message.message?.usage);
2429
2468
  const capabilities = modelCapabilities(
2430
2469
  session.models,
@@ -2577,6 +2616,7 @@ function messageTime(message) {
2577
2616
  function applyTaskUpdate(tasks, input, turnId, onIntermediate, at) {
2578
2617
  const task = tasks.get(String(input.taskId));
2579
2618
  if (!task) return false;
2619
+ if (input.status === "deleted") return tasks.delete(String(input.taskId));
2580
2620
  if (input.subject) task.subject = input.subject;
2581
2621
  const status = input.status;
2582
2622
  if (status === "in_progress" || status === "completed") {
@@ -2693,6 +2733,11 @@ function updatePlanFromToolResult(session, pending, message) {
2693
2733
  temporary.subject = created.subject || temporary.subject;
2694
2734
  temporary.status = created.status || temporary.status;
2695
2735
  session.tasks.set(temporary.id, temporary);
2736
+ } else if (temporary) {
2737
+ // A failed TaskCreate leaves no task to update, so its placeholder would
2738
+ // stay pending forever. Redraw only if the plan already went out.
2739
+ session.tasks.delete(temporary.id);
2740
+ if (!session.planCreatePending) emitPlan(session);
2696
2741
  }
2697
2742
  } else if (pending.name === "TaskList" && Array.isArray(value?.tasks || value)) {
2698
2743
  const turnId = session.turn?.id;
@@ -2844,6 +2889,10 @@ function keepBackgroundSubagent(session, toolUseId, result) {
2844
2889
  .find((agent) => agent !== running && agent.taskId === running.taskId) : null;
2845
2890
  if (placeholder && placeholder !== running) {
2846
2891
  running.command ||= placeholder.command;
2892
+ // The snapshot is what names the parent; without it a nested row sat at the
2893
+ // top level until the next snapshot.
2894
+ running.parentTaskId ||= placeholder.parentTaskId;
2895
+ if (!running.tool) running.tool = placeholder.tool;
2847
2896
  if (placeholder.runId && (!running.runId || running.runId < placeholder.runId)) running.runId = placeholder.runId;
2848
2897
  session.subagents.delete(placeholder.id);
2849
2898
  }
@@ -3452,13 +3501,15 @@ function notificationTag(body, name) {
3452
3501
 
3453
3502
  // 완료 통지는 SDK 빌드에 따라 문자열·text 블록·다른 블록 형태로 올 수 있다.
3454
3503
  // 감지가 본문 구조에 좌우되면 백그라운드 서브에이전트가 영원히 남으므로, 잡을 수
3455
- // 있는 모든 문자열을 한데 모은다.
3504
+ // 있는 모든 문자열을 한데 모은다. 도구 결과는 통지가 아니다: 통지 XML이 든 파일을
3505
+ // 읽은 결과를 통지로 보면 그 도구 항목이 끝나지 않고 살아 있는 행이 지워졌다.
3456
3506
  function messageAllText(message) {
3457
3507
  const content = message.message?.content;
3458
3508
  if (typeof content === "string") return content;
3459
3509
  if (!Array.isArray(content)) return "";
3460
3510
  const parts = [];
3461
3511
  for (const block of content) {
3512
+ if (block?.type === "tool_result") continue;
3462
3513
  if (typeof block === "string") parts.push(block);
3463
3514
  else if (typeof block?.text === "string") parts.push(block.text);
3464
3515
  else if (typeof block?.content === "string") parts.push(block.content);
@@ -3581,6 +3632,8 @@ function processUser(session, message) {
3581
3632
  } else if (completed.type === "dynamicToolCall") {
3582
3633
  completed.contentItems = structured ?? [{ type: "text", text: output }];
3583
3634
  } else {
3635
+ // A rejected Edit kept its start status, so the host drew it as applied.
3636
+ if (completed.type === "fileChange") completed.status = block.is_error ? "failed" : "completed";
3584
3637
  completed.result = structured ?? output;
3585
3638
  }
3586
3639
  emitItem(session, "completed", completed);
@@ -3605,6 +3658,8 @@ function clearUsageLimitWait(session) {
3605
3658
  return true;
3606
3659
  }
3607
3660
 
3661
+ const USAGE_LIMIT_RESUME_TEXT = "사용량 한도로 중단된 작업을 이어서 진행하세요. 이미 완료한 작업은 반복하지 말고 현재 상태를 확인한 뒤 남은 작업을 수행하세요.";
3662
+
3608
3663
  function resumeAfterUsageLimit(session, wait, now = Date.now()) {
3609
3664
  if (!wait || session.usageLimitWait !== wait || now < wait.resetsAt) return;
3610
3665
  clearUsageLimitWait(session);
@@ -3612,6 +3667,8 @@ function resumeAfterUsageLimit(session, wait, now = Date.now()) {
3612
3667
  // A long sleep must not launch unattended work when the machine wakes up.
3613
3668
  if (now - wait.lastTick > 30 * 60 * 1000) {
3614
3669
  finishTurn(session, new Error("사용량 한도가 초기화되었습니다. 계속하려면 요청을 보내 주세요."));
3670
+ // Prompts the user queued behind the limited turn were asked for; they run.
3671
+ drainPendingPrompt(session);
3615
3672
  return;
3616
3673
  }
3617
3674
  session.turn.rateLimitInfo = null;
@@ -3624,12 +3681,13 @@ function resumeAfterUsageLimit(session, wait, now = Date.now()) {
3624
3681
  try {
3625
3682
  session.queue.push({
3626
3683
  type: "user",
3627
- message: { role: "user", content: [{ type: "text", text: "사용량 한도로 중단된 작업을 이어서 진행하세요. 이미 완료한 작업은 반복하지 말고 현재 상태를 확인한 뒤 남은 작업을 수행하세요." }] },
3684
+ message: { role: "user", content: [{ type: "text", text: USAGE_LIMIT_RESUME_TEXT }] },
3628
3685
  parent_tool_use_id: null,
3629
3686
  session_id: session.id,
3630
3687
  });
3631
3688
  } catch (error) {
3632
3689
  finishTurn(session, error);
3690
+ drainPendingPrompt(session);
3633
3691
  }
3634
3692
  }
3635
3693
 
@@ -3713,7 +3771,13 @@ function abnormalStopOutcome(stopReason) {
3713
3771
  }
3714
3772
 
3715
3773
  async function processResult(session, message) {
3716
- if (!session.turn) return;
3774
+ // 호스트 턴 없이 끝난 실행(/clear, 응답 없는 자동 실행)의 예약은 쓸 곳이 없다.
3775
+ // 이어지는 자동 실행은 init이 다시 예약한다.
3776
+ if (!session.turn) {
3777
+ session.automaticTurnsPending = 0;
3778
+ drainPendingPrompt(session);
3779
+ return;
3780
+ }
3717
3781
  for (const denial of Array.isArray(message.permission_denials) ? message.permission_denials : []) {
3718
3782
  rememberPermissionDenial(session, {
3719
3783
  tool: denial.tool_name,
@@ -3792,7 +3856,7 @@ async function processResult(session, message) {
3792
3856
  withSessionQuery(session, (query) => Promise.all([safeAccount(query), safeUsage(query)]))
3793
3857
  .then(([account, usage]) => notify("claude/account/updated", { threadId: session.id, account, usage }))
3794
3858
  .catch(() => {});
3795
- if (!steerFollows) await runPendingPrompt(session);
3859
+ if (!steerFollows) drainPendingPrompt(session);
3796
3860
  }
3797
3861
 
3798
3862
  // Compaction ends the turn's only assistant message, so the context figure would
@@ -3842,7 +3906,7 @@ function rememberPermissionDenial(session, denial) {
3842
3906
  // The turn that was waiting starts on its own, so the host sees it exactly like a
3843
3907
  // prompt sent the moment the previous turn ended.
3844
3908
  async function runPendingPrompt(session) {
3845
- const next = session.pendingPrompts.shift();
3909
+ const next = session.pendingPrompts?.shift();
3846
3910
  if (!next) return;
3847
3911
  try {
3848
3912
  await runPrompt(session, next);
@@ -3853,7 +3917,7 @@ async function runPendingPrompt(session) {
3853
3917
  error: { message: error instanceof Error ? error.message : String(error) },
3854
3918
  willRetry: false,
3855
3919
  });
3856
- await runPendingPrompt(session);
3920
+ drainPendingPrompt(session);
3857
3921
  }
3858
3922
  }
3859
3923
 
@@ -3897,10 +3961,20 @@ async function consumeMessage(session, message) {
3897
3961
  if (session.clearWaiter) session.clearPending = true;
3898
3962
  return;
3899
3963
  }
3964
+ // SDK가 스스로 시작한 실행(백그라운드 작업 완료, Monitor 이벤트)은 init으로 시작한다.
3965
+ // 완료 통지는 같은 run_id의 task_updated에 가려 예약되지 않을 수 있고, Monitor
3966
+ // 이벤트는 통지가 없다. 첫 턴 전(재개 재생)의 init은 예약하지 않는다.
3967
+ if (message.type === "system" && message.subtype === "init" && !session.turn && !session.initializing
3968
+ && session.turnSequence > 1 && !session.automaticTurnsPending && !session.steerPending) {
3969
+ session.automaticTurnsPending = 1;
3970
+ }
3900
3971
  adoptSessionId(session, message.session_id);
3901
3972
  beginUntrackedTurn(session, message);
3902
- // A queued SDK response may beat the timer. It already resumes the work.
3903
- if (!message.parent_tool_use_id && (message.type === "assistant" || message.type === "stream_event")) {
3973
+ // A queued SDK response may beat the timer. It already resumes the work. A run
3974
+ // that is itself refused by the same limit (an automatic run during the wait)
3975
+ // resumes nothing; clearing on it spent a retry per refusal.
3976
+ if (!message.parent_tool_use_id && (message.type === "assistant" || message.type === "stream_event")
3977
+ && message.error !== "rate_limit") {
3904
3978
  clearUsageLimitWait(session);
3905
3979
  if (session.turn) session.turn.awaitingSteer = false;
3906
3980
  }
@@ -3938,6 +4012,7 @@ async function consumeMessage(session, message) {
3938
4012
  notify("thread/compacted", { threadId: session.id });
3939
4013
  } else if (message.type === "system" && message.subtype === "session_state_changed") {
3940
4014
  noteRuntimeActive(session, message.state !== "idle");
4015
+ if (message.state === "idle") drainPendingPrompt(session);
3941
4016
  } else if (message.type === "system" && message.subtype === "permission_denied") {
3942
4017
  const reason = message.decision_reason || message.decision_reason_type;
3943
4018
  rememberPermissionDenial(session, {
@@ -4045,11 +4120,37 @@ async function startPrompt(params) {
4045
4120
  cancelUsageLimitWait(session);
4046
4121
  // Claude runs one turn at a time, so extra input waits its turn instead of
4047
4122
  // failing — the same queueing the CLI does for a prompt typed while it works.
4048
- if (session.turn) {
4123
+ // Prompts already waiting (behind a cancelled usage-limit wait) go first.
4124
+ if (promptMustWait(session) || session.pendingPrompts.length) {
4049
4125
  session.pendingPrompts.push(params);
4050
- return { turn: { id: session.turn.id }, queued: true };
4126
+ drainPendingPrompt(session);
4127
+ // The prompt's own turn does not exist yet; it arrives marked `prompt`.
4128
+ return { turn: { id: null }, queued: true };
4051
4129
  }
4052
- return runPrompt(session, params);
4130
+ return startQueuedSafely(session, params);
4131
+ }
4132
+
4133
+ // A turn is running, or another prompt is still being set up (its turn opens
4134
+ // after model and effort calls); two setups at once overwrote each other's turn.
4135
+ function promptMustWait(session) {
4136
+ return Boolean(session.turn || session.promptStarting > 0);
4137
+ }
4138
+
4139
+ // A prompt that fails to start must not strand the ones queued behind it.
4140
+ function startQueuedSafely(session, params) {
4141
+ return runPrompt(session, params).catch((error) => {
4142
+ drainPendingPrompt(session);
4143
+ throw error;
4144
+ });
4145
+ }
4146
+
4147
+ // Starts the next waiting prompt once nothing else holds the session. A usage
4148
+ // limit wait keeps its queue until the wait resolves. Never awaited from message
4149
+ // handling: the prompt's setup awaits SDK calls, and holding the message loop
4150
+ // meanwhile hid an automatic run's init from the check that defers to it.
4151
+ function drainPendingPrompt(session) {
4152
+ if (session.closed || promptMustWait(session) || session.usageLimitWait) return;
4153
+ runPendingPrompt(session).catch(() => {});
4053
4154
  }
4054
4155
 
4055
4156
  // Steering pushes the prompt straight into the SDK input stream, so the running
@@ -4060,10 +4161,24 @@ async function steerPrompt(params) {
4060
4161
  const session = sessions.get(id);
4061
4162
  if (!session) throw new Error(`Claude 세션을 찾을 수 없습니다: ${id}`);
4062
4163
  cancelUsageLimitWait(session);
4063
- if (!session.turn) return runPrompt(session, params);
4164
+ if (!session.turn) {
4165
+ // With no turn to join it is a prompt, and waits behind prompts already queued.
4166
+ if (!promptMustWait(session) && !session.pendingPrompts.length) return startQueuedSafely(session, params);
4167
+ session.pendingPrompts.push(params);
4168
+ drainPendingPrompt(session);
4169
+ return { turn: { id: null }, queued: true };
4170
+ }
4171
+ // Typed after a prompt that is still waiting: it follows that prompt instead
4172
+ // of joining the run ahead of it (often an automatic turn).
4173
+ if (session.pendingPrompts.length) {
4174
+ session.pendingPrompts.push(params);
4175
+ return { turn: { id: null }, queued: true };
4176
+ }
4064
4177
  if (params.expectedTurnId && params.expectedTurnId !== session.turn.id) {
4065
4178
  throw new Error(`turn ID가 일치하지 않습니다: ${params.expectedTurnId}`);
4066
4179
  }
4180
+ // Read before awaiting: the turn may close while an image is read.
4181
+ const turnId = session.turn.id;
4067
4182
  // The CLI may answer the steered message in a cycle of its own, ending the
4068
4183
  // running turn first. Remember the debt so that answer opens a fresh turn
4069
4184
  // instead of arriving with no turn to attach to.
@@ -4076,7 +4191,7 @@ async function steerPrompt(params) {
4076
4191
  session_id: id,
4077
4192
  origin: { kind: "human" },
4078
4193
  });
4079
- return { turn: { id: session.turn.id }, steered: true };
4194
+ return { turn: { id: turnId }, steered: true };
4080
4195
  }
4081
4196
 
4082
4197
  async function runPrompt(session, params) {
@@ -4103,6 +4218,10 @@ async function runPrompt(session, params) {
4103
4218
  const ultracode = (params.ultracode ?? session.ultracode) === true && effort === "xhigh";
4104
4219
  if (effort) {
4105
4220
  await session.query.applyFlagSettings({ effortLevel: effort, ultracode });
4221
+ } else if (session.effort) {
4222
+ // A model without effort levels: clear the previous model's level instead
4223
+ // of leaving it in the flag layer for the next model that has them.
4224
+ await session.query.applyFlagSettings({ effortLevel: null });
4106
4225
  }
4107
4226
  // The SDK takes the flag without complaint even where dynamic workflows are
4108
4227
  // off, so ask whether it actually took hold.
@@ -4123,6 +4242,14 @@ async function runPrompt(session, params) {
4123
4242
  : null;
4124
4243
  }
4125
4244
  const content = await inputContent(params.input, params.handoffContext);
4245
+ // An automatic run may have opened a turn during the awaits above. Taking it
4246
+ // over left that turn without a completion; this prompt goes first after it.
4247
+ if (session.turn) {
4248
+ session.pendingPrompts.unshift(params);
4249
+ return { turn: { id: null }, queued: true };
4250
+ }
4251
+ // 지난 턴에 흡수된 통지의 예약을 비운다. 이후 자동 실행은 init이 다시 예약한다.
4252
+ session.automaticTurnsPending = 0;
4126
4253
  const turnId = beginTurn(session, params.input);
4127
4254
  session.queue.push({
4128
4255
  type: "user",
@@ -4188,6 +4315,7 @@ const INTERNAL_TAGS = [
4188
4315
  "session-start-hook",
4189
4316
  "ide_selection",
4190
4317
  "ide_opened_file",
4318
+ "devez-vibe-explicit-skills",
4191
4319
  ];
4192
4320
 
4193
4321
  /** Drops every internal block, leaving only what the user actually typed. */
@@ -4204,6 +4332,8 @@ function stripInternalTags(text) {
4204
4332
  function isInternalHistoryText(message, text) {
4205
4333
  if (message.isMeta || message.subtype === "local_command") return true;
4206
4334
  if (isCompactSummary(message, text)) return true;
4335
+ // The bridge sends this itself after a usage limit resets; it is not a prompt.
4336
+ if (text.trim() === USAGE_LIMIT_RESUME_TEXT) return true;
4207
4337
  // The interruption marker carries a reason ("… for tool use"), so it has to be
4208
4338
  // matched by prefix rather than by the bare sentence.
4209
4339
  return text.trim().startsWith("[Request interrupted by user");
@@ -4252,7 +4382,9 @@ function historyState(messages) {
4252
4382
  if (completedAt != null) turn.completedAt = Math.floor(completedAt / 1000);
4253
4383
  if (message.type === "assistant") {
4254
4384
  if (message.message?.model === "<synthetic>") {
4255
- turn.synthetic = true;
4385
+ // Only a turn the model never answered is dropped. An interrupt or API
4386
+ // error appends a synthetic reply after real work, and that turn stays.
4387
+ turn.synthetic ??= true;
4256
4388
  continue;
4257
4389
  }
4258
4390
  turn.synthetic = false;
@@ -4763,11 +4895,38 @@ async function dispatch(method, params = {}) {
4763
4895
  if (method === "skills/list") return claudeSkills(params);
4764
4896
  if (method === "app/list") return { data: [] };
4765
4897
  if (method === "account/read") {
4766
- return await runClaudeJson(params, ["auth", "status", "--json"]) || {};
4898
+ // Signed out, `auth status --json` still prints {"loggedIn": false} but
4899
+ // exits 1; failing here left the host showing the previous account.
4900
+ const args = ["auth", "status", "--json"];
4901
+ const signedOut = (error) => {
4902
+ try {
4903
+ const status = JSON.parse(error.stdout);
4904
+ if (status?.loggedIn === false) return status;
4905
+ } catch {}
4906
+ return null;
4907
+ };
4908
+ // Checked before the crash retry, which would run the CLI a second time.
4909
+ return await runClaudeCommand(params, args)
4910
+ .then((output) => output ? JSON.parse(output) : null)
4911
+ .catch((error) => signedOut(error) || runClaudeJson(params, args).catch((retry) => {
4912
+ const status = signedOut(retry);
4913
+ if (status) return status;
4914
+ throw retry;
4915
+ })) || {};
4767
4916
  }
4768
4917
  if (method === "account/login/start") return startClaudeLogin(params);
4769
4918
  if (method === "account/login/cancel") return cancelClaudeLogin(params);
4770
- if (method === "plugin/reload") return {};
4919
+ if (method === "plugin/reload") {
4920
+ // A live session keeps the plugins and MCP servers it started with until its
4921
+ // CLI reloads them; answering without that made /reload-plugins look applied.
4922
+ // One session failing must not report the whole reload as failed.
4923
+ const reloads = await Promise.allSettled([...sessions.values()]
4924
+ .filter((session) => session.query && !session.closed && !session.initializing)
4925
+ .map((session) => withSessionQuery(session, (query) => query.reloadPlugins?.())));
4926
+ const failed = reloads.filter((reload) => reload.status === "rejected");
4927
+ if (failed.length && failed.length === reloads.length) throw failed[0].reason;
4928
+ return {};
4929
+ }
4771
4930
  if (method === "permissions/status") return claudePermissionStatus(params);
4772
4931
  if (method === "permissions/update") return updateClaudePermission(params);
4773
4932
  if (method === "permissions/auto-mode") return setClaudeAutoModeDisabled(params);
@@ -4782,7 +4941,10 @@ async function dispatch(method, params = {}) {
4782
4941
  // turn you are still waiting on actually running?" from the bridge's own state.
4783
4942
  if (method === "session/turnStatus") {
4784
4943
  const session = lookupSession(params.sessionId);
4785
- if (!session) return { known: false, running: false, turnId: null };
4944
+ // A session this bridge does not hold runs nothing here: the bridge that ran
4945
+ // it has exited or released it. `sessionMissing` lets the host's stall probe
4946
+ // end the turn, where a bare "unknown" kept it waiting forever.
4947
+ if (!session) return { known: false, running: false, turnId: null, sessionMissing: true };
4786
4948
  return { known: true, running: Boolean(session.turn), turnId: session.turn?.id ?? null };
4787
4949
  }
4788
4950
  if (method === "session/start") {
@@ -4814,6 +4976,8 @@ async function dispatch(method, params = {}) {
4814
4976
  id,
4815
4977
  thread: { id, turns: [] },
4816
4978
  initialTurnsPage: { data: [], nextCursor: null },
4979
+ // Returning to a session mid-turn: the host restores its busy state from this.
4980
+ activeTurnId: existing.turn?.id ?? null,
4817
4981
  cwd: existing.cwd,
4818
4982
  model: existing.model,
4819
4983
  reasoningEffort: existing.effort,
@@ -4830,7 +4994,9 @@ async function dispatch(method, params = {}) {
4830
4994
  const messages = await sessionMessages(id, params.cwd);
4831
4995
  if (!messages.length) throw new Error(`Claude 세션을 찾을 수 없습니다: ${id}`);
4832
4996
  const info = await getSessionInfo(id, { dir });
4833
- const lastModel = [...messages].reverse().find((message) => message.type === "assistant")?.message?.model;
4997
+ // An interrupt or API error leaves a `<synthetic>` reply last; it names no model.
4998
+ const lastModel = [...messages].reverse().find((message) => message.type === "assistant"
4999
+ && message.message?.model && message.message.model !== "<synthetic>")?.message?.model;
4834
5000
  // The transcript's own model outranks the host's fallback, which is only what
4835
5001
  // a new session would have opened on.
4836
5002
  const { session, account, usage } = await createSession({
@@ -4893,13 +5059,18 @@ async function dispatch(method, params = {}) {
4893
5059
  if (session) {
4894
5060
  session.pendingPrompts.length = 0;
4895
5061
  session.steerPending = 0;
5062
+ session.automaticTurnsPending = 0;
4896
5063
  if (cancelUsageLimitWait(session)) return {};
4897
5064
  }
4898
5065
  if (session?.turn) {
4899
5066
  const turn = session.turn;
4900
5067
  turn.interruptRequested = true;
4901
5068
  try {
4902
- await withSessionQuery(session, (query) => query.interrupt());
5069
+ // A plain interrupt keeps steers the CLI has queued, and they then ran as
5070
+ // a new turn after the stop (measured on 0.3.309). `cancelQueued` drops
5071
+ // them; the runtime has it (capability `interrupt_cancel_queued_v1`)
5072
+ // though the typings do not, and older CLIs ignore the field.
5073
+ await withSessionQuery(session, (query) => query.interrupt({ cancelQueued: true }));
4903
5074
  } catch (error) {
4904
5075
  if (session.turn === turn) delete turn.interruptRequested;
4905
5076
  throw error;
@@ -4960,6 +5131,17 @@ async function dispatch(method, params = {}) {
4960
5131
  if (session) {
4961
5132
  closeLiveSession(session);
4962
5133
  if (params.delete) await deleteSession(session.id, { dir: session.cwd });
5134
+ } else if (params.delete) {
5135
+ // Idle cleanup may already have closed it; the transcript still goes.
5136
+ const id = liveSessionId(params.sessionId);
5137
+ const dir = await readableCwd(id, params.cwd);
5138
+ // Only "already gone" is fine; a locked or unreadable transcript must fail
5139
+ // loudly, or the deleted session returns in /resume.
5140
+ if (dir) {
5141
+ await deleteSession(id, { dir }).catch((error) => {
5142
+ if (error?.code !== "ENOENT" && !/not found/i.test(String(error?.message))) throw error;
5143
+ });
5144
+ }
4963
5145
  }
4964
5146
  return {};
4965
5147
  }
@@ -5158,8 +5340,26 @@ function runToolPolicySelfTest() {
5158
5340
  [planner, "Write", { file_path: "docs/plans/2026-09-05-x.md" }],
5159
5341
  [planner, "Write", { file_path: `${cwd}${sep}docs${sep}plans${sep}x.md` }],
5160
5342
  [reviewer, COMPUTER_TOOL, { action: "screenshot" }],
5343
+ [reviewer, "Bash", { command: "rg move src && git log --grep copy" }],
5344
+ [reviewer, "Bash", { command: "git config --get user.name" }],
5345
+ [reviewer, "Bash", { command: "git diff -- src/config.rs && git log --oneline -- config/ && git show HEAD:config.json" }],
5346
+ [reviewer, "Bash", { command: "rg -n writeFileSync npm/bridge && git log -S writeFileSync" }],
5347
+ [reviewer, "Bash", { command: "git config get user.name; git config core.editor 2>/dev/null" }],
5348
+ [reviewer, "Bash", { command: "node -e \"console.log(process.version)\" && rg -n writeFileSync npm/bridge" }],
5349
+ [reviewer, "Bash", { command: "rg -n \"node\" -e writeFileSync npm/bridge" }],
5350
+ [reviewer, "Bash", { command: "python -c \"print(1)\"" }],
5161
5351
  ];
5162
5352
  const denied = [
5353
+ [reviewer, "PowerShell", { command: "del a.txt" }],
5354
+ [reviewer, "PowerShell", { command: "Invoke-WebRequest https://x -OutFile y" }],
5355
+ [reviewer, "Bash", { command: "find . -delete" }],
5356
+ [reviewer, "Bash", { command: "git config user.name x" }],
5357
+ [reviewer, "Bash", { command: "git config --file=x a.b c" }],
5358
+ [reviewer, "Bash", { command: "git config --show-scope a.b c" }],
5359
+ [reviewer, "Bash", { command: "node -e \"const fs=require('fs'); fs.writeFileSync('a','b')\"" }],
5360
+ [reviewer, "Bash", { command: "curl -sSLo out https://example.com" }],
5361
+ [reviewer, "Bash", { command: "node -e \"require('fs').writeFileSync('a','b')\"" }],
5362
+ [reviewer, "Bash", { command: "python -c \"open('a.txt','w').write('x')\"" }],
5163
5363
  [reviewer, "Edit", { file_path: "src/main.rs" }],
5164
5364
  [reviewer, "Write", { file_path: "docs/plans/x.md" }],
5165
5365
  [reviewer, "NotebookEdit", { notebook_path: "a.ipynb" }],
@@ -5511,6 +5711,8 @@ async function runSelfTest() {
5511
5711
  await consumeMessage(session, { type: "system", subtype: "task_notification", task_id: "absorbed-task", status: "completed" });
5512
5712
  session.steerPending = 1;
5513
5713
  await consumeMessage(session, { type: "result", is_error: false, modelUsage: {}, permission_denials: [], duration_ms: 1, queued_turn_count: 0 });
5714
+ // The result's account lookup runs detached; let it settle.
5715
+ await new Promise((resolve) => setTimeout(resolve, 10));
5514
5716
  if (session.turn || session.automaticTurnsPending !== 1 || sessionHasLiveWork(session)) {
5515
5717
  throw new Error("Claude absorbed follow-up booking kept the session busy");
5516
5718
  }
@@ -5927,6 +6129,26 @@ async function runSelfTest() {
5927
6129
  if (interrupted.length !== 1 || interrupted[0].status !== "interrupted") {
5928
6130
  throw new Error(`Claude interrupted prompt history self-test failed: ${JSON.stringify(interrupted)}`);
5929
6131
  }
6132
+ // 실제 작업 뒤 Esc나 API 오류로 붙은 합성 응답은 그 턴을 지우지 않는다.
6133
+ const stopped = historyTurns([
6134
+ user("stopped", "길게 써 줘"),
6135
+ assistant("partial", "claude-opus-5", "앞부분"),
6136
+ user("marker", "[Request interrupted by user]"),
6137
+ assistant("stop-synthetic", "<synthetic>", "No response requested."),
6138
+ ]);
6139
+ if (stopped.length !== 1 || !stopped[0].items.some((item) => item.type === "agentMessage" && item.text === "앞부분")) {
6140
+ throw new Error(`Claude stopped turn history self-test failed: ${JSON.stringify(stopped)}`);
6141
+ }
6142
+ // 브리지가 붙인 스킬 지시문과 한도 재개 문구는 사용자 입력으로 복원하지 않는다.
6143
+ const injected = historyTurns([
6144
+ user("skill", "<devez-vibe-explicit-skills>\nInvoke each skill\n- /x\n</devez-vibe-explicit-skills>\n고쳐 줘"),
6145
+ assistant("skill-a", "claude-opus-5", "네."),
6146
+ user("resume", USAGE_LIMIT_RESUME_TEXT),
6147
+ assistant("resume-a", "claude-opus-5", "이어서 합니다."),
6148
+ ]);
6149
+ if (injected.length !== 1 || injected[0].items[0].content[0].text !== "고쳐 줘") {
6150
+ throw new Error(`Claude injected prompt history self-test failed: ${JSON.stringify(injected)}`);
6151
+ }
5930
6152
  const taskUse = (uuid, id, name, input) => ({
5931
6153
  type: "assistant",
5932
6154
  uuid,
@@ -6130,6 +6352,18 @@ async function runSelfTest() {
6130
6352
  applyTaskUpdate(reopenedTasks, { taskId: "2", status: "completed" }, "turn");
6131
6353
  applyTaskUpdate(reopenedTasks, { taskId: "4", status: "completed" }, "turn");
6132
6354
  applyTaskUpdate(reopenedTasks, { taskId: "3", status: "in_progress" }, "turn");
6355
+ const deletedTasks = new Map([["1", { id: "1", subject: "1. a", status: "pending" }]]);
6356
+ if (!applyTaskUpdate(deletedTasks, { taskId: "1", status: "deleted" }, "turn") || deletedTasks.size !== 0) {
6357
+ throw new Error("Claude deleted task self-test failed");
6358
+ }
6359
+ const failedCreate = {
6360
+ planCreatePending: true,
6361
+ tasks: new Map([["pending:tu-fail", { id: "pending:tu-fail", subject: "1. a", status: "pending" }]]),
6362
+ };
6363
+ updatePlanFromToolResult(failedCreate, { name: "TaskCreate", toolUseId: "tu-fail" }, {
6364
+ message: { content: [{ type: "tool_result", is_error: true, content: "Error: invalid input" }] },
6365
+ });
6366
+ if (failedCreate.tasks.size !== 0) throw new Error("Claude failed TaskCreate left a placeholder step");
6133
6367
  const reopenedPlan = [...reopenedTasks.entries()].map(([key, task]) => `${key}:${task.status}`).join(",");
6134
6368
  if (reopenedPlan !== "1:completed,2:completed,4:completed,3:in_progress") {
6135
6369
  throw new Error(`Claude reopened task order self-test failed: ${reopenedPlan}`);
@@ -6240,8 +6474,12 @@ async function runSelfTest() {
6240
6474
  catalogEntry({ value: "haiku", resolvedModel: "claude-haiku-5-5" }, "").contextWindow,
6241
6475
  catalogEntry({ value: "claude-haiku-5-5-20261007" }, "").contextWindow,
6242
6476
  catalogEntry({ value: "claude-haiku-4-5-20251001" }, "").contextWindow,
6477
+ catalogEntry({ value: "opus", resolvedModel: "claude-opus-5-5" }, "").contextWindow,
6478
+ catalogEntry({ value: "sonnet", resolvedModel: "claude-sonnet-5-5" }, "").contextWindow,
6479
+ catalogEntry({ value: "fable", resolvedModel: "claude-fable-5-1" }, "").contextWindow,
6480
+ catalogEntry({ value: "claude-opus-5", resolvedModel: "claude-opus-5" }, "").contextWindow,
6243
6481
  ];
6244
- if (windows.join(",") !== "1000000,200000,300000,1000000,1000000,200000") {
6482
+ if (windows.join(",") !== "1000000,200000,300000,1000000,1000000,200000,1000000,1000000,1000000,200000") {
6245
6483
  throw new Error(`Claude context window self-test failed: ${windows.join(",")}`);
6246
6484
  }
6247
6485
  for (const disabled of ["1", "true"]) {
@@ -6803,6 +7041,40 @@ async function runSelfTest() {
6803
7041
  || automaticTurnSession.automaticTurnsPending !== 0) {
6804
7042
  throw new Error("Claude consecutive automatic responses left a pending turn");
6805
7043
  }
7044
+ // 실측 순서: 백그라운드 명령 완료는 완료 task_updated 뒤 같은 run_id의 통지, init,
7045
+ // 응답 순이다. Monitor 이벤트는 통지 없이 init부터 온다. 둘 다 턴 하나를 열고 닫는다.
7046
+ const automaticRun = async (frames) => {
7047
+ for (const frame of frames) await consumeMessage(automaticTurnSession, frame);
7048
+ const opened = automaticTurnSession.turn !== null;
7049
+ await consumeMessage(automaticTurnSession, {
7050
+ type: "result", is_error: false, modelUsage: {}, permission_denials: [], duration_ms: 1,
7051
+ });
7052
+ return opened && automaticTurnSession.turn === null && automaticTurnSession.automaticTurnsPending === 0;
7053
+ };
7054
+ const reply = { type: "assistant", parent_tool_use_id: null, message: { content: [{ type: "text", text: "auto" }] } };
7055
+ const completed = (subtype) => ({
7056
+ type: "system", subtype, task_id: "bash-done", run_id: "r1", status: "completed", patch: { status: "completed" },
7057
+ });
7058
+ if (!await automaticRun([completed("task_updated"), completed("task_notification"), { type: "system", subtype: "init" }, reply])
7059
+ || !await automaticRun([{ type: "system", subtype: "init" }, reply])) {
7060
+ throw new Error("Claude background completion or monitor event did not open one host turn");
7061
+ }
7062
+ // 첫 턴 전(재개 재생)의 init은 예약하지 않는다.
7063
+ const sequence = automaticTurnSession.turnSequence;
7064
+ automaticTurnSession.turnSequence = 1;
7065
+ await consumeMessage(automaticTurnSession, { type: "system", subtype: "init" });
7066
+ automaticTurnSession.turnSequence = sequence;
7067
+ if (automaticTurnSession.automaticTurnsPending !== 0) {
7068
+ throw new Error("Claude init before the first turn booked an automatic turn");
7069
+ }
7070
+ // /clear 실측 순서: init이 예약해도 응답 없이 result로 끝나면 예약이 남지 않는다.
7071
+ await consumeMessage(automaticTurnSession, { type: "system", subtype: "init" });
7072
+ await consumeMessage(automaticTurnSession, {
7073
+ type: "result", is_error: false, modelUsage: {}, permission_denials: [], duration_ms: 1,
7074
+ });
7075
+ if (automaticTurnSession.turn !== null || automaticTurnSession.automaticTurnsPending !== 0) {
7076
+ throw new Error("Claude turnless run left an automatic turn booking");
7077
+ }
6806
7078
 
6807
7079
  processUser(lifecycleSession, {
6808
7080
  message: { content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "launched" }] },
@@ -7760,6 +8032,63 @@ async function runSelfTest() {
7760
8032
  if (openingMessageIndex >= 0 || openingToolIndex < 0) {
7761
8033
  throw new Error(`Claude tool-first turn self-test failed: ${JSON.stringify(openingEvents)}`);
7762
8034
  }
8035
+ // 백그라운드 에이전트가 도는 동안(CLI는 running)에도 프롬프트는 바로 시작한다.
8036
+ const waitSession = {
8037
+ ...openingSession,
8038
+ id: "prompt-wait-self-test",
8039
+ turn: null,
8040
+ turnSequence: 2,
8041
+ pendingPrompts: [],
8042
+ steerPending: 0,
8043
+ automaticTurnsPending: 0,
8044
+ runtimeActive: true,
8045
+ query: { applyFlagSettings: async () => {} },
8046
+ queue: { values: [], push(value) { this.values.push(value); } },
8047
+ };
8048
+ sessions.set(waitSession.id, waitSession);
8049
+ process.stdout.write = () => true;
8050
+ try {
8051
+ const direct = await startPrompt({ sessionId: waitSession.id, input: [{ type: "text", text: "now" }] });
8052
+ if (direct.queued || !waitSession.turn) {
8053
+ throw new Error("Claude prompt waited on a background agent's running state");
8054
+ }
8055
+ // 다른 프롬프트를 준비하는 동안 온 프롬프트·steer는 기다렸다가 idle에 이어 시작한다.
8056
+ Object.assign(waitSession, { turn: null, runtimeActive: false, promptStarting: 1 });
8057
+ waitSession.queue.values.length = 0;
8058
+ const queued = await startPrompt({ sessionId: waitSession.id, input: [{ type: "text", text: "wait" }] });
8059
+ const steered = await steerPrompt({ sessionId: waitSession.id, input: [{ type: "text", text: "steer" }] });
8060
+ if (!queued.queued || queued.turn.id !== null || !steered.queued || waitSession.turn || waitSession.pendingPrompts.length !== 2) {
8061
+ throw new Error("Claude prompt during another prompt's setup did not wait");
8062
+ }
8063
+ waitSession.promptStarting = 0;
8064
+ await consumeMessage(waitSession, { type: "system", subtype: "session_state_changed", state: "idle" });
8065
+ await new Promise((resolve) => setTimeout(resolve, 20));
8066
+ if (!waitSession.turn || waitSession.queue.values.length !== 1 || waitSession.pendingPrompts.length !== 1) {
8067
+ throw new Error("Claude waiting prompt did not start when the session went idle");
8068
+ }
8069
+ // 아직 기다리는 프롬프트가 있으면 추가 입력은 지금 턴이 아니라 그 뒤에 선다.
8070
+ const behind = await steerPrompt({ sessionId: waitSession.id, input: [{ type: "text", text: "later" }] });
8071
+ if (!behind.queued || waitSession.pendingPrompts.length !== 2 || waitSession.queue.values.length !== 1) {
8072
+ throw new Error("Claude steer overtook a waiting prompt");
8073
+ }
8074
+ waitSession.pendingPrompts.length = 1;
8075
+ // 한도 대기를 취소한 새 프롬프트보다 먼저 기다리던 프롬프트가 먼저 시작한다.
8076
+ Object.assign(waitSession, {
8077
+ turn: { id: "limited" },
8078
+ runtimeActive: false,
8079
+ usageLimitWait: { timer: null },
8080
+ pendingPrompts: [{ input: [{ type: "text", text: "older" }] }],
8081
+ });
8082
+ waitSession.queue.values.length = 0;
8083
+ await startPrompt({ sessionId: waitSession.id, input: [{ type: "text", text: "newer" }] });
8084
+ await new Promise((resolve) => setTimeout(resolve, 20));
8085
+ if (waitSession.queue.values[0]?.message?.content?.[0]?.text !== "older" || waitSession.pendingPrompts.length !== 1) {
8086
+ throw new Error(`Claude prompt overtook one queued behind a usage limit: ${JSON.stringify(waitSession.queue.values)}`);
8087
+ }
8088
+ } finally {
8089
+ process.stdout.write = stdoutWrite;
8090
+ sessions.delete(waitSession.id);
8091
+ }
7763
8092
  const continuationSession = {
7764
8093
  ...openingSession,
7765
8094
  turn: null,