@lobehub/cli 0.0.131 → 0.0.133

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/index.js CHANGED
@@ -110,16 +110,16 @@ var init_escapeRegExp = __esmMin((() => {}));
110
110
 
111
111
  //#endregion
112
112
  //#region ../../packages/utils/src/object.ts
113
- var isObjectLike$1, isRecord$7, isPlainRecord, toRecord, pickString$1;
113
+ var isObjectLike$1, isRecord$8, isPlainRecord, toRecord, pickString$1;
114
114
  var init_object$1 = __esmMin((() => {
115
115
  isObjectLike$1 = (value) => typeof value === "object" && value !== null;
116
- isRecord$7 = (value) => isObjectLike$1(value) && !Array.isArray(value);
116
+ isRecord$8 = (value) => isObjectLike$1(value) && !Array.isArray(value);
117
117
  isPlainRecord = (value) => {
118
- if (!isRecord$7(value)) return false;
118
+ if (!isRecord$8(value)) return false;
119
119
  const prototype = Object.getPrototypeOf(value);
120
120
  return prototype === Object.prototype || prototype === null;
121
121
  };
122
- toRecord = (value) => isRecord$7(value) ? value : void 0;
122
+ toRecord = (value) => isRecord$8(value) ? value : void 0;
123
123
  pickString$1 = (value) => typeof value === "string" ? value : void 0;
124
124
  }));
125
125
 
@@ -7950,6 +7950,20 @@ var init_device = __esmMin((() => {
7950
7950
  init_workingDir();
7951
7951
  }));
7952
7952
 
7953
+ //#endregion
7954
+ //#region ../../packages/types/src/heteroPermissionMode.ts
7955
+ var HETERO_PERMISSION_MODES, isHeteroPermissionMode;
7956
+ var init_heteroPermissionMode = __esmMin((() => {
7957
+ HETERO_PERMISSION_MODES = [
7958
+ "default",
7959
+ "acceptEdits",
7960
+ "auto",
7961
+ "plan",
7962
+ "bypassPermissions"
7963
+ ];
7964
+ isHeteroPermissionMode = (value) => typeof value === "string" && HETERO_PERMISSION_MODES.includes(value);
7965
+ }));
7966
+
7953
7967
  //#endregion
7954
7968
  //#region ../../packages/types/src/agentExecution/credentialFacts.ts
7955
7969
  var init_credentialFacts = __esmMin((() => {}));
