@karlorz/codexhost-cli-win32-x64 0.17.1-0 → 0.17.4-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15946,6 +15946,21 @@ var threadSteeringInspectParamsSchema = external_exports.object({
15946
15946
  /** The text about to be steered; a Harness command always stops and restarts. */
15947
15947
  text: external_exports.string().optional()
15948
15948
  }).strict();
15949
+ var threadSteeringContextSchema = external_exports.object({
15950
+ kind: external_exports.literal("application"),
15951
+ value: external_exports.string().transform((text, context) => {
15952
+ try {
15953
+ return JSON.parse(text);
15954
+ } catch {
15955
+ context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
15956
+ return external_exports.NEVER;
15957
+ }
15958
+ }).pipe(external_exports.object({
15959
+ expectedTurnId: hostTurnIdSchema,
15960
+ clientUserMessageId: external_exports.string().min(1),
15961
+ delivery: external_exports.enum(["newTurn", "activeTurn"])
15962
+ }).strict())
15963
+ }).strict().transform((context) => context.value);
15949
15964
  var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
15950
15965
  var threadSteeringInspectResultSchema = external_exports.object({
15951
15966
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
@@ -22480,6 +22495,33 @@ function grokHiddenInput(event) {
22480
22495
  function grokHostTurn(event) {
22481
22496
  return event.metadata?.hostTurn === true || event.metadata?.host_turn === true;
22482
22497
  }
22498
+ var GROK_SIBLING_TERMINAL = /^(?:subagent-completed-|task-completed-)/u;
22499
+ function grokSiblingTerminalKey(key) {
22500
+ return GROK_SIBLING_TERMINAL.test(key);
22501
+ }
22502
+ function grokForeignBackgroundEvent(event) {
22503
+ if (event.type === "turn.completed")
22504
+ return grokSiblingTerminalKey(event.nativeTurnKey);
22505
+ if (event.type === "user.text") {
22506
+ return grokHiddenInput(event) && /background subagent completed|Background task/iu.test(event.text);
22507
+ }
22508
+ const promptId = event.metadata?.promptId ?? event.metadata?.prompt_id;
22509
+ return typeof promptId === "string" && grokSiblingTerminalKey(promptId);
22510
+ }
22511
+ function grokBackgroundOwnedTurn(input) {
22512
+ return input.turnId.startsWith("grok-autonomous-") || input.backgroundPromptIndex !== void 0;
22513
+ }
22514
+ function selectGrokSettledTurn(created, expectedKey, backgroundPromptIndex) {
22515
+ if (expectedKey) {
22516
+ const matched = created.filter((turn) => turn.nativeTurnRef.nativeTurnKey === expectedKey);
22517
+ return matched.length === 1 ? matched[0] : void 0;
22518
+ }
22519
+ if (backgroundPromptIndex !== void 0) {
22520
+ const matched = created.filter((turn) => Number(turn.checkpoint?.checkpointId) === backgroundPromptIndex);
22521
+ return matched.length === 1 ? matched[0] : void 0;
22522
+ }
22523
+ return created.length === 1 ? created[0] : void 0;
22524
+ }
22483
22525
  var GrokNativeIdentityReuseError = class extends Error {
22484
22526
  constructor(key) {
22485
22527
  super(`Grok Native terminal identity reused by a new prompt: ${key}`);
@@ -25113,8 +25155,20 @@ function grokElicitationResolvedToolCallId(update) {
25113
25155
  // dist/permission-modes.js
25114
25156
  var nativePermissionModes = /* @__PURE__ */ new Set(["ask", "auto", "always-approve"]);
25115
25157
  var GROK_DEFAULT_PERMISSION_MODE_ID = harnessPermissionModeIdSchema.parse("ask");
25158
+ var GROK_PLAN_MODE_ID = harnessPermissionModeIdSchema.parse("plan");
25116
25159
  var GROK_PERMISSION_MODE_CATALOG = harnessPermissionModeCatalogSchema.parse({
25117
25160
  modes: [
25161
+ {
25162
+ id: "plan",
25163
+ label: "Plan",
25164
+ localizations: {
25165
+ "zh-CN": {
25166
+ label: "规划模式",
25167
+ description: "先探索并写计划;批准后退出规划并开始实现。工具权限仍由询问/自动/始终批准决定。"
25168
+ }
25169
+ },
25170
+ description: "Explore and write a plan; approval exits planning and starts implementation. Tool permission stays Ask, Auto, or Always approve."
25171
+ },
25118
25172
  {
25119
25173
  id: "ask",
25120
25174
  label: "Ask",
@@ -25141,6 +25195,9 @@ var GROK_PERMISSION_MODE_CATALOG = harnessPermissionModeCatalogSchema.parse({
25141
25195
  ],
25142
25196
  defaultModeId: GROK_DEFAULT_PERMISSION_MODE_ID
25143
25197
  });
25198
+ function isGrokPlanModeId(permissionModeId) {
25199
+ return String(permissionModeId ?? "") === "plan";
25200
+ }
25144
25201
  function decodeGrokPermissionModeId(permissionModeId) {
25145
25202
  const parsed = harnessPermissionModeIdSchema.parse(permissionModeId);
25146
25203
  if (!nativePermissionModes.has(parsed)) {
@@ -25148,6 +25205,16 @@ function decodeGrokPermissionModeId(permissionModeId) {
25148
25205
  }
25149
25206
  return parsed;
25150
25207
  }
25208
+ function grokCatalogPermissionModeId(permissionModeId) {
25209
+ if (isGrokPlanModeId(permissionModeId))
25210
+ return GROK_PLAN_MODE_ID;
25211
+ return harnessPermissionModeIdSchema.parse(decodeGrokPermissionModeId(permissionModeId));
25212
+ }
25213
+ function grokOpenPermissionPolicy(permissionModeId, kind) {
25214
+ if (isGrokPlanModeId(permissionModeId))
25215
+ return kind === "create" ? "ask" : void 0;
25216
+ return decodeGrokPermissionModeId(permissionModeId);
25217
+ }
25151
25218
  function grokPermissionModeSessionMeta(permissionMode) {
25152
25219
  return {
25153
25220
  yoloMode: permissionMode === "always-approve",
@@ -25412,6 +25479,163 @@ var GrokQuestions = class {
25412
25479
  }
25413
25480
  };
25414
25481
 
25482
+ // dist/grok-plan-approval.js
25483
+ var GROK_EXIT_PLAN_MODE_METHODS = ["_x.ai/exit_plan_mode", "x.ai/exit_plan_mode"];
25484
+ var DECISION_ID = "plan-decision";
25485
+ var FEEDBACK_ID = "plan-feedback";
25486
+ function isRecord16(value) {
25487
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25488
+ }
25489
+ function nonEmptyString3(value) {
25490
+ return typeof value === "string" && value.trim().length > 0;
25491
+ }
25492
+ function isGrokExitPlanModeMethod(method) {
25493
+ return GROK_EXIT_PLAN_MODE_METHODS.includes(method);
25494
+ }
25495
+ function parseGrokPlanApprovalRequest(value) {
25496
+ if (!isRecord16(value) || !nonEmptyString3(value.sessionId) || !nonEmptyString3(value.toolCallId)) {
25497
+ throw new Error("Grok plan approval requires sessionId and toolCallId");
25498
+ }
25499
+ const raw = value.planContent ?? value.plan_content;
25500
+ if (raw != null && typeof raw !== "string") {
25501
+ throw new Error("Grok plan approval planContent must be text");
25502
+ }
25503
+ return {
25504
+ sessionId: value.sessionId,
25505
+ toolCallId: value.toolCallId,
25506
+ planContent: typeof raw === "string" && raw.trim().length > 0 ? raw : null
25507
+ };
25508
+ }
25509
+ function createGrokPlanReview(request, interactionId, turnId) {
25510
+ const warning = "Approving this plan will exit Grok plan mode and let Grok begin implementation under the current Ask, Auto, or Always approve setting. This is not a one-time tool approval.";
25511
+ const prompt = request.planContent ? `${warning}
25512
+
25513
+ ${request.planContent}` : `${warning}
25514
+
25515
+ # No plan written yet
25516
+
25517
+ Grok exited plan mode without a plan body. You can still approve and start implementing, stay in plan mode, or turn plan mode off.`;
25518
+ return {
25519
+ type: "question",
25520
+ interactionId,
25521
+ turnId,
25522
+ title: "Review plan",
25523
+ questions: [
25524
+ {
25525
+ id: DECISION_ID,
25526
+ type: "choice",
25527
+ prompt,
25528
+ options: [
25529
+ {
25530
+ value: "cancelled",
25531
+ label: "Stay in plan mode",
25532
+ description: "Keep planning. Optional comments below are sent as change requests."
25533
+ },
25534
+ {
25535
+ value: "approved",
25536
+ label: "Approve plan and start implementation",
25537
+ description: "Exit plan mode and begin implementing."
25538
+ },
25539
+ {
25540
+ value: "abandoned",
25541
+ label: "Exit plan mode without implementing",
25542
+ description: "Turn plan mode off and do not start implementation."
25543
+ }
25544
+ ],
25545
+ multiple: false,
25546
+ allowOther: false,
25547
+ optional: false
25548
+ },
25549
+ {
25550
+ id: FEEDBACK_ID,
25551
+ type: "text",
25552
+ prompt: "Optional changes to request if you stay in plan mode",
25553
+ multiline: true,
25554
+ secret: false,
25555
+ optional: true
25556
+ }
25557
+ ]
25558
+ };
25559
+ }
25560
+ function grokPlanReviewResponse(response) {
25561
+ if (response.cancelled)
25562
+ return { outcome: "cancelled" };
25563
+ const decision = response.answers[DECISION_ID]?.[0];
25564
+ const outcome = decision === "approved" || decision === "abandoned" ? decision : "cancelled";
25565
+ const feedback = response.answers[FEEDBACK_ID]?.[0]?.trim();
25566
+ return {
25567
+ outcome,
25568
+ ...outcome === "cancelled" && feedback ? { feedback } : {}
25569
+ };
25570
+ }
25571
+ var GrokPlanApprovals = class {
25572
+ turnId;
25573
+ randomUUID;
25574
+ emit;
25575
+ #pending = /* @__PURE__ */ new Map();
25576
+ #seenToolCalls = /* @__PURE__ */ new Set();
25577
+ #closed = false;
25578
+ constructor(turnId, randomUUID3, emit) {
25579
+ this.turnId = turnId;
25580
+ this.randomUUID = randomUUID3;
25581
+ this.emit = emit;
25582
+ }
25583
+ has(interactionId) {
25584
+ return this.#pending.has(interactionId);
25585
+ }
25586
+ ask(request) {
25587
+ if (this.#closed || this.#seenToolCalls.has(request.toolCallId))
25588
+ return Promise.resolve({ outcome: "cancelled" });
25589
+ this.#seenToolCalls.add(request.toolCallId);
25590
+ const interaction = createGrokPlanReview(request, hostInteractionIdSchema.parse(this.randomUUID()), this.turnId);
25591
+ return new Promise((resolve) => {
25592
+ this.#pending.set(interaction.interactionId, { request, interaction, resolve });
25593
+ this.emit({ kind: "interaction", interaction });
25594
+ });
25595
+ }
25596
+ respond(command) {
25597
+ const pending = this.#pending.get(command.interactionId);
25598
+ if (!pending)
25599
+ return this.#error("invalidState", "Grok plan approval is not pending");
25600
+ if (command.response.type !== "question") {
25601
+ return this.#error("invalidRequest", "Grok plan approval requires a Question Response");
25602
+ }
25603
+ const error53 = validateHostQuestionResponse(pending.interaction, command.response);
25604
+ if (error53)
25605
+ return { ok: false, error: error53 };
25606
+ this.#settle(pending, grokPlanReviewResponse(command.response), command.response.cancelled ? "cancelled" : "responded");
25607
+ return { ok: true, value: { accepted: true } };
25608
+ }
25609
+ withdraw(toolCallId) {
25610
+ for (const pending of this.#pending.values()) {
25611
+ if (pending.request.toolCallId === toolCallId)
25612
+ this.#settle(pending, { outcome: "cancelled" }, "cancelled");
25613
+ }
25614
+ }
25615
+ cancel() {
25616
+ this.#closed = true;
25617
+ for (const pending of this.#pending.values())
25618
+ this.#settle(pending, { outcome: "cancelled" }, "cancelled");
25619
+ }
25620
+ #settle(pending, response, reason) {
25621
+ if (!this.#pending.delete(pending.interaction.interactionId))
25622
+ return;
25623
+ pending.resolve(response);
25624
+ this.emit({
25625
+ kind: "event",
25626
+ event: {
25627
+ type: "interaction.closed",
25628
+ interactionId: pending.interaction.interactionId,
25629
+ turnId: this.turnId,
25630
+ reason
25631
+ }
25632
+ });
25633
+ }
25634
+ #error(code, message) {
25635
+ return { ok: false, error: { code, message, retryable: false } };
25636
+ }
25637
+ };
25638
+
25415
25639
  // dist/grok-interject.js
25416
25640
  var GROK_INTERJECT_METHOD = "x.ai/interject";
25417
25641
  var GROK_INTERJECT_FALLBACK_METHOD = "_x.ai/interject";
@@ -25445,16 +25669,16 @@ var GrokTransportError = class extends Error {
25445
25669
  this.name = "GrokTransportError";
25446
25670
  }
25447
25671
  };
25448
- function isRecord16(value) {
25672
+ function isRecord17(value) {
25449
25673
  return typeof value === "object" && value !== null && !Array.isArray(value);
25450
25674
  }
25451
25675
  function acpToolName(update, metadata) {
25452
- if (!isRecord16(update))
25676
+ if (!isRecord17(update))
25453
25677
  return void 0;
25454
25678
  if (typeof update.name === "string" && update.name.length > 0)
25455
25679
  return update.name;
25456
- const meta3 = isRecord16(update._meta) ? update._meta : metadata;
25457
- const tool = meta3 && isRecord16(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
25680
+ const meta3 = isRecord17(update._meta) ? update._meta : metadata;
25681
+ const tool = meta3 && isRecord17(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
25458
25682
  return tool && typeof tool.name === "string" && tool.name.length > 0 ? tool.name : void 0;
25459
25683
  }
25460
25684
  function errorText(error53) {
@@ -25510,20 +25734,20 @@ function signalProcessTree(child, signal) {
25510
25734
  try {
25511
25735
  process.kill(-child.pid, signal);
25512
25736
  } catch (error53) {
25513
- if (!isRecord16(error53) || error53.code === "ESRCH")
25737
+ if (!isRecord17(error53) || error53.code === "ESRCH")
25514
25738
  return;
25515
25739
  try {
25516
25740
  child.kill(signal);
25517
25741
  } catch (fallback) {
25518
- if (!isRecord16(fallback) || fallback.code !== "ESRCH")
25742
+ if (!isRecord17(fallback) || fallback.code !== "ESRCH")
25519
25743
  throw fallback;
25520
25744
  }
25521
25745
  }
25522
25746
  }
25523
25747
  function grokNotificationMetadata(envelope, update) {
25524
- if (!isRecord16(envelope) && !isRecord16(update))
25748
+ if (!isRecord17(envelope) && !isRecord17(update))
25525
25749
  return void 0;
25526
- return { ...isRecord16(update) ? update : {}, ...isRecord16(envelope) ? envelope : {} };
25750
+ return { ...isRecord17(update) ? update : {}, ...isRecord17(envelope) ? envelope : {} };
25527
25751
  }
25528
25752
  function transportEvent(update, metadata) {
25529
25753
  const extension = update;
@@ -25555,6 +25779,12 @@ function transportEvent(update, metadata) {
25555
25779
  ...metadata ? { metadata } : {}
25556
25780
  };
25557
25781
  }
25782
+ if (extension.sessionUpdate === "current_mode_update") {
25783
+ const modeId = typeof extension.currentModeId === "string" ? extension.currentModeId : typeof extension.current_mode_id === "string" ? extension.current_mode_id : "";
25784
+ if (!modeId)
25785
+ return null;
25786
+ return { type: "session.mode", modeId, ...metadata ? { metadata } : {} };
25787
+ }
25558
25788
  if (extension.sessionUpdate === "rewind_marker") {
25559
25789
  const targetPromptIndex = typeof extension.targetPromptIndex === "number" ? extension.targetPromptIndex : typeof extension.target_prompt_index === "number" ? extension.target_prompt_index : null;
25560
25790
  if (targetPromptIndex === null || !Number.isInteger(targetPromptIndex) || targetPromptIndex < 0) {
@@ -25646,7 +25876,7 @@ async function readNativeSignals(options, sessionId) {
25646
25876
  }
25647
25877
  }
25648
25878
  function isMissingFile(error53) {
25649
- return isRecord16(error53) && error53.code === "ENOENT";
25879
+ return isRecord17(error53) && error53.code === "ENOENT";
25650
25880
  }
25651
25881
  async function locateGrokNativeSession(options, sessionId) {
25652
25882
  if (sessionId.length === 0)
@@ -25669,7 +25899,7 @@ async function locateGrokNativeSession(options, sessionId) {
25669
25899
  try {
25670
25900
  summaryRaw = await readFile5(path17.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
25671
25901
  } catch (error53) {
25672
- if (isMissingFile(error53) || isRecord16(error53) && error53.code === "ENOTDIR")
25902
+ if (isMissingFile(error53) || isRecord17(error53) && error53.code === "ENOTDIR")
25673
25903
  continue;
25674
25904
  throw new GrokTransportError("unavailable", "Grok Native Session metadata could not be read", {
25675
25905
  cause: error53
@@ -25681,10 +25911,10 @@ async function locateGrokNativeSession(options, sessionId) {
25681
25911
  } catch {
25682
25912
  continue;
25683
25913
  }
25684
- if (!isRecord16(parsed))
25914
+ if (!isRecord17(parsed))
25685
25915
  continue;
25686
25916
  const info = parsed.info;
25687
- const cwd = isRecord16(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path17.resolve(info.cwd) : path17.resolve(decodeURIComponent(entry.name));
25917
+ const cwd = isRecord17(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path17.resolve(info.cwd) : path17.resolve(decodeURIComponent(entry.name));
25688
25918
  const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path17.resolve(parsed.source_workspace_dir) : void 0;
25689
25919
  matches.push({
25690
25920
  cwd,
@@ -25717,10 +25947,10 @@ function parseNativeHistory(contents, sessionId) {
25717
25947
  } catch {
25718
25948
  throw new GrokTransportError("protocolError", "Grok Native history contains invalid JSON");
25719
25949
  }
25720
- if (!isRecord16(record3) || !isRecord16(record3.params))
25950
+ if (!isRecord17(record3) || !isRecord17(record3.params))
25721
25951
  continue;
25722
25952
  const params = record3.params;
25723
- if (params.sessionId !== sessionId || !isRecord16(params.update))
25953
+ if (params.sessionId !== sessionId || !isRecord17(params.update))
25724
25954
  continue;
25725
25955
  let metadata = grokNotificationMetadata(params._meta, params.update._meta);
25726
25956
  if (typeof record3.timestamp === "number" && Number.isFinite(record3.timestamp))
@@ -25790,7 +26020,7 @@ var GrokAcpTransport = class {
25790
26020
  if (!this.#connection)
25791
26021
  throw new GrokTransportError("unavailable", "Grok ACP is unavailable");
25792
26022
  const result = await withTimeout(this.#connection.request("_x.ai/session/usage", { sessionId: this.sessionId }), this.#options.commandTimeoutMs, "Grok Session usage");
25793
- return isRecord16(result) ? result.usage : void 0;
26023
+ return isRecord17(result) ? result.usage : void 0;
25794
26024
  }
25795
26025
  async readHistory(sessionId, cwd = this.#options.cwd) {
25796
26026
  return readGrokNativeHistory({ ...this.#options, cwd }, sessionId);
@@ -25821,7 +26051,7 @@ var GrokAcpTransport = class {
25821
26051
  let session;
25822
26052
  let sessionId;
25823
26053
  if (input.kind === "create") {
25824
- const permissionMode = decodeGrokPermissionModeId(input.permissionModeId);
26054
+ const permissionMode = grokOpenPermissionPolicy(input.permissionModeId, "create");
25825
26055
  const created = await withTimeout(connection.newSession({
25826
26056
  cwd: this.#options.cwd,
25827
26057
  mcpServers: [],
@@ -25850,7 +26080,7 @@ var GrokAcpTransport = class {
25850
26080
  }
25851
26081
  sessionId = forked.newSessionId;
25852
26082
  } else {
25853
- const permissionMode = input.kind === "resume" ? decodeGrokPermissionModeId(input.permissionModeId) : void 0;
26083
+ const permissionMode = input.kind === "resume" ? grokOpenPermissionPolicy(input.permissionModeId, "resume") : void 0;
25854
26084
  session = await withTimeout(connection.loadSession({
25855
26085
  cwd: this.#options.cwd,
25856
26086
  mcpServers: [],
@@ -25895,7 +26125,7 @@ var GrokAcpTransport = class {
25895
26125
  sessionId: this.#sessionId,
25896
26126
  toolCallId
25897
26127
  }), 3e3, "Grok question activity");
25898
- if (!isRecord16(raw) || !("timeout" in raw))
26128
+ if (!isRecord17(raw) || !("timeout" in raw))
25899
26129
  throw new GrokTransportError("protocolError", "Invalid Grok activity acknowledgement");
25900
26130
  return raw.timeout === null ? null : questionAutoResolutionSchema.parse(raw.timeout);
25901
26131
  } catch (error53) {
@@ -26037,7 +26267,7 @@ var GrokAcpTransport = class {
26037
26267
  this.#goalPrompts--;
26038
26268
  }
26039
26269
  }
26040
- async runTurn(text, onEvent, onPermission, onElicitation, onQuestion = async () => ({ outcome: "cancelled" })) {
26270
+ async runTurn(text, onEvent, onPermission, onElicitation, onQuestion = async () => ({ outcome: "cancelled" }), onPlanApproval = async () => ({ outcome: "cancelled" })) {
26041
26271
  const connection = this.#connection;
26042
26272
  if (!connection || !this.#sessionId || this.#closed || this.#closing) {
26043
26273
  throw new GrokTransportError("unavailable", "Grok ACP Session is unavailable");
@@ -26046,7 +26276,7 @@ var GrokAcpTransport = class {
26046
26276
  throw new Error("Grok ACP Session already has an active Prompt");
26047
26277
  if (this.#permissionConfirmation)
26048
26278
  throw new GrokTransportError("unavailable", "Grok ACP Session has an active operation");
26049
- const active = { onEvent, onPermission, onElicitation, onQuestion };
26279
+ const active = { onEvent, onPermission, onElicitation, onQuestion, onPlanApproval };
26050
26280
  this.#activePrompt = active;
26051
26281
  try {
26052
26282
  const historyStart = (await this.getHistory()).length;
@@ -26167,7 +26397,7 @@ var GrokAcpTransport = class {
26167
26397
  }
26168
26398
  } : {}
26169
26399
  });
26170
- if (!isRecord16(response) || !isRecord16(response._meta) || !isRecord16(response._meta.model)) {
26400
+ if (!isRecord17(response) || !isRecord17(response._meta) || !isRecord17(response._meta.model)) {
26171
26401
  throw new GrokTransportError("protocolError", "Grok rejected Model configuration");
26172
26402
  }
26173
26403
  const selected = response._meta.model.Ok;
@@ -26207,7 +26437,7 @@ var GrokAcpTransport = class {
26207
26437
  permission_mode: mode
26208
26438
  });
26209
26439
  const response = await connection.request("_x.ai/session/info", { sessionId });
26210
- if (!isRecord16(response) || !isRecord16(response.result) || response.result.sessionId !== sessionId) {
26440
+ if (!isRecord17(response) || !isRecord17(response.result) || response.result.sessionId !== sessionId) {
26211
26441
  throw new Error("Grok did not confirm the target Session");
26212
26442
  }
26213
26443
  })()
@@ -26223,6 +26453,17 @@ var GrokAcpTransport = class {
26223
26453
  this.#permissionConfirmation = null;
26224
26454
  }
26225
26455
  }
26456
+ async setSessionMode(modeId) {
26457
+ const connection = this.#connection;
26458
+ const sessionId = this.#sessionId;
26459
+ if (!connection || !sessionId || this.#closed || this.#closing) {
26460
+ throw new GrokTransportError("unavailable", "Grok ACP Session is unavailable");
26461
+ }
26462
+ if (this.#activePrompt || this.#activeCompact || this.#permissionConfirmation) {
26463
+ throw new GrokTransportError("unavailable", "Grok ACP Session has an active operation");
26464
+ }
26465
+ await withTimeout(connection.request("session/set_mode", { sessionId, modeId }), this.#options.commandTimeoutMs, "Grok Session Mode");
26466
+ }
26226
26467
  close() {
26227
26468
  return this.#closePromise ??= this.#close();
26228
26469
  }
@@ -26282,7 +26523,7 @@ var GrokAcpTransport = class {
26282
26523
  if (!isGrokExtensionSessionUpdateMethod(method) && !isGrokBackgroundNotificationMethod(method)) {
26283
26524
  return;
26284
26525
  }
26285
- if (typeof params.sessionId !== "string" || !isRecord16(params.update))
26526
+ if (typeof params.sessionId !== "string" || !isRecord17(params.update))
26286
26527
  return;
26287
26528
  this.#handleUpdate(params);
26288
26529
  }
@@ -26292,7 +26533,7 @@ var GrokAcpTransport = class {
26292
26533
  taskId,
26293
26534
  source
26294
26535
  });
26295
- if (!isRecord16(result) || result.taskId !== taskId || !["killed", "already_exited", "not_found"].includes(String(result.outcome)))
26536
+ if (!isRecord17(result) || result.taskId !== taskId || !["killed", "already_exited", "not_found"].includes(String(result.outcome)))
26296
26537
  throw new GrokTransportError("protocolError", "Malformed Grok task kill response");
26297
26538
  return result.outcome;
26298
26539
  }
@@ -26307,7 +26548,7 @@ var GrokAcpTransport = class {
26307
26548
  sessionId: this.sessionId,
26308
26549
  taskId
26309
26550
  });
26310
- if (!isRecord16(result) || result.taskId !== taskId || typeof result.deleted !== "boolean")
26551
+ if (!isRecord17(result) || result.taskId !== taskId || typeof result.deleted !== "boolean")
26311
26552
  throw new GrokTransportError("protocolError", "Malformed Grok scheduler delete response");
26312
26553
  return result.deleted;
26313
26554
  }
@@ -26319,21 +26560,21 @@ var GrokAcpTransport = class {
26319
26560
  try {
26320
26561
  raw = await withTimeout(this.#connection.request(method, params), this.#options.commandTimeoutMs, `Grok ${method}`);
26321
26562
  } catch (error53) {
26322
- if (!isRecord16(error53) || error53.code !== -32601)
26563
+ if (!isRecord17(error53) || error53.code !== -32601)
26323
26564
  throw error53;
26324
26565
  try {
26325
26566
  raw = await withTimeout(this.#connection.request(`_${method}`, params), this.#options.commandTimeoutMs, `Grok _${method}`);
26326
26567
  } catch (fallback) {
26327
- if (isRecord16(fallback) && fallback.code === -32601)
26568
+ if (isRecord17(fallback) && fallback.code === -32601)
26328
26569
  throw new GrokTransportError("unsupported", `Grok does not support ${method}`);
26329
26570
  throw fallback;
26330
26571
  }
26331
26572
  }
26332
- if (isRecord16(raw) && raw.error !== void 0 && raw.error !== null) {
26333
- const message = typeof raw.error === "string" ? raw.error : isRecord16(raw.error) && typeof raw.error.message === "string" ? raw.error.message : `Grok ${method} failed`;
26573
+ if (isRecord17(raw) && raw.error !== void 0 && raw.error !== null) {
26574
+ const message = typeof raw.error === "string" ? raw.error : isRecord17(raw.error) && typeof raw.error.message === "string" ? raw.error.message : `Grok ${method} failed`;
26334
26575
  throw new GrokTransportError("unavailable", message);
26335
26576
  }
26336
- return isRecord16(raw) && "result" in raw ? raw.result : raw;
26577
+ return isRecord17(raw) && "result" in raw ? raw.result : raw;
26337
26578
  }
26338
26579
  #handlePermission(params) {
26339
26580
  const observer = this.#activePrompt ?? this.#background;
@@ -26358,6 +26599,19 @@ var GrokAcpTransport = class {
26358
26599
  return { outcome: "cancelled" };
26359
26600
  return { ...await activePrompt.onQuestion(request) };
26360
26601
  }
26602
+ if (isGrokExitPlanModeMethod(method)) {
26603
+ let request;
26604
+ try {
26605
+ request = parseGrokPlanApprovalRequest(params);
26606
+ } catch (error53) {
26607
+ throw RequestError.invalidParams(void 0, error53 instanceof Error ? error53.message : "Invalid Grok plan approval");
26608
+ }
26609
+ if (!activePrompt || request.sessionId !== this.#sessionId)
26610
+ return { outcome: "cancelled" };
26611
+ return {
26612
+ ...await activePrompt.onPlanApproval?.(request) ?? { outcome: "cancelled" }
26613
+ };
26614
+ }
26361
26615
  if (method !== GROK_MCP_ELICIT_METHOD) {
26362
26616
  throw RequestError.methodNotFound(method);
26363
26617
  }
@@ -26505,7 +26759,7 @@ var SessionImportScope = class {
26505
26759
  // dist/session-import.js
26506
26760
  var MAX_METADATA_BYTES = 4 * 1024 * 1024;
26507
26761
  var SUBAGENT_SESSION_KINDS = /* @__PURE__ */ new Set(["subagent", "subagent_resume"]);
26508
- function isRecord17(value) {
26762
+ function isRecord18(value) {
26509
26763
  return typeof value === "object" && value !== null && !Array.isArray(value);
26510
26764
  }
26511
26765
  async function readJson(file2, signal) {
@@ -26518,7 +26772,7 @@ function processAlive(pid) {
26518
26772
  process.kill(pid, 0);
26519
26773
  return true;
26520
26774
  } catch (error53) {
26521
- return isRecord17(error53) && error53.code === "EPERM";
26775
+ return isRecord18(error53) && error53.code === "EPERM";
26522
26776
  }
26523
26777
  }
26524
26778
  async function firstUserText(file2, signal) {
@@ -26535,10 +26789,10 @@ async function firstUserText(file2, signal) {
26535
26789
  } catch {
26536
26790
  continue;
26537
26791
  }
26538
- const update = isRecord17(entry) && isRecord17(entry.params) ? entry.params.update : null;
26539
- if (!isRecord17(update) || update.sessionUpdate !== "user_message_chunk")
26792
+ const update = isRecord18(entry) && isRecord18(entry.params) ? entry.params.update : null;
26793
+ if (!isRecord18(update) || update.sessionUpdate !== "user_message_chunk")
26540
26794
  continue;
26541
- const text = isRecord17(update.content) ? update.content.text : null;
26795
+ const text = isRecord18(update.content) ? update.content.text : null;
26542
26796
  return typeof text === "string" ? text : "";
26543
26797
  }
26544
26798
  return null;
@@ -26615,7 +26869,7 @@ var GrokSessionImport = class {
26615
26869
  if (!Array.isArray(entries))
26616
26870
  return active;
26617
26871
  for (const entry of entries) {
26618
- if (isRecord17(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
26872
+ if (isRecord18(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
26619
26873
  active.add(entry.session_id);
26620
26874
  }
26621
26875
  return active;
@@ -26664,7 +26918,7 @@ var GrokSessionImport = class {
26664
26918
  return null;
26665
26919
  try {
26666
26920
  const summary = await readJson(files[0], signal);
26667
- if (!isRecord17(summary) || !isRecord17(summary.info) || summary.info.id !== nativeSessionId)
26921
+ if (!isRecord18(summary) || !isRecord18(summary.info) || summary.info.id !== nativeSessionId)
26668
26922
  return null;
26669
26923
  if (typeof summary.session_kind === "string" && SUBAGENT_SESSION_KINDS.has(summary.session_kind))
26670
26924
  return null;
@@ -27386,17 +27640,17 @@ var GrokBackgroundItems = class {
27386
27640
  await handle.close();
27387
27641
  }
27388
27642
  } catch (error53) {
27389
- if (isRecord18(error53) && error53.code === "ENOENT")
27643
+ if (isRecord19(error53) && error53.code === "ENOENT")
27390
27644
  return;
27391
27645
  }
27392
27646
  }
27393
27647
  };
27394
- function isRecord18(value) {
27648
+ function isRecord19(value) {
27395
27649
  return typeof value === "object" && value !== null && !Array.isArray(value);
27396
27650
  }
27397
27651
 
27398
27652
  // dist/grok-models.js
27399
- function isRecord19(value) {
27653
+ function isRecord20(value) {
27400
27654
  return typeof value === "object" && value !== null && !Array.isArray(value);
27401
27655
  }
27402
27656
  function nonBlank(value) {
@@ -27408,7 +27662,7 @@ function thinkingOptions(value) {
27408
27662
  const seen = /* @__PURE__ */ new Set();
27409
27663
  const options = [];
27410
27664
  for (const candidate of value) {
27411
- if (!isRecord19(candidate) || !nonBlank(candidate.label))
27665
+ if (!isRecord20(candidate) || !nonBlank(candidate.label))
27412
27666
  continue;
27413
27667
  const id = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
27414
27668
  if (!id.success || seen.has(id.data))
@@ -27419,7 +27673,7 @@ function thinkingOptions(value) {
27419
27673
  return options;
27420
27674
  }
27421
27675
  function parseGrokModelState(value) {
27422
- if (!isRecord19(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
27676
+ if (!isRecord20(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
27423
27677
  return null;
27424
27678
  }
27425
27679
  const currentModel = harnessModelRefSchema.safeParse({ id: value.currentModelId });
@@ -27431,12 +27685,12 @@ function parseGrokModelState(value) {
27431
27685
  const models = [];
27432
27686
  let currentThinkingOptionId;
27433
27687
  for (const candidate of value.availableModels) {
27434
- if (!isRecord19(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
27688
+ if (!isRecord20(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
27435
27689
  continue;
27436
27690
  const ref = harnessModelRefSchema.safeParse({ id: candidate.modelId });
27437
27691
  if (!ref.success)
27438
27692
  continue;
27439
- const metadata = isRecord19(candidate._meta) ? candidate._meta : {};
27693
+ const metadata = isRecord20(candidate._meta) ? candidate._meta : {};
27440
27694
  const options2 = thinkingOptions(metadata.reasoningEfforts);
27441
27695
  if (Array.isArray(metadata.contextWindows) && metadata.contextWindows.includes(5e5)) {
27442
27696
  defaultContextWindowTokensByModel.set(ref.data.id, 5e5);
@@ -27475,10 +27729,10 @@ function parseGrokModelState(value) {
27475
27729
  };
27476
27730
  }
27477
27731
  function modelStateFromInitialize(response) {
27478
- return parseGrokModelState(isRecord19(response._meta) ? response._meta.modelState : void 0);
27732
+ return parseGrokModelState(isRecord20(response._meta) ? response._meta.modelState : void 0);
27479
27733
  }
27480
27734
  function modelStateFromSessionResponse(response) {
27481
- return parseGrokModelState(isRecord19(response) ? response.models : void 0);
27735
+ return parseGrokModelState(isRecord20(response) ? response.models : void 0);
27482
27736
  }
27483
27737
  function stateForGrokModel(modelState, nativeState, model2 = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
27484
27738
  const selectedModel = model2;
@@ -27505,12 +27759,12 @@ var GROK_SETTINGS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/settings";
27505
27759
  var REQUEST_TIMEOUT_MS = 15e3;
27506
27760
  var PLAN_TIMEOUT_MS = 2e3;
27507
27761
  function parseGrokPlan(value) {
27508
- if (!isRecord20(value) || typeof value.subscription_tier_display !== "string")
27762
+ if (!isRecord21(value) || typeof value.subscription_tier_display !== "string")
27509
27763
  return void 0;
27510
27764
  const plan = value.subscription_tier_display.trim();
27511
27765
  return plan && plan.length <= 128 && !/[\u0000-\u001f\u007f]/u.test(plan) ? plan : void 0;
27512
27766
  }
27513
- function isRecord20(value) {
27767
+ function isRecord21(value) {
27514
27768
  return typeof value === "object" && value !== null && !Array.isArray(value);
27515
27769
  }
27516
27770
  function finitePercent(value) {
@@ -27519,7 +27773,7 @@ function finitePercent(value) {
27519
27773
  return Math.min(100, Math.max(0, value));
27520
27774
  }
27521
27775
  function nonNegativeCentValue(value) {
27522
- if (!isRecord20(value))
27776
+ if (!isRecord21(value))
27523
27777
  return void 0;
27524
27778
  const amount = value.val === void 0 ? 0 : value.val;
27525
27779
  if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
@@ -27543,7 +27797,7 @@ function productUsageFrom(value) {
27543
27797
  if (!Array.isArray(value))
27544
27798
  return void 0;
27545
27799
  const products = value.flatMap((entry) => {
27546
- if (!isRecord20(entry) || typeof entry.product !== "string")
27800
+ if (!isRecord21(entry) || typeof entry.product !== "string")
27547
27801
  return [];
27548
27802
  const usagePercent = finitePercent(entry.usagePercent);
27549
27803
  const labels = {
@@ -27564,10 +27818,10 @@ function productUsageFrom(value) {
27564
27818
  return products.length > 0 ? products : void 0;
27565
27819
  }
27566
27820
  function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
27567
- if (!isRecord20(value) || !isRecord20(value.config))
27821
+ if (!isRecord21(value) || !isRecord21(value.config))
27568
27822
  return null;
27569
27823
  const config2 = value.config;
27570
- const period = isRecord20(config2.currentPeriod) ? config2.currentPeriod : void 0;
27824
+ const period = isRecord21(config2.currentPeriod) ? config2.currentPeriod : void 0;
27571
27825
  const periodType = periodTypeFrom(period?.type);
27572
27826
  const resetsAt = (typeof period?.end === "string" && period.end.length > 0 ? period.end : void 0) ?? (typeof config2.billingPeriodEnd === "string" && config2.billingPeriodEnd.length > 0 ? config2.billingPeriodEnd : void 0);
27573
27827
  let usedPercent = finitePercent(config2.creditUsagePercent);
@@ -27594,11 +27848,11 @@ function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()
27594
27848
  };
27595
27849
  }
27596
27850
  function selectAccessToken(auth, now) {
27597
- if (!isRecord20(auth))
27851
+ if (!isRecord21(auth))
27598
27852
  return null;
27599
- const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord20(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
27853
+ const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord21(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
27600
27854
  for (const [, value] of entries) {
27601
- if (!isRecord20(value) || typeof value.key !== "string")
27855
+ if (!isRecord21(value) || typeof value.key !== "string")
27602
27856
  continue;
27603
27857
  if (typeof value.expires_at === "string") {
27604
27858
  const expiresAt = Date.parse(value.expires_at);
@@ -27674,7 +27928,7 @@ async function fetchGrokCredits(input = {}) {
27674
27928
 
27675
27929
  // dist/grok-usage.js
27676
27930
  var USD_TICKS_PER_DOLLAR = 1e10;
27677
- function isRecord21(value) {
27931
+ function isRecord22(value) {
27678
27932
  return typeof value === "object" && value !== null && !Array.isArray(value);
27679
27933
  }
27680
27934
  function optionalToken(value) {
@@ -27691,7 +27945,7 @@ function combineUsage(base, next) {
27691
27945
  return base === null ? next : parseHostUsage({ ...base, ...next });
27692
27946
  }
27693
27947
  function usageFromNative(value) {
27694
- if (!isRecord21(value))
27948
+ if (!isRecord22(value))
27695
27949
  return null;
27696
27950
  const inputTokens = optionalToken(value.inputTokens);
27697
27951
  const cachedRead = optionalToken(value.cachedReadTokens);
@@ -27715,7 +27969,7 @@ function usageFromNative(value) {
27715
27969
  }
27716
27970
  }
27717
27971
  function usageFromResponse(value) {
27718
- if (!isRecord21(value))
27972
+ if (!isRecord22(value))
27719
27973
  return null;
27720
27974
  const buckets = [
27721
27975
  value.input_tokens,
@@ -27815,7 +28069,7 @@ var GrokTurnUsage = class {
27815
28069
  }
27816
28070
  };
27817
28071
  function usageFromSignals(value) {
27818
- if (!isRecord21(value))
28072
+ if (!isRecord22(value))
27819
28073
  return null;
27820
28074
  try {
27821
28075
  return parseHostUsage({
@@ -27835,7 +28089,7 @@ var summedUsageFields = [
27835
28089
  "totalTokens"
27836
28090
  ];
27837
28091
  function nativeCostTicks(value) {
27838
- if (!isRecord21(value))
28092
+ if (!isRecord22(value))
27839
28093
  return void 0;
27840
28094
  const ticks = value.costUsdTicks;
27841
28095
  if (typeof ticks !== "number" || !Number.isSafeInteger(ticks) || ticks < 0)
@@ -27843,7 +28097,7 @@ function nativeCostTicks(value) {
27843
28097
  return ticks;
27844
28098
  }
27845
28099
  function sessionCostFromNative(value, initialCostUsd) {
27846
- if (!isRecord21(value))
28100
+ if (!isRecord22(value))
27847
28101
  return void 0;
27848
28102
  if (value.costIsPartial !== void 0 && value.costIsPartial !== false)
27849
28103
  return void 0;
@@ -27874,7 +28128,7 @@ function sessionUsageFromHistory(events) {
27874
28128
  continue;
27875
28129
  const usage = usageFromNative(event.usage);
27876
28130
  const ticks2 = nativeCostTicks(event.usage);
27877
- const complete = isRecord21(event.usage) && (event.usage.usageIsIncomplete === void 0 || event.usage.usageIsIncomplete === false) && usage?.inputTokens !== void 0 && usage.cachedInputTokens !== void 0 && usage.cachedInputTokens <= usage.inputTokens;
28131
+ const complete = isRecord22(event.usage) && (event.usage.usageIsIncomplete === void 0 || event.usage.usageIsIncomplete === false) && usage?.inputTokens !== void 0 && usage.cachedInputTokens !== void 0 && usage.cachedInputTokens <= usage.inputTokens;
27878
28132
  latestByKey.set(key, { usage, complete, ...ticks2 !== void 0 ? { ticks: ticks2 } : {} });
27879
28133
  }
27880
28134
  if (latestByKey.size === 0)
@@ -27928,7 +28182,7 @@ function usageFromCompact(tokensAfter, contextWindowTokens) {
27928
28182
  function usageFromUpdate(update, metadata, contextWindowTokens) {
27929
28183
  try {
27930
28184
  if (update?.sessionUpdate === "usage_update") {
27931
- const cost = isRecord21(update.cost) ? update.cost : null;
28185
+ const cost = isRecord22(update.cost) ? update.cost : null;
27932
28186
  return parseHostUsage({
27933
28187
  contextUsedTokens: update.used,
27934
28188
  contextWindowTokens: update.size,
@@ -28056,6 +28310,7 @@ var GrokHarnessSession = class {
28056
28310
  #configuring = false;
28057
28311
  #phase = "open";
28058
28312
  #state;
28313
+ #permissionPolicyId;
28059
28314
  #usage = null;
28060
28315
  #initialCostUsd;
28061
28316
  #costRequest = 0;
@@ -28132,7 +28387,9 @@ var GrokHarnessSession = class {
28132
28387
  ...capabilitiesForModels(this.#modelState),
28133
28388
  steer: this.#canSteerActiveTurn()
28134
28389
  });
28135
- this.#state = stateForGrokModel(modelState, { nativeRef: nativeRef(opened.sessionId) }, modelState.currentModel, modelState.currentThinkingOptionId, options.initialPermissionModeId);
28390
+ this.#permissionPolicyId = isGrokPlanModeId(options.initialPermissionModeId) ? GROK_DEFAULT_PERMISSION_MODE_ID : options.initialPermissionModeId;
28391
+ const restoredPlan = options.history.findLast((event) => event.type === "session.mode")?.modeId === "plan";
28392
+ this.#state = stateForGrokModel(modelState, { nativeRef: nativeRef(opened.sessionId) }, modelState.currentModel, modelState.currentThinkingOptionId, isGrokPlanModeId(options.initialPermissionModeId) || restoredPlan ? GROK_PLAN_MODE_ID : options.initialPermissionModeId);
28136
28393
  this.initialState = this.#state;
28137
28394
  this.#snapshot = {
28138
28395
  ...mapGrokReplay(options.history, this.harnessId, opened.sessionId, cwd, options.knownTurnRefs, this.#toolOutputLimit, options.sessionDirectory),
@@ -28207,6 +28464,10 @@ var GrokHarnessSession = class {
28207
28464
  onQuestion: async (request) => {
28208
28465
  await this.#backgroundQueue;
28209
28466
  return this.#active ? this.#active.questions.ask(request) : { outcome: "cancelled" };
28467
+ },
28468
+ onPlanApproval: async (request) => {
28469
+ await this.#backgroundQueue;
28470
+ return this.#active ? this.#active.planApprovals.ask(request) : { outcome: "cancelled" };
28210
28471
  }
28211
28472
  });
28212
28473
  void goals?.read();
@@ -28312,7 +28573,10 @@ var GrokHarnessSession = class {
28312
28573
  const active = this.#newActive(command, catalogCommand);
28313
28574
  this.#active = active;
28314
28575
  this.#event({ type: "turn.started", turnId: command.turnId });
28315
- void this.#transport.runTurn(text, (event) => this.#handleEvent(active, event), (request) => this.#requestPermission(active, request), (request) => this.#requestElicitation(active, request), (request) => this.#active === active && this.#phase === "open" && !active.cancellationRequested ? active.questions.ask(request) : Promise.resolve({ outcome: "cancelled" })).finally(() => active.questions.cancel()).then((response) => this.#settleFromHistory(active, terminalOutcome2(response, active.cancellationRequested), response), (error53) => this.#settleFromHistory(active, {
28576
+ void this.#transport.runTurn(text, (event) => this.#handleEvent(active, event), (request) => this.#requestPermission(active, request), (request) => this.#requestElicitation(active, request), (request) => this.#active === active && this.#phase === "open" && !active.cancellationRequested ? active.questions.ask(request) : Promise.resolve({ outcome: "cancelled" }), (request) => this.#active === active && this.#phase === "open" && !active.cancellationRequested ? active.planApprovals.ask(request) : Promise.resolve({ outcome: "cancelled" })).finally(() => {
28577
+ active.questions.cancel();
28578
+ active.planApprovals.cancel();
28579
+ }).then((response) => this.#settleFromHistory(active, terminalOutcome2(response, active.cancellationRequested), response), (error53) => this.#settleFromHistory(active, {
28316
28580
  status: "failed",
28317
28581
  error: normalizeError(error53, "nativeFailure")
28318
28582
  }));
@@ -28379,6 +28643,7 @@ var GrokHarnessSession = class {
28379
28643
  approvals: /* @__PURE__ */ new Map(),
28380
28644
  elicitations: /* @__PURE__ */ new Map(),
28381
28645
  questions: new GrokQuestions(command.turnId, this.#randomUUID, (output) => this.#channel.emit(output)),
28646
+ planApprovals: new GrokPlanApprovals(command.turnId, this.#randomUUID, (output) => this.#channel.emit(output)),
28382
28647
  cancellationRequested: false,
28383
28648
  beforeNativeTurnKeys: new Set(this.#snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey)),
28384
28649
  historyStart: this.#historyLength,
@@ -28535,6 +28800,10 @@ var GrokHarnessSession = class {
28535
28800
  await this.#goalCommand;
28536
28801
  if (this.#phase !== "open")
28537
28802
  return;
28803
+ if (event.type === "session.mode") {
28804
+ this.#applyNativeSessionMode(event.modeId);
28805
+ return;
28806
+ }
28538
28807
  if (this.#bufferGoalHelper(event))
28539
28808
  return;
28540
28809
  if (!this.#active && event.type === "subagent.finished") {
@@ -28575,8 +28844,16 @@ var GrokHarnessSession = class {
28575
28844
  const active = this.#active;
28576
28845
  if (!active)
28577
28846
  return;
28847
+ const backgroundOwned = grokBackgroundOwnedTurn({
28848
+ turnId: active.command.turnId,
28849
+ backgroundPromptIndex: active.backgroundPromptIndex
28850
+ });
28851
+ if (!backgroundOwned && grokForeignBackgroundEvent(event))
28852
+ return;
28578
28853
  this.#handleEvent(active, event);
28579
28854
  if (event.type === "turn.completed") {
28855
+ if (!backgroundOwned)
28856
+ return;
28580
28857
  const deadline = Date.now() + 3e3;
28581
28858
  while (Date.now() < deadline && this.#phase === "open") {
28582
28859
  const history = await this.#transport.getHistory();
@@ -28759,6 +29036,7 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
28759
29036
  approvals: /* @__PURE__ */ new Map(),
28760
29037
  elicitations: /* @__PURE__ */ new Map(),
28761
29038
  questions: new GrokQuestions(command.turnId, this.#randomUUID, (output) => this.#channel.emit(output)),
29039
+ planApprovals: new GrokPlanApprovals(command.turnId, this.#randomUUID, (output) => this.#channel.emit(output)),
28762
29040
  cancellationRequested: false,
28763
29041
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
28764
29042
  historyStart: this.#historyLength,
@@ -28885,7 +29163,7 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
28885
29163
  }
28886
29164
  async #selectPermissionMode(command) {
28887
29165
  try {
28888
- decodeGrokPermissionModeId(command.permissionModeId);
29166
+ grokCatalogPermissionModeId(command.permissionModeId);
28889
29167
  } catch {
28890
29168
  return {
28891
29169
  ok: false,
@@ -28906,12 +29184,50 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
28906
29184
  }
28907
29185
  };
28908
29186
  }
29187
+ const wantPlan = isGrokPlanModeId(command.permissionModeId);
29188
+ const inPlan = isGrokPlanModeId(this.#state.effectivePermissionModeId);
29189
+ if (wantPlan && !this.#transport.setSessionMode) {
29190
+ return {
29191
+ ok: false,
29192
+ error: {
29193
+ code: "unsupported",
29194
+ message: "Grok Session Mode is unavailable",
29195
+ retryable: false
29196
+ }
29197
+ };
29198
+ }
28909
29199
  this.#configuring = true;
28910
29200
  try {
28911
- await this.#transport.setPermissionMode(command.permissionModeId);
29201
+ if (wantPlan) {
29202
+ if (!inPlan)
29203
+ await this.#transport.setSessionMode?.("plan");
29204
+ } else {
29205
+ if (inPlan) {
29206
+ try {
29207
+ await this.#transport.setSessionMode?.("default");
29208
+ } catch (error53) {
29209
+ return { ok: false, error: normalizeError(error53, "nativeFailure") };
29210
+ }
29211
+ }
29212
+ try {
29213
+ await this.#transport.setPermissionMode(command.permissionModeId);
29214
+ } catch (error53) {
29215
+ if (inPlan) {
29216
+ try {
29217
+ await this.#transport.setSessionMode?.("plan");
29218
+ } catch {
29219
+ }
29220
+ }
29221
+ throw error53;
29222
+ }
29223
+ this.#permissionPolicyId = command.permissionModeId;
29224
+ }
28912
29225
  if (this.#phase !== "open")
28913
29226
  return { ok: false, error: invalidState("Grok Session is closed") };
28914
- this.#state = { ...this.#state, effectivePermissionModeId: command.permissionModeId };
29227
+ this.#state = {
29228
+ ...this.#state,
29229
+ effectivePermissionModeId: wantPlan ? GROK_PLAN_MODE_ID : command.permissionModeId
29230
+ };
28915
29231
  this.#event({ type: "session.state.changed", state: this.#state });
28916
29232
  return { ok: true, value: { completed: true } };
28917
29233
  } catch (error53) {
@@ -28933,6 +29249,7 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
28933
29249
  }
28934
29250
  this.#cancelActiveElicitations(active);
28935
29251
  active.questions.cancel();
29252
+ active.planApprovals.cancel();
28936
29253
  try {
28937
29254
  await this.#transport.cancel();
28938
29255
  return { ok: true, value: { cancellationRequested: true } };
@@ -28946,6 +29263,8 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
28946
29263
  const elicitation = active?.elicitations.get(command.interactionId);
28947
29264
  if (active?.questions.has(command.interactionId))
28948
29265
  return active.questions.respond(command);
29266
+ if (active?.planApprovals.has(command.interactionId))
29267
+ return active.planApprovals.respond(command);
28949
29268
  if (!active || !permission && !elicitation)
28950
29269
  return { ok: false, error: invalidState("Grok Interaction is not pending") };
28951
29270
  if (command.response.type !== "approval") {
@@ -29072,9 +29391,20 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
29072
29391
  this.#settleElicitation(active, pending, grokMcpElicitCancel(), "cancelled");
29073
29392
  }
29074
29393
  }
29394
+ #applyNativeSessionMode(modeId) {
29395
+ const next = modeId === "plan" ? GROK_PLAN_MODE_ID : this.#permissionPolicyId;
29396
+ if (this.#state.effectivePermissionModeId === next)
29397
+ return;
29398
+ this.#state = { ...this.#state, effectivePermissionModeId: next };
29399
+ this.#event({ type: "session.state.changed", state: this.#state });
29400
+ }
29075
29401
  #handleEvent(active, event) {
29076
29402
  if (this.#active !== active || this.#phase !== "open")
29077
29403
  return;
29404
+ if (event.type === "session.mode") {
29405
+ this.#applyNativeSessionMode(event.modeId);
29406
+ return;
29407
+ }
29078
29408
  const requestUsage = active.usage?.observe(event);
29079
29409
  if (requestUsage) {
29080
29410
  this.#publishUsage(requestUsage, active.command.turnId, true);
@@ -29104,6 +29434,7 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
29104
29434
  this.#completeCompaction(active, event);
29105
29435
  } else if (event.type === "interaction.resolved") {
29106
29436
  active.questions.withdraw(event.toolCallId);
29437
+ active.planApprovals.withdraw(event.toolCallId);
29107
29438
  for (const pending of [...active.elicitations.values()]) {
29108
29439
  if (pending.nativeToolCallId === event.toolCallId) {
29109
29440
  this.#settleElicitation(active, pending, grokMcpElicitCancel(), "cancelled");
@@ -29503,19 +29834,20 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
29503
29834
  const expectedKey = terminalKey ?? (typeof response?._meta?.promptId === "string" ? response._meta.promptId : void 0);
29504
29835
  const group = expectedKey ? classifyGrokHistory(history).findLast((g) => g.terminalIndex >= active.historyStart && g.terminal.nativeTurnKey === expectedKey && (active.backgroundPromptIndex === void 0 || g.user && grokPromptIndex(g.user) === active.backgroundPromptIndex)) : void 0;
29505
29836
  const created = this.#snapshot.turns.filter((turn) => !active.beforeNativeTurnKeys.has(turn.nativeTurnRef.nativeTurnKey));
29837
+ const settled = selectGrokSettledTurn(created, expectedKey, active.backgroundPromptIndex);
29506
29838
  const lastUser = history.findLast((event) => event.type === "user.text");
29507
29839
  ephemeral = terminalKey !== void 0 && group?.disposition === "ephemeral" && created.length === 0 || created.length === 0 && active.catalogCommand && outcome.status === "succeeded" && response?.stopReason === "end_turn" && response._meta?.totalTokens === 0 && lastUser?.type === "user.text" && lastUser.text === active.command.input.map(({ text }) => text).join("\n") && (lastUser?.metadata?.hostTurn === true || lastUser?.metadata?.host_turn === true);
29508
- if (created.length !== 1 && !ephemeral) {
29840
+ if (!settled && !ephemeral) {
29509
29841
  throw new Error(`Grok Turn persisted ${created.length} new Native Turns; exactly one is required`);
29510
29842
  }
29511
- if (!ephemeral && expectedKey && (created[0]?.nativeTurnRef.nativeTurnKey !== expectedKey || terminalKey && !group))
29843
+ if (!ephemeral && expectedKey && (settled?.nativeTurnRef.nativeTurnKey !== expectedKey || terminalKey && !group))
29512
29844
  throw new Error("Grok persisted terminal does not match the live Turn occurrence");
29513
- nativeTurnRef = created[0]?.nativeTurnRef;
29514
- checkpoint = created[0]?.checkpoint;
29845
+ nativeTurnRef = settled?.nativeTurnRef;
29846
+ checkpoint = settled?.checkpoint;
29515
29847
  if (nativeTurnRef)
29516
29848
  this.#publishGoalHelpers(active, nativeTurnRef.nativeTurnKey);
29517
29849
  if (active.backgroundPromptIndex !== void 0 && !ephemeral)
29518
- persistedItems = created[0]?.items;
29850
+ persistedItems = settled?.items;
29519
29851
  } catch (error53) {
29520
29852
  if (outcome.status === "succeeded" || error53 instanceof GrokNativeIdentityReuseError) {
29521
29853
  outcome = { status: "failed", error: normalizeError(error53, "protocolError") };
@@ -29585,6 +29917,7 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
29585
29917
  }
29586
29918
  this.#cancelActiveElicitations(active);
29587
29919
  active.questions.cancel();
29920
+ active.planApprovals.cancel();
29588
29921
  this.#active = null;
29589
29922
  if (usage || this.#usage)
29590
29923
  this.#publishUsage({ ...usage, ...active.usage?.metrics() }, active.command.turnId, true);
@@ -29629,6 +29962,7 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
29629
29962
  approval.resolve({ outcome: { outcome: "cancelled" } });
29630
29963
  this.#cancelActiveElicitations(active);
29631
29964
  active.questions.cancel();
29965
+ active.planApprovals.cancel();
29632
29966
  await this.#transport.cancel().catch(() => void 0);
29633
29967
  await Promise.race([
29634
29968
  active.completion,
@@ -29821,7 +30155,7 @@ var GrokAdapter = class {
29821
30155
  };
29822
30156
  const requestedPermissionModeId = input.kind === "create" ? input.permissionModeId ?? (input.executionPolicy === "unattended-full-access" ? harnessPermissionModeIdSchema.parse("always-approve") : GROK_DEFAULT_PERMISSION_MODE_ID) : input.kind === "resume" ? input.permissionModeId ?? GROK_DEFAULT_PERMISSION_MODE_ID : GROK_DEFAULT_PERMISSION_MODE_ID;
29823
30157
  try {
29824
- decodeGrokPermissionModeId(requestedPermissionModeId);
30158
+ grokCatalogPermissionModeId(requestedPermissionModeId);
29825
30159
  } catch {
29826
30160
  return {
29827
30161
  ok: false,
@@ -29999,7 +30333,22 @@ var GrokAdapter = class {
29999
30333
  ]);
30000
30334
  }
30001
30335
  }
30002
- await transport.setPermissionMode(initialPermissionModeId);
30336
+ if (isGrokPlanModeId(initialPermissionModeId)) {
30337
+ if (!transport.setSessionMode) {
30338
+ await transport.close().catch(() => void 0);
30339
+ return {
30340
+ ok: false,
30341
+ error: {
30342
+ code: "unsupported",
30343
+ message: "Grok Session Mode is unavailable",
30344
+ retryable: false
30345
+ }
30346
+ };
30347
+ }
30348
+ await transport.setSessionMode("plan");
30349
+ } else {
30350
+ await transport.setPermissionMode(initialPermissionModeId);
30351
+ }
30003
30352
  const history = await transport.getHistory();
30004
30353
  let initialUsage = input.kind === "resume" || input.kind === "fork" || input.kind === "rollbackLastTurn" || input.kind === "rollbackToCheckpoint" ? combineUsage(sessionUsageFromHistory(history), usageFromSignals(opened.signals)) : null;
30005
30354
  if (contextWindow !== void 0 && initialUsage?.contextUsedTokens !== void 0) {