@@ -7968,10 +7982,16 @@ var initialTopicMetadataSchema;
7968
7982
  var init_agentExecution = __esmMin((() => {
7969
7983
  init_zod$1();
7970
7984
  init_device();
7985
+ init_heteroPermissionMode();
7971
7986
  init_credentialFacts();
7972
7987
  init_initRequest();
7973
7988
  init_modelFacts();
7974
7989
  initialTopicMetadataSchema = object$1({
7990
+ /**
7991
+ * Claude Code permission mode the composer chip showed (Better Coding
7992
+ * Experience); the topic's first dispatched run starts in it.
7993
+ */
7994
+ heteroPermissionMode: _enum(HETERO_PERMISSION_MODES).optional(),
7975
7995
  repos: array(string()).optional(),
7976
7996
  /**
7977
7997
  * Cloud-sandbox placement the composer chose before any topic existed — an
@@ -11014,6 +11034,7 @@ var init_topic$1 = __esmMin((() => {
11014
11034
  init_aiModel();
11015
11035
  init_zod$1();
11016
11036
  init_device();
11037
+ init_heteroPermissionMode();
11017
11038
  topicScheduledRunClaimSchema = object$1({
11018
11039
  claimedAt: string(),
11019
11040
  expiresAt: string(),
@@ -11114,6 +11135,8 @@ var init_topic$1 = __esmMin((() => {
11114
11135
  heteroSessionBindingKeyByWorkingDirectory: record(string(), string()).optional(),
11115
11136
  heteroSessionId: string().optional(),
11116
11137
  heteroSessionIdByWorkingDirectory: record(string(), string()).optional(),
11138
+ heteroPermissionMode: _enum(HETERO_PERMISSION_MODES).optional(),
11139
+ heteroPermissionModeFallback: _enum(["outdatedCli", "root"]).nullable().optional(),
11117
11140
  heteroSpeed: _enum([
11118
11141
  "default",
11119
11142
  "normal",
@@ -12359,6 +12382,7 @@ var init_src$2 = __esmMin((() => {
12359
12382
  init_artboard();
12360
12383
  init_connector();
12361
12384
  init_connectorToolIdentifier();
12385
+ init_heteroPermissionMode();
12362
12386
  init_inboundWebhook();
12363
12387
  init_oauthApp();
12364
12388
  init_chat();
@@ -16292,7 +16316,7 @@ var wrapper_default = import_websocket.default;
16292
16316
 
16293
16317
  //#endregion
16294
16318
  //#region ../../packages/device-gateway-client/src/endpoint.ts
16295
- const isRecord$6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16319
+ const isRecord$7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16296
16320
  const parseHttpUrl = (value) => {
16297
16321
  if (typeof value !== "string") return void 0;
16298
16322
  const trimmed = value.trim();
@@ -16339,7 +16363,7 @@ const toDeviceGatewayWebSocketUrl = (gatewayUrl) => {
16339
16363
  * (including `null` or an empty string) is `invalid`.
16340
16364
  */
16341
16365
  const parseDeviceGatewayDiscovery = (globalConfig) => {
16342
- if (!isRecord$6(globalConfig) || !isRecord$6(globalConfig.serverConfig)) return {
16366
+ if (!isRecord$7(globalConfig) || !isRecord$7(globalConfig.serverConfig)) return {
16343
16367
  reason: "the server response is not a global config",
16344
16368
  status: "failed"
16345
16369
  };
@@ -39091,7 +39115,7 @@ async function validateAcceptanceReport(reportDir) {
39091
39115
  path: issue.path.map((part) => typeof part === "number" ? `[${part}]` : part).join(".").replaceAll(".[", "["),
39092
39116
  message: issue.message
39093
39117
  });
39094
- const rawObject = isRecord$7(raw) ? raw : void 0;
39118
+ const rawObject = isRecord$8(raw) ? raw : void 0;
39095
39119
  return {
39096
39120
  valid: false,
39097
39121
  draft: true,
@@ -59675,13 +59699,13 @@ const execFilePromise$1 = promisify(execFile);
59675
59699
  const nonnegative = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
59676
59700
  /** The native command envelope is distinct from a model response. Fail closed on older CLIs. */
59677
59701
  const parseAntigravityQuota = (payload) => {
59678
- if (!isRecord$7(payload) || payload.status !== "SUCCESS" || !isRecord$7(payload.command) || payload.command.name !== "usage" || !isRecord$7(payload.command.data) || !Array.isArray(payload.command.data.groups)) throw new Error("Antigravity did not return a structured usage command result");
59702
+ if (!isRecord$8(payload) || payload.status !== "SUCCESS" || !isRecord$8(payload.command) || payload.command.name !== "usage" || !isRecord$8(payload.command.data) || !Array.isArray(payload.command.data.groups)) throw new Error("Antigravity did not return a structured usage command result");
59679
59703
  return payload.command.data.groups.flatMap((group) => {
59680
- if (!isRecord$7(group) || !pickString$1(group.name) || !Array.isArray(group.buckets)) return [];
59704
+ if (!isRecord$8(group) || !pickString$1(group.name) || !Array.isArray(group.buckets)) return [];
59681
59705
  const seen = /* @__PURE__ */ new Set();
59682
59706
  return [{
59683
59707
  buckets: group.buckets.flatMap((bucket) => {
59684
- if (!isRecord$7(bucket)) return [];
59708
+ if (!isRecord$8(bucket)) return [];
59685
59709
  const id = pickString$1(bucket.id);
59686
59710
  if (!id || seen.has(id)) return [];
59687
59711
  seen.add(id);
@@ -59741,7 +59765,7 @@ const fetchAntigravityQuota = async (params = {}) => {
59741
59765
  } catch {
59742
59766
  return failure("unsupported_client");
59743
59767
  }
59744
- if (isRecord$7(payload) && payload.status !== "SUCCESS") return failure(typeof payload.error === "string" && isHeterogeneousAgentAuthRequired("antigravity", payload.error) ? "auth_required" : "command_failed");
59768
+ if (isRecord$8(payload) && payload.status !== "SUCCESS") return failure(typeof payload.error === "string" && isHeterogeneousAgentAuthRequired("antigravity", payload.error) ? "auth_required" : "command_failed");
59745
59769
  try {
59746
59770
  return {
59747
59771
  error: null,
@@ -59754,7 +59778,7 @@ const fetchAntigravityQuota = async (params = {}) => {
59754
59778
  return failure("unsupported_client");
59755
59779
  }
59756
59780
  } catch (error) {
59757
- const record = isRecord$7(error) ? error : {};
59781
+ const record = isRecord$8(error) ? error : {};
59758
59782
  const detail = `${record.stderr ?? ""} ${record.message ?? ""}`;
59759
59783
  return failure(record.code === "ENOENT" ? "cli_not_found" : record.killed || record.code === "ETIMEDOUT" ? "timeout" : isHeterogeneousAgentAuthRequired("antigravity", detail) ? "auth_required" : "command_failed");
59760
59784
  }
@@ -60741,7 +60765,7 @@ const lobeHubCliGuideBody = [
60741
60765
  "- **When to use it:** only when the user asks for something that lives in LobeHub rather than in this working directory — saving a document, recalling an earlier conversation, generating an image, or changing your own agent configuration. A request about local files, code or another tool does not need `lh`. Say what you did and where it landed.",
60742
60766
  "- **You already know where you are.** `LOBEHUB_TOPIC_ID` (this conversation) and `LOBEHUB_OPERATION_ID` (this run) are in your environment, and `LOBEHUB_AGENT_ID` (you) and `LOBEHUB_WORKSPACE_ID` (the workspace this conversation belongs to, which scopes every `lh` call) are too whenever the run carries them. They are ordinary environment variables, so every sub-shell, script or tool you spawn inherits them. Pass them straight to commands rather than listing agents or topics to find yourself; if the one you need is empty, say so instead of guessing an id. LobeHub topic ids start with `tpc_` — an id in the user's message without that prefix belongs to something else.",
60743
60767
  "- **Earlier conversations:** read one with `lh topic view <id>`. This run can always read its own conversation and the ones the user names in it (a `tpc_…` id or a `<refer_topic>` tag); for any other, ask the user to name it here.",
60744
- "- **Talking to another conversation:** `lh topic send <tpc_id> -c \"…\"` delivers a message to that conversation and has its agent act on it (queued behind its current turn if it is busy). To hand work to a fresh conversation instead, `lh topic send --new -c \"…\"` opens one for you (or `--agent-id` another agent), optionally on a given machine with `--device <id|local>` and named with `--title`; `lh message send -c \"…\"` is the same thing spelled message-first: without `--topic-id` it opens a new conversation, with `--topic-id <tpc_id>` it sends to that one. Prefer these over `lh agent run` for handing off work. `lh message create` only writes a row — nobody sees or answers it. A message another agent sent you starts with an `<agent_sender>` header; answer it with `lh message reply <message_id> -c \"…\"`, which wakes the sender's conversation. Your ordinary response is not delivered to that agent.",
60768
+ "- **Talking to another conversation:** `lh topic send <tpc_id> -c \"…\"` delivers a message to that conversation and has its agent act on it (queued behind its current turn if it is busy). To hand work to a fresh conversation instead, `lh topic send --new -c \"…\"` opens one for you (or `--agent-id` another agent), optionally on a given machine with `--device <id|local>` and named with `--title`; it is linked to this conversation as its parent (`--parent-topic-id <tpc_id>` names another, `--detach` links none), and `lh topic list --opened-by-me` lists the ones you opened; `lh topic stop <tpc_id>` stops a topic's running turn and `lh topic archive <tpc_id>` archives it; `lh message send -c \"…\"` is the same thing spelled message-first: without `--topic-id` it opens a new conversation, with `--topic-id <tpc_id>` it sends to that one. Prefer these over `lh agent run` for handing off work. `lh message create` only writes a row — nobody sees or answers it. A message another agent sent you starts with an `<agent_sender>` header; answer it with `lh message reply <message_id> -c \"…\"`, which wakes the sender's conversation. Your ordinary response is not delivered to that agent.",
60745
60769
  "- **If `lh` is too old** — `lh man` lacks a command you expect, or `lh` reports an unknown command or option — the shell may have found a stale global install first. When `LOBEHUB_CLI` is set it is the path of the CLI this app ships — run that path instead of `lh` for the rest of the session. Otherwise, or if that one is too old as well, run the latest CLI once without installing it: `pnpm --package @lobehub/cli@latest dlx lh …` (or `npx -y -p @lobehub/cli@latest lh …`). It reads the same environment and saved login as `lh`. If the user asks you to run `lh` this way, do so.",
60746
60770
  "- **Look commands up, do not guess them.** `lh man` lists every command, and `lh man <command>` (e.g. `lh man doc create`) prints the manual for the CLI actually installed here, including exactly which flags that command takes. Many commands offer `--json` for structured output, but not all of them — the manual is what says so, and an invented flag just fails the call.",
60747
60771
  "- **What it reaches:** `lh kb` knowledge bases · `lh doc` documents · `lh file` files · `lh artifact` artifacts · `lh topic` / `lh message` past conversations · `lh agent` agents · `lh task` / `lh project` work · `lh widget` / `lh dashboard` monitoring widgets and dashboards · `lh search` local resources and the web · `lh recall` past messages, topics, goals and pages in a time window · `lh gen` text/image/video/TTS/ASR generation · `lh memory` user memory · `lh notify` notifications to the user · `lh model` / `lh provider` / `lh legacy-plugin` / `lh skill` platform configuration · `lh bot` chat-platform bots.",
@@ -60844,18 +60868,23 @@ const buildHeterogeneousPrompt = (input) => new HeterogeneousPromptEngine(input)
60844
60868
  * always a new session by definition — it exists precisely because native
60845
60869
  * resume failed and the CLI is starting the agent from scratch — so it carries
60846
60870
  * session-scoped context regardless of what the primary attempt got.
60871
+ *
60872
+ * `permissionMode` (Claude Code, Better Coding Experience lab) rides the same
60873
+ * envelope for the same reason: an `lh` that predates it unwraps `content` and
60874
+ * keeps allowing everything, rather than failing on an unknown flag.
60847
60875
  */
60848
60876
  const buildHeteroExecStdinPayload = (params) => {
60849
- const { imageList = [], isNewSession, prompt, resumeFallbackSystemContext, systemContext } = params;
60877
+ const { imageList = [], isNewSession, permissionMode, prompt, resumeFallbackSystemContext, systemContext } = params;
60850
60878
  const blocks = buildHeterogeneousPrompt({
60851
60879
  imageList,
60852
60880
  isNewSession,
60853
60881
  prompt,
60854
60882
  systemContext
60855
60883
  });
60856
- if (resumeFallbackSystemContext !== void 0) return JSON.stringify({
60884
+ if (resumeFallbackSystemContext !== void 0 || permissionMode) return JSON.stringify({
60857
60885
  content: blocks,
60858
- resumeFallback: buildHeterogeneousPrompt({
60886
+ ...permissionMode && { permissionMode },
60887
+ resumeFallback: resumeFallbackSystemContext === void 0 ? void 0 : buildHeterogeneousPrompt({
60859
60888
  imageList,
60860
60889
  isNewSession: true,
60861
60890
  prompt,
@@ -61260,21 +61289,21 @@ const SHELL_POLICY_KEY = "shell_environment_policy";
61260
61289
  */
61261
61290
  const withCodexThreadEnv = (params, provenance) => {
61262
61291
  const config = { ...params.config };
61263
- const policy = isRecord$7(config[SHELL_POLICY_KEY]) ? structuredClone(config[SHELL_POLICY_KEY]) : {};
61292
+ const policy = isRecord$8(config[SHELL_POLICY_KEY]) ? structuredClone(config[SHELL_POLICY_KEY]) : {};
61264
61293
  delete config[SHELL_POLICY_KEY];
61265
61294
  for (const key of Object.keys(config)) {
61266
61295
  if (!key.startsWith(`${SHELL_POLICY_KEY}.`)) continue;
61267
61296
  const path = key.slice(25).split(".");
61268
61297
  let target = policy;
61269
61298
  for (const segment of path.slice(0, -1)) {
61270
- if (!isRecord$7(target[segment])) target[segment] = {};
61299
+ if (!isRecord$8(target[segment])) target[segment] = {};
61271
61300
  target = target[segment];
61272
61301
  }
61273
61302
  target[path.at(-1)] = config[key];
61274
61303
  delete config[key];
61275
61304
  }
61276
61305
  policy.set = {
61277
- ...isRecord$7(policy.set) ? policy.set : {},
61306
+ ...isRecord$8(policy.set) ? policy.set : {},
61278
61307
  ...Object.fromEntries(CODEX_PROVENANCE_KEYS.map((key) => [key, provenance[key] ?? ""]))
61279
61308
  };
61280
61309
  config[SHELL_POLICY_KEY] = policy;
@@ -61582,7 +61611,7 @@ var CodexAppServerClient = class {
61582
61611
  method,
61583
61612
  reject,
61584
61613
  resolve: (result) => resolve(result),
61585
- threadId: isRecord$7(params) ? pickString$1(params.threadId) : void 0,
61614
+ threadId: isRecord$8(params) ? pickString$1(params.threadId) : void 0,
61586
61615
  timeout
61587
61616
  };
61588
61617
  this.pendingRequests.set(key, pending);
@@ -61621,8 +61650,8 @@ var CodexAppServerClient = class {
61621
61650
  }
61622
61651
  }
61623
61652
  getMessageThreadId(generation, message) {
61624
- if (!isRecord$7(message)) return;
61625
- if (isRecord$7(message.params)) {
61653
+ if (!isRecord$8(message)) return;
61654
+ if (isRecord$8(message.params)) {
61626
61655
  const threadId = pickString$1(message.params.threadId);
61627
61656
  if (threadId) return threadId;
61628
61657
  }
@@ -61633,7 +61662,7 @@ var CodexAppServerClient = class {
61633
61662
  }
61634
61663
  routeMessage(generation, message) {
61635
61664
  if (!this.isCurrentGeneration(generation)) return;
61636
- if (!isRecord$7(message)) throw new TypeError("Expected an app-server RPC object");
61665
+ if (!isRecord$8(message)) throw new TypeError("Expected an app-server RPC object");
61637
61666
  const method = pickString$1(message.method);
61638
61667
  const id = message.id;
61639
61668
  if (method) {
@@ -61647,16 +61676,16 @@ var CodexAppServerClient = class {
61647
61676
  if (!pending || pending.generation !== generation) return;
61648
61677
  this.pendingRequests.delete(key);
61649
61678
  clearTimeout(pending.timeout);
61650
- if (isRecord$7(message.error)) pending.reject(new CodexAppServerRpcError(pickString$1(message.error.message) ?? `Codex app-server request failed: ${pending.method}`, typeof message.error.code === "number" ? message.error.code : void 0, message.error.data, pending.method));
61679
+ if (isRecord$8(message.error)) pending.reject(new CodexAppServerRpcError(pickString$1(message.error.message) ?? `Codex app-server request failed: ${pending.method}`, typeof message.error.code === "number" ? message.error.code : void 0, message.error.data, pending.method));
61651
61680
  else pending.resolve(message.result);
61652
61681
  }
61653
61682
  routeNotification(method, params) {
61654
- const threadId = isRecord$7(params) ? pickString$1(params.threadId) : void 0;
61683
+ const threadId = isRecord$8(params) ? pickString$1(params.threadId) : void 0;
61655
61684
  if (!threadId) return;
61656
61685
  for (const handler of this.notificationHandlers.get(threadId) ?? []) handler(method, params);
61657
61686
  }
61658
61687
  async routeServerRequest(generation, id, method, params) {
61659
- const threadId = isRecord$7(params) ? pickString$1(params.threadId) : void 0;
61688
+ const threadId = isRecord$8(params) ? pickString$1(params.threadId) : void 0;
61660
61689
  const handler = (threadId ? this.serverRequestHandlers.get(threadId) : void 0)?.values().next().value;
61661
61690
  let response;
61662
61691
  try {
@@ -63229,7 +63258,7 @@ const codexUserInputArguments = (request) => ({ questions: request.questions.map
63229
63258
  question: question.question
63230
63259
  })) });
63231
63260
  const codexUserInputResponse = (request, answer) => {
63232
- if (answer.cancelled || !isRecord$7(answer.result)) return { answers: {} };
63261
+ if (answer.cancelled || !isRecord$8(answer.result)) return { answers: {} };
63233
63262
  const result = answer.result;
63234
63263
  const entries = request.questions.flatMap((question, index) => {
63235
63264
  const value = result[question.question];
@@ -63709,8 +63738,8 @@ var CodexThreadSession = class {
63709
63738
  await this.emitEvents(events.filter(turnEnded), operationId);
63710
63739
  }
63711
63740
  isCurrentTurnNotification(method, params, activeTurn) {
63712
- if (!isRecord$7(params)) return false;
63713
- const notificationTurnId = method === "turn/started" || method === "turn/completed" ? isRecord$7(params.turn) ? pickString$1(params.turn.id) : void 0 : pickString$1(params.turnId);
63741
+ if (!isRecord$8(params)) return false;
63742
+ const notificationTurnId = method === "turn/started" || method === "turn/completed" ? isRecord$8(params.turn) ? pickString$1(params.turn.id) : void 0 : pickString$1(params.turnId);
63714
63743
  if (method === "turn/started" && !activeTurn.turnId && notificationTurnId) activeTurn.turnId = notificationTurnId;
63715
63744
  return !activeTurn.turnId || !notificationTurnId || activeTurn.turnId === notificationTurnId;
63716
63745
  }
@@ -64183,7 +64212,7 @@ init_config();
64183
64212
  const AMP_IDENTIFIER = "amp";
64184
64213
  const AMP_DOCS_URL = getHeterogeneousAgentConfigOrThrow(AMP_IDENTIFIER).auth.docsUrl;
64185
64214
  const AMP_MISSING_RESULT_MESSAGE = "Amp stream ended without the required terminal `result` event.";
64186
- const isRecord$5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
64215
+ const isRecord$6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
64187
64216
  const stringifyUnknown$2 = (value) => {
64188
64217
  if (typeof value === "string") return value;
64189
64218
  if (value === void 0 || value === null) return "";
@@ -64195,7 +64224,7 @@ const stringifyUnknown$2 = (value) => {
64195
64224
  };
64196
64225
  const toFiniteNumber$4 = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
64197
64226
  const toUsageData$4 = (value) => {
64198
- if (!isRecord$5(value)) return;
64227
+ if (!isRecord$6(value)) return;
64199
64228
  const usage = value;
64200
64229
  const inputCacheMissTokens = toFiniteNumber$4(usage.input_tokens) ?? 0;
64201
64230
  const inputCachedTokens = toFiniteNumber$4(usage.cache_read_input_tokens) ?? 0;
@@ -64231,10 +64260,10 @@ const normalizeToolResult$1 = (value) => {
64231
64260
  return {
64232
64261
  content: value.map((item) => {
64233
64262
  if (typeof item === "string") return item;
64234
- if (!isRecord$5(item)) return stringifyUnknown$2(item);
64263
+ if (!isRecord$6(item)) return stringifyUnknown$2(item);
64235
64264
  if (item.type === "tool_reference" && typeof item.tool_name === "string") return item.tool_name;
64236
64265
  if (item.type === "image") {
64237
- const source = isRecord$5(item.source) ? item.source : void 0;
64266
+ const source = isRecord$6(item.source) ? item.source : void 0;
64238
64267
  const mediaType = typeof source?.media_type === "string" ? source.media_type : "image";
64239
64268
  if (source?.type === "base64" && typeof source.data === "string") images.push({
64240
64269
  data: source.data,
@@ -64261,7 +64290,7 @@ const toToolPayload$2 = (block) => {
64261
64290
  };
64262
64291
  const getErrorText = (value) => {
64263
64292
  if (typeof value === "string" && value.trim()) return value.trim();
64264
- if (!isRecord$5(value)) return;
64293
+ if (!isRecord$6(value)) return;
64265
64294
  for (const key of [
64266
64295
  "message",
64267
64296
  "error",
@@ -64324,7 +64353,7 @@ var AmpAdapter = class {
64324
64353
  toolSubagentById = /* @__PURE__ */ new Map();
64325
64354
  sessionId;
64326
64355
  adapt(raw) {
64327
- if (!isRecord$5(raw)) return [];
64356
+ if (!isRecord$6(raw)) return [];
64328
64357
  this.captureSessionId(raw);
64329
64358
  switch (raw.type) {
64330
64359
  case "system": return this.handleSystem(raw);
@@ -64369,7 +64398,7 @@ var AmpAdapter = class {
64369
64398
  return [this.makeEvent("stream_start", this.getStreamStartData())];
64370
64399
  }
64371
64400
  handleAssistant(raw) {
64372
- const message = isRecord$5(raw.message) ? raw.message : void 0;
64401
+ const message = isRecord$6(raw.message) ? raw.message : void 0;
64373
64402
  const content = Array.isArray(message?.content) ? message.content : typeof message?.content === "string" ? [{
64374
64403
  text: message.content,
64375
64404
  type: "text"
@@ -64379,7 +64408,7 @@ var AmpAdapter = class {
64379
64408
  const events = this.openMainAssistantTurn();
64380
64409
  const turnKey = `main:${this.stepIndex}`;
64381
64410
  for (const block of content) {
64382
- if (!isRecord$5(block)) continue;
64411
+ if (!isRecord$6(block)) continue;
64383
64412
  if (block.type === "thinking" && typeof block.thinking === "string" && block.thinking) {
64384
64413
  events.push(this.makeEvent("stream_chunk", {
64385
64414
  chunkType: "reasoning",
@@ -64397,7 +64426,7 @@ var AmpAdapter = class {
64397
64426
  if (block.type === "tool_use") {
64398
64427
  const tool = toToolPayload$2(block);
64399
64428
  if (!tool) continue;
64400
- if (isRecord$5(block.input)) this.mainToolInputsById.set(tool.id, block.input);
64429
+ if (isRecord$6(block.input)) this.mainToolInputsById.set(tool.id, block.input);
64401
64430
  events.push(...this.emitToolCall(tool, turnKey));
64402
64431
  }
64403
64432
  }
@@ -64420,7 +64449,7 @@ var AmpAdapter = class {
64420
64449
  const turnKey = `subagent:${subagentMessageId}`;
64421
64450
  const events = [];
64422
64451
  for (const block of content) {
64423
- if (!isRecord$5(block)) continue;
64452
+ if (!isRecord$6(block)) continue;
64424
64453
  if (block.type === "thinking" && typeof block.thinking === "string" && block.thinking) {
64425
64454
  events.push(this.makeEvent("stream_chunk", {
64426
64455
  chunkType: "reasoning",
@@ -64454,13 +64483,13 @@ var AmpAdapter = class {
64454
64483
  return events;
64455
64484
  }
64456
64485
  handleUser(raw) {
64457
- const message = isRecord$5(raw.message) ? raw.message : void 0;
64486
+ const message = isRecord$6(raw.message) ? raw.message : void 0;
64458
64487
  if (!Array.isArray(message?.content)) return [];
64459
64488
  const parentToolCallId = typeof raw.parent_tool_use_id === "string" ? raw.parent_tool_use_id : void 0;
64460
64489
  const subagent = parentToolCallId ? { parentToolCallId } : void 0;
64461
64490
  const events = [];
64462
64491
  for (const block of message.content) {
64463
- if (!isRecord$5(block) || block.type !== "tool_result") continue;
64492
+ if (!isRecord$6(block) || block.type !== "tool_result") continue;
64464
64493
  if (typeof block.tool_use_id !== "string") continue;
64465
64494
  const toolCallId = block.tool_use_id;
64466
64495
  const normalized = normalizeToolResult$1(block.content);
@@ -64552,7 +64581,7 @@ var AmpAdapter = class {
64552
64581
  const spawnMetadata = this.buildSpawnMetadata(parentToolCallId);
64553
64582
  if (!spawnMetadata) return;
64554
64583
  const firstEvent = events[0];
64555
- const firstSubagent = isRecord$5(firstEvent.data?.subagent) ? firstEvent.data.subagent : { parentToolCallId };
64584
+ const firstSubagent = isRecord$6(firstEvent.data?.subagent) ? firstEvent.data.subagent : { parentToolCallId };
64556
64585
  firstEvent.data = {
64557
64586
  ...firstEvent.data,
64558
64587
  subagent: {
@@ -64704,7 +64733,7 @@ init_object$1();
64704
64733
  const IDENTIFIER = "antigravity";
64705
64734
  const tokenCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
64706
64735
  const extractUsage = (raw) => {
64707
- if (!isRecord$7(raw)) return;
64736
+ if (!isRecord$8(raw)) return;
64708
64737
  const inputCacheMissTokens = tokenCount(raw.input_tokens);
64709
64738
  const inputCachedTokens = tokenCount(raw.cache_read_tokens);
64710
64739
  const totalOutputTokens = tokenCount(raw.output_tokens);
@@ -64743,14 +64772,14 @@ var AntigravityAdapter = class {
64743
64772
  toolSinceResponse = false;
64744
64773
  usageByStep = /* @__PURE__ */ new Map();
64745
64774
  adapt(raw) {
64746
- if (this.flushed || this.resultReceived || !isRecord$7(raw)) return [];
64775
+ if (this.flushed || this.resultReceived || !isRecord$8(raw)) return [];
64747
64776
  if (raw.event === "init") {
64748
64777
  this.sessionId = pickString$1(raw.conversation_id);
64749
64778
  this.model = pickString$1(toRecord(raw.init)?.model);
64750
64779
  return this.openStream();
64751
64780
  }
64752
- if (raw.event === "result" && isRecord$7(raw.result)) return this.handleResult(raw.result);
64753
- if (raw.event !== "step_update" || !isRecord$7(raw.step_update)) return [];
64781
+ if (raw.event === "result" && isRecord$8(raw.result)) return this.handleResult(raw.result);
64782
+ if (raw.event !== "step_update" || !isRecord$8(raw.step_update)) return [];
64754
64783
  const step = raw.step_update;
64755
64784
  const index = step.step_index;
64756
64785
  if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) return [];
@@ -64776,7 +64805,7 @@ var AntigravityAdapter = class {
64776
64805
  content: step.text_delta
64777
64806
  }));
64778
64807
  }
64779
- } else if (step.step_type === "tool" || isRecord$7(step.subagent_info)) events.push(...this.handleTool(index, step));
64808
+ } else if (step.step_type === "tool" || isRecord$8(step.subagent_info)) events.push(...this.handleTool(index, step));
64780
64809
  if (step.state === "DONE") {
64781
64810
  this.completedSteps.add(index);
64782
64811
  const usage = extractUsage(step.usage);
@@ -66800,7 +66829,7 @@ const synthesizeFileChangePluginState = (item) => {
66800
66829
  linesDeleted: item.linesDeleted ?? 0
66801
66830
  };
66802
66831
  };
66803
- const isRecord$4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
66832
+ const isRecord$5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
66804
66833
  const stringifyUnknown$1 = (value) => {
66805
66834
  if (typeof value === "string") return value;
66806
66835
  if (value === void 0 || value === null) return "";
@@ -66821,7 +66850,7 @@ const getFirstStringFromArray = (value) => {
66821
66850
  const getWebSearchActionQuery = (action) => getRecordString(action, "query")?.trim() || getFirstStringFromArray(action.queries);
66822
66851
  const getWebSearchQuery = (item) => {
66823
66852
  if (typeof item.query === "string" && item.query.trim()) return item.query.trim();
66824
- return isRecord$4(item.action) ? getWebSearchActionQuery(item.action) : void 0;
66853
+ return isRecord$5(item.action) ? getWebSearchActionQuery(item.action) : void 0;
66825
66854
  };
66826
66855
  const synthesizeWebSearchPluginState = (item) => {
66827
66856
  const query = getWebSearchQuery(item);
@@ -66833,7 +66862,7 @@ const synthesizeWebSearchPluginState = (item) => {
66833
66862
  };
66834
66863
  };
66835
66864
  const unwrapMcpResultEnvelope = (value) => {
66836
- if (!isRecord$4(value)) return value;
66865
+ if (!isRecord$5(value)) return value;
66837
66866
  if ("Ok" in value) return value.Ok;
66838
66867
  if ("Err" in value) return value.Err;
66839
66868
  if ("ok" in value) return value.ok;
@@ -66841,7 +66870,7 @@ const unwrapMcpResultEnvelope = (value) => {
66841
66870
  };
66842
66871
  const getMcpContentItemText = (item) => {
66843
66872
  if (typeof item === "string") return item;
66844
- if (!isRecord$4(item)) return stringifyUnknown$1(item);
66873
+ if (!isRecord$5(item)) return stringifyUnknown$1(item);
66845
66874
  const text = getRecordString(item, "text") || getRecordString(item, "content");
66846
66875
  if (text) return text;
66847
66876
  return stringifyUnknown$1(item);
@@ -66849,7 +66878,7 @@ const getMcpContentItemText = (item) => {
66849
66878
  const getMcpResultContent = (item) => {
66850
66879
  const result = unwrapMcpResultEnvelope(item.result);
66851
66880
  if (Array.isArray(result)) return result.map(getMcpContentItemText).filter(Boolean).join("\n\n");
66852
- if (isRecord$4(result)) {
66881
+ if (isRecord$5(result)) {
66853
66882
  if (Array.isArray(result.content)) return result.content.map(getMcpContentItemText).filter(Boolean).join("\n\n");
66854
66883
  const text = getRecordString(result, "text") || getRecordString(result, "output");
66855
66884
  if (text) return text;
@@ -66858,16 +66887,16 @@ const getMcpResultContent = (item) => {
66858
66887
  };
66859
66888
  const getMcpErrorContent = (item) => {
66860
66889
  const error = item.error || unwrapMcpResultEnvelope(item.result);
66861
- if (isRecord$4(error)) return getRecordString(error, "message") || getRecordString(error, "error") || stringifyUnknown$1(error);
66890
+ if (isRecord$5(error)) return getRecordString(error, "message") || getRecordString(error, "error") || stringifyUnknown$1(error);
66862
66891
  return stringifyUnknown$1(error);
66863
66892
  };
66864
66893
  const hasMcpResultError = (item) => {
66865
66894
  if (item.error) return true;
66866
66895
  const result = item.result;
66867
- if (!isRecord$4(result)) return false;
66896
+ if (!isRecord$5(result)) return false;
66868
66897
  if ("Err" in result) return true;
66869
66898
  const ok = unwrapMcpResultEnvelope(result);
66870
- return isRecord$4(ok) && ok.isError === true;
66899
+ return isRecord$5(ok) && ok.isError === true;
66871
66900
  };
66872
66901
  const synthesizeMcpToolPluginState = (item) => ({
66873
66902
  arguments: item.arguments,
@@ -67519,10 +67548,10 @@ var AcpStreamLifecycle = class {
67519
67548
  */
67520
67549
  const acpContentBlockText = (value) => {
67521
67550
  if (typeof value === "string") return value;
67522
- if (!isRecord$7(value)) return "";
67551
+ if (!isRecord$8(value)) return "";
67523
67552
  if (value.type === "text" && typeof value.text === "string") return value.text;
67524
67553
  if (typeof value.content === "string") return value.content;
67525
- if (isRecord$7(value.content)) return acpContentBlockText(value.content);
67554
+ if (isRecord$8(value.content)) return acpContentBlockText(value.content);
67526
67555
  if (typeof value.diff === "string") return value.diff;
67527
67556
  if (typeof value.output === "string") return value.output;
67528
67557
  return "";
@@ -67768,7 +67797,7 @@ var TraeAcpAdapter = class {
67768
67797
  * Returns `undefined` when required fields are missing or invalid.
67769
67798
  */
67770
67799
  toUsageData(usage) {
67771
- if (!isRecord$7(usage)) return;
67800
+ if (!isRecord$8(usage)) return;
67772
67801
  const total = toFiniteNumber$2(usage.totalTokens) ?? toFiniteNumber$2(usage.total_tokens);
67773
67802
  const input = toFiniteNumber$2(usage.inputTokens) ?? toFiniteNumber$2(usage.input_tokens);
67774
67803
  const output = toFiniteNumber$2(usage.outputTokens) ?? toFiniteNumber$2(usage.output_tokens);
@@ -67799,7 +67828,7 @@ var TraeAcpAdapter = class {
67799
67828
  extractUsageFromUsageUpdate(_raw) {}
67800
67829
  /** Extract a USD cost amount from an ACP `cost` object. */
67801
67830
  toCostUsd(cost) {
67802
- if (!isRecord$7(cost)) return;
67831
+ if (!isRecord$8(cost)) return;
67803
67832
  if (cost.currency !== "USD") return;
67804
67833
  const amount = toFiniteNumber$2(cost.amount);
67805
67834
  if (amount === void 0 || amount <= 0) return;
@@ -67856,16 +67885,16 @@ var CopilotAcpAdapter = class extends TraeAcpAdapter {
67856
67885
  init_config();
67857
67886
  const CURSOR_CONFIG = getHeterogeneousAgentConfigOrThrow("cursor");
67858
67887
  const INCOMPLETE_TOOL_MESSAGE = "Cursor ended before the tool call completed.";
67859
- const isRecord$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
67888
+ const isRecord$4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
67860
67889
  const serialize$1 = (value, fallback = "") => typeof value === "string" ? value : value === void 0 ? fallback : JSON.stringify(value);
67861
67890
  const readAssistantText = (message) => {
67862
- if (!isRecord$3(message) || !Array.isArray(message.content)) return "";
67863
- return message.content.filter((block) => isRecord$3(block) && block.type === "text" && typeof block.text === "string").map((block) => block.text).join("");
67891
+ if (!isRecord$4(message) || !Array.isArray(message.content)) return "";
67892
+ return message.content.filter((block) => isRecord$4(block) && block.type === "text" && typeof block.text === "string").map((block) => block.text).join("");
67864
67893
  };
67865
67894
  const readTool = (value) => {
67866
- if (!isRecord$3(value)) return;
67895
+ if (!isRecord$4(value)) return;
67867
67896
  const [apiName, details] = Object.entries(value)[0] ?? [];
67868
- if (!apiName || !isRecord$3(details)) return;
67897
+ if (!apiName || !isRecord$4(details)) return;
67869
67898
  if (apiName === "function") return {
67870
67899
  apiName: typeof details.name === "string" && details.name ? details.name : "function",
67871
67900
  arguments: serialize$1(details.arguments, "{}"),
@@ -67878,7 +67907,7 @@ const readTool = (value) => {
67878
67907
  };
67879
67908
  };
67880
67909
  const readContent = (value) => {
67881
- if (isRecord$3(value)) {
67910
+ if (isRecord$4(value)) {
67882
67911
  if (typeof value.content === "string") return value.content;
67883
67912
  if (typeof value.message === "string") return value.message;
67884
67913
  if (typeof value.error === "string") return value.error;
@@ -67886,7 +67915,7 @@ const readContent = (value) => {
67886
67915
  return serialize$1(value);
67887
67916
  };
67888
67917
  const readResult = (value) => {
67889
- if (!isRecord$3(value)) return {
67918
+ if (!isRecord$4(value)) return {
67890
67919
  content: readContent(value),
67891
67920
  isError: false
67892
67921
  };
@@ -67922,7 +67951,7 @@ var CursorAdapter = class {
67922
67951
  streamOpen = false;
67923
67952
  terminal = false;
67924
67953
  adapt(raw) {
67925
- if (!isRecord$3(raw) || this.terminal) return [];
67954
+ if (!isRecord$4(raw) || this.terminal) return [];
67926
67955
  if (typeof raw.session_id === "string") this.sessionId = raw.session_id;
67927
67956
  if (raw.type === "system" && raw.subtype === "init") {
67928
67957
  if (typeof raw.model === "string") this.model = raw.model;
@@ -68139,7 +68168,7 @@ var DevinAcpAdapter = class extends TraeAcpAdapter {
68139
68168
  });
68140
68169
  }
68141
68170
  extractUsageFromUsageUpdate(raw) {
68142
- const meta = isRecord$7(raw._meta) ? raw._meta : void 0;
68171
+ const meta = isRecord$8(raw._meta) ? raw._meta : void 0;
68143
68172
  if (!meta) return;
68144
68173
  const input = toFiniteNumber$1(meta["cognition.ai/inputTokens"]);
68145
68174
  const output = toFiniteNumber$1(meta["cognition.ai/outputTokens"]);
@@ -68198,7 +68227,7 @@ const GROK_BUILD_IDENTIFIER = "grok-build";
68198
68227
  const GROK_BUILD_AUTH_DOCS_URL = getHeterogeneousAgentConfigOrThrow(GROK_BUILD_IDENTIFIER).auth.docsUrl;
68199
68228
  const finiteNumber$2 = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
68200
68229
  const toUsageData$2 = (usage) => {
68201
- if (!isRecord$7(usage)) return;
68230
+ if (!isRecord$8(usage)) return;
68202
68231
  const value = usage;
68203
68232
  const input = finiteNumber$2(value.inputTokens ?? value.input_tokens);
68204
68233
  const output = finiteNumber$2(value.outputTokens ?? value.output_tokens);
@@ -68247,20 +68276,20 @@ var GrokBuildAdapter = class {
68247
68276
  toolPayloadById = /* @__PURE__ */ new Map();
68248
68277
  toolResultStateById = /* @__PURE__ */ new Map();
68249
68278
  adapt(raw) {
68250
- if (!isRecord$7(raw) || isAcpReplayMessage(raw)) return [];
68279
+ if (!isRecord$8(raw) || isAcpReplayMessage(raw)) return [];
68251
68280
  const eventId = acpEventIdOf(raw);
68252
68281
  if (eventId) {
68253
68282
  if (this.seenEventIds.has(eventId)) return [];
68254
68283
  this.seenEventIds.add(eventId);
68255
68284
  }
68256
- if (isRecord$7(raw.result) && typeof raw.result.sessionId === "string") this.sessionId = raw.result.sessionId;
68257
- if (isRecord$7(raw.error)) {
68285
+ if (isRecord$8(raw.result) && typeof raw.result.sessionId === "string") this.sessionId = raw.result.sessionId;
68286
+ if (isRecord$8(raw.error)) {
68258
68287
  const requestMethod = typeof raw.requestMethod === "string" ? raw.requestMethod : void 0;
68259
68288
  return this.handleRpcError(raw.error, requestMethod);
68260
68289
  }
68261
68290
  if (raw.method === "x.ai/session/prompt_complete") return this.handlePromptComplete(raw.params);
68262
68291
  if (raw.method === "session/update" || raw.method === "x.ai/session_notification" || raw.method === "x.ai/session/update" || raw.method === "_x.ai/session/update") return this.handleNotification(raw.params);
68263
- if (isRecord$7(raw.result) && typeof raw.result.stopReason === "string") return this.handlePromptResult(raw.result);
68292
+ if (isRecord$8(raw.result) && typeof raw.result.stopReason === "string") return this.handlePromptResult(raw.result);
68264
68293
  return [];
68265
68294
  }
68266
68295
  flush() {
@@ -68268,9 +68297,9 @@ var GrokBuildAdapter = class {
68268
68297
  return this.stream.closeStream();
68269
68298
  }
68270
68299
  handleNotification(paramsValue) {
68271
- if (!isRecord$7(paramsValue)) return [];
68300
+ if (!isRecord$8(paramsValue)) return [];
68272
68301
  if (typeof paramsValue.sessionId === "string") this.sessionId = paramsValue.sessionId;
68273
- const update = isRecord$7(paramsValue.update) ? paramsValue.update : void 0;
68302
+ const update = isRecord$8(paramsValue.update) ? paramsValue.update : void 0;
68274
68303
  if (!update || typeof update.sessionUpdate !== "string") return [];
68275
68304
  switch (update.sessionUpdate) {
68276
68305
  case "agent_message_chunk": {
@@ -68361,7 +68390,7 @@ var GrokBuildAdapter = class {
68361
68390
  return state;
68362
68391
  }
68363
68392
  handlePromptComplete(paramsValue) {
68364
- if (!isRecord$7(paramsValue)) return [];
68393
+ if (!isRecord$8(paramsValue)) return [];
68365
68394
  if (typeof paramsValue.sessionId === "string") this.sessionId = paramsValue.sessionId;
68366
68395
  return [];
68367
68396
  }
@@ -68383,7 +68412,7 @@ var GrokBuildAdapter = class {
68383
68412
  handlePromptResult(result) {
68384
68413
  if (this.settled) return [];
68385
68414
  this.settled = true;
68386
- const meta = isRecord$7(result._meta) ? result._meta : void 0;
68415
+ const meta = isRecord$8(result._meta) ? result._meta : void 0;
68387
68416
  const usage = toUsageData$2(meta?.usage ?? meta);
68388
68417
  const model = typeof meta?.modelId === "string" ? meta.modelId : void 0;
68389
68418
  const turnUsage = this.lastTurnUsage?.stepIndex === this.stream.stepIndex ? this.lastTurnUsage.usage : void 0;
@@ -69739,18 +69768,18 @@ const createCodexImageOutputReader = (options) => {
69739
69768
  };
69740
69769
  const readImageOutputs = async (source, startedAt) => {
69741
69770
  const records = parseJsonlRecords(await readFile(source, "utf8"));
69742
- const turnStart = records.findLastIndex((record) => isRecord$7(record) && record.type === "event_msg" && isRecord$7(record.payload) && record.payload.type === "task_started");
69771
+ const turnStart = records.findLastIndex((record) => isRecord$8(record) && record.type === "event_msg" && isRecord$8(record.payload) && record.payload.type === "task_started");
69743
69772
  const timestamp = records[turnStart]?.timestamp;
69744
69773
  const turnStartedAt = typeof timestamp === "string" ? Date.parse(timestamp) : NaN;
69745
69774
  if (!Number.isFinite(turnStartedAt) || turnStartedAt < startedAt) return [];
69746
69775
  const outputs = /* @__PURE__ */ new Map();
69747
69776
  for (const record of records.slice(turnStart + 1)) {
69748
- if (!isRecord$7(record)) continue;
69777
+ if (!isRecord$8(record)) continue;
69749
69778
  const payload = record.payload;
69750
- if (record.type !== "response_item" || !isRecord$7(payload) || payload.type !== "custom_tool_call_output" && payload.type !== "function_call_output" || typeof payload.call_id !== "string" || !Array.isArray(payload.output)) continue;
69779
+ if (record.type !== "response_item" || !isRecord$8(payload) || payload.type !== "custom_tool_call_output" && payload.type !== "function_call_output" || typeof payload.call_id !== "string" || !Array.isArray(payload.output)) continue;
69751
69780
  const images = [];
69752
69781
  for (const block of payload.output) {
69753
- if (!isRecord$7(block) || block.type !== "input_image" || typeof block.image_url !== "string") continue;
69782
+ if (!isRecord$8(block) || block.type !== "input_image" || typeof block.image_url !== "string") continue;
69754
69783
  const match = /^data:(image\/[\w.+-]+);base64,([\s\S]+)$/.exec(block.image_url);
69755
69784
  if (match) images.push({
69756
69785
  data: match[2],
@@ -70249,9 +70278,9 @@ init_object$1();
70249
70278
  const DEFAULT_CANCEL_GRACE_MS = 2e3;
70250
70279
  /** Parse the `options` array of a `session/request_permission` request. */
70251
70280
  const parseAcpPermissionOptions = (params) => {
70252
- const options = isRecord$7(params) ? params.options : void 0;
70281
+ const options = isRecord$8(params) ? params.options : void 0;
70253
70282
  if (!Array.isArray(options)) return [];
70254
- return options.flatMap((value) => isRecord$7(value) ? [value] : []);
70283
+ return options.flatMap((value) => isRecord$8(value) ? [value] : []);
70255
70284
  };
70256
70285
  /**
70257
70286
  * Pick a permission option by ordered preference tiers. Returns the winning
@@ -70534,6 +70563,718 @@ const classifyHeteroProcessFailure = (params) => {
70534
70563
  });
70535
70564
  };
70536
70565
 
70566
+ //#endregion
70567
+ //#region ../../packages/heterogeneous-agents/src/claudeCodePermission/mode.ts
70568
+ /**
70569
+ * The mode Claude Code can actually run in: as root, `bypassPermissions` falls
70570
+ * back to `acceptEdits`. Pure (the caller says whether it runs as root), so the
70571
+ * browser-safe mode report can use it.
70572
+ */
70573
+ const resolveClaudeCodePermissionMode = (mode, isRoot = false) => isRoot && mode === "bypassPermissions" ? {
70574
+ fallback: "root",
70575
+ mode: "acceptEdits"
70576
+ } : { mode };
70577
+
70578
+ //#endregion
70579
+ //#region ../../packages/heterogeneous-agents/src/claudeCodePermission/args.ts
70580
+ /**
70581
+ * Tools pre-approved for a root run with the lab off, where nobody can answer a
70582
+ * prompt. Never with a mode: an allow rule outlives a later switch to a
70583
+ * stricter mode (`set_permission_mode` keeps it), so it would silently approve
70584
+ * what the user then asked to be asked about.
70585
+ */
70586
+ const ROOT_PRE_APPROVED_TOOLS = "Bash,Read,Write,Edit,MultiEdit,WebSearch,mcp__*";
70587
+ /** Claude Code refuses `bypassPermissions` as root (a cloud sandbox). */
70588
+ const isRunningAsRoot = () => process.getuid?.() === 0;
70589
+ /**
70590
+ * Claude Code permission flags for one spawn, shared by every CLI host
70591
+ * (desktop IPC, `lh hetero exec`).
70592
+ *
70593
+ * - No `mode` (Better Coding Experience lab off): every action is allowed, as
70594
+ * before — `bypassPermissions`, or `acceptEdits` with the common tools
70595
+ * pre-approved as root. Nothing asks the host.
70596
+ * - With a `mode`: Claude Code asks the host over stdio
70597
+ * (`--permission-prompt-tool stdio`) whenever the mode wants a decision.
70598
+ * `--allow-dangerously-skip-permissions` only PERMITS a later switch to
70599
+ * `bypassPermissions` (the mode chip, approving a plan with "don't ask
70600
+ * again"): without it Claude Code silently turns that switch into `default`.
70601
+ * Root never gets it, since Claude Code refuses it there; root's stand-in
70602
+ * for `bypassPermissions` is plain `acceptEdits`, asking before commands.
70603
+ * - With a `mode` but no host to answer prompts (`hostPrompts: false`, e.g.
70604
+ * the card bridge failed to start): fail closed. The mode still applies and
70605
+ * print mode denies whatever it would have asked about; it never falls back
70606
+ * to allowing everything.
70607
+ */
70608
+ const buildClaudeCodePermissionArgs = ({ hostPrompts = true, isRoot = isRunningAsRoot(), mode }) => {
70609
+ if (!mode) return isRoot ? [
70610
+ "--permission-mode",
70611
+ "acceptEdits",
70612
+ "--allowed-tools",
70613
+ ROOT_PRE_APPROVED_TOOLS
70614
+ ] : ["--permission-mode", "bypassPermissions"];
70615
+ const resolved = resolveClaudeCodePermissionMode(mode, isRoot);
70616
+ if (!hostPrompts) return ["--permission-mode", resolved.mode];
70617
+ return [
70618
+ "--permission-mode",
70619
+ resolved.mode,
70620
+ "--permission-prompt-tool",
70621
+ "stdio",
70622
+ ...isRoot ? [] : ["--allow-dangerously-skip-permissions"]
70623
+ ];
70624
+ };
70625
+
70626
+ //#endregion
70627
+ //#region ../../packages/heterogeneous-agents/src/claudeCodePermission/modeReport.ts
70628
+ init_src$2();
70629
+ /** `step_complete` phase carrying the mode Claude Code reports it is in. */
70630
+ const PERMISSION_MODE_PHASE = "permission_mode";
70631
+ /**
70632
+ * The permission mode a Claude Code record reports: `system:init` at each
70633
+ * turn, `system:status` after a switch (the host's, or Claude Code's own when
70634
+ * a plan is approved). A mode not offered here (`dontAsk`) reports nothing.
70635
+ */
70636
+ const readClaudeCodePermissionMode = (message) => {
70637
+ if (typeof message !== "object" || message === null) return;
70638
+ const record = message;
70639
+ if (record.type !== "system" || record.subtype !== "init" && record.subtype !== "status") return;
70640
+ if (record.parent_tool_use_id) return;
70641
+ return isHeteroPermissionMode(record.permissionMode) ? record.permissionMode : void 0;
70642
+ };
70643
+ /**
70644
+ * Turns Claude Code's mode reports into `step_complete` events, one per
70645
+ * change. Rides `step_complete` like other advisory phases, so the gateway
70646
+ * needs no change and consumers that do not know it ignore it.
70647
+ */
70648
+ var PermissionModeReporter = class {
70649
+ last;
70650
+ /** Why the session started outside the picked mode; dropped once it leaves that mode. */
70651
+ fallback;
70652
+ constructor(operationId, fallback) {
70653
+ this.operationId = operationId;
70654
+ this.fallback = fallback;
70655
+ }
70656
+ /**
70657
+ * The user switched the running session to `mode`. Reports from now on
70658
+ * explain against that pick: as root a bypass pick runs as `acceptEdits`
70659
+ * with the root fallback, so the topic keeps the pick instead of taking
70660
+ * `acceptEdits`. The next report is emitted even if the mode is unchanged.
70661
+ */
70662
+ requested(mode, isRoot) {
70663
+ this.fallback = resolveClaudeCodePermissionMode(mode, isRoot).fallback;
70664
+ this.last = void 0;
70665
+ }
70666
+ /** The event for a record that reports a new mode, else undefined. */
70667
+ observe(message, stepIndex = 0) {
70668
+ const mode = readClaudeCodePermissionMode(message);
70669
+ if (!mode || mode === this.last) return;
70670
+ this.last = mode;
70671
+ if (this.fallback === "root" && mode !== "acceptEdits") this.fallback = void 0;
70672
+ return {
70673
+ data: {
70674
+ fallback: this.fallback ?? null,
70675
+ permissionMode: mode,
70676
+ phase: PERMISSION_MODE_PHASE
70677
+ },
70678
+ operationId: this.operationId,
70679
+ stepIndex,
70680
+ timestamp: Date.now(),
70681
+ type: "step_complete"
70682
+ };
70683
+ }
70684
+ };
70685
+
70686
+ //#endregion
70687
+ //#region ../../packages/heterogeneous-agents/src/claudeCodePermission/request.ts
70688
+ const CLAUDE_CODE_PERMISSION_OPTION = {
70689
+ allow: "allow",
70690
+ allowSession: "allow_session",
70691
+ approveAcceptEdits: "approve_accept_edits",
70692
+ approveBypass: "approve_bypass",
70693
+ approveDefault: "approve_default",
70694
+ deny: "deny",
70695
+ keepPlanning: "keep_planning"
70696
+ };
70697
+ /** Answer key for the note a user adds to a denial or to "keep planning". */
70698
+ const CLAUDE_CODE_PERMISSION_NOTE_KEY = "__note";
70699
+ const MAX_PREVIEW_CHARS = 2e3;
70700
+ /** Review surfaces accept at most this much question text. */
70701
+ const MAX_QUESTION_CHARS = 4e3;
70702
+ const OPTION_LABELS = {
70703
+ allow: "Allow",
70704
+ allow_session: "Always allow in this session",
70705
+ approve_accept_edits: "Approve and auto-accept edits",
70706
+ approve_bypass: "Approve and don't ask again",
70707
+ approve_default: "Approve and ask before each edit",
70708
+ deny: "Deny",
70709
+ keep_planning: "Keep planning"
70710
+ };
70711
+ const isRecord$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
70712
+ const optionalString = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
70713
+ const cut = (text, max) => text.length > max ? `${text.slice(0, max - 1)}…` : text;
70714
+ /** The `can_use_tool` request in a parsed stdout line, if it is one. */
70715
+ const parseClaudeCodePermissionRequest = (message) => {
70716
+ if (!isRecord$3(message) || message.type !== "control_request") return;
70717
+ const request = message.request;
70718
+ if (!isRecord$3(request) || request.subtype !== "can_use_tool") return;
70719
+ if (typeof message.request_id !== "string" || typeof request.tool_name !== "string") return;
70720
+ return fromCanUseTool(message.request_id, request.tool_name, request.input, {
70721
+ blockedPath: request.blocked_path,
70722
+ decisionReason: request.decision_reason,
70723
+ description: request.description,
70724
+ displayName: request.display_name,
70725
+ suggestions: request.permission_suggestions,
70726
+ title: request.title,
70727
+ toolUseId: request.tool_use_id
70728
+ });
70729
+ };
70730
+ /** The same request as the SDK's `canUseTool` callback receives it. */
70731
+ const fromCanUseTool = (requestId, toolName, input, extra) => ({
70732
+ blockedPath: optionalString(extra.blockedPath),
70733
+ decisionReason: optionalString(extra.decisionReason),
70734
+ description: optionalString(extra.description),
70735
+ displayName: optionalString(extra.displayName),
70736
+ input: isRecord$3(input) ? input : {},
70737
+ requestId,
70738
+ suggestions: Array.isArray(extra.suggestions) ? extra.suggestions.filter((entry) => isRecord$3(entry) && typeof entry.type === "string") : void 0,
70739
+ title: optionalString(extra.title),
70740
+ toolName,
70741
+ toolUseId: optionalString(extra.toolUseId)
70742
+ });
70743
+ const classifyClaudeCodePermission = (toolName) => toolName === "ExitPlanMode" ? "exitPlan" : toolName === "EnterPlanMode" ? "enterPlan" : "tool";
70744
+ const previewInput = (input) => Object.fromEntries(Object.entries(input).map(([key, value]) => [key, typeof value === "string" ? cut(value, MAX_PREVIEW_CHARS) : value]));
70745
+ const readAllowedPrompts = (input) => {
70746
+ if (!Array.isArray(input.allowedPrompts)) return;
70747
+ const prompts = input.allowedPrompts.flatMap((entry) => isRecord$3(entry) && typeof entry.prompt === "string" ? [{
70748
+ prompt: entry.prompt,
70749
+ tool: typeof entry.tool === "string" ? entry.tool : "Bash"
70750
+ }] : []);
70751
+ return prompts.length > 0 ? prompts : void 0;
70752
+ };
70753
+ const optionsFor = (kind, request, isRoot) => {
70754
+ const o = CLAUDE_CODE_PERMISSION_OPTION;
70755
+ if (kind === "exitPlan") return [
70756
+ ...isRoot ? [] : [o.approveBypass],
70757
+ o.approveAcceptEdits,
70758
+ o.approveDefault,
70759
+ o.keepPlanning
70760
+ ];
70761
+ if (kind === "enterPlan") return [o.allow, o.deny];
70762
+ return request.suggestions?.length ? [
70763
+ o.allow,
70764
+ o.allowSession,
70765
+ o.deny
70766
+ ] : [o.allow, o.deny];
70767
+ };
70768
+ /** Stable card id per request, distinct from the tool the request is about. */
70769
+ const claudeCodePermissionToolCallId = (requestId) => `cc-permission-${requestId}`;
70770
+ /**
70771
+ * The intervention a request raises: the AskUserQuestion-shaped question every
70772
+ * surface (card, durable review, notification) understands, plus the detail
70773
+ * the dedicated Claude Code card renders.
70774
+ */
70775
+ const buildClaudeCodePermissionIntervention = (request, { isRoot = false } = {}) => {
70776
+ const kind = classifyClaudeCodePermission(request.toolName);
70777
+ const options = optionsFor(kind, request, isRoot);
70778
+ const plan = kind === "exitPlan" ? optionalString(request.input.plan) : void 0;
70779
+ const toolLabel = request.displayName ?? request.toolName;
70780
+ const question = kind === "exitPlan" ? plan ?? "Claude has finished planning." : kind === "enterPlan" ? "Claude wants to enter plan mode." : request.title ?? `Claude wants to use ${toolLabel}.`;
70781
+ return {
70782
+ arguments: {
70783
+ claudeCodePermission: {
70784
+ allowedPrompts: kind === "exitPlan" ? readAllowedPrompts(request.input) : void 0,
70785
+ blockedPath: request.blockedPath,
70786
+ decisionReason: request.decisionReason,
70787
+ description: request.description,
70788
+ displayName: request.displayName,
70789
+ input: kind === "tool" ? previewInput(request.input) : void 0,
70790
+ kind,
70791
+ options,
70792
+ plan,
70793
+ title: request.title,
70794
+ toolName: request.toolName
70795
+ },
70796
+ questions: [{
70797
+ header: kind === "exitPlan" ? "Review plan" : cut(toolLabel, 200),
70798
+ multiSelect: false,
70799
+ options: options.map((id) => ({
70800
+ id,
70801
+ label: OPTION_LABELS[id]
70802
+ })),
70803
+ question: cut(question, MAX_QUESTION_CHARS)
70804
+ }]
70805
+ },
70806
+ interactionKind: kind === "exitPlan" ? "plan" : "permission",
70807
+ toolCallId: claudeCodePermissionToolCallId(request.requestId)
70808
+ };
70809
+ };
70810
+ const readAnswer = (answer, options) => {
70811
+ if (answer.cancelled || !isRecord$3(answer.result)) return {};
70812
+ const optionId = Object.entries(answer.result).filter(([key]) => key !== CLAUDE_CODE_PERMISSION_NOTE_KEY).flatMap(([, value]) => Array.isArray(value) ? value : [value]).find((value) => typeof value === "string" && options.includes(value));
70813
+ const note = answer.result[CLAUDE_CODE_PERMISSION_NOTE_KEY];
70814
+ return {
70815
+ note: typeof note === "string" && note.trim() ? note.trim() : void 0,
70816
+ optionId
70817
+ };
70818
+ };
70819
+ const setMode = (mode) => ({
70820
+ destination: "session",
70821
+ mode,
70822
+ type: "setMode"
70823
+ });
70824
+ /**
70825
+ * Turn the user's answer into Claude Code's decision.
70826
+ *
70827
+ * - "Always allow in this session" applies Claude Code's own suggestions, kept
70828
+ * to this session whatever destination it proposed.
70829
+ * - A denial without a note interrupts the turn, like "No" in Claude Code's
70830
+ * terminal: the user says what to do next. With a note Claude carries on
70831
+ * with it. "Keep planning" works the same way.
70832
+ * - No answer (the run stopped, the card was dismissed) denies and interrupts.
70833
+ */
70834
+ const resolveClaudeCodePermissionDecision = (request, answer, { isRoot = false } = {}) => {
70835
+ const o = CLAUDE_CODE_PERMISSION_OPTION;
70836
+ const { note, optionId } = readAnswer(answer, optionsFor(classifyClaudeCodePermission(request.toolName), request, isRoot));
70837
+ const allow = (updatedPermissions) => ({
70838
+ behavior: "allow",
70839
+ updatedInput: request.input,
70840
+ ...updatedPermissions?.length ? { updatedPermissions } : {}
70841
+ });
70842
+ switch (optionId) {
70843
+ case o.allow: return allow();
70844
+ case o.allowSession: return allow(request.suggestions?.map((suggestion) => ({
70845
+ ...suggestion,
70846
+ destination: "session"
70847
+ })));
70848
+ case o.approveBypass: return allow([setMode("bypassPermissions")]);
70849
+ case o.approveAcceptEdits: return allow([setMode("acceptEdits")]);
70850
+ case o.approveDefault: return allow([setMode("default")]);
70851
+ case o.keepPlanning: return note ? {
70852
+ behavior: "deny",
70853
+ message: `The user wants to keep planning. Revise the plan: ${note}`
70854
+ } : {
70855
+ behavior: "deny",
70856
+ interrupt: true,
70857
+ message: "The user wants to keep planning and will say what to change."
70858
+ };
70859
+ case o.deny: return note ? {
70860
+ behavior: "deny",
70861
+ message: `The user denied this: ${note}`
70862
+ } : {
70863
+ behavior: "deny",
70864
+ interrupt: true,
70865
+ message: "The user denied this."
70866
+ };
70867
+ default: return {
70868
+ behavior: "deny",
70869
+ interrupt: true,
70870
+ message: "The user stopped the run before answering."
70871
+ };
70872
+ }
70873
+ };
70874
+
70875
+ //#endregion
70876
+ //#region ../../packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.ts
70877
+ /**
70878
+ * How long the session may sit between turns with no stdout before stdin is
70879
+ * closed anyway. Background tasks that stream (sub-agents) keep resetting it;
70880
+ * a silent one (a long background shell) would otherwise hold the process open
70881
+ * forever, since Claude Code's own wind-down ceiling only starts once stdin is
70882
+ * closed.
70883
+ */
70884
+ const DEFAULT_IDLE_CLOSE_MS = 1800 * 1e3;
70885
+ /**
70886
+ * How long a task that ends between turns may wait for the main-agent turn its
70887
+ * notification wakes. Claude Code opens that turn within milliseconds; the
70888
+ * grace only bounds an end that unexpectedly wakes nothing. A stopped task
70889
+ * never wakes one, so it does not wait (see `observeSystem`).
70890
+ */
70891
+ const DEFAULT_WAKE_UP_GRACE_MS = 30 * 1e3;
70892
+ const TERMINAL_TASK_STATUSES = new Set([
70893
+ "completed",
70894
+ "failed",
70895
+ "killed"
70896
+ ]);
70897
+ const readIdleCloseMs = () => {
70898
+ const value = Number(process.env.LOBE_CLAUDE_CODE_LIVE_INPUT_IDLE_MS);
70899
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_IDLE_CLOSE_MS;
70900
+ };
70901
+ /** Stamp a stream-json `user` line with the uuid Claude Code replays it under. */
70902
+ const withUserMessageUuid = (stdinLine, uuid) => `${JSON.stringify({
70903
+ ...JSON.parse(stdinLine),
70904
+ uuid
70905
+ })}\n`;
70906
+ const isAbortedResult = (message) => !!message.is_error && String(message.terminal_reason ?? "").startsWith("aborted");
70907
+ /**
70908
+ * The runtime end a live session (stdin kept open, see `ClaudeCodeLiveInput`)
70909
+ * reports once, at process exit: complete, or interrupted when its last turn
70910
+ * was stopped. Only a clean exit after a finished turn ends the run here — a
70911
+ * crash after a result is a failure, not a completion. Print mode exits 1 when
70912
+ * its last turn was an error result, which an interrupt is.
70913
+ *
70914
+ * Shared by every host of a live CLI (`lh hetero exec`, the desktop's local
70915
+ * spawn) so they end a run by the same rule.
70916
+ *
70917
+ * @returns the `completeRuntime` data, or undefined when the run does not end here
70918
+ */
70919
+ const resolveClaudeCodeLiveRuntimeEnd = (lastTurn, exit) => {
70920
+ if (!lastTurn || exit.killedByHost || exit.sawError) return;
70921
+ if (!(exit.code === 0 || lastTurn.aborted && exit.code === 1 && exit.signal === null)) return;
70922
+ return {
70923
+ ...lastTurn.aborted ? {
70924
+ kind: "aborted",
70925
+ reason: "interrupted",
70926
+ terminalReason: lastTurn.terminalReason
70927
+ } : { reason: "complete" },
70928
+ transport: "cli-live"
70929
+ };
70930
+ };
70931
+ /**
70932
+ * Key of host-only metadata on a control request (e.g. the mode the user
70933
+ * picked, where the request carries the mode Claude Code can run). Stripped
70934
+ * before the request reaches Claude Code; handed to `onControlRequestSent`.
70935
+ */
70936
+ const CONTROL_REQUEST_HOST_META = "__host";
70937
+ const SESSION_ENDED = {
70938
+ error: "The session ended before answering",
70939
+ subtype: "error"
70940
+ };
70941
+ /**
70942
+ * Keeps a Claude Code print-mode (`-p --input-format stream-json`) stdin open
70943
+ * for as long as the run can still use input, so the host can deliver a user
70944
+ * message into the running session or interrupt only the current turn.
70945
+ *
70946
+ * Closing stdin early is not neutral: once input is closed, print mode stops
70947
+ * waiting for background tasks after `CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`
70948
+ * (10 minutes by default) and kills them. So stdin stays open until the session
70949
+ * is between turns with no running task and no delivered message it has not
70950
+ * picked up yet.
70951
+ *
70952
+ * A task that ends between turns does not make the session idle: its
70953
+ * notification wakes the main agent for a turn, and that turn can start a new
70954
+ * task or resume a finished sub-agent with `SendMessage`. Closing at the end
70955
+ * would put those tasks under the ceiling, so the decision waits for the
70956
+ * wake-up turn's result.
70957
+ *
70958
+ * Requires `--replay-user-messages`: the replayed `uuid` is how a delivered
70959
+ * message is known to have been picked up.
70960
+ */
70961
+ var ClaudeCodeLiveInput = class {
70962
+ activeTasks = /* @__PURE__ */ new Set();
70963
+ closed = false;
70964
+ idleTimer;
70965
+ idleCloseMs;
70966
+ lastOutcome;
70967
+ lineBuffer = "";
70968
+ listeners = /* @__PURE__ */ new Set();
70969
+ sentListeners = /* @__PURE__ */ new Set();
70970
+ pendingControl = /* @__PURE__ */ new Map();
70971
+ turnOpen = true;
70972
+ unconsumed = /* @__PURE__ */ new Set();
70973
+ wakeUpGraceMs;
70974
+ wakeUpTimer;
70975
+ constructor(stdin, options = {}) {
70976
+ this.stdin = stdin;
70977
+ this.idleCloseMs = options.idleCloseMs ?? readIdleCloseMs();
70978
+ this.wakeUpGraceMs = options.wakeUpGraceMs ?? DEFAULT_WAKE_UP_GRACE_MS;
70979
+ stdin.on("error", () => this.markClosed());
70980
+ stdin.on("close", () => this.markClosed());
70981
+ }
70982
+ get isOpen() {
70983
+ return !this.closed;
70984
+ }
70985
+ /** How the last turn ended; undefined while the session has not finished one. */
70986
+ get lastTurn() {
70987
+ return this.lastOutcome;
70988
+ }
70989
+ /**
70990
+ * Deliver a `user` line into the session; it stays pending until Claude Code
70991
+ * replays it. Returns false once input has closed.
70992
+ */
70993
+ send(stdinLine, uuid = randomUUID()) {
70994
+ if (this.closed) return false;
70995
+ this.unconsumed.add(uuid);
70996
+ this.clearIdleTimer();
70997
+ this.stdin.write(withUserMessageUuid(stdinLine, uuid));
70998
+ return true;
70999
+ }
71000
+ /** Stop the current turn without ending the process. Returns false once input has closed. */
71001
+ interrupt() {
71002
+ return !!this.sendControlRequest({ subtype: "interrupt" });
71003
+ }
71004
+ /**
71005
+ * Write a stream-json `control_request` into the session — the protocol
71006
+ * Claude Code's SDK uses to steer a live process (interrupt, stop a task,
71007
+ * change the model…).
71008
+ *
71009
+ * @returns the request and its answer, or `undefined` once input has closed
71010
+ */
71011
+ sendControlRequest(request) {
71012
+ if (this.closed) return;
71013
+ const { [CONTROL_REQUEST_HOST_META]: meta, ...wire } = request;
71014
+ const requestId = randomUUID();
71015
+ const response = new Promise((resolve) => {
71016
+ this.pendingControl.set(requestId, resolve);
71017
+ });
71018
+ this.stdin.write(`${JSON.stringify({
71019
+ request: wire,
71020
+ request_id: requestId,
71021
+ type: "control_request"
71022
+ })}\n`);
71023
+ for (const listener of this.sentListeners) listener(wire, meta);
71024
+ return {
71025
+ requestId,
71026
+ response
71027
+ };
71028
+ }
71029
+ /** Watch every control request the host writes, with its host-only metadata. */
71030
+ onControlRequestSent(listener) {
71031
+ this.sentListeners.add(listener);
71032
+ return () => this.sentListeners.delete(listener);
71033
+ }
71034
+ /**
71035
+ * Answer a control request Claude Code sent the host (`can_use_tool` under
71036
+ * `--permission-prompt-tool stdio`). Returns false once input has closed.
71037
+ */
71038
+ respondToControlRequest(requestId, response) {
71039
+ if (this.closed) return false;
71040
+ this.stdin.write(`${JSON.stringify({
71041
+ response: {
71042
+ request_id: requestId,
71043
+ response,
71044
+ subtype: "success"
71045
+ },
71046
+ type: "control_response"
71047
+ })}\n`);
71048
+ return true;
71049
+ }
71050
+ /** Watch every record Claude Code writes, as `observe` parses it. */
71051
+ subscribe(listener) {
71052
+ this.listeners.add(listener);
71053
+ return () => this.listeners.delete(listener);
71054
+ }
71055
+ /** Feed raw stdout so the session state tracks what Claude Code reports. */
71056
+ observe(chunk) {
71057
+ this.lineBuffer += chunk.toString();
71058
+ const lines = this.lineBuffer.split("\n");
71059
+ this.lineBuffer = lines.pop() ?? "";
71060
+ for (const line of lines) {
71061
+ if (!line.trim()) continue;
71062
+ try {
71063
+ const message = JSON.parse(line);
71064
+ if (message?.type === "result") this.lastOutcome = {
71065
+ aborted: isAbortedResult(message),
71066
+ terminalReason: message.terminal_reason
71067
+ };
71068
+ this.observeMessage(message);
71069
+ for (const listener of this.listeners) listener(message);
71070
+ } catch {}
71071
+ }
71072
+ if (this.closed) return;
71073
+ if (this.turnOpen) this.clearIdleTimer();
71074
+ else this.armIdleTimer();
71075
+ }
71076
+ /**
71077
+ * stdout ended: take a final record left without a trailing newline, then
71078
+ * close input, since nothing can read it any more.
71079
+ */
71080
+ finish() {
71081
+ if (this.lineBuffer.trim()) this.observe("\n");
71082
+ this.close();
71083
+ for (const resolve of this.pendingControl.values()) resolve(SESSION_ENDED);
71084
+ this.pendingControl.clear();
71085
+ }
71086
+ close() {
71087
+ if (this.closed) return;
71088
+ this.markClosed();
71089
+ this.stdin.end();
71090
+ }
71091
+ observeMessage(message) {
71092
+ if (message?.type === "control_response") {
71093
+ this.observeControlResponse(message.response);
71094
+ return;
71095
+ }
71096
+ if (message?.parent_tool_use_id && message.type !== "system") return;
71097
+ switch (message?.type) {
71098
+ case "user":
71099
+ if (message.isReplay && typeof message.uuid === "string") {
71100
+ this.unconsumed.delete(message.uuid);
71101
+ this.openTurn();
71102
+ }
71103
+ return;
71104
+ case "assistant":
71105
+ case "stream_event":
71106
+ this.openTurn();
71107
+ return;
71108
+ case "system":
71109
+ this.observeSystem(message);
71110
+ return;
71111
+ case "result":
71112
+ this.turnOpen = false;
71113
+ if (message.is_error && !isAbortedResult(message)) this.close();
71114
+ else this.closeIfIdle();
71115
+ return;
71116
+ }
71117
+ }
71118
+ /** Answers arrive even after input closed, for requests written before. */
71119
+ observeControlResponse(response) {
71120
+ const requestId = response?.request_id;
71121
+ const resolve = typeof requestId === "string" && this.pendingControl.get(requestId);
71122
+ if (!resolve) return;
71123
+ this.pendingControl.delete(requestId);
71124
+ resolve(response.subtype === "success" ? {
71125
+ response: response.response ?? void 0,
71126
+ subtype: "success"
71127
+ } : {
71128
+ error: String(response.error ?? "Control request failed"),
71129
+ subtype: "error"
71130
+ });
71131
+ }
71132
+ observeSystem(message) {
71133
+ if (message.subtype === "init") {
71134
+ this.openTurn();
71135
+ return;
71136
+ }
71137
+ if (message.subtype === "task_started" && message.task_id) {
71138
+ this.activeTasks.add(message.task_id);
71139
+ return;
71140
+ }
71141
+ if ((message.subtype === "task_notification" || message.subtype === "task_updated" && TERMINAL_TASK_STATUSES.has(message.patch?.status)) && message.task_id) {
71142
+ this.activeTasks.delete(message.task_id);
71143
+ if (message.patch?.status === "killed" || message.subtype === "task_notification" && message.status === "stopped") this.closeIfIdle();
71144
+ else this.awaitWakeUpTurn();
71145
+ }
71146
+ }
71147
+ /** A newer turn supersedes how the last one ended until it reports its own. */
71148
+ openTurn() {
71149
+ this.turnOpen = true;
71150
+ this.lastOutcome = void 0;
71151
+ this.clearWakeUpTimer();
71152
+ }
71153
+ closeIfIdle() {
71154
+ if (this.turnOpen || this.activeTasks.size > 0 || this.unconsumed.size > 0) return;
71155
+ this.close();
71156
+ }
71157
+ /**
71158
+ * The last task ended between turns. The turn its notification wakes decides
71159
+ * at its result; close here only if no turn opens within the grace.
71160
+ */
71161
+ awaitWakeUpTurn() {
71162
+ if (this.closed) return;
71163
+ if (this.turnOpen || this.activeTasks.size > 0 || this.unconsumed.size > 0) return;
71164
+ this.clearWakeUpTimer();
71165
+ this.wakeUpTimer = setTimeout(() => this.closeIfIdle(), this.wakeUpGraceMs);
71166
+ this.wakeUpTimer.unref?.();
71167
+ }
71168
+ clearWakeUpTimer() {
71169
+ if (!this.wakeUpTimer) return;
71170
+ clearTimeout(this.wakeUpTimer);
71171
+ this.wakeUpTimer = void 0;
71172
+ }
71173
+ armIdleTimer() {
71174
+ this.clearIdleTimer();
71175
+ this.idleTimer = setTimeout(() => this.close(), this.idleCloseMs);
71176
+ this.idleTimer.unref?.();
71177
+ }
71178
+ clearIdleTimer() {
71179
+ if (!this.idleTimer) return;
71180
+ clearTimeout(this.idleTimer);
71181
+ this.idleTimer = void 0;
71182
+ }
71183
+ markClosed() {
71184
+ this.closed = true;
71185
+ this.clearIdleTimer();
71186
+ this.clearWakeUpTimer();
71187
+ }
71188
+ };
71189
+
71190
+ //#endregion
71191
+ //#region ../../packages/heterogeneous-agents/src/claudeCodePermission/responder.ts
71192
+ /**
71193
+ * Ask through an `AskUserBridge` without a deadline: a permission request waits
71194
+ * for the user however long it takes (stopping the run ends it).
71195
+ */
71196
+ const askThroughBridge = (bridge) => (intervention) => bridge.pending(intervention, { timeoutMs: Number.POSITIVE_INFINITY });
71197
+ /**
71198
+ * Answer one permission request: raise its card, wait, and turn the answer into
71199
+ * Claude Code's decision. Shared by the stdio responder and the SDK's
71200
+ * `canUseTool`, so both paths decide alike.
71201
+ */
71202
+ const decideClaudeCodePermission = async (request, ask, { isRoot = false } = {}) => {
71203
+ const intervention = buildClaudeCodePermissionIntervention(request, { isRoot });
71204
+ let answer;
71205
+ try {
71206
+ answer = await ask(intervention);
71207
+ } catch {
71208
+ answer = {
71209
+ cancelled: true,
71210
+ cancelReason: "session_ended"
71211
+ };
71212
+ }
71213
+ return resolveClaudeCodePermissionDecision(request, answer, { isRoot });
71214
+ };
71215
+ /**
71216
+ * Host side of `--permission-prompt-tool stdio`: answers every `can_use_tool`
71217
+ * control request Claude Code writes to stdout with a `control_response` on
71218
+ * stdin, after the user decides on a card.
71219
+ *
71220
+ * @returns a detach function
71221
+ */
71222
+ const attachClaudeCodePermissionResponder = (transport, { ask, cancel, isRoot = false }) => transport.subscribe((message) => {
71223
+ const record = message;
71224
+ if (record?.type === "control_cancel_request" && typeof record.request_id === "string") {
71225
+ cancel?.(claudeCodePermissionToolCallId(record.request_id));
71226
+ return;
71227
+ }
71228
+ const request = parseClaudeCodePermissionRequest(message);
71229
+ if (!request) return;
71230
+ decideClaudeCodePermission(request, ask, { isRoot }).then((decision) => {
71231
+ transport.respondToControlRequest(request.requestId, {
71232
+ ...decision,
71233
+ ...request.toolUseId && { toolUseID: request.toolUseId }
71234
+ });
71235
+ });
71236
+ });
71237
+ /**
71238
+ * The `set_permission_mode` control request for a mode the user picked mid-run,
71239
+ * adjusted to what Claude Code can run (root has no `bypassPermissions`).
71240
+ */
71241
+ const buildSetPermissionModeRequest = (mode, isRoot) => ({
71242
+ [CONTROL_REQUEST_HOST_META]: { requestedMode: mode },
71243
+ mode: resolveClaudeCodePermissionMode(mode, isRoot).mode,
71244
+ subtype: "set_permission_mode"
71245
+ });
71246
+ /** How long Claude Code gets to confirm a mode switch. */
71247
+ const SET_PERMISSION_MODE_TIMEOUT_MS = 1e4;
71248
+ /**
71249
+ * Switch a live CLI session's mode: write `set_permission_mode` into its stdin
71250
+ * and wait for Claude Code to confirm. The mode report follows on stdout.
71251
+ *
71252
+ * @param send Writes a control request; `undefined` once input has closed.
71253
+ * @returns the mode Claude Code switched to
71254
+ * @throws When input is closed, Claude Code refuses or never answers, or `signal` aborts.
71255
+ */
71256
+ const setClaudeCodePermissionMode = async (send, mode, { isRoot, signal, timeoutMs = SET_PERMISSION_MODE_TIMEOUT_MS } = {}) => {
71257
+ const request = buildSetPermissionModeRequest(mode, isRoot);
71258
+ const sent = send(request);
71259
+ if (!sent) throw new Error("The Claude Code session no longer takes input");
71260
+ let timer;
71261
+ let onAbort;
71262
+ const cutOff = new Promise((_, reject) => {
71263
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error("Claude Code did not confirm the mode switch in time")), timeoutMs);
71264
+ onAbort = () => reject(/* @__PURE__ */ new Error("The run ended before Claude Code confirmed the mode"));
71265
+ if (signal?.aborted) onAbort();
71266
+ else signal?.addEventListener("abort", onAbort, { once: true });
71267
+ });
71268
+ try {
71269
+ const answer = await Promise.race([sent.response, cutOff]);
71270
+ if (answer.subtype === "error") throw new Error(answer.error);
71271
+ return request.mode;
71272
+ } finally {
71273
+ clearTimeout(timer);
71274
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
71275
+ }
71276
+ };
71277
+
70537
71278
  //#endregion
70538
71279
  //#region ../../packages/heterogeneous-agents/src/transcript/rebuildClaudeCode.ts
70539
71280
  const MAX_DIR_SLUG = 200;
@@ -71279,7 +72020,7 @@ var CopilotAcpSession = class CopilotAcpSession extends AcpAgentSession {
71279
72020
  async settlePrompt(result) {
71280
72021
  await this.drainNotifications();
71281
72022
  await this.client.drain();
71282
- const promptResult = isRecord$7(result) ? result : void 0;
72023
+ const promptResult = isRecord$8(result) ? result : void 0;
71283
72024
  await this.pushToPipeline({
71284
72025
  stopReason: promptResult?.stopReason,
71285
72026
  type: "copilot_prompt_completed",
@@ -71288,7 +72029,7 @@ var CopilotAcpSession = class CopilotAcpSession extends AcpAgentSession {
71288
72029
  }
71289
72030
  async onRunFailure(error) {
71290
72031
  this.options.askUserBridge?.cancelAll("session_ended");
71291
- const detail = error instanceof AcpRpcResponseError && isRecord$7(error.rpcError.data) && typeof error.rpcError.data.details === "string" && error.rpcError.data.details ? `${error.message}: ${error.rpcError.data.details}` : error.message;
72032
+ const detail = error instanceof AcpRpcResponseError && isRecord$8(error.rpcError.data) && typeof error.rpcError.data.details === "string" && error.rpcError.data.details ? `${error.message}: ${error.rpcError.data.details}` : error.message;
71292
72033
  await this.pushToPipeline({
71293
72034
  message: detail,
71294
72035
  type: "copilot_error"
@@ -71310,7 +72051,7 @@ var CopilotAcpSession = class CopilotAcpSession extends AcpAgentSession {
71310
72051
  if (message.method !== "session/update" || !this.acceptUpdates) return;
71311
72052
  this.lastSessionUpdateAt = Date.now();
71312
72053
  const update = message.params?.update;
71313
- if (!isRecord$7(update)) return;
72054
+ if (!isRecord$8(update)) return;
71314
72055
  if (update.sessionUpdate === "config_option_update") {
71315
72056
  const catalog = parseCopilotAcpModelCatalog({ configOptions: update.configOptions });
71316
72057
  if (catalog?.currentModelId) {
@@ -71440,7 +72181,7 @@ var CopilotAcpSession = class CopilotAcpSession extends AcpAgentSession {
71440
72181
  if (!requestedEffort || requestedEffort === "default") return;
71441
72182
  const reasoningConfig = getReasoningEffortConfig(configOptions) ?? (!hasSessionConfigOptions && this.options.resumeSessionId ? { id: "reasoning_effort" } : void 0);
71442
72183
  if (!reasoningConfig || typeof reasoningConfig.id !== "string" || !reasoningConfig.id) return;
71443
- const availableValues = Array.isArray(reasoningConfig.options) ? reasoningConfig.options.flatMap((option) => isRecord$7(option) && typeof option.value === "string" && option.value ? [option.value] : []) : [];
72184
+ const availableValues = Array.isArray(reasoningConfig.options) ? reasoningConfig.options.flatMap((option) => isRecord$8(option) && typeof option.value === "string" && option.value ? [option.value] : []) : [];
71444
72185
  const targetValue = availableValues.length === 0 || availableValues.includes(requestedEffort) ? requestedEffort : void 0;
71445
72186
  if (!targetValue || hasSessionConfigOptions && reasoningConfig.currentValue === targetValue) return;
71446
72187
  await this.client.request("session/set_config_option", {
@@ -71473,9 +72214,9 @@ var CopilotAcpSession = class CopilotAcpSession extends AcpAgentSession {
71473
72214
  }
71474
72215
  }
71475
72216
  parsePermissionRequest(value) {
71476
- if (!isRecord$7(value) || !Array.isArray(value.options) || !isRecord$7(value.toolCall)) throw new AcpServerRequestError(-32602, "Invalid session/request_permission request");
72217
+ if (!isRecord$8(value) || !Array.isArray(value.options) || !isRecord$8(value.toolCall)) throw new AcpServerRequestError(-32602, "Invalid session/request_permission request");
71477
72218
  const options = value.options.flatMap((option) => {
71478
- if (!isRecord$7(option) || typeof option.name !== "string" || option.name.length === 0 || option.name.length > 200 || typeof option.optionId !== "string" || option.optionId.length === 0 || option.optionId.length > 200) return [];
72219
+ if (!isRecord$8(option) || typeof option.name !== "string" || option.name.length === 0 || option.name.length > 200 || typeof option.optionId !== "string" || option.optionId.length === 0 || option.optionId.length > 200) return [];
71479
72220
  return [{
71480
72221
  kind: typeof option.kind === "string" && option.kind.length > 0 && option.kind.length <= 1e3 ? option.kind : option.optionId,
71481
72222
  name: option.name,
@@ -71485,7 +72226,7 @@ var CopilotAcpSession = class CopilotAcpSession extends AcpAgentSession {
71485
72226
  const optionIds = new Set(options.map(({ optionId }) => optionId));
71486
72227
  if (options.length !== value.options.length || options.length === 0 || optionIds.size !== options.length || typeof value.toolCall.toolCallId !== "string" || value.toolCall.toolCallId.length === 0) throw new AcpServerRequestError(-32602, "Invalid session/request_permission options");
71487
72228
  const rawTitle = typeof value.toolCall.title === "string" ? value.toolCall.title.trim() : "";
71488
- const rawInput = isRecord$7(value.toolCall.rawInput) ? value.toolCall.rawInput : void 0;
72229
+ const rawInput = isRecord$8(value.toolCall.rawInput) ? value.toolCall.rawInput : void 0;
71489
72230
  const command = typeof rawInput?.command === "string" ? rawInput.command.trim() : "";
71490
72231
  return {
71491
72232
  options,
@@ -71538,7 +72279,7 @@ var CopilotAcpSession = class CopilotAcpSession extends AcpAgentSession {
71538
72279
  return `copilot-permission-${String(message.id)}-${sourceToolCallId}`;
71539
72280
  }
71540
72281
  getAnswerSelections(answer, question) {
71541
- if (answer.cancelled || !isRecord$7(answer.result)) return [];
72282
+ if (answer.cancelled || !isRecord$8(answer.result)) return [];
71542
72283
  const rawSelection = answer.result[question];
71543
72284
  return (Array.isArray(rawSelection) ? rawSelection : [rawSelection]).flatMap((selection) => typeof selection === "string" ? [selection] : []);
71544
72285
  }
@@ -71698,8 +72439,8 @@ var CursorAcpSession = class extends AcpAgentSession {
71698
72439
  }
71699
72440
  async handleAgentMessage(message) {
71700
72441
  if (!this.acceptUpdates || message.method !== "session/update") return;
71701
- const params = isRecord$7(message.params) ? message.params : void 0;
71702
- if (!isRecord$7(params?.update)) return;
72442
+ const params = isRecord$8(message.params) ? message.params : void 0;
72443
+ if (!isRecord$8(params?.update)) return;
71703
72444
  await this.pushToPipeline(this.normalizeSessionUpdate(params.update));
71704
72445
  }
71705
72446
  async handleServerRequest(message) {
@@ -71759,7 +72500,7 @@ var CursorAcpSession = class extends AcpAgentSession {
71759
72500
  throw new AcpServerRequestError(-32601, `Unsupported ACP client request: ${message.method}`);
71760
72501
  }
71761
72502
  normalizeSessionUpdate(update) {
71762
- if (update.sessionUpdate !== "tool_call" || typeof update.toolCallId !== "string" || !isRecord$7(update.rawInput)) return update;
72503
+ if (update.sessionUpdate !== "tool_call" || typeof update.toolCallId !== "string" || !isRecord$8(update.rawInput)) return update;
71763
72504
  try {
71764
72505
  const request = this.parseAskQuestionRequest({
71765
72506
  ...update.rawInput,
@@ -71776,9 +72517,9 @@ var CursorAcpSession = class extends AcpAgentSession {
71776
72517
  }
71777
72518
  }
71778
72519
  parsePermissionRequest(value) {
71779
- if (!isRecord$7(value) || !Array.isArray(value.options) || !isRecord$7(value.toolCall)) throw new AcpServerRequestError(-32602, "Invalid session/request_permission request");
72520
+ if (!isRecord$8(value) || !Array.isArray(value.options) || !isRecord$8(value.toolCall)) throw new AcpServerRequestError(-32602, "Invalid session/request_permission request");
71780
72521
  const options = value.options.flatMap((option) => {
71781
- if (!isRecord$7(option) || typeof option.kind !== "string" || typeof option.name !== "string" || typeof option.optionId !== "string") return [];
72522
+ if (!isRecord$8(option) || typeof option.kind !== "string" || typeof option.name !== "string" || typeof option.optionId !== "string") return [];
71782
72523
  return [{
71783
72524
  kind: option.kind,
71784
72525
  name: option.name,
@@ -71795,7 +72536,7 @@ var CursorAcpSession = class extends AcpAgentSession {
71795
72536
  };
71796
72537
  }
71797
72538
  parseCreatePlanRequest(value) {
71798
- if (!isRecord$7(value) || typeof value.toolCallId !== "string" || typeof value.plan !== "string") throw new AcpServerRequestError(-32602, "Invalid cursor/create_plan request");
72539
+ if (!isRecord$8(value) || typeof value.toolCallId !== "string" || typeof value.plan !== "string") throw new AcpServerRequestError(-32602, "Invalid cursor/create_plan request");
71799
72540
  return {
71800
72541
  name: typeof value.name === "string" ? value.name : void 0,
71801
72542
  overview: typeof value.overview === "string" ? value.overview : void 0,
@@ -71839,16 +72580,16 @@ var CursorAcpSession = class extends AcpAgentSession {
71839
72580
  return `cursor-${kind}-${String(message.id)}-${sourceToolCallId}`;
71840
72581
  }
71841
72582
  getAnswerSelections(answer, question) {
71842
- if (answer.cancelled || !isRecord$7(answer.result)) return [];
72583
+ if (answer.cancelled || !isRecord$8(answer.result)) return [];
71843
72584
  const rawSelection = answer.result[question];
71844
72585
  return (Array.isArray(rawSelection) ? rawSelection : [rawSelection]).flatMap((selection) => typeof selection === "string" ? [selection] : []);
71845
72586
  }
71846
72587
  parseAskQuestionRequest(value) {
71847
- if (!isRecord$7(value) || typeof value.toolCallId !== "string" || !Array.isArray(value.questions)) throw new AcpServerRequestError(-32602, "Invalid cursor/ask_question request");
72588
+ if (!isRecord$8(value) || typeof value.toolCallId !== "string" || !Array.isArray(value.questions)) throw new AcpServerRequestError(-32602, "Invalid cursor/ask_question request");
71848
72589
  const questions = value.questions.flatMap((questionValue) => {
71849
- if (!isRecord$7(questionValue)) return [];
72590
+ if (!isRecord$8(questionValue)) return [];
71850
72591
  if (typeof questionValue.id !== "string" || typeof questionValue.prompt !== "string" || !Array.isArray(questionValue.options)) return [];
71851
- const options = questionValue.options.flatMap((optionValue) => isRecord$7(optionValue) && typeof optionValue.id === "string" && typeof optionValue.label === "string" ? [{
72592
+ const options = questionValue.options.flatMap((optionValue) => isRecord$8(optionValue) && typeof optionValue.id === "string" && typeof optionValue.label === "string" ? [{
71852
72593
  id: optionValue.id,
71853
72594
  label: optionValue.label
71854
72595
  }] : []);
@@ -71869,7 +72610,7 @@ var CursorAcpSession = class extends AcpAgentSession {
71869
72610
  }
71870
72611
  buildQuestionResponse(request, answer) {
71871
72612
  if (answer.cancelled) return { outcome: { outcome: "cancelled" } };
71872
- if (!isRecord$7(answer.result)) return { outcome: { outcome: "cancelled" } };
72613
+ if (!isRecord$8(answer.result)) return { outcome: { outcome: "cancelled" } };
71873
72614
  const freeform = answer.result.__freeform__;
71874
72615
  if (typeof freeform === "string" && freeform.trim()) return { outcome: {
71875
72616
  answers: request.questions.map(({ id }) => ({
@@ -71909,8 +72650,8 @@ const splitThinkingModel = (model) => {
71909
72650
  thoughtLevel: match[2].toLowerCase()
71910
72651
  } : void 0;
71911
72652
  };
71912
- const getThinkingConfig = (configOptions) => Array.isArray(configOptions) ? configOptions.filter(isRecord$7).find((option) => option.id === "thought_level") : void 0;
71913
- const getModeConfigValue = (configOptions) => Array.isArray(configOptions) ? configOptions.filter(isRecord$7).find((option) => option.id === "mode")?.currentValue : void 0;
72653
+ const getThinkingConfig = (configOptions) => Array.isArray(configOptions) ? configOptions.filter(isRecord$8).find((option) => option.id === "thought_level") : void 0;
72654
+ const getModeConfigValue = (configOptions) => Array.isArray(configOptions) ? configOptions.filter(isRecord$8).find((option) => option.id === "mode")?.currentValue : void 0;
71914
72655
  const buildDevinAcpArgs = (extraArgs = []) => {
71915
72656
  const args = [...extraArgs];
71916
72657
  let resolvedMode;
@@ -72008,7 +72749,7 @@ var DevinAcpSession = class extends AcpAgentSession {
72008
72749
  }
72009
72750
  async settlePrompt(result) {
72010
72751
  await this.client.drain();
72011
- const promptResult = isRecord$7(result) ? result : void 0;
72752
+ const promptResult = isRecord$8(result) ? result : void 0;
72012
72753
  await this.pushToPipeline({
72013
72754
  stopReason: promptResult?.stopReason,
72014
72755
  type: "devin_prompt_completed",
@@ -72031,8 +72772,8 @@ var DevinAcpSession = class extends AcpAgentSession {
72031
72772
  }
72032
72773
  async handleAgentMessage(message) {
72033
72774
  if (!this.acceptUpdates || message.method !== "session/update") return;
72034
- const params = isRecord$7(message.params) ? message.params : void 0;
72035
- if (!isRecord$7(params?.update)) return;
72775
+ const params = isRecord$8(message.params) ? message.params : void 0;
72776
+ if (!isRecord$8(params?.update)) return;
72036
72777
  const update = this.normalizeSessionUpdate(params.update);
72037
72778
  if (update.sessionUpdate === "config_option_update") {
72038
72779
  const model = this.resolveCurrentModel(update.configOptions);
@@ -72090,7 +72831,7 @@ var DevinAcpSession = class extends AcpAgentSession {
72090
72831
  }
72091
72832
  normalizeSessionUpdate(update) {
72092
72833
  if (typeof update.name === "string") return update;
72093
- const inferenceToolName = (isRecord$7(update._meta) ? update._meta : void 0)?.["cognition.ai/inferenceToolName"];
72834
+ const inferenceToolName = (isRecord$8(update._meta) ? update._meta : void 0)?.["cognition.ai/inferenceToolName"];
72094
72835
  return typeof inferenceToolName === "string" && inferenceToolName ? {
72095
72836
  ...update,
72096
72837
  name: inferenceToolName
@@ -72125,7 +72866,7 @@ var DevinAcpSession = class extends AcpAgentSession {
72125
72866
  });
72126
72867
  const thinking = getThinkingConfig(result.configOptions);
72127
72868
  if (thinking) {
72128
- if (!Array.isArray(thinking.options) || !thinking.options.some((option) => isRecord$7(option) && option.value === requestedThinking.thoughtLevel)) throw new Error(`Devin ACP thinking level is unavailable: ${requestedModel}`);
72869
+ if (!Array.isArray(thinking.options) || !thinking.options.some((option) => isRecord$8(option) && option.value === requestedThinking.thoughtLevel)) throw new Error(`Devin ACP thinking level is unavailable: ${requestedModel}`);
72129
72870
  if (thinking.currentValue !== requestedThinking.thoughtLevel) result = await this.client.request("session/set_config_option", {
72130
72871
  configId: thinking.id,
72131
72872
  sessionId,
@@ -72150,13 +72891,13 @@ var DevinAcpSession = class extends AcpAgentSession {
72150
72891
  return value.toLowerCase().replaceAll(/[^a-z0-9]/g, "");
72151
72892
  }
72152
72893
  parsePermissionRequest(value) {
72153
- if (!isRecord$7(value) || !Array.isArray(value.options) || !isRecord$7(value.toolCall)) throw new AcpServerRequestError(-32602, "Invalid session/request_permission request");
72154
- const options = value.options.flatMap((option) => isRecord$7(option) && typeof option.name === "string" && typeof option.optionId === "string" ? [{
72894
+ if (!isRecord$8(value) || !Array.isArray(value.options) || !isRecord$8(value.toolCall)) throw new AcpServerRequestError(-32602, "Invalid session/request_permission request");
72895
+ const options = value.options.flatMap((option) => isRecord$8(option) && typeof option.name === "string" && typeof option.optionId === "string" ? [{
72155
72896
  name: option.name,
72156
72897
  optionId: option.optionId
72157
72898
  }] : []);
72158
72899
  if (options.length !== value.options.length || options.length === 0 || typeof value.toolCall.toolCallId !== "string") throw new AcpServerRequestError(-32602, "Invalid session/request_permission options");
72159
- const editableCommand = (isRecord$7(value.toolCall._meta) ? value.toolCall._meta : void 0)?.["cognition.ai/editableCommand"];
72900
+ const editableCommand = (isRecord$8(value.toolCall._meta) ? value.toolCall._meta : void 0)?.["cognition.ai/editableCommand"];
72160
72901
  return {
72161
72902
  options,
72162
72903
  toolCall: {
@@ -72199,7 +72940,7 @@ var DevinAcpSession = class extends AcpAgentSession {
72199
72940
  return request.options.find(({ optionId }) => selections.includes(optionId));
72200
72941
  }
72201
72942
  getAnswerSelections(answer, question) {
72202
- if (answer.cancelled || !isRecord$7(answer.result)) return [];
72943
+ if (answer.cancelled || !isRecord$8(answer.result)) return [];
72203
72944
  const selection = answer.result[question];
72204
72945
  return (Array.isArray(selection) ? selection : [selection]).flatMap((value) => typeof value === "string" ? [value] : []);
72205
72946
  }
@@ -72417,7 +73158,7 @@ var DroidAcpSession = class DroidAcpSession extends AcpAgentSession {
72417
73158
  if (message.method !== "session/update" || !this.acceptUpdates) return;
72418
73159
  this.lastSessionUpdateAt = Date.now();
72419
73160
  const update = message.params?.update;
72420
- if (!isRecord$7(update)) return;
73161
+ if (!isRecord$8(update)) return;
72421
73162
  if (update.sessionUpdate === "config_option_update") {
72422
73163
  const catalog = parseDroidAcpModelCatalog({ configOptions: update.configOptions });
72423
73164
  if (catalog?.currentModelId) {
@@ -72476,9 +73217,9 @@ var DroidAcpSession = class DroidAcpSession extends AcpAgentSession {
72476
73217
  }
72477
73218
  }
72478
73219
  parsePermissionRequest(value) {
72479
- if (!isRecord$7(value) || !Array.isArray(value.options) || !isRecord$7(value.toolCall)) throw new AcpServerRequestError(-32602, "Invalid session/request_permission request");
73220
+ if (!isRecord$8(value) || !Array.isArray(value.options) || !isRecord$8(value.toolCall)) throw new AcpServerRequestError(-32602, "Invalid session/request_permission request");
72480
73221
  const options = value.options.flatMap((option) => {
72481
- if (!isRecord$7(option) || typeof option.kind !== "string" || option.kind.length === 0 || option.kind.length > 1e3 || typeof option.name !== "string" || option.name.length === 0 || option.name.length > 200 || typeof option.optionId !== "string" || option.optionId.length === 0 || option.optionId.length > 200) return [];
73222
+ if (!isRecord$8(option) || typeof option.kind !== "string" || option.kind.length === 0 || option.kind.length > 1e3 || typeof option.name !== "string" || option.name.length === 0 || option.name.length > 200 || typeof option.optionId !== "string" || option.optionId.length === 0 || option.optionId.length > 200) return [];
72482
73223
  return [{
72483
73224
  kind: option.kind,
72484
73225
  name: option.name,
@@ -72538,7 +73279,7 @@ var DroidAcpSession = class DroidAcpSession extends AcpAgentSession {
72538
73279
  return `droid-permission-${String(message.id)}-${sourceToolCallId}`;
72539
73280
  }
72540
73281
  getAnswerSelections(answer, question) {
72541
- if (answer.cancelled || !isRecord$7(answer.result)) return [];
73282
+ if (answer.cancelled || !isRecord$8(answer.result)) return [];
72542
73283
  const rawSelection = answer.result[question];
72543
73284
  return (Array.isArray(rawSelection) ? rawSelection : [rawSelection]).flatMap((selection) => typeof selection === "string" ? [selection] : []);
72544
73285
  }
@@ -72629,7 +73370,7 @@ const DSH_MODEL_CONFIG_ID = "model";
72629
73370
  const modelChoices = (configOptions) => {
72630
73371
  const option = configOptions?.find(({ id }) => id === DSH_MODEL_CONFIG_ID);
72631
73372
  const flatten = (entries) => Array.isArray(entries) ? entries.flatMap((entry) => {
72632
- if (!isRecord$7(entry)) return [];
73373
+ if (!isRecord$8(entry)) return [];
72633
73374
  if (Array.isArray(entry.options)) return flatten(entry.options);
72634
73375
  return typeof entry.value === "string" ? [{
72635
73376
  name: typeof entry.name === "string" ? entry.name : void 0,
@@ -72745,7 +73486,7 @@ var DshAcpSession = class extends AcpAgentSession {
72745
73486
  async settlePrompt(result) {
72746
73487
  await this.client.drain();
72747
73488
  await this.pushToPipeline({
72748
- stopReason: isRecord$7(result) ? result.stopReason : void 0,
73489
+ stopReason: isRecord$8(result) ? result.stopReason : void 0,
72749
73490
  type: "dsh_prompt_completed"
72750
73491
  });
72751
73492
  }
@@ -72759,7 +73500,7 @@ var DshAcpSession = class extends AcpAgentSession {
72759
73500
  async handleAgentMessage(message) {
72760
73501
  if (message.method !== "session/update") return;
72761
73502
  const update = message.params?.update;
72762
- if (isRecord$7(update)) await this.pushToPipeline(update);
73503
+ if (isRecord$8(update)) await this.pushToPipeline(update);
72763
73504
  }
72764
73505
  /**
72765
73506
  * LobeHub runs agents headless. The harness's default `workspace-write`
@@ -73287,284 +74028,6 @@ const prepareClaudeCodeLobeHubCli = async (prompt, args = [], options = {}) => {
73287
74028
  };
73288
74029
  };
73289
74030
 
73290
- //#endregion
73291
- //#region ../../packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.ts
73292
- /**
73293
- * How long the session may sit between turns with no stdout before stdin is
73294
- * closed anyway. Background tasks that stream (sub-agents) keep resetting it;
73295
- * a silent one (a long background shell) would otherwise hold the process open
73296
- * forever, since Claude Code's own wind-down ceiling only starts once stdin is
73297
- * closed.
73298
- */
73299
- const DEFAULT_IDLE_CLOSE_MS = 1800 * 1e3;
73300
- /**
73301
- * How long a task that ends between turns may wait for the main-agent turn its
73302
- * notification wakes. Claude Code opens that turn within milliseconds; the
73303
- * grace only bounds an end that unexpectedly wakes nothing. A stopped task
73304
- * never wakes one, so it does not wait (see `observeSystem`).
73305
- */
73306
- const DEFAULT_WAKE_UP_GRACE_MS = 30 * 1e3;
73307
- const TERMINAL_TASK_STATUSES = new Set([
73308
- "completed",
73309
- "failed",
73310
- "killed"
73311
- ]);
73312
- const readIdleCloseMs = () => {
73313
- const value = Number(process.env.LOBE_CLAUDE_CODE_LIVE_INPUT_IDLE_MS);
73314
- return Number.isFinite(value) && value > 0 ? value : DEFAULT_IDLE_CLOSE_MS;
73315
- };
73316
- /** Stamp a stream-json `user` line with the uuid Claude Code replays it under. */
73317
- const withUserMessageUuid = (stdinLine, uuid) => `${JSON.stringify({
73318
- ...JSON.parse(stdinLine),
73319
- uuid
73320
- })}\n`;
73321
- const isAbortedResult = (message) => !!message.is_error && String(message.terminal_reason ?? "").startsWith("aborted");
73322
- /**
73323
- * The runtime end a live session (stdin kept open, see `ClaudeCodeLiveInput`)
73324
- * reports once, at process exit: complete, or interrupted when its last turn
73325
- * was stopped. Only a clean exit after a finished turn ends the run here — a
73326
- * crash after a result is a failure, not a completion. Print mode exits 1 when
73327
- * its last turn was an error result, which an interrupt is.
73328
- *
73329
- * Shared by every host of a live CLI (`lh hetero exec`, the desktop's local
73330
- * spawn) so they end a run by the same rule.
73331
- *
73332
- * @returns the `completeRuntime` data, or undefined when the run does not end here
73333
- */
73334
- const resolveClaudeCodeLiveRuntimeEnd = (lastTurn, exit) => {
73335
- if (!lastTurn || exit.killedByHost || exit.sawError) return;
73336
- if (!(exit.code === 0 || lastTurn.aborted && exit.code === 1 && exit.signal === null)) return;
73337
- return {
73338
- ...lastTurn.aborted ? {
73339
- kind: "aborted",
73340
- reason: "interrupted",
73341
- terminalReason: lastTurn.terminalReason
73342
- } : { reason: "complete" },
73343
- transport: "cli-live"
73344
- };
73345
- };
73346
- const SESSION_ENDED = {
73347
- error: "The session ended before answering",
73348
- subtype: "error"
73349
- };
73350
- /**
73351
- * Keeps a Claude Code print-mode (`-p --input-format stream-json`) stdin open
73352
- * for as long as the run can still use input, so the host can deliver a user
73353
- * message into the running session or interrupt only the current turn.
73354
- *
73355
- * Closing stdin early is not neutral: once input is closed, print mode stops
73356
- * waiting for background tasks after `CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`
73357
- * (10 minutes by default) and kills them. So stdin stays open until the session
73358
- * is between turns with no running task and no delivered message it has not
73359
- * picked up yet.
73360
- *
73361
- * A task that ends between turns does not make the session idle: its
73362
- * notification wakes the main agent for a turn, and that turn can start a new
73363
- * task or resume a finished sub-agent with `SendMessage`. Closing at the end
73364
- * would put those tasks under the ceiling, so the decision waits for the
73365
- * wake-up turn's result.
73366
- *
73367
- * Requires `--replay-user-messages`: the replayed `uuid` is how a delivered
73368
- * message is known to have been picked up.
73369
- */
73370
- var ClaudeCodeLiveInput = class {
73371
- activeTasks = /* @__PURE__ */ new Set();
73372
- closed = false;
73373
- idleTimer;
73374
- idleCloseMs;
73375
- lastOutcome;
73376
- lineBuffer = "";
73377
- pendingControl = /* @__PURE__ */ new Map();
73378
- turnOpen = true;
73379
- unconsumed = /* @__PURE__ */ new Set();
73380
- wakeUpGraceMs;
73381
- wakeUpTimer;
73382
- constructor(stdin, options = {}) {
73383
- this.stdin = stdin;
73384
- this.idleCloseMs = options.idleCloseMs ?? readIdleCloseMs();
73385
- this.wakeUpGraceMs = options.wakeUpGraceMs ?? DEFAULT_WAKE_UP_GRACE_MS;
73386
- stdin.on("error", () => this.markClosed());
73387
- stdin.on("close", () => this.markClosed());
73388
- }
73389
- get isOpen() {
73390
- return !this.closed;
73391
- }
73392
- /** How the last turn ended; undefined while the session has not finished one. */
73393
- get lastTurn() {
73394
- return this.lastOutcome;
73395
- }
73396
- /**
73397
- * Deliver a `user` line into the session; it stays pending until Claude Code
73398
- * replays it. Returns false once input has closed.
73399
- */
73400
- send(stdinLine, uuid = randomUUID()) {
73401
- if (this.closed) return false;
73402
- this.unconsumed.add(uuid);
73403
- this.clearIdleTimer();
73404
- this.stdin.write(withUserMessageUuid(stdinLine, uuid));
73405
- return true;
73406
- }
73407
- /** Stop the current turn without ending the process. Returns false once input has closed. */
73408
- interrupt() {
73409
- return !!this.sendControlRequest({ subtype: "interrupt" });
73410
- }
73411
- /**
73412
- * Write a stream-json `control_request` into the session — the protocol
73413
- * Claude Code's SDK uses to steer a live process (interrupt, stop a task,
73414
- * change the model…).
73415
- *
73416
- * @returns the request and its answer, or `undefined` once input has closed
73417
- */
73418
- sendControlRequest(request) {
73419
- if (this.closed) return;
73420
- const requestId = randomUUID();
73421
- const response = new Promise((resolve) => {
73422
- this.pendingControl.set(requestId, resolve);
73423
- });
73424
- this.stdin.write(`${JSON.stringify({
73425
- request,
73426
- request_id: requestId,
73427
- type: "control_request"
73428
- })}\n`);
73429
- return {
73430
- requestId,
73431
- response
73432
- };
73433
- }
73434
- /** Feed raw stdout so the session state tracks what Claude Code reports. */
73435
- observe(chunk) {
73436
- this.lineBuffer += chunk.toString();
73437
- const lines = this.lineBuffer.split("\n");
73438
- this.lineBuffer = lines.pop() ?? "";
73439
- for (const line of lines) {
73440
- if (!line.trim()) continue;
73441
- try {
73442
- const message = JSON.parse(line);
73443
- if (message?.type === "result") this.lastOutcome = {
73444
- aborted: isAbortedResult(message),
73445
- terminalReason: message.terminal_reason
73446
- };
73447
- this.observeMessage(message);
73448
- } catch {}
73449
- }
73450
- if (this.closed) return;
73451
- if (this.turnOpen) this.clearIdleTimer();
73452
- else this.armIdleTimer();
73453
- }
73454
- /**
73455
- * stdout ended: take a final record left without a trailing newline, then
73456
- * close input, since nothing can read it any more.
73457
- */
73458
- finish() {
73459
- if (this.lineBuffer.trim()) this.observe("\n");
73460
- this.close();
73461
- for (const resolve of this.pendingControl.values()) resolve(SESSION_ENDED);
73462
- this.pendingControl.clear();
73463
- }
73464
- close() {
73465
- if (this.closed) return;
73466
- this.markClosed();
73467
- this.stdin.end();
73468
- }
73469
- observeMessage(message) {
73470
- if (message?.type === "control_response") {
73471
- this.observeControlResponse(message.response);
73472
- return;
73473
- }
73474
- if (message?.parent_tool_use_id && message.type !== "system") return;
73475
- switch (message?.type) {
73476
- case "user":
73477
- if (message.isReplay && typeof message.uuid === "string") {
73478
- this.unconsumed.delete(message.uuid);
73479
- this.openTurn();
73480
- }
73481
- return;
73482
- case "assistant":
73483
- case "stream_event":
73484
- this.openTurn();
73485
- return;
73486
- case "system":
73487
- this.observeSystem(message);
73488
- return;
73489
- case "result":
73490
- this.turnOpen = false;
73491
- if (message.is_error && !isAbortedResult(message)) this.close();
73492
- else this.closeIfIdle();
73493
- return;
73494
- }
73495
- }
73496
- /** Answers arrive even after input closed, for requests written before. */
73497
- observeControlResponse(response) {
73498
- const requestId = response?.request_id;
73499
- const resolve = typeof requestId === "string" && this.pendingControl.get(requestId);
73500
- if (!resolve) return;
73501
- this.pendingControl.delete(requestId);
73502
- resolve(response.subtype === "success" ? {
73503
- response: response.response ?? void 0,
73504
- subtype: "success"
73505
- } : {
73506
- error: String(response.error ?? "Control request failed"),
73507
- subtype: "error"
73508
- });
73509
- }
73510
- observeSystem(message) {
73511
- if (message.subtype === "init") {
73512
- this.openTurn();
73513
- return;
73514
- }
73515
- if (message.subtype === "task_started" && message.task_id) {
73516
- this.activeTasks.add(message.task_id);
73517
- return;
73518
- }
73519
- if ((message.subtype === "task_notification" || message.subtype === "task_updated" && TERMINAL_TASK_STATUSES.has(message.patch?.status)) && message.task_id) {
73520
- this.activeTasks.delete(message.task_id);
73521
- if (message.patch?.status === "killed" || message.subtype === "task_notification" && message.status === "stopped") this.closeIfIdle();
73522
- else this.awaitWakeUpTurn();
73523
- }
73524
- }
73525
- /** A newer turn supersedes how the last one ended until it reports its own. */
73526
- openTurn() {
73527
- this.turnOpen = true;
73528
- this.lastOutcome = void 0;
73529
- this.clearWakeUpTimer();
73530
- }
73531
- closeIfIdle() {
73532
- if (this.turnOpen || this.activeTasks.size > 0 || this.unconsumed.size > 0) return;
73533
- this.close();
73534
- }
73535
- /**
73536
- * The last task ended between turns. The turn its notification wakes decides
73537
- * at its result; close here only if no turn opens within the grace.
73538
- */
73539
- awaitWakeUpTurn() {
73540
- if (this.closed) return;
73541
- if (this.turnOpen || this.activeTasks.size > 0 || this.unconsumed.size > 0) return;
73542
- this.clearWakeUpTimer();
73543
- this.wakeUpTimer = setTimeout(() => this.closeIfIdle(), this.wakeUpGraceMs);
73544
- this.wakeUpTimer.unref?.();
73545
- }
73546
- clearWakeUpTimer() {
73547
- if (!this.wakeUpTimer) return;
73548
- clearTimeout(this.wakeUpTimer);
73549
- this.wakeUpTimer = void 0;
73550
- }
73551
- armIdleTimer() {
73552
- this.clearIdleTimer();
73553
- this.idleTimer = setTimeout(() => this.close(), this.idleCloseMs);
73554
- this.idleTimer.unref?.();
73555
- }
73556
- clearIdleTimer() {
73557
- if (!this.idleTimer) return;
73558
- clearTimeout(this.idleTimer);
73559
- this.idleTimer = void 0;
73560
- }
73561
- markClosed() {
73562
- this.closed = true;
73563
- this.clearIdleTimer();
73564
- this.clearWakeUpTimer();
73565
- }
73566
- };
73567
-
73568
74031
  //#endregion
73569
74032
  //#region ../../packages/heterogeneous-agents/src/spawn/claudeCodeStopTask.ts
73570
74033
  /** How long Claude Code gets to accept a stop before the request is given up. */
@@ -74020,6 +74483,7 @@ const spawnTraeAcpAgent = async (options) => {
74020
74483
 
74021
74484
  //#endregion
74022
74485
  //#region ../../packages/heterogeneous-agents/src/spawn/spawnAgent.ts
74486
+ init_src$2();
74023
74487
  init_config();
74024
74488
  init_cliSpawn();
74025
74489
  /**
@@ -74066,13 +74530,6 @@ const CODEBUDDY_BASE_ARGS = [
74066
74530
  "--disallowedTools",
74067
74531
  CODEBUDDY_DISALLOWED_TOOLS.join(",")
74068
74532
  ];
74069
- const isRunningAsRoot = () => process.getuid?.() === 0;
74070
- const CLAUDE_CODE_PERMISSION_ARGS = () => isRunningAsRoot() ? [
74071
- "--permission-mode",
74072
- "acceptEdits",
74073
- "--allowed-tools",
74074
- "Bash,Read,Write,Edit,MultiEdit,WebSearch,mcp__*"
74075
- ] : ["--permission-mode", "bypassPermissions"];
74076
74533
  const CODEX_REQUIRED_ARGS = ["--json", "--skip-git-repo-check"];
74077
74534
  const CODEX_BYPASS_APPROVALS_AND_SANDBOX_ARG = "--dangerously-bypass-approvals-and-sandbox";
74078
74535
  const CODEX_DEFAULT_EXECUTION_ARGS = [CODEX_BYPASS_APPROVALS_AND_SANDBOX_ARG];
@@ -74116,11 +74573,14 @@ const QODER_BASE_ARGS = [
74116
74573
  "bypass_permissions"
74117
74574
  ];
74118
74575
  const hasAnyFlag = (args, flags) => args.some((arg) => flags.includes(arg));
74119
- const buildClaudeCodeArgs = ({ extraArgs, includePartialMessages, inputArgs, liveInput, resumeSessionId }) => [
74576
+ const buildClaudeCodeArgs = ({ extraArgs, includePartialMessages, inputArgs, liveInput, permissionMode, permissionPrompts, resumeSessionId }) => [
74120
74577
  ...CLAUDE_CODE_BASE_ARGS,
74121
74578
  ...includePartialMessages ? ["--include-partial-messages"] : [],
74122
74579
  ...liveInput ? ["--replay-user-messages"] : [],
74123
- ...CLAUDE_CODE_PERMISSION_ARGS(),
74580
+ ...buildClaudeCodePermissionArgs({
74581
+ hostPrompts: permissionPrompts,
74582
+ mode: permissionMode
74583
+ }),
74124
74584
  ...resumeSessionId ? ["--resume", resumeSessionId] : [],
74125
74585
  ...inputArgs,
74126
74586
  ...extraArgs
@@ -74264,6 +74724,8 @@ const spawnAgent = async (options) => {
74264
74724
  /** One-shot JSONL CLI spawn; `spawnAgent` owns the Codex JWT file around it. */
74265
74725
  const spawnCliAgent = async (options, command, cwd, inputPlan, childEnv, codexJwtFile) => {
74266
74726
  const liveInput = options.agentType === "claude-code" && options.liveInput === true;
74727
+ const permissionMode = options.agentType === "claude-code" ? options.permissionMode : void 0;
74728
+ const permissionPrompts = liveInput && !!options.askUserBridge;
74267
74729
  const args = buildSpawnArgs({
74268
74730
  agentType: options.agentType,
74269
74731
  configArgs: options.agentType === "codex" ? [...buildCodexLobeHubContextArgs(childEnv), ...codexJwtFile?.args ?? []] : void 0,
@@ -74271,6 +74733,8 @@ const spawnCliAgent = async (options, command, cwd, inputPlan, childEnv, codexJw
74271
74733
  includePartialMessages: options.includePartialMessages ?? false,
74272
74734
  inputArgs: inputPlan.args,
74273
74735
  liveInput,
74736
+ permissionMode,
74737
+ permissionPrompts,
74274
74738
  resumeSessionId: options.resumeSessionId
74275
74739
  });
74276
74740
  const initialModel = options.agentType === "codex" ? (await resolveCodexInitialModel({
@@ -74347,6 +74811,26 @@ const spawnCliAgent = async (options, command, cwd, inputPlan, childEnv, codexJw
74347
74811
  exit.then(removeJwtFile, removeJwtFile);
74348
74812
  }
74349
74813
  const live = liveInput && proc.stdin ? new ClaudeCodeLiveInput(proc.stdin) : void 0;
74814
+ if (live && permissionMode && permissionPrompts && options.askUserBridge) {
74815
+ const bridge = options.askUserBridge;
74816
+ const isRoot = isRunningAsRoot();
74817
+ attachClaudeCodePermissionResponder(live, {
74818
+ ask: askThroughBridge(bridge),
74819
+ cancel: (toolCallId) => bridge.cancel(toolCallId, "session_ended"),
74820
+ isRoot
74821
+ });
74822
+ const reporter = new PermissionModeReporter(options.operationId, resolveClaudeCodePermissionMode(permissionMode, isRoot).fallback);
74823
+ live.onControlRequestSent((request, meta) => {
74824
+ const requestedMode = meta?.requestedMode;
74825
+ if (request.subtype === "set_permission_mode" && isHeteroPermissionMode(requestedMode)) reporter.requested(requestedMode, isRoot);
74826
+ });
74827
+ live.subscribe((message) => {
74828
+ const event = reporter.observe(message);
74829
+ if (!event) return;
74830
+ queue.push(event);
74831
+ wake();
74832
+ });
74833
+ }
74350
74834
  if (live) live.send(inputPlan.stdin);
74351
74835
  else if (proc.stdin) proc.stdin.write(inputPlan.stdin, () => {
74352
74836
  proc.stdin?.end();
@@ -266781,12 +267265,12 @@ const summarizeListeners = (entries, options) => {
266781
267265
  };
266782
267266
  }).sort((a, b) => Number(b.inProject) - Number(a.inProject) || a.port - b.port).slice(0, MAX_PORTS);
266783
267267
  };
266784
- const run$1 = async (file, args) => (await execFileAsync$3(file, args, {
267268
+ const run$2 = async (file, args) => (await execFileAsync$3(file, args, {
266785
267269
  maxBuffer: 4 * 1024 * 1024,
266786
267270
  timeout: COMMAND_TIMEOUT_MS
266787
267271
  })).stdout;
266788
267272
  const collectDarwin = async () => {
266789
- const entries = parseLsofListen(await run$1("lsof", [
267273
+ const entries = parseLsofListen(await run$2("lsof", [
266790
267274
  "-nP",
266791
267275
  "-iTCP",
266792
267276
  "-sTCP:LISTEN",
@@ -266798,7 +267282,7 @@ const collectDarwin = async () => {
266798
267282
  }));
266799
267283
  const pids = [...new Set(entries.map((e) => e.pid).filter((p) => !!p))];
266800
267284
  return {
266801
- cwds: pids.length ? parseLsofCwd(await run$1("lsof", [
267285
+ cwds: pids.length ? parseLsofCwd(await run$2("lsof", [
266802
267286
  "-a",
266803
267287
  "-p",
266804
267288
  pids.join(","),
@@ -266847,17 +267331,17 @@ const collectLinux = async () => {
266847
267331
  };
266848
267332
  const collectWindows = async () => {
266849
267333
  const [v4, v6, tasks] = await Promise.all([
266850
- run$1("netstat", [
267334
+ run$2("netstat", [
266851
267335
  "-ano",
266852
267336
  "-p",
266853
267337
  "TCP"
266854
267338
  ]),
266855
- run$1("netstat", [
267339
+ run$2("netstat", [
266856
267340
  "-ano",
266857
267341
  "-p",
266858
267342
  "TCPv6"
266859
267343
  ]),
266860
- run$1("tasklist", [
267344
+ run$2("tasklist", [
266861
267345
  "/FO",
266862
267346
  "CSV",
266863
267347
  "/NH"
@@ -304044,15 +304528,15 @@ const listCodexModels = async ({ args = [], commandPath, cwd, env, timeoutMs })
304044
304528
  includeHidden: false,
304045
304529
  limit: 100
304046
304530
  });
304047
- if (!isRecord$7(page) || !Array.isArray(page.data)) throw new Error("Invalid Codex model catalog");
304531
+ if (!isRecord$8(page) || !Array.isArray(page.data)) throw new Error("Invalid Codex model catalog");
304048
304532
  for (const item of page.data) {
304049
- if (!isRecord$7(item) || typeof item.model !== "string" || !item.model.trim()) throw new Error("Invalid Codex model catalog entry");
304533
+ if (!isRecord$8(item) || typeof item.model !== "string" || !item.model.trim()) throw new Error("Invalid Codex model catalog entry");
304050
304534
  if (item.hidden === true || models.has(item.model)) continue;
304051
304535
  models.set(item.model, {
304052
304536
  id: item.model,
304053
304537
  ...typeof item.displayName === "string" && item.displayName.trim() ? { label: item.displayName } : {},
304054
304538
  ...typeof item.isDefault === "boolean" ? { isDefault: item.isDefault } : {},
304055
- ...Array.isArray(item.serviceTiers) || Array.isArray(item.additionalSpeedTiers) ? { speedModes: [...new Set(["normal", ...(Array.isArray(item.serviceTiers) ? item.serviceTiers.map((tier) => isRecord$7(tier) ? tier.id : void 0) : item.additionalSpeedTiers).flatMap((tier) => tier === "fast" || tier === "priority" ? ["fast"] : tier === "ultrafast" ? ["ultrafast"] : [])])] } : {},
304539
+ ...Array.isArray(item.serviceTiers) || Array.isArray(item.additionalSpeedTiers) ? { speedModes: [...new Set(["normal", ...(Array.isArray(item.serviceTiers) ? item.serviceTiers.map((tier) => isRecord$8(tier) ? tier.id : void 0) : item.additionalSpeedTiers).flatMap((tier) => tier === "fast" || tier === "priority" ? ["fast"] : tier === "ultrafast" ? ["ultrafast"] : [])])] } : {},
304056
304540
  modelId: item.model,
304057
304541
  providerId: "codex"
304058
304542
  });
@@ -304143,13 +304627,13 @@ const parseDevinModelCatalog = (stdout) => {
304143
304627
  } catch {
304144
304628
  return [];
304145
304629
  }
304146
- if (!isRecord$7(result) || !Array.isArray(result.families)) return [];
304630
+ if (!isRecord$8(result) || !Array.isArray(result.families)) return [];
304147
304631
  const seen = /* @__PURE__ */ new Set();
304148
304632
  const models = [];
304149
304633
  for (const family of result.families) {
304150
- if (!isRecord$7(family) || !Array.isArray(family.variants)) continue;
304634
+ if (!isRecord$8(family) || !Array.isArray(family.variants)) continue;
304151
304635
  for (const variant of family.variants) {
304152
- if (!isRecord$7(variant) || typeof variant.model_uid !== "string" || !variant.model_uid) continue;
304636
+ if (!isRecord$8(variant) || typeof variant.model_uid !== "string" || !variant.model_uid) continue;
304153
304637
  if (seen.has(variant.model_uid)) continue;
304154
304638
  seen.add(variant.model_uid);
304155
304639
  models.push({
@@ -304229,10 +304713,10 @@ const parseKimiCodeModelCatalog = (stdout) => {
304229
304713
  } catch {
304230
304714
  return [];
304231
304715
  }
304232
- if (!isRecord$7(result) || !isRecord$7(result.models)) return [];
304716
+ if (!isRecord$8(result) || !isRecord$8(result.models)) return [];
304233
304717
  const models = [];
304234
304718
  for (const [alias, entry] of Object.entries(result.models)) {
304235
- if (!alias || !isRecord$7(entry) || typeof entry.model !== "string" || !entry.model) continue;
304719
+ if (!alias || !isRecord$8(entry) || typeof entry.model !== "string" || !entry.model) continue;
304236
304720
  const separatorIndex = alias.indexOf("/");
304237
304721
  models.push({
304238
304722
  id: alias,
@@ -307089,7 +307573,7 @@ async function writeMaintenanceState(file, operation) {
307089
307573
  await writeFile(temporary, JSON.stringify(operation), { mode: 384 });
307090
307574
  await rename(temporary, file);
307091
307575
  }
307092
- async function run(command, args, timeout) {
307576
+ async function run$1(command, args, timeout) {
307093
307577
  await new Promise((resolve, reject) => {
307094
307578
  const child = spawn(command, args, {
307095
307579
  stdio: "inherit",
@@ -307110,7 +307594,7 @@ async function runMaintenanceWorker(config, ready) {
307110
307594
  await writeMaintenanceState(statePath, operation);
307111
307595
  };
307112
307596
  try {
307113
- if (config.install) await run(config.install.command, config.install.args, 18e4);
307597
+ if (config.install) await run$1(config.install.command, config.install.args, 18e4);
307114
307598
  const { stdout } = await promisify(execFile)(executable, [entry, "--version"], { timeout: 3e4 });
307115
307599
  if (stdout.trim() !== operation.targetVersion) throw new Error("Installed CLI version did not match the requested version. The existing connection was kept.");
307116
307600
  operation.stage = "restarting";
@@ -307128,7 +307612,7 @@ async function runMaintenanceWorker(config, ready) {
307128
307612
  await setTimeout$1(100);
307129
307613
  }
307130
307614
  if (!config.restartArgs) return;
307131
- await run(executable, [
307615
+ await run$1(executable, [
307132
307616
  entry,
307133
307617
  ...config.restartArgs,
307134
307618
  "--daemon"
@@ -553502,6 +553986,7 @@ function startHeteroAgentRun(params, accountEnv, logger) {
553502
553986
  const stdinPayload = buildHeteroExecStdinPayload({
553503
553987
  imageList,
553504
553988
  isNewSession: !resumeSessionId,
553989
+ permissionMode: params.permissionMode,
553505
553990
  prompt,
553506
553991
  resumeFallbackSystemContext,
553507
553992
  systemContext
@@ -555869,6 +556354,7 @@ function bindGatewayClientHandlers(client, ctx, connectionWorkspaceId) {
555869
556354
  imageList: request.imageList,
555870
556355
  jwt: request.jwt,
555871
556356
  operationId: request.operationId,
556357
+ permissionMode: request.permissionMode,
555872
556358
  prompt: request.prompt,
555873
556359
  resumeFallbackSystemContext: request.resumeFallbackSystemContext,
555874
556360
  resumeSessionId: request.resumeSessionId,
@@ -562608,6 +563094,11 @@ const DEFAULT_ASK_USER_TIMEOUT_MS = 600 * 1e3;
562608
563094
  //#endregion
562609
563095
  //#region ../../packages/heterogeneous-agents/src/askUser/AskUserBridge.ts
562610
563096
  /**
563097
+ * Wire deadline of a request that never times out: durable review rows need a
563098
+ * finite one, and a year outlives any run.
563099
+ */
563100
+ const NO_DEADLINE_MS = 365 * 24 * 60 * 60 * 1e3;
563101
+ /**
562611
563102
  * Per-operation channel between an MCP tool handler (which awaits the user)
562612
563103
  * and the producer's outbound stream (which carries the request to UI and
562613
563104
  * receives the user's answer back).
@@ -562664,9 +563155,10 @@ var AskUserBridge = class {
562664
563155
  const timeoutMs = options.timeoutMs ?? 6e5;
562665
563156
  const progressIntervalMs = options.progressIntervalMs ?? 3e4;
562666
563157
  const startedAt = Date.now();
562667
- const deadline = startedAt + timeoutMs;
563158
+ const expires = Number.isFinite(timeoutMs);
563159
+ const deadline = startedAt + (expires ? timeoutMs : NO_DEADLINE_MS);
562668
563160
  return new Promise((resolve, reject) => {
562669
- const timeoutTimer = setTimeout(() => {
563161
+ const onTimeout = () => {
562670
563162
  this.pending_.delete(toolCallId);
562671
563163
  clearInterval(progressTimer);
562672
563164
  this.emitResponse(toolCallId, {
@@ -562677,13 +563169,14 @@ var AskUserBridge = class {
562677
563169
  cancelled: true,
562678
563170
  cancelReason: "timeout"
562679
563171
  });
562680
- }, timeoutMs);
563172
+ };
563173
+ const timeoutTimer = expires ? setTimeout(onTimeout, timeoutMs) : void 0;
562681
563174
  const progressTimer = options.onProgress ? setInterval(() => {
562682
563175
  const elapsed = Date.now() - startedAt;
562683
563176
  Promise.resolve(options.onProgress(elapsed, timeoutMs)).catch(() => {});
562684
563177
  }, progressIntervalMs) : void 0;
562685
563178
  const cleanup = () => {
562686
- clearTimeout(timeoutTimer);
563179
+ if (timeoutTimer) clearTimeout(timeoutTimer);
562687
563180
  if (progressTimer) clearInterval(progressTimer);
562688
563181
  };
562689
563182
  this.pending_.set(toolCallId, {
@@ -582657,6 +583150,26 @@ const dispatchHeteroControl = async (message, context) => {
582657
583150
  }
582658
583151
  };
582659
583152
 
583153
+ //#endregion
583154
+ //#region src/utils/heteroPermissionMode.ts
583155
+ init_src$2();
583156
+ /** The control command the server queues when the user switches mode mid-run. */
583157
+ const HETERO_SET_PERMISSION_MODE_COMMAND = "set_permission_mode";
583158
+ /**
583159
+ * Switch the running Claude Code session's permission mode (the composer's
583160
+ * mode chip). Reports the mode Claude Code took — `acceptEdits` for
583161
+ * `bypassPermissions` as root; the mode report on the event stream follows.
583162
+ */
583163
+ const setPermissionModeHandler = async ({ params, sendControlRequest, signal }) => {
583164
+ const mode = params?.mode;
583165
+ if (!isHeteroPermissionMode(mode)) throw new Error("set_permission_mode needs a valid mode");
583166
+ return { mode: await setClaudeCodePermissionMode(sendControlRequest, mode, {
583167
+ isRoot: isRunningAsRoot(),
583168
+ signal
583169
+ }) };
583170
+ };
583171
+ registerHeteroControlHandler(HETERO_SET_PERMISSION_MODE_COMMAND, setPermissionModeHandler);
583172
+
582660
583173
  //#endregion
582661
583174
  //#region src/utils/heteroStopTask.ts
582662
583175
  /** The control command the server queues to stop one background task. */
@@ -583059,6 +583572,121 @@ const buildExtraArgs = (options) => {
583059
583572
  return extraArgs.length > 0 ? extraArgs : void 0;
583060
583573
  };
583061
583574
 
583575
+ //#endregion
583576
+ //#region src/commands/hetero/prompt.ts
583577
+ init_src$2();
583578
+ const readStdin = async () => {
583579
+ const chunks = [];
583580
+ for await (const chunk of process.stdin) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
583581
+ return Buffer.concat(chunks).toString("utf8");
583582
+ };
583583
+ /**
583584
+ * Resolve a raw `--input-json` argument: `'-'` (or empty) reads stdin, anything
583585
+ * else is treated as a filesystem path.
583586
+ */
583587
+ const readInputJson = async (location) => {
583588
+ if (location === "-" || location === "") return readStdin();
583589
+ return readFile(location, "utf8");
583590
+ };
583591
+ const looksLikeJsonInput = (value) => {
583592
+ const trimmed = value.trimStart();
583593
+ return trimmed.startsWith("{") || trimmed.startsWith("[");
583594
+ };
583595
+ /**
583596
+ * Convert an `--image <value>` argument into an image source. Recognized
583597
+ * shapes: `https?://...` URL, `data:` URL, otherwise a filesystem path
583598
+ * resolved relative to the CLI's cwd.
583599
+ */
583600
+ const parseImageArg = (value) => {
583601
+ if (/^https?:\/\//i.test(value)) return {
583602
+ type: "url",
583603
+ url: value
583604
+ };
583605
+ if (value.startsWith("data:")) {
583606
+ const match = value.match(/^data:([^;,]+);base64,(.+)$/);
583607
+ if (!match) throw new Error(`Invalid data URL for --image: ${value.slice(0, 40)}…`);
583608
+ return {
583609
+ data: match[2],
583610
+ mediaType: match[1],
583611
+ type: "base64"
583612
+ };
583613
+ }
583614
+ return {
583615
+ path: path.resolve(process.cwd(), value),
583616
+ type: "path"
583617
+ };
583618
+ };
583619
+ /**
583620
+ * Best-effort coercion of a JSON-decoded value into an `AgentPromptInput`.
583621
+ * Accepts:
583622
+ * - `'plain text'` → single text block
583623
+ * - `[{ type: 'text', text }, { type: 'image', source }]` → content blocks
583624
+ * - `{ content: [...], resumeFallback?: [...], permissionMode? }` → unwraps the
583625
+ * primary prompt, reserves the fallback for a retry without native resume,
583626
+ * and takes the Claude Code permission mode the run was dispatched with
583627
+ * - `{ type: 'text', ... } | { type: 'image', ... }` → single block
583628
+ */
583629
+ const coerceJsonPrompt = (parsed) => {
583630
+ if (typeof parsed === "string") return { prompt: parsed };
583631
+ if (Array.isArray(parsed)) return { prompt: parsed };
583632
+ if (parsed && typeof parsed === "object") {
583633
+ const obj = parsed;
583634
+ if (Array.isArray(obj.content)) return {
583635
+ ...isHeteroPermissionMode(obj.permissionMode) && { permissionMode: obj.permissionMode },
583636
+ prompt: obj.content,
583637
+ ...Array.isArray(obj.resumeFallback) ? { resumeFallbackPrompt: obj.resumeFallback } : {}
583638
+ };
583639
+ if (obj.type === "text" || obj.type === "image") return { prompt: [obj] };
583640
+ }
583641
+ throw new Error("Invalid --input-json shape: expected a string, array of content blocks, or `{ content: [...] }` envelope.");
583642
+ };
583643
+ const buildPromptFromText = (text, images) => {
583644
+ if (images.length === 0) return {
583645
+ describe: () => text.trim(),
583646
+ prompt: text
583647
+ };
583648
+ const blocks = [];
583649
+ if (text.length > 0) blocks.push({
583650
+ text,
583651
+ type: "text"
583652
+ });
583653
+ for (const image of images) blocks.push({
583654
+ source: parseImageArg(image),
583655
+ type: "image"
583656
+ });
583657
+ return {
583658
+ describe: () => blocks.map((b) => b.type === "text" ? b.text.trim() : "[image]").filter(Boolean).join(" ").trim(),
583659
+ prompt: blocks
583660
+ };
583661
+ };
583662
+ /**
583663
+ * Decide which input mode the user requested and produce a unified prompt.
583664
+ *
583665
+ * Mode resolution (mutually exclusive):
583666
+ * 1. `--input-json` → read JSON file or stdin, parse to content blocks
583667
+ * 2. `--prompt` (with optional `--image` flags) → text + images
583668
+ * 3. (default) read stdin: auto-detect JSON vs plain text by first char
583669
+ */
583670
+ const resolvePrompt = async (options) => {
583671
+ const images = options.image ?? [];
583672
+ if (options.inputJson !== void 0) {
583673
+ if (options.prompt !== void 0) throw new Error("--prompt and --input-json are mutually exclusive.");
583674
+ if (images.length > 0) throw new Error("--image cannot be combined with --input-json (put images in the JSON).");
583675
+ const raw = await readInputJson(options.inputJson);
583676
+ return {
583677
+ describe: () => raw.trim(),
583678
+ ...coerceJsonPrompt(JSON.parse(raw))
583679
+ };
583680
+ }
583681
+ if (options.prompt !== void 0 && options.prompt !== "-") return buildPromptFromText(options.prompt, images);
583682
+ const raw = await readStdin();
583683
+ if (looksLikeJsonInput(raw)) return {
583684
+ describe: () => raw.trim(),
583685
+ ...coerceJsonPrompt(JSON.parse(raw))
583686
+ };
583687
+ return buildPromptFromText(raw, images);
583688
+ };
583689
+
583062
583690
  //#endregion
583063
583691
  //#region src/commands/hetero/index.ts
583064
583692
  init_resolveCliCommand();
@@ -583170,122 +583798,13 @@ const RESUME_RETRY_PATTERNS = [
583170
583798
  ];
583171
583799
  const looksLikeNeedsRetryWithoutResume = (text) => RESUME_RETRY_PATTERNS.some((p) => p.test(text));
583172
583800
  const isMissingGrokResumeSession = (data) => {
583173
- if (data?.agentType !== "grok-build" || !isRecord$7(data.details)) return false;
583801
+ if (data?.agentType !== "grok-build" || !isRecord$8(data.details)) return false;
583174
583802
  const { details } = data;
583175
583803
  const rpcData = details.data;
583176
- return details.method === "session/load" && isRecord$7(rpcData) && rpcData.code === "FS_NOT_FOUND";
583804
+ return details.method === "session/load" && isRecord$8(rpcData) && rpcData.code === "FS_NOT_FOUND";
583177
583805
  };
583178
583806
  const collectImage = (value, previous = []) => [...previous, value];
583179
583807
  const collectAgentArg = (value, previous = []) => [...previous, value];
583180
- const readStdin = async () => {
583181
- const chunks = [];
583182
- for await (const chunk of process.stdin) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
583183
- return Buffer.concat(chunks).toString("utf8");
583184
- };
583185
- /**
583186
- * Resolve a raw `--input-json` argument: `'-'` (or empty) reads stdin, anything
583187
- * else is treated as a filesystem path.
583188
- */
583189
- const readInputJson = async (location) => {
583190
- if (location === "-" || location === "") return readStdin();
583191
- return readFile(location, "utf8");
583192
- };
583193
- const looksLikeJsonInput = (value) => {
583194
- const trimmed = value.trimStart();
583195
- return trimmed.startsWith("{") || trimmed.startsWith("[");
583196
- };
583197
- /**
583198
- * Convert an `--image <value>` argument into an image source. Recognized
583199
- * shapes: `https?://...` URL, `data:` URL, otherwise a filesystem path
583200
- * resolved relative to the CLI's cwd.
583201
- */
583202
- const parseImageArg = (value) => {
583203
- if (/^https?:\/\//i.test(value)) return {
583204
- type: "url",
583205
- url: value
583206
- };
583207
- if (value.startsWith("data:")) {
583208
- const match = value.match(/^data:([^;,]+);base64,(.+)$/);
583209
- if (!match) throw new Error(`Invalid data URL for --image: ${value.slice(0, 40)}…`);
583210
- return {
583211
- data: match[2],
583212
- mediaType: match[1],
583213
- type: "base64"
583214
- };
583215
- }
583216
- return {
583217
- path: path.resolve(process.cwd(), value),
583218
- type: "path"
583219
- };
583220
- };
583221
- /**
583222
- * Best-effort coercion of a JSON-decoded value into an `AgentPromptInput`.
583223
- * Accepts:
583224
- * - `'plain text'` → single text block
583225
- * - `[{ type: 'text', text }, { type: 'image', source }]` → content blocks
583226
- * - `{ content: [...], resumeFallback?: [...] }` → unwraps the primary prompt
583227
- * and reserves the fallback for a retry without native resume
583228
- * - `{ type: 'text', ... } | { type: 'image', ... }` → single block
583229
- */
583230
- const coerceJsonPrompt = (parsed) => {
583231
- if (typeof parsed === "string") return { prompt: parsed };
583232
- if (Array.isArray(parsed)) return { prompt: parsed };
583233
- if (parsed && typeof parsed === "object") {
583234
- const obj = parsed;
583235
- if (Array.isArray(obj.content)) return {
583236
- prompt: obj.content,
583237
- ...Array.isArray(obj.resumeFallback) ? { resumeFallbackPrompt: obj.resumeFallback } : {}
583238
- };
583239
- if (obj.type === "text" || obj.type === "image") return { prompt: [obj] };
583240
- }
583241
- throw new Error("Invalid --input-json shape: expected a string, array of content blocks, or `{ content: [...] }` envelope.");
583242
- };
583243
- const buildPromptFromText = (text, images) => {
583244
- if (images.length === 0) return {
583245
- describe: () => text.trim(),
583246
- prompt: text
583247
- };
583248
- const blocks = [];
583249
- if (text.length > 0) blocks.push({
583250
- text,
583251
- type: "text"
583252
- });
583253
- for (const image of images) blocks.push({
583254
- source: parseImageArg(image),
583255
- type: "image"
583256
- });
583257
- return {
583258
- describe: () => blocks.map((b) => b.type === "text" ? b.text.trim() : "[image]").filter(Boolean).join(" ").trim(),
583259
- prompt: blocks
583260
- };
583261
- };
583262
- /**
583263
- * Decide which input mode the user requested and produce a unified prompt.
583264
- *
583265
- * Mode resolution (mutually exclusive):
583266
- * 1. `--input-json` → read JSON file or stdin, parse to content blocks
583267
- * 2. `--prompt` (with optional `--image` flags) → text + images
583268
- * 3. (default) read stdin: auto-detect JSON vs plain text by first char
583269
- */
583270
- const resolvePrompt = async (options) => {
583271
- const images = options.image ?? [];
583272
- if (options.inputJson !== void 0) {
583273
- if (options.prompt !== void 0) throw new Error("--prompt and --input-json are mutually exclusive.");
583274
- if (images.length > 0) throw new Error("--image cannot be combined with --input-json (put images in the JSON).");
583275
- const raw = await readInputJson(options.inputJson);
583276
- return {
583277
- describe: () => raw.trim(),
583278
- ...coerceJsonPrompt(JSON.parse(raw))
583279
- };
583280
- }
583281
- if (options.prompt !== void 0 && options.prompt !== "-") return buildPromptFromText(options.prompt, images);
583282
- const raw = await readStdin();
583283
- if (looksLikeJsonInput(raw)) return {
583284
- describe: () => raw.trim(),
583285
- ...coerceJsonPrompt(JSON.parse(raw))
583286
- };
583287
- return buildPromptFromText(raw, images);
583288
- };
583289
583808
  /**
583290
583809
  * Persists the agent process's RAW stdout/stderr — the untouched stream-json,
583291
583810
  * BEFORE the adapter — to disk for post-hoc debugging. The adapted/ingested
@@ -583822,6 +584341,7 @@ const exec = async (options) => {
583822
584341
  initialModel: usesHeterogeneousSessionInitialModel(options.type) ? options.model : void 0,
583823
584342
  liveInput: options.type === "claude-code",
583824
584343
  operationId,
584344
+ ...options.type === "claude-code" && resolved.permissionMode && { permissionMode: resolved.permissionMode },
583825
584345
  uploadImage
583826
584346
  };
583827
584347
  const first = await runOneAgent({
@@ -584876,6 +585396,8 @@ const resolveTargetDevice = async (client, device) => {
584876
585396
  */
584877
585397
  const sendToNewConversation = async (client, params) => {
584878
585398
  const agentId = params.agentId ?? process.env.LOBEHUB_AGENT_ID;
585399
+ if (params.detach && params.parentTopicId) throw new Error("Pass either --parent-topic-id or --detach, not both.");
585400
+ const parentTopicId = params.detach ? void 0 : params.parentTopicId || process.env.LOBEHUB_TOPIC_ID || void 0;
584879
585401
  if (!agentId) throw new Error("No agent to start the new conversation with: pass --agent-id (LOBEHUB_AGENT_ID is not set).");
584880
585402
  const request = {
584881
585403
  agentId,
@@ -584888,6 +585410,7 @@ const sendToNewConversation = async (client, params) => {
584888
585410
  request.requireDevice = true;
584889
585411
  }
584890
585412
  if (params.title) request.title = params.title;
585413
+ if (parentTopicId) request.openedByTopicId = parentTopicId;
584891
585414
  const sourceOperationId = process.env.LOBEHUB_OPERATION_ID;
584892
585415
  if (sourceOperationId) request.sourceOperationId = sourceOperationId;
584893
585416
  const started = await client.aiAgent.execAgent.mutate(request);
@@ -584922,10 +585445,15 @@ const reportConversationSend = async (send, options) => {
584922
585445
  console.log(import_picocolors.default.dim("The answer arrives in that conversation. If it replies to you, the reply wakes this one."));
584923
585446
  };
584924
585447
  function registerTopicSendCommand(topic) {
584925
- topic.command("send [topicId]").description("Send a message to another conversation and have its agent act on it (queued if it is busy), or with --new hand it to a new conversation. Unlike 'lh message create', this wakes the agent").requiredOption("-c, --content <content>", "Message content").option("--new", "Open a new conversation for the message instead of sending to <topicId>").option("--agent-id <id>", `With --new: ${NEW_CONVERSATION_OPTIONS_HELP.agentId}`).option("--device <target>", `With --new: ${NEW_CONVERSATION_OPTIONS_HELP.device}`).option("--title <title>", `With --new: ${NEW_CONVERSATION_OPTIONS_HELP.title}`).option("--workspace <id|slug>", "The workspace the topic lives in (overrides LOBEHUB_WORKSPACE_ID and 'workspace use')").option("--json", "Output JSON").addHelpText("after", `
585448
+ topic.command("send [topicId]").description("Send a message to another conversation and have its agent act on it (queued if it is busy), or with --new hand it to a new conversation. Unlike 'lh message create', this wakes the agent").requiredOption("-c, --content <content>", "Message content").option("--new", "Open a new conversation for the message instead of sending to <topicId>").option("--agent-id <id>", `With --new: ${NEW_CONVERSATION_OPTIONS_HELP.agentId}`).option("--device <target>", `With --new: ${NEW_CONVERSATION_OPTIONS_HELP.device}`).option("--title <title>", `With --new: ${NEW_CONVERSATION_OPTIONS_HELP.title}`).option("--parent-topic-id <tpc_id>", "With --new: the parent topic the new one lists under (default: the conversation running this command, LOBEHUB_TOPIC_ID)").option("--detach", "With --new: link the new topic to no parent, even from inside a conversation").option("--workspace <id|slug>", "The workspace the topic lives in (overrides LOBEHUB_WORKSPACE_ID and 'workspace use')").option("--json", "Output JSON").addHelpText("after", `
584926
585449
  Examples:
584927
585450
  lh topic send tpc_xxx -c "Iterate the verifier with these notes"
584928
585451
  lh topic send --new -c "Draft the release notes" --device local --title "Release notes"
585452
+ lh topic send --new -c "Check the flaky test" --parent-topic-id tpc_xxx
585453
+
585454
+ Run from inside a conversation, --new opens a topic linked to it as its parent
585455
+ ('lh topic list --parent-topic-id <id>' lists them); --detach opens one that
585456
+ stands on its own.
584929
585457
 
584930
585458
  Run by an agent, the message is shown as written by that agent, and the
584931
585459
  receiving agent can answer it with 'lh message reply <messageId>', which wakes
@@ -584938,7 +585466,7 @@ after a few rounds, so a person can step in.`).action(async (topicId, options) =
584938
585466
  return sendToNewConversation(client, { ...options });
584939
585467
  }
584940
585468
  if (!topicId) throw new Error("Pass the <topicId> to send to, or --new to open a new conversation.");
584941
- if (options.agentId || options.device || options.title) throw new Error("--agent-id, --device and --title only apply with --new; an existing conversation keeps its own.");
585469
+ if (options.agentId || options.device || options.title || options.parentTopicId || options.detach) throw new Error("--agent-id, --device, --title, --parent-topic-id and --detach only apply with --new; an existing conversation keeps its own.");
584942
585470
  return sendToConversation(client, {
584943
585471
  content: options.content,
584944
585472
  topicId
@@ -590128,6 +590656,52 @@ function registerTopicExportCommand(topic) {
590128
590656
  });
590129
590657
  }
590130
590658
 
590659
+ //#endregion
590660
+ //#region src/commands/topic/lifecycle.ts
590661
+ /** Print a refusal and exit 1 instead of a stack trace. */
590662
+ const run = async (fn) => {
590663
+ try {
590664
+ await fn();
590665
+ } catch (error) {
590666
+ log$15.error(error.message);
590667
+ process.exit(1);
590668
+ }
590669
+ };
590670
+ const WORKSPACE_OPTION_HELP = "Workspace (overrides LOBEHUB_WORKSPACE_ID and 'workspace use')";
590671
+ /**
590672
+ * A topic's lifecycle from the CLI: stop its running turn, archive it, or bring
590673
+ * it back — through the same entries the app's own buttons use
590674
+ * (`aiAgent.interruptTask`, `topic.updateTopic`).
590675
+ */
590676
+ function registerTopicLifecycleCommands(topic) {
590677
+ topic.command("stop <topicId>").description("Stop the topic's running turn (the ones you started)").option("--workspace <id|slug>", WORKSPACE_OPTION_HELP).option("--json", "Output JSON").action((topicId, options) => run(async () => {
590678
+ const result = await (await getTrpcClient(await resolveWorkspaceRef(options.workspace))).aiAgent.interruptTask.mutate({ topicId });
590679
+ if (options.json) return outputJson(result);
590680
+ if (!result.success) throw new Error(`${topicId}: ${(result.running ?? 0) - (result.stopped ?? 0)} run(s) could not be confirmed stopped (a device may still be running them). Try again once the device is reachable.`);
590681
+ console.log(result.stopped ? `${import_picocolors.default.green("✓")} Stopped ${topicId}.` : `${topicId} was not running.`);
590682
+ }));
590683
+ topic.command("archive <topicId>").description("Archive a topic: it leaves the agent list, and its auto-created worktree is cleaned up").option("--workspace <id|slug>", WORKSPACE_OPTION_HELP).action((topicId, options) => run(async () => {
590684
+ await (await getTrpcClient(await resolveWorkspaceRef(options.workspace))).topic.updateTopic.mutate({
590685
+ id: topicId,
590686
+ value: {
590687
+ completedAt: /* @__PURE__ */ new Date(),
590688
+ status: "completed"
590689
+ }
590690
+ });
590691
+ console.log(`${import_picocolors.default.green("✓")} Archived ${topicId}.`);
590692
+ }));
590693
+ topic.command("unarchive <topicId>").description("Bring an archived topic back to the agent list").option("--workspace <id|slug>", WORKSPACE_OPTION_HELP).action((topicId, options) => run(async () => {
590694
+ await (await getTrpcClient(await resolveWorkspaceRef(options.workspace))).topic.updateTopic.mutate({
590695
+ id: topicId,
590696
+ value: {
590697
+ completedAt: null,
590698
+ status: "active"
590699
+ }
590700
+ });
590701
+ console.log(`${import_picocolors.default.green("✓")} Unarchived ${topicId}.`);
590702
+ }));
590703
+ }
590704
+
590131
590705
  //#endregion
590132
590706
  //#region src/commands/topic/readTranscript.ts
590133
590707
  /** A server that predates the operation route answers this for the unknown path. */
@@ -590337,10 +590911,17 @@ function registerTopicViewCommand(topic) {
590337
590911
  //#region src/commands/topic.ts
590338
590912
  function registerTopicCommand(program) {
590339
590913
  const topic = program.command("topic").description("Manage conversation topics");
590340
- topic.command("list").description("List topics").option("--agent-id <id>", "Filter by agent ID").option("-L, --limit <n>", "Page size", "30").option("-P, --page <n>", "Page number", "1").option("--json [fields]", "Output JSON, optionally specify fields (comma-separated)").action(async (options) => {
590914
+ topic.command("list").description("List topics").option("--agent-id <id>", "Filter by agent ID").option("--parent-topic-id <tpc_id>", "Only the topics opened from this one (its child topics), whatever their agent").option("--opened-by-me", "Only the topics this conversation opened (--parent-topic-id from LOBEHUB_TOPIC_ID)").option("-L, --limit <n>", "Page size", "30").option("-P, --page <n>", "Page number", "1").option("--json [fields]", "Output JSON, optionally specify fields (comma-separated)").action(async (options) => {
590915
+ const parentTopicId = options.parentTopicId ?? (options.openedByMe ? process.env.LOBEHUB_TOPIC_ID : void 0);
590916
+ if (options.openedByMe && !parentTopicId) {
590917
+ log$15.error("--opened-by-me needs LOBEHUB_TOPIC_ID; pass --parent-topic-id instead.");
590918
+ process.exit(1);
590919
+ return;
590920
+ }
590341
590921
  const client = await getTrpcClient();
590342
590922
  const input = {};
590343
590923
  if (options.agentId) input.agentId = options.agentId;
590924
+ if (parentTopicId) input.openedByTopicId = parentTopicId;
590344
590925
  if (options.limit) input.pageSize = Number.parseInt(options.limit, 10);
590345
590926
  const page = options.page ? Number.parseInt(options.page, 10) : void 0;
590346
590927
  if (page !== void 0 && page > 1) input.current = page - 1;
@@ -590358,6 +590939,20 @@ function registerTopicCommand(program) {
590358
590939
  console.log("No topics found.");
590359
590940
  return;
590360
590941
  }
590942
+ if (parentTopicId) {
590943
+ printTable(items.map((t) => [
590944
+ t.id || "",
590945
+ truncate$2(t.title || "Untitled", 50),
590946
+ t.agentId || "",
590947
+ t.updatedAt ? timeAgo(t.updatedAt) : ""
590948
+ ]), [
590949
+ "ID",
590950
+ "TITLE",
590951
+ "AGENT",
590952
+ "UPDATED"
590953
+ ]);
590954
+ return;
590955
+ }
590361
590956
  printTable(items.map((t) => [
590362
590957
  t.id || "",
590363
590958
  truncate$2(t.title || "Untitled", 50),
@@ -590525,6 +591120,7 @@ function registerTopicCommand(program) {
590525
591120
  registerTopicExportCommand(topic);
590526
591121
  registerTopicViewCommand(topic);
590527
591122
  registerTopicSendCommand(topic);
591123
+ registerTopicLifecycleCommands(topic);
590528
591124
  }
590529
591125
 
590530
591126
  //#endregion