@liberseek/boft-cli-linux-x64 0.8.4 → 0.8.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +2 -2
  2. package/THIRD_PARTY_NOTICES.txt +6 -2
  3. package/app/codexhost-distribution.json +1 -1
  4. package/app/console-server.mjs +129 -28
  5. package/app/console-web.js +336 -78
  6. package/app/desktop-controller.mjs +1741 -60
  7. package/app/host-runtime.mjs +4983 -2002
  8. package/app/plugins/antigravity/plugin.mjs +423 -63
  9. package/app/plugins/claude-code/plugin.mjs +417 -264
  10. package/app/plugins/codebuddy/plugin.mjs +256 -134
  11. package/app/plugins/codex-usage/plugin.mjs +97 -32
  12. package/app/plugins/copilot/plugin.mjs +122 -57
  13. package/app/plugins/cursor-cli/plugin.mjs +236 -139
  14. package/app/plugins/deepseek-harness/plugin.mjs +584 -86
  15. package/app/plugins/devin/assets/icon.svg +1 -0
  16. package/app/plugins/devin/manifest.json +30 -0
  17. package/app/plugins/devin/plugin.mjs +23425 -0
  18. package/app/plugins/enabled.json +2 -0
  19. package/app/plugins/grok/plugin.mjs +839 -500
  20. package/app/plugins/hermes/plugin.mjs +522 -200
  21. package/app/plugins/kimi-code/plugin.mjs +134 -22
  22. package/app/plugins/kiro-cli/plugin.mjs +84 -19
  23. package/app/plugins/muse/plugin.mjs +74 -9
  24. package/app/plugins/omp/plugin.mjs +104 -39
  25. package/app/plugins/opencode/plugin.mjs +126 -61
  26. package/app/plugins/pi/plugin.mjs +1769 -468
  27. package/app/plugins/qoder/plugin.mjs +9617 -8682
  28. package/app/plugins/qoder-cn/plugin.mjs +9617 -8682
  29. package/app/plugins/qwen-code/assets/icon.svg +1 -0
  30. package/app/plugins/qwen-code/manifest.json +29 -0
  31. package/app/plugins/qwen-code/plugin.mjs +29366 -0
  32. package/app/plugins/workbuddy/plugin.mjs +256 -134
  33. package/app/plugins/zcode/plugin.mjs +265 -42
  34. package/app/renderer-extension.js +3286 -528
  35. package/bin/boft +0 -0
  36. package/libexec/boft-shim +0 -0
  37. package/libexec/boft-updater +0 -0
  38. package/licenses/Qwen-Code-SDK-LICENSE.txt +203 -0
  39. package/package.json +2 -2
@@ -603,7 +603,7 @@ async function readGrokCredentials(environment) {
603
603
  }
604
604
 
605
605
  // dist/grok-adapter.js
606
- import path15 from "node:path";
606
+ import path16 from "node:path";
607
607
 
608
608
  // ../../../node_modules/@agentclientprotocol/sdk/dist/schema/index.js
609
609
  var AGENT_METHODS = {
@@ -1423,10 +1423,10 @@ function mergeDefs(...defs) {
1423
1423
  function cloneDef(schema) {
1424
1424
  return mergeDefs(schema._zod.def);
1425
1425
  }
1426
- function getElementAtPath(obj, path16) {
1427
- if (!path16)
1426
+ function getElementAtPath(obj, path17) {
1427
+ if (!path17)
1428
1428
  return obj;
1429
- return path16.reduce((acc, key) => acc?.[key], obj);
1429
+ return path17.reduce((acc, key) => acc?.[key], obj);
1430
1430
  }
1431
1431
  function promiseAllObject(promisesObj) {
1432
1432
  const keys = Object.keys(promisesObj);
@@ -1835,11 +1835,11 @@ function explicitlyAborted(x, startIndex = 0) {
1835
1835
  }
1836
1836
  return false;
1837
1837
  }
1838
- function prefixIssues(path16, issues) {
1838
+ function prefixIssues(path17, issues) {
1839
1839
  return issues.map((iss) => {
1840
1840
  var _a3;
1841
1841
  (_a3 = iss).path ?? (_a3.path = []);
1842
- iss.path.unshift(path16);
1842
+ iss.path.unshift(path17);
1843
1843
  return iss;
1844
1844
  });
1845
1845
  }
@@ -1986,16 +1986,16 @@ function flattenError(error53, mapper = (issue2) => issue2.message) {
1986
1986
  }
1987
1987
  function formatError(error53, mapper = (issue2) => issue2.message) {
1988
1988
  const fieldErrors = { _errors: [] };
1989
- const processError = (error54, path16 = []) => {
1989
+ const processError = (error54, path17 = []) => {
1990
1990
  for (const issue2 of error54.issues) {
1991
1991
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1992
- issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
1992
+ issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
1993
1993
  } else if (issue2.code === "invalid_key") {
1994
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1994
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1995
1995
  } else if (issue2.code === "invalid_element") {
1996
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1996
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1997
1997
  } else {
1998
- const fullpath = [...path16, ...issue2.path];
1998
+ const fullpath = [...path17, ...issue2.path];
1999
1999
  if (fullpath.length === 0) {
2000
2000
  fieldErrors._errors.push(mapper(issue2));
2001
2001
  } else {
@@ -2022,17 +2022,17 @@ function formatError(error53, mapper = (issue2) => issue2.message) {
2022
2022
  }
2023
2023
  function treeifyError(error53, mapper = (issue2) => issue2.message) {
2024
2024
  const result = { errors: [] };
2025
- const processError = (error54, path16 = []) => {
2025
+ const processError = (error54, path17 = []) => {
2026
2026
  var _a3, _b;
2027
2027
  for (const issue2 of error54.issues) {
2028
2028
  if (issue2.code === "invalid_union" && issue2.errors.length) {
2029
- issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
2029
+ issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
2030
2030
  } else if (issue2.code === "invalid_key") {
2031
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
2031
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
2032
2032
  } else if (issue2.code === "invalid_element") {
2033
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
2033
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
2034
2034
  } else {
2035
- const fullpath = [...path16, ...issue2.path];
2035
+ const fullpath = [...path17, ...issue2.path];
2036
2036
  if (fullpath.length === 0) {
2037
2037
  result.errors.push(mapper(issue2));
2038
2038
  continue;
@@ -2064,8 +2064,8 @@ function treeifyError(error53, mapper = (issue2) => issue2.message) {
2064
2064
  }
2065
2065
  function toDotPath(_path) {
2066
2066
  const segs = [];
2067
- const path16 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2068
- for (const seg of path16) {
2067
+ const path17 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2068
+ for (const seg of path17) {
2069
2069
  if (typeof seg === "number")
2070
2070
  segs.push(`[${seg}]`);
2071
2071
  else if (typeof seg === "symbol")
@@ -3686,10 +3686,10 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
3686
3686
  const shape = def.shape;
3687
3687
  const propValues = {};
3688
3688
  for (const key in shape) {
3689
- const field = shape[key]._zod;
3690
- if (field.values) {
3689
+ const field2 = shape[key]._zod;
3690
+ if (field2.values) {
3691
3691
  propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
3692
- for (const v of field.values)
3692
+ for (const v of field2.values)
3693
3693
  propValues[key].add(v);
3694
3694
  }
3695
3695
  }
@@ -14757,13 +14757,13 @@ function resolveRef(ref, ctx) {
14757
14757
  if (!ref.startsWith("#")) {
14758
14758
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14759
14759
  }
14760
- const path16 = ref.slice(1).split("/").filter(Boolean);
14761
- if (path16.length === 0) {
14760
+ const path17 = ref.slice(1).split("/").filter(Boolean);
14761
+ if (path17.length === 0) {
14762
14762
  return ctx.rootSchema;
14763
14763
  }
14764
14764
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14765
- if (path16[0] === defsKey) {
14766
- const key = path16[1];
14765
+ if (path17[0] === defsKey) {
14766
+ const key = path17[1];
14767
14767
  if (!key || !ctx.defs[key]) {
14768
14768
  throw new Error(`Reference not found: ${ref}`);
14769
14769
  }
@@ -19438,6 +19438,8 @@ var usageStatisticsTotalsSchema = external_exports.strictObject({
19438
19438
  cachedInputTokens: count2,
19439
19439
  cacheWriteInputTokens: count2,
19440
19440
  cacheKnownInputTokens: count2,
19441
+ cacheHitCachedInputTokens: count2,
19442
+ cacheHitInputTokens: count2,
19441
19443
  outputTokens: count2,
19442
19444
  reasoningOutputTokens: count2,
19443
19445
  /** USD at the public price, summed over the priced requests only. */
@@ -19545,6 +19547,51 @@ var hostInteractionIdSchema = opaqueIdSchema.brand();
19545
19547
  var threadPrewarmDiscardParamsSchema = external_exports.object({ threadId: hostThreadIdSchema });
19546
19548
  var threadPrewarmDiscardResultSchema = external_exports.object({ discarded: external_exports.boolean() });
19547
19549
 
19550
+ // ../../shared-contracts/dist/thread-questions.js
19551
+ var field = external_exports.discriminatedUnion("type", [
19552
+ external_exports.object({
19553
+ id: external_exports.string().min(1),
19554
+ type: external_exports.literal("choice"),
19555
+ prompt: external_exports.string(),
19556
+ options: external_exports.array(external_exports.object({
19557
+ value: external_exports.string().min(1),
19558
+ label: external_exports.string(),
19559
+ description: external_exports.string().optional()
19560
+ })).min(1),
19561
+ multiple: external_exports.boolean(),
19562
+ allowOther: external_exports.boolean(),
19563
+ optional: external_exports.boolean()
19564
+ }),
19565
+ external_exports.object({
19566
+ id: external_exports.string().min(1),
19567
+ type: external_exports.literal("text"),
19568
+ prompt: external_exports.string(),
19569
+ multiline: external_exports.boolean(),
19570
+ secret: external_exports.literal(false),
19571
+ optional: external_exports.boolean(),
19572
+ placeholder: external_exports.string().optional(),
19573
+ prefill: external_exports.string().optional()
19574
+ })
19575
+ ]);
19576
+ var threadQuestionSchema = external_exports.object({
19577
+ interactionId: external_exports.string().min(1),
19578
+ turnId: external_exports.string().min(1),
19579
+ title: external_exports.string().optional(),
19580
+ questions: external_exports.array(field).min(1)
19581
+ }).refine(({ questions }) => questions.some((q) => q.type === "choice" && q.multiple), {
19582
+ message: "Shared cards require at least one multi-select question"
19583
+ });
19584
+ var threadQuestionsListParamsSchema = external_exports.strictObject({ threadId: external_exports.string().min(1) });
19585
+ var threadQuestionsResultSchema = external_exports.object({ questions: external_exports.array(threadQuestionSchema) });
19586
+ var threadQuestionRespondParamsSchema = external_exports.strictObject({
19587
+ threadId: external_exports.string().min(1),
19588
+ turnId: external_exports.string().min(1),
19589
+ interactionId: external_exports.string().min(1),
19590
+ answers: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())),
19591
+ cancelled: external_exports.boolean().default(false)
19592
+ });
19593
+ var threadQuestionRespondResultSchema = external_exports.object({ accepted: external_exports.literal(true) });
19594
+
19548
19595
  // ../../shared-contracts/dist/harness-plugins.js
19549
19596
  var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
19550
19597
  var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
@@ -20304,6 +20351,21 @@ var threadSteeringInspectParamsSchema = external_exports.object({
20304
20351
  /** The text about to be steered; a Harness command always stops and restarts. */
20305
20352
  text: external_exports.string().optional()
20306
20353
  }).strict();
20354
+ var threadSteeringContextSchema = external_exports.object({
20355
+ kind: external_exports.literal("application"),
20356
+ value: external_exports.string().transform((text, context) => {
20357
+ try {
20358
+ return JSON.parse(text);
20359
+ } catch {
20360
+ context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
20361
+ return external_exports.NEVER;
20362
+ }
20363
+ }).pipe(external_exports.object({
20364
+ expectedTurnId: hostTurnIdSchema,
20365
+ clientUserMessageId: external_exports.string().min(1),
20366
+ delivery: external_exports.enum(["newTurn", "activeTurn"])
20367
+ }).strict())
20368
+ }).strict().transform((context) => context.value);
20307
20369
  var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
20308
20370
  var threadSteeringInspectResultSchema = external_exports.object({
20309
20371
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
@@ -20314,7 +20376,10 @@ var harnessPluginRouteSchema = external_exports.object({
20314
20376
  harnessId: harnessPluginIdSchema,
20315
20377
  model: harnessModelRefSchema.optional(),
20316
20378
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
20317
- permissionModeId: harnessPermissionModeIdSchema.optional()
20379
+ permissionModeId: harnessPermissionModeIdSchema.optional(),
20380
+ /** A draft prewarm create: stays unsubmitted until the user's first Turn.
20381
+ * Desktop forwards only the Model of a main-process prewarm to thread/start. */
20382
+ prewarm: external_exports.literal(true).optional()
20318
20383
  }).strict();
20319
20384
 
20320
20385
  // ../../shared-contracts/dist/harness-launch-settings.js
@@ -20925,26 +20990,26 @@ function parseHostUsage(value) {
20925
20990
  }
20926
20991
  }
20927
20992
  const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
20928
- for (const field of [
20993
+ for (const field2 of [
20929
20994
  "totalCredits",
20930
20995
  "contextUsagePercent",
20931
20996
  "apiOutputTokensPerSecond"
20932
20997
  ]) {
20933
- const candidate = value[field];
20998
+ const candidate = value[field2];
20934
20999
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
20935
- throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
21000
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
20936
21001
  }
20937
21002
  }
20938
- for (const field of tokenFields) {
20939
- const candidate = value[field];
21003
+ for (const field2 of tokenFields) {
21004
+ const candidate = value[field2];
20940
21005
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
20941
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
21006
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
20942
21007
  }
20943
21008
  }
20944
- for (const field of safeIntegerFields) {
20945
- const candidate = value[field];
21009
+ for (const field2 of safeIntegerFields) {
21010
+ const candidate = value[field2];
20946
21011
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
20947
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
21012
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
20948
21013
  }
20949
21014
  }
20950
21015
  if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
@@ -20953,16 +21018,16 @@ function parseHostUsage(value) {
20953
21018
  if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
20954
21019
  throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
20955
21020
  }
20956
- for (const field of ["totalCredits", "contextUsagePercent"]) {
20957
- const candidate = value[field];
21021
+ for (const field2 of ["totalCredits", "contextUsagePercent"]) {
21022
+ const candidate = value[field2];
20958
21023
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
20959
- throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
21024
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
20960
21025
  }
20961
21026
  }
20962
- for (const field of percentFields) {
20963
- const candidate = value[field];
21027
+ for (const field2 of percentFields) {
21028
+ const candidate = value[field2];
20964
21029
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
20965
- throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
21030
+ throw new Error(`Harness Usage '${field2}' must be between 0 and 100`);
20966
21031
  }
20967
21032
  }
20968
21033
  if (value.sessionCacheUsage !== void 0) {
@@ -21141,11 +21206,371 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
21141
21206
  return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
21142
21207
  }
21143
21208
 
21209
+ // ../../harness-adapter/dist/local-media-markdown.js
21210
+ import { existsSync, statSync } from "node:fs";
21211
+ import path7 from "node:path";
21212
+ import { fileURLToPath } from "node:url";
21213
+ var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
21214
+ ".aac",
21215
+ ".gif",
21216
+ ".jpeg",
21217
+ ".jpg",
21218
+ ".m4a",
21219
+ ".m4v",
21220
+ ".mov",
21221
+ ".mp3",
21222
+ ".mp4",
21223
+ ".ogg",
21224
+ ".png",
21225
+ ".svg",
21226
+ ".wav",
21227
+ ".webm",
21228
+ ".webp"
21229
+ ]);
21230
+ function rewriteLocalMediaMarkdown(text, roots, options = {}) {
21231
+ return projectLocalMedia(text, roots, options.exists ?? mediaFileExists, options.holdIncomplete === true, options.relativeImagesOnly === true).text;
21232
+ }
21233
+ var LocalMediaMarkdownStream = class {
21234
+ #roots;
21235
+ #exists;
21236
+ #relativeImagesOnly;
21237
+ #native = "";
21238
+ #text = "";
21239
+ /** Native text length represented by `#text`; the rest is held. */
21240
+ #consumed = 0;
21241
+ #verbatim = false;
21242
+ constructor(roots, exists = mediaFileExists, options = {}) {
21243
+ this.#roots = [...roots];
21244
+ this.#relativeImagesOnly = options.relativeImagesOnly === true;
21245
+ const known = /* @__PURE__ */ new Map();
21246
+ this.#exists = (absolutePath) => {
21247
+ let found = known.get(absolutePath);
21248
+ if (found === void 0) {
21249
+ found = exists(absolutePath);
21250
+ known.set(absolutePath, found);
21251
+ }
21252
+ return found;
21253
+ };
21254
+ }
21255
+ /** Projected text published so far: every returned delta, concatenated. */
21256
+ get text() {
21257
+ return this.#text;
21258
+ }
21259
+ /** Add native text and return the projected text it makes publishable, possibly empty. */
21260
+ append(text) {
21261
+ this.#native += text;
21262
+ return this.#advance(true);
21263
+ }
21264
+ /** Return the projected text still held at the end of the stream. */
21265
+ flush() {
21266
+ return this.#advance(false);
21267
+ }
21268
+ #advance(holdIncomplete) {
21269
+ const next = this.#verbatim ? void 0 : projectLocalMedia(this.#native, this.#roots, this.#exists, holdIncomplete, this.#relativeImagesOnly);
21270
+ let delta;
21271
+ if (next?.text.startsWith(this.#text)) {
21272
+ delta = next.text.slice(this.#text.length);
21273
+ this.#consumed = next.consumed;
21274
+ } else {
21275
+ this.#verbatim = true;
21276
+ delta = this.#native.slice(this.#consumed);
21277
+ this.#consumed = this.#native.length;
21278
+ }
21279
+ this.#text += delta;
21280
+ return delta;
21281
+ }
21282
+ };
21283
+ function projectLocalMedia(text, roots, exists, holdIncomplete, relativeImagesOnly) {
21284
+ let output = "";
21285
+ let index = 0;
21286
+ let fence = null;
21287
+ while (index < text.length) {
21288
+ if (fence) {
21289
+ const close = closingFenceEnd(text, index, fence.marker, fence.length);
21290
+ if (close === -1)
21291
+ break;
21292
+ output += text.slice(index, close);
21293
+ index = close;
21294
+ fence = null;
21295
+ continue;
21296
+ }
21297
+ const next = earliestIndex([
21298
+ text.indexOf("![", index),
21299
+ text.indexOf("`", index),
21300
+ indexOfLineStartTilde(text, index)
21301
+ ]);
21302
+ if (next === -1)
21303
+ break;
21304
+ output += text.slice(index, next);
21305
+ index = next;
21306
+ const marker = text[next];
21307
+ let markerLength = 1;
21308
+ if (marker === "`" || marker === "~") {
21309
+ let runEnd = next;
21310
+ while (text[runEnd] === marker)
21311
+ runEnd += 1;
21312
+ markerLength = runEnd - next;
21313
+ if (runEnd === text.length && holdIncomplete) {
21314
+ return { text: output, consumed: next };
21315
+ }
21316
+ if (runEnd - next >= 3) {
21317
+ const kind = fenceLineKind(text, next);
21318
+ if (kind === "opaque")
21319
+ break;
21320
+ if (kind === "flat") {
21321
+ fence = { marker, length: runEnd - next };
21322
+ output += text.slice(next, runEnd);
21323
+ index = runEnd;
21324
+ continue;
21325
+ }
21326
+ }
21327
+ if (marker === "~") {
21328
+ output += text.slice(next, runEnd);
21329
+ index = runEnd;
21330
+ continue;
21331
+ }
21332
+ }
21333
+ if (text.startsWith("![", next)) {
21334
+ const image = parseMarkdownImage(text, next);
21335
+ if (image.kind === "text") {
21336
+ output += text.slice(next, image.end);
21337
+ index = image.end;
21338
+ continue;
21339
+ }
21340
+ if (image.kind === "open") {
21341
+ if (!holdIncomplete)
21342
+ break;
21343
+ return { text: output + text.slice(next, image.holdFrom), consumed: image.holdFrom };
21344
+ }
21345
+ const resolved2 = relativeImagesOnly && /^(?:[\\/]|[a-z][a-z\d+.-]*:)/i.test(image.destination.trim()) ? null : resolveLocalMediaPath(image.destination, roots, exists);
21346
+ output += resolved2 === null ? text.slice(next, image.end) : text.slice(next, image.destinationStart) + markdownDestination(resolved2, image.bracketed) + text.slice(image.destinationEnd, image.end);
21347
+ index = image.end;
21348
+ continue;
21349
+ }
21350
+ const code = parseInlineCode(text, next, markerLength);
21351
+ if (code.kind !== "code" || holdIncomplete && code.end === text.length) {
21352
+ if (holdIncomplete && code.kind !== "text")
21353
+ return { text: output, consumed: next };
21354
+ output += text.slice(next, next + markerLength);
21355
+ index = next + markerLength;
21356
+ continue;
21357
+ }
21358
+ const resolved = relativeImagesOnly || markerLength !== 1 || /[\r\n]/u.test(code.content) ? null : resolveLocalMediaPath(code.content, roots, exists);
21359
+ output += resolved === null ? text.slice(next, code.end) : mediaMarkdownImage(resolved);
21360
+ index = code.end;
21361
+ }
21362
+ return { text: output + text.slice(index), consumed: text.length };
21363
+ }
21364
+ function fenceLineKind(text, index) {
21365
+ const prefix = text.slice(text.lastIndexOf("\n", index - 1) + 1, index);
21366
+ if (prefix === "")
21367
+ return "flat";
21368
+ let remaining = prefix.replace(/^[ \t]+/u, "");
21369
+ while (remaining) {
21370
+ const marker = /^(?:>|(?:[-+*]|\d{1,9}[.)])(?=[ \t]))[ \t]*/u.exec(remaining);
21371
+ if (!marker)
21372
+ return null;
21373
+ remaining = remaining.slice(marker[0].length);
21374
+ }
21375
+ return "opaque";
21376
+ }
21377
+ function indexOfLineStartTilde(text, start) {
21378
+ for (let tilde = text.indexOf("~", start); tilde !== -1; tilde = text.indexOf("~", tilde + 1)) {
21379
+ if (fenceLineKind(text, tilde) !== null)
21380
+ return tilde;
21381
+ }
21382
+ return -1;
21383
+ }
21384
+ function closingFenceEnd(text, start, marker, length) {
21385
+ const closing = new RegExp(`^ {0,3}${marker === "`" ? "`" : "~"}{${length},}[ \\t]*\\r?$`, "u");
21386
+ let lineStart = text.indexOf("\n", start);
21387
+ while (lineStart !== -1) {
21388
+ lineStart += 1;
21389
+ const newline2 = text.indexOf("\n", lineStart);
21390
+ const lineEnd = newline2 === -1 ? text.length : newline2;
21391
+ if (closing.test(text.slice(lineStart, lineEnd)))
21392
+ return lineEnd;
21393
+ lineStart = newline2;
21394
+ }
21395
+ return -1;
21396
+ }
21397
+ function earliestIndex(candidates) {
21398
+ let next = -1;
21399
+ for (const candidate of candidates) {
21400
+ if (candidate === -1)
21401
+ continue;
21402
+ if (next === -1 || candidate < next)
21403
+ next = candidate;
21404
+ }
21405
+ return next;
21406
+ }
21407
+ function parseInlineCode(text, start, length) {
21408
+ let index = start + length;
21409
+ while (index < text.length) {
21410
+ const tick = text.indexOf("`", index);
21411
+ if (/\n[^\S\n]*\n/u.test(text.slice(index, tick < 0 ? text.length : tick))) {
21412
+ return { kind: "text" };
21413
+ }
21414
+ if (tick === -1)
21415
+ break;
21416
+ let end = tick + 1;
21417
+ while (text[end] === "`")
21418
+ end += 1;
21419
+ if (end - tick === length) {
21420
+ return { kind: "code", content: text.slice(start + length, tick), end };
21421
+ }
21422
+ index = end;
21423
+ }
21424
+ return { kind: "open" };
21425
+ }
21426
+ function parseMarkdownImage(text, start) {
21427
+ const openLabel = { kind: "open", holdFrom: start + 2 };
21428
+ let index = start + 2;
21429
+ while (index < text.length) {
21430
+ const character = text[index];
21431
+ if (character === "\n")
21432
+ return { kind: "text", end: start + 1 };
21433
+ if (character === "\\") {
21434
+ index += 2;
21435
+ continue;
21436
+ }
21437
+ if (character === "]")
21438
+ break;
21439
+ index += 1;
21440
+ }
21441
+ if (index + 1 >= text.length)
21442
+ return openLabel;
21443
+ if (text[index + 1] !== "(")
21444
+ return { kind: "text", end: start + 1 };
21445
+ const destinationStart = index + 2;
21446
+ const open = { kind: "open", holdFrom: destinationStart };
21447
+ const malformed = { kind: "text", end: destinationStart };
21448
+ index = skipBlanks(text, destinationStart);
21449
+ if (index >= text.length)
21450
+ return open;
21451
+ let destination;
21452
+ let destinationEnd;
21453
+ let bracketed = false;
21454
+ if (text[index] === "<") {
21455
+ bracketed = true;
21456
+ let close = index + 1;
21457
+ while (close < text.length && text[close] !== ">" && text[close] !== "\n")
21458
+ close += 1;
21459
+ if (close >= text.length)
21460
+ return open;
21461
+ if (text[close] === "\n")
21462
+ return malformed;
21463
+ destination = text.slice(index + 1, close);
21464
+ destinationEnd = close + 1;
21465
+ index = destinationEnd;
21466
+ } else {
21467
+ const begin = index;
21468
+ while (index < text.length) {
21469
+ const character = text[index];
21470
+ if (character === "\n" || character === " " || character === " " || character === ")")
21471
+ break;
21472
+ index += character === "\\" ? 2 : 1;
21473
+ }
21474
+ if (index >= text.length)
21475
+ return open;
21476
+ destination = unescapeMarkdown(text.slice(begin, index));
21477
+ destinationEnd = index;
21478
+ }
21479
+ index = skipBlanks(text, index);
21480
+ if (index >= text.length)
21481
+ return open;
21482
+ const opener = text[index];
21483
+ if (opener === '"' || opener === "'" || opener === "(") {
21484
+ const closer = opener === "(" ? ")" : opener;
21485
+ index += 1;
21486
+ while (index < text.length && text[index] !== closer && text[index] !== "\n")
21487
+ index += 1;
21488
+ if (index >= text.length)
21489
+ return open;
21490
+ if (text[index] === "\n")
21491
+ return malformed;
21492
+ index = skipBlanks(text, index + 1);
21493
+ if (index >= text.length)
21494
+ return open;
21495
+ }
21496
+ if (text[index] !== ")")
21497
+ return malformed;
21498
+ return {
21499
+ kind: "image",
21500
+ destination,
21501
+ destinationStart,
21502
+ destinationEnd,
21503
+ end: index + 1,
21504
+ bracketed
21505
+ };
21506
+ }
21507
+ function skipBlanks(text, start) {
21508
+ let index = start;
21509
+ while (text[index] === " " || text[index] === " ")
21510
+ index += 1;
21511
+ return index;
21512
+ }
21513
+ function mediaMarkdownImage(absolutePath) {
21514
+ const name = path7.basename(absolutePath).replaceAll("]", "\\]");
21515
+ return `![${name}](${markdownDestination(absolutePath, false)})`;
21516
+ }
21517
+ function markdownDestination(absolutePath, bracketed) {
21518
+ const encoded = absolutePath.replaceAll("%", "%2525");
21519
+ const destination = /^[A-Za-z]:\\/.test(encoded) ? encoded.replaceAll("\\", "/") : encoded.replaceAll("\\", "\\\\");
21520
+ return bracketed || /[\s()]/.test(destination) ? `<${destination}>` : destination;
21521
+ }
21522
+ function unescapeMarkdown(value) {
21523
+ return value.replace(/\\([\\()])/g, "$1");
21524
+ }
21525
+ function resolveLocalMediaPath(raw, roots, exists = mediaFileExists) {
21526
+ const trimmed = raw.trim();
21527
+ if (trimmed.length === 0 || isRemoteMediaUrl(trimmed))
21528
+ return null;
21529
+ const stripped = stripFileUrl(trimmed);
21530
+ if (stripped === null)
21531
+ return null;
21532
+ if (isAbsoluteMediaPath(stripped)) {
21533
+ const absolute = path7.resolve(stripped);
21534
+ return hasMediaExtension(absolute) && exists(absolute) ? absolute : null;
21535
+ }
21536
+ for (const root of roots) {
21537
+ const absolute = path7.resolve(root, stripped);
21538
+ if (hasMediaExtension(absolute) && exists(absolute))
21539
+ return absolute;
21540
+ }
21541
+ return null;
21542
+ }
21543
+ function isRemoteMediaUrl(value) {
21544
+ return /^(?:https?:|data:|app:|blob:)/i.test(value);
21545
+ }
21546
+ function stripFileUrl(value) {
21547
+ if (!value.toLowerCase().startsWith("file:"))
21548
+ return value;
21549
+ try {
21550
+ return fileURLToPath(value);
21551
+ } catch {
21552
+ return null;
21553
+ }
21554
+ }
21555
+ function isAbsoluteMediaPath(value) {
21556
+ return path7.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
21557
+ }
21558
+ function hasMediaExtension(value) {
21559
+ return MEDIA_EXTENSIONS.has(path7.extname(value).toLowerCase());
21560
+ }
21561
+ function mediaFileExists(absolutePath) {
21562
+ try {
21563
+ return existsSync(absolutePath) && statSync(absolutePath).isFile();
21564
+ } catch {
21565
+ return false;
21566
+ }
21567
+ }
21568
+
21144
21569
  // dist/acp-transport.js
21145
21570
  import { spawn, spawnSync } from "node:child_process";
21146
21571
  import { readdir, readFile as readFile3 } from "node:fs/promises";
21147
21572
  import os5 from "node:os";
21148
- import path12 from "node:path";
21573
+ import path13 from "node:path";
21149
21574
  import { Readable, Writable } from "node:stream";
21150
21575
 
21151
21576
  // dist/grok-slash-commands.js
@@ -21172,8 +21597,8 @@ function parseGrokAvailableCommands(value) {
21172
21597
  });
21173
21598
  }
21174
21599
  function isGrokSkill(command) {
21175
- const path16 = command.meta?.path;
21176
- return typeof path16 === "string" && /(^|[\\/])SKILL\.md$/u.test(path16) || typeof command.meta?.qualifiedName === "string";
21600
+ const path17 = command.meta?.path;
21601
+ return typeof path17 === "string" && /(^|[\\/])SKILL\.md$/u.test(path17) || typeof command.meta?.qualifiedName === "string";
21177
21602
  }
21178
21603
  function grokLiveCommands(native) {
21179
21604
  return native.map((command) => ({
@@ -21184,7 +21609,7 @@ function grokLiveCommands(native) {
21184
21609
  }
21185
21610
 
21186
21611
  // dist/command.js
21187
- import path7 from "node:path";
21612
+ import path8 from "node:path";
21188
21613
  var GrokExecutableError = class extends Error {
21189
21614
  code = "GROK_NOT_FOUND";
21190
21615
  };
@@ -21213,7 +21638,7 @@ function resolveGrokExecutable(input = {}) {
21213
21638
  });
21214
21639
  if (!resolution)
21215
21640
  throw new GrokExecutableError("Grok CLI is not installed");
21216
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path7.resolve(resolution.executable);
21641
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path8.resolve(resolution.executable);
21217
21642
  }
21218
21643
  function grokInvocation(command, platform = process.platform, modelId) {
21219
21644
  const arguments_ = ["agent", "--no-leader"];
@@ -21225,11 +21650,11 @@ function grokInvocation(command, platform = process.platform, modelId) {
21225
21650
 
21226
21651
  // dist/grok-fork.js
21227
21652
  import { isDeepStrictEqual } from "node:util";
21228
- import path10 from "node:path";
21653
+ import path11 from "node:path";
21229
21654
 
21230
21655
  // dist/grok-file-change.js
21231
21656
  import { Buffer as Buffer2 } from "node:buffer";
21232
- import path8 from "node:path";
21657
+ import path9 from "node:path";
21233
21658
 
21234
21659
  // ../../../node_modules/diff/libesm/diff/base.js
21235
21660
  var Diff = class {
@@ -21331,16 +21756,16 @@ var Diff = class {
21331
21756
  }
21332
21757
  }
21333
21758
  }
21334
- addToPath(path16, added, removed, oldPosInc, options) {
21335
- const last = path16.lastComponent;
21759
+ addToPath(path17, added, removed, oldPosInc, options) {
21760
+ const last = path17.lastComponent;
21336
21761
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
21337
21762
  return {
21338
- oldPos: path16.oldPos + oldPosInc,
21763
+ oldPos: path17.oldPos + oldPosInc,
21339
21764
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
21340
21765
  };
21341
21766
  } else {
21342
21767
  return {
21343
- oldPos: path16.oldPos + oldPosInc,
21768
+ oldPos: path17.oldPos + oldPosInc,
21344
21769
  lastComponent: { count: 1, added, removed, previousComponent: last }
21345
21770
  };
21346
21771
  }
@@ -21653,13 +22078,13 @@ function isRecord5(value) {
21653
22078
  return typeof value === "object" && value !== null && !Array.isArray(value);
21654
22079
  }
21655
22080
  function validAbsolutePath(value) {
21656
- return typeof value === "string" && path8.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
22081
+ return typeof value === "string" && path9.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
21657
22082
  }
21658
22083
  function displayPath(nativePath, cwd) {
21659
- const resolvedCwd = path8.resolve(cwd);
21660
- const resolvedPath = path8.resolve(nativePath);
21661
- const relative = path8.relative(resolvedCwd, resolvedPath);
21662
- const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path8.sep}`);
22084
+ const resolvedCwd = path9.resolve(cwd);
22085
+ const resolvedPath = path9.resolve(nativePath);
22086
+ const relative = path9.relative(resolvedCwd, resolvedPath);
22087
+ const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path9.sep}`);
21663
22088
  const selected = inside ? relative : resolvedPath;
21664
22089
  const normalized = selected.replaceAll("\\", "/");
21665
22090
  if (normalized.length === 0 || normalized === ".")
@@ -21720,299 +22145,19 @@ function projectGrokFileChanges(content, cwd, textLimit = DEFAULT_GROK_FILE_CHAN
21720
22145
  }
21721
22146
 
21722
22147
  // dist/local-media-markdown.js
21723
- import { existsSync, statSync } from "node:fs";
21724
22148
  import os4 from "node:os";
21725
- import path9 from "node:path";
21726
- var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
21727
- ".aac",
21728
- ".gif",
21729
- ".jpeg",
21730
- ".jpg",
21731
- ".m4a",
21732
- ".m4v",
21733
- ".mov",
21734
- ".mp3",
21735
- ".mp4",
21736
- ".ogg",
21737
- ".png",
21738
- ".svg",
21739
- ".wav",
21740
- ".webm",
21741
- ".webp"
21742
- ]);
22149
+ import path10 from "node:path";
21743
22150
  function grokMediaResolveRoots(cwd, sessionDirectory) {
21744
- const roots = [path9.resolve(cwd)];
22151
+ const roots = [path10.resolve(cwd)];
21745
22152
  if (sessionDirectory) {
21746
- const session = path9.resolve(sessionDirectory);
21747
- roots.push(session, path9.join(session, "videos"), path9.join(session, "images"));
22153
+ const session = path10.resolve(sessionDirectory);
22154
+ roots.push(session, path10.join(session, "videos"), path10.join(session, "images"));
21748
22155
  }
21749
22156
  const home = process.env.HOME ?? process.env.USERPROFILE ?? os4.homedir();
21750
22157
  if (home)
21751
- roots.push(path9.join(home, "Downloads"));
22158
+ roots.push(path10.join(home, "Downloads"));
21752
22159
  return roots;
21753
22160
  }
21754
- function rewriteLocalMediaMarkdown(text, roots, options = {}) {
21755
- const exists = options.exists ?? mediaFileExists;
21756
- const holdIncomplete = options.holdIncomplete === true;
21757
- let output = "";
21758
- let index = 0;
21759
- let fence = false;
21760
- while (index < text.length) {
21761
- if (fence) {
21762
- const fenceEnd = text.indexOf("```", index);
21763
- if (fenceEnd === -1) {
21764
- output += text.slice(index);
21765
- break;
21766
- }
21767
- output += text.slice(index, fenceEnd + 3);
21768
- index = fenceEnd + 3;
21769
- fence = false;
21770
- continue;
21771
- }
21772
- const fenceStart = text.indexOf("```", index);
21773
- const imageStart = text.indexOf("![", index);
21774
- const tickStart = indexOfInlineTick(text, index);
21775
- const next = earliestIndex([fenceStart, imageStart, tickStart]);
21776
- if (next === -1) {
21777
- output += text.slice(index);
21778
- break;
21779
- }
21780
- output += text.slice(index, next);
21781
- if (next === fenceStart) {
21782
- output += "```";
21783
- index = fenceStart + 3;
21784
- fence = true;
21785
- continue;
21786
- }
21787
- if (next === imageStart) {
21788
- const parsed = parseMarkdownImage(text, imageStart);
21789
- if (!parsed) {
21790
- output += "!";
21791
- index = imageStart + 1;
21792
- continue;
21793
- }
21794
- if (!parsed.closed) {
21795
- output += holdIncomplete ? text.slice(imageStart, parsed.destinationStart) : text.slice(imageStart);
21796
- break;
21797
- }
21798
- const resolved2 = resolveLocalMediaPath(parsed.destination, roots, exists);
21799
- output += text.slice(imageStart, parsed.destinationStart) + formatMarkdownDestination(resolved2 ?? parsed.destination, parsed.bracketed) + text.slice(parsed.destinationEnd, parsed.end);
21800
- index = parsed.end;
21801
- continue;
21802
- }
21803
- const inline = parseInlineCode(text, tickStart);
21804
- if (!inline.closed) {
21805
- if (!holdIncomplete)
21806
- output += text.slice(tickStart);
21807
- break;
21808
- }
21809
- const resolved = resolveLocalMediaPath(inline.content, roots, exists);
21810
- output += resolved ? mediaMarkdownImage(resolved) : text.slice(tickStart, inline.end);
21811
- index = inline.end;
21812
- }
21813
- return output;
21814
- }
21815
- function indexOfInlineTick(text, start) {
21816
- let index = start;
21817
- while (index < text.length) {
21818
- const tick = text.indexOf("`", index);
21819
- if (tick === -1)
21820
- return -1;
21821
- if (text.startsWith("```", tick)) {
21822
- index = tick + 3;
21823
- continue;
21824
- }
21825
- return tick;
21826
- }
21827
- return -1;
21828
- }
21829
- function earliestIndex(candidates) {
21830
- let next = -1;
21831
- for (const candidate of candidates) {
21832
- if (candidate === -1)
21833
- continue;
21834
- if (next === -1 || candidate < next)
21835
- next = candidate;
21836
- }
21837
- return next;
21838
- }
21839
- function parseInlineCode(text, start) {
21840
- let index = start + 1;
21841
- while (index < text.length) {
21842
- const character = text[index];
21843
- if (character === "\n")
21844
- return { closed: false, content: text.slice(start + 1, index), end: index };
21845
- if (character === "`")
21846
- return { closed: true, content: text.slice(start + 1, index), end: index + 1 };
21847
- index += 1;
21848
- }
21849
- return { closed: false, content: text.slice(start + 1), end: text.length };
21850
- }
21851
- function mediaMarkdownImage(absolutePath) {
21852
- const name = path9.basename(absolutePath).replaceAll("]", "\\]");
21853
- return `![${name}](${formatMarkdownDestination(absolutePath, false)})`;
21854
- }
21855
- function parseMarkdownImage(text, start) {
21856
- if (text.slice(start, start + 2) !== "![")
21857
- return null;
21858
- let index = start + 2;
21859
- while (index < text.length) {
21860
- const character = text[index];
21861
- if (character === "\n")
21862
- return null;
21863
- if (character === "\\" && index + 1 < text.length) {
21864
- index += 2;
21865
- continue;
21866
- }
21867
- if (character === "]")
21868
- break;
21869
- index += 1;
21870
- }
21871
- if (text[index] !== "]" || text[index + 1] !== "(")
21872
- return null;
21873
- const destinationStart = index + 2;
21874
- index = destinationStart;
21875
- while (text[index] === " " || text[index] === " ")
21876
- index += 1;
21877
- if (index >= text.length) {
21878
- return {
21879
- closed: false,
21880
- destination: "",
21881
- destinationStart,
21882
- destinationEnd: index,
21883
- end: text.length,
21884
- bracketed: false
21885
- };
21886
- }
21887
- let destination;
21888
- let destinationEnd;
21889
- let bracketed = false;
21890
- if (text[index] === "<") {
21891
- bracketed = true;
21892
- const close = text.indexOf(">", index + 1);
21893
- if (close === -1 || text.slice(index, close).includes("\n")) {
21894
- return {
21895
- closed: false,
21896
- destination: text.slice(index + 1),
21897
- destinationStart,
21898
- destinationEnd: text.length,
21899
- end: text.length,
21900
- bracketed: true
21901
- };
21902
- }
21903
- destination = text.slice(index + 1, close);
21904
- destinationEnd = close + 1;
21905
- index = destinationEnd;
21906
- } else {
21907
- const begin = index;
21908
- while (index < text.length) {
21909
- const character = text[index];
21910
- if (character === "\n" || character === " " || character === " " || character === ")")
21911
- break;
21912
- if (character === "\\" && index + 1 < text.length) {
21913
- index += 2;
21914
- continue;
21915
- }
21916
- index += 1;
21917
- }
21918
- destination = unescapeMarkdown(text.slice(begin, index));
21919
- destinationEnd = index;
21920
- }
21921
- while (text[index] === " " || text[index] === " ")
21922
- index += 1;
21923
- if (text[index] === '"' || text[index] === "'" || text[index] === "(") {
21924
- const closer = text[index] === "(" ? ")" : text[index];
21925
- index += 1;
21926
- while (index < text.length && text[index] !== closer && text[index] !== "\n")
21927
- index += 1;
21928
- if (text[index] !== closer) {
21929
- return {
21930
- closed: false,
21931
- destination,
21932
- destinationStart,
21933
- destinationEnd,
21934
- end: text.length,
21935
- bracketed
21936
- };
21937
- }
21938
- index += 1;
21939
- while (text[index] === " " || text[index] === " ")
21940
- index += 1;
21941
- }
21942
- if (text[index] !== ")") {
21943
- return {
21944
- closed: false,
21945
- destination,
21946
- destinationStart,
21947
- destinationEnd,
21948
- end: text.length,
21949
- bracketed
21950
- };
21951
- }
21952
- return {
21953
- closed: true,
21954
- destination,
21955
- destinationStart,
21956
- destinationEnd,
21957
- end: index + 1,
21958
- bracketed
21959
- };
21960
- }
21961
- function formatMarkdownDestination(destination, bracketed) {
21962
- if (bracketed || /[\s()]/.test(destination))
21963
- return `<${destination}>`;
21964
- return destination.replaceAll(" ", "%20");
21965
- }
21966
- function unescapeMarkdown(value) {
21967
- return value.replace(/\\([\\()])/g, "$1");
21968
- }
21969
- function resolveLocalMediaPath(raw, roots, exists = mediaFileExists) {
21970
- const trimmed = raw.trim();
21971
- if (trimmed.length === 0 || isRemoteMediaUrl(trimmed))
21972
- return null;
21973
- const stripped = stripFileUrl(trimmed);
21974
- if (!hasMediaExtension(stripped))
21975
- return null;
21976
- if (isAbsoluteMediaPath(stripped)) {
21977
- const absolute = path9.resolve(stripped);
21978
- return exists(absolute) ? absolute : null;
21979
- }
21980
- for (const root of roots) {
21981
- const absolute = path9.resolve(root, stripped);
21982
- if (exists(absolute))
21983
- return absolute;
21984
- }
21985
- return null;
21986
- }
21987
- function isRemoteMediaUrl(value) {
21988
- return /^(?:https?:|data:|app:|blob:)/i.test(value);
21989
- }
21990
- function stripFileUrl(value) {
21991
- if (!value.toLowerCase().startsWith("file:"))
21992
- return value;
21993
- try {
21994
- const url2 = new URL(value);
21995
- if (url2.protocol !== "file:")
21996
- return value;
21997
- return decodeURIComponent(url2.pathname);
21998
- } catch {
21999
- return value.replace(/^file:\/\//i, "");
22000
- }
22001
- }
22002
- function isAbsoluteMediaPath(value) {
22003
- return path9.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
22004
- }
22005
- function hasMediaExtension(value) {
22006
- const pathname = value.split(/[?#]/, 1)[0] ?? value;
22007
- return MEDIA_EXTENSIONS.has(path9.extname(pathname).toLowerCase());
22008
- }
22009
- function mediaFileExists(absolutePath) {
22010
- try {
22011
- return existsSync(absolutePath) && statSync(absolutePath).isFile();
22012
- } catch {
22013
- return false;
22014
- }
22015
- }
22016
22161
 
22017
22162
  // dist/grok-tool-output.js
22018
22163
  var DEFAULT_GROK_TOOL_OUTPUT_LIMIT = 64e3;
@@ -22026,10 +22171,10 @@ function stringField(value, key) {
22026
22171
  function numberField(value, key) {
22027
22172
  if (!isRecord6(value))
22028
22173
  return void 0;
22029
- const field = value[key];
22030
- if (field === null)
22174
+ const field2 = value[key];
22175
+ if (field2 === null)
22031
22176
  return null;
22032
- return typeof field === "number" && Number.isFinite(field) ? field : void 0;
22177
+ return typeof field2 === "number" && Number.isFinite(field2) ? field2 : void 0;
22033
22178
  }
22034
22179
  function decodeBytes(value) {
22035
22180
  if (!Array.isArray(value) || value.length === 0)
@@ -22228,13 +22373,13 @@ function isRecord7(value) {
22228
22373
  function idField(value, key) {
22229
22374
  if (!isRecord7(value))
22230
22375
  return void 0;
22231
- const field = value[key];
22232
- if (typeof field === "string") {
22233
- const trimmed = field.trim();
22376
+ const field2 = value[key];
22377
+ if (typeof field2 === "string") {
22378
+ const trimmed = field2.trim();
22234
22379
  return trimmed.length > 0 ? trimmed : void 0;
22235
22380
  }
22236
- if (typeof field === "number" && Number.isFinite(field))
22237
- return String(field);
22381
+ if (typeof field2 === "number" && Number.isFinite(field2))
22382
+ return String(field2);
22238
22383
  return void 0;
22239
22384
  }
22240
22385
  function stringField2(value, key) {
@@ -23013,11 +23158,11 @@ function parseGrokForkResponse(value) {
23013
23158
  }
23014
23159
  function projectRelativePath(value, cwds) {
23015
23160
  const normalized = value.replaceAll("\\", "/");
23016
- if (!path10.isAbsolute(value))
23161
+ if (!path11.isAbsolute(value))
23017
23162
  return normalized;
23018
23163
  for (const cwd of cwds) {
23019
- const relative = path10.relative(path10.resolve(cwd), path10.resolve(value));
23020
- if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path10.sep}`)) {
23164
+ const relative = path11.relative(path11.resolve(cwd), path11.resolve(value));
23165
+ if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path11.sep}`)) {
23021
23166
  return relative.replaceAll("\\", "/");
23022
23167
  }
23023
23168
  }
@@ -23082,8 +23227,8 @@ async function forkGrokSession(input) {
23082
23227
  error: error51("sessionNotFound", "Grok Native Session is unavailable")
23083
23228
  };
23084
23229
  }
23085
- const sourceCwd = path10.resolve(located.cwd);
23086
- const targetCwd = path10.resolve(input.cwd);
23230
+ const sourceCwd = path11.resolve(located.cwd);
23231
+ const targetCwd = path11.resolve(input.cwd);
23087
23232
  const source = await readSnapshot({ ...input, cwd: sourceCwd }, sourceRef.data.nativeSessionId);
23088
23233
  if (!source.ok)
23089
23234
  return source;
@@ -23266,7 +23411,7 @@ function parseGrokCompactResult(value, cancelled = false) {
23266
23411
  }
23267
23412
 
23268
23413
  // dist/grok-rewind.js
23269
- import path11 from "node:path";
23414
+ import path12 from "node:path";
23270
23415
  var GROK_REWIND_EXECUTE_METHOD = "_x.ai/rewind/execute";
23271
23416
  function error52(code, message, retryable = false) {
23272
23417
  return { code, message, retryable };
@@ -23339,8 +23484,8 @@ async function rewindGrokLastTurn(input) {
23339
23484
  error: error52("sessionNotFound", "Grok Native Session is unavailable")
23340
23485
  };
23341
23486
  }
23342
- const sourceCwd = path11.resolve(located.cwd);
23343
- const targetCwd = path11.resolve(input.cwd);
23487
+ const sourceCwd = path12.resolve(located.cwd);
23488
+ const targetCwd = path12.resolve(input.cwd);
23344
23489
  if (sourceCwd !== targetCwd) {
23345
23490
  return {
23346
23491
  ok: false,
@@ -23407,9 +23552,9 @@ function isRecord12(value) {
23407
23552
  }
23408
23553
  function stringField3(value, ...keys) {
23409
23554
  for (const key of keys) {
23410
- const field = value[key];
23411
- if (typeof field === "string" && field.length > 0)
23412
- return field;
23555
+ const field2 = value[key];
23556
+ if (typeof field2 === "string" && field2.length > 0)
23557
+ return field2;
23413
23558
  }
23414
23559
  return void 0;
23415
23560
  }
@@ -23493,17 +23638,17 @@ function isRecord13(value) {
23493
23638
  }
23494
23639
  function stringField4(value, ...keys) {
23495
23640
  for (const key of keys) {
23496
- const field = value[key];
23497
- if (typeof field === "string" && field.length > 0)
23498
- return field;
23641
+ const field2 = value[key];
23642
+ if (typeof field2 === "string" && field2.length > 0)
23643
+ return field2;
23499
23644
  }
23500
23645
  return void 0;
23501
23646
  }
23502
23647
  function optionalTimeoutMs(value) {
23503
23648
  for (const key of ["timeoutMs", "timeout_ms", "timeoutSecs", "timeout_secs"]) {
23504
- const field = value[key];
23505
- if (typeof field === "number" && Number.isFinite(field) && field > 0) {
23506
- return key.endsWith("secs") || key.endsWith("Secs") ? field * 1e3 : field;
23649
+ const field2 = value[key];
23650
+ if (typeof field2 === "number" && Number.isFinite(field2) && field2 > 0) {
23651
+ return key.endsWith("secs") || key.endsWith("Secs") ? field2 * 1e3 : field2;
23507
23652
  }
23508
23653
  }
23509
23654
  return void 0;
@@ -23723,6 +23868,163 @@ var GrokPermissionConfirmation = class {
23723
23868
  }
23724
23869
  };
23725
23870
 
23871
+ // dist/grok-questions.js
23872
+ var GROK_ASK_USER_QUESTION_METHOD = "_x.ai/ask_user_question";
23873
+ function isRecord14(value) {
23874
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23875
+ }
23876
+ function nonEmptyString(value) {
23877
+ return typeof value === "string" && value.trim().length > 0;
23878
+ }
23879
+ function parseGrokQuestionRequest(value) {
23880
+ if (!isRecord14(value) || !nonEmptyString(value.sessionId) || !nonEmptyString(value.toolCallId) || value.mode !== "default" && value.mode !== "plan" || !Array.isArray(value.questions) || value.questions.length === 0)
23881
+ throw new Error("Grok question requires sessionId, toolCallId, mode and nonempty questions");
23882
+ const seen = /* @__PURE__ */ new Set();
23883
+ const questions = value.questions.map((question) => {
23884
+ if (!isRecord14(question) || !nonEmptyString(question.question) || seen.has(question.question) || !Array.isArray(question.options) || question.multiSelect != null && typeof question.multiSelect !== "boolean" || question.multi_select != null && typeof question.multi_select !== "boolean")
23885
+ throw new Error("Grok question text must be unique and options/multiSelect must be valid");
23886
+ if (question.multiSelect != null && question.multi_select != null && question.multiSelect !== question.multi_select)
23887
+ throw new Error("Grok question contains conflicting multi-select flags");
23888
+ seen.add(question.question);
23889
+ const labels = /* @__PURE__ */ new Set();
23890
+ const options = question.options.map((option) => {
23891
+ if (!isRecord14(option) || !nonEmptyString(option.label) || labels.has(option.label) || typeof option.description !== "string" || option.preview != null && typeof option.preview !== "string")
23892
+ throw new Error("Grok question options require unique labels and text descriptions/previews");
23893
+ labels.add(option.label);
23894
+ return {
23895
+ label: option.label,
23896
+ description: option.description,
23897
+ ...typeof option.preview === "string" ? { preview: option.preview } : {}
23898
+ };
23899
+ });
23900
+ return {
23901
+ question: question.question,
23902
+ options,
23903
+ multiple: question.multiSelect === true || question.multi_select === true
23904
+ };
23905
+ });
23906
+ return { sessionId: value.sessionId, toolCallId: value.toolCallId, mode: value.mode, questions };
23907
+ }
23908
+ var GrokQuestions = class {
23909
+ turnId;
23910
+ randomUUID;
23911
+ emit;
23912
+ #pending = /* @__PURE__ */ new Map();
23913
+ #seenToolCalls = /* @__PURE__ */ new Set();
23914
+ #closed = false;
23915
+ constructor(turnId, randomUUID2, emit) {
23916
+ this.turnId = turnId;
23917
+ this.randomUUID = randomUUID2;
23918
+ this.emit = emit;
23919
+ }
23920
+ has(interactionId) {
23921
+ return this.#pending.has(interactionId);
23922
+ }
23923
+ ask(request) {
23924
+ if (this.#closed || this.#seenToolCalls.has(request.toolCallId))
23925
+ return Promise.resolve({ outcome: "cancelled" });
23926
+ this.#seenToolCalls.add(request.toolCallId);
23927
+ const interaction = {
23928
+ type: "question",
23929
+ interactionId: hostInteractionIdSchema.parse(this.randomUUID()),
23930
+ turnId: this.turnId,
23931
+ title: "Grok",
23932
+ questions: request.questions.map((question, index) => question.options.length ? {
23933
+ id: `q${index}`,
23934
+ type: "choice",
23935
+ prompt: question.question,
23936
+ options: question.options.map(({ label, description, preview }) => ({
23937
+ value: label,
23938
+ label,
23939
+ description: [description, preview].filter(Boolean).join("\n\n")
23940
+ })),
23941
+ multiple: question.multiple,
23942
+ allowOther: true,
23943
+ optional: true
23944
+ } : {
23945
+ id: `q${index}`,
23946
+ type: "text",
23947
+ prompt: question.question,
23948
+ multiline: true,
23949
+ secret: false,
23950
+ optional: true
23951
+ })
23952
+ };
23953
+ return new Promise((resolve) => {
23954
+ this.#pending.set(interaction.interactionId, { request, interaction, resolve });
23955
+ this.emit({ kind: "interaction", interaction });
23956
+ });
23957
+ }
23958
+ respond(command) {
23959
+ const pending = this.#pending.get(command.interactionId);
23960
+ if (!pending)
23961
+ return this.#error("invalidState", "Grok Question is not pending");
23962
+ if (command.response.type !== "question")
23963
+ return this.#error("invalidRequest", "Grok Question requires a Question Response");
23964
+ const response = command.response;
23965
+ const error53 = validateHostQuestionResponse(pending.interaction, response);
23966
+ if (error53)
23967
+ return { ok: false, error: error53 };
23968
+ if (response.cancelled) {
23969
+ this.#settle(pending, { outcome: "cancelled" }, "cancelled");
23970
+ return { ok: true, value: { accepted: true } };
23971
+ }
23972
+ const answers = /* @__PURE__ */ new Map();
23973
+ const annotations = /* @__PURE__ */ new Map();
23974
+ for (const [index, question] of pending.request.questions.entries()) {
23975
+ const values = response.answers[`q${index}`];
23976
+ if (!values?.length)
23977
+ continue;
23978
+ if (values.some((answer) => !nonEmptyString(answer)) || new Set(values).size !== values.length)
23979
+ return this.#error("invalidRequest", "Grok answers must be nonempty and unique");
23980
+ const selected = values.map((answer) => question.options.find(({ label }) => label === answer));
23981
+ const other = values.filter((_, position) => !selected[position]);
23982
+ if (other.length > 1)
23983
+ return this.#error("invalidRequest", "Grok question accepts only one Other response");
23984
+ answers.set(question.question, selected.map((option) => option?.label ?? "Other"));
23985
+ const previews = selected.flatMap((option) => option?.preview !== void 0 ? [option.preview] : []);
23986
+ if (previews.length || other.length)
23987
+ annotations.set(question.question, {
23988
+ ...previews.length ? { preview: previews.join("\n\n") } : {},
23989
+ ...other.length ? { notes: other[0] } : {}
23990
+ });
23991
+ }
23992
+ this.#settle(pending, {
23993
+ outcome: "accepted",
23994
+ answers: Object.fromEntries(answers),
23995
+ ...annotations.size ? { annotations: Object.fromEntries(annotations) } : {}
23996
+ }, "responded");
23997
+ return { ok: true, value: { accepted: true } };
23998
+ }
23999
+ withdraw(toolCallId) {
24000
+ for (const pending of this.#pending.values()) {
24001
+ if (pending.request.toolCallId === toolCallId)
24002
+ this.#settle(pending, { outcome: "cancelled" }, "cancelled");
24003
+ }
24004
+ }
24005
+ cancel() {
24006
+ this.#closed = true;
24007
+ for (const pending of this.#pending.values())
24008
+ this.#settle(pending, { outcome: "cancelled" }, "cancelled");
24009
+ }
24010
+ #settle(pending, response, reason) {
24011
+ this.#pending.delete(pending.interaction.interactionId);
24012
+ pending.resolve(response);
24013
+ this.emit({
24014
+ kind: "event",
24015
+ event: {
24016
+ type: "interaction.closed",
24017
+ interactionId: pending.interaction.interactionId,
24018
+ turnId: this.turnId,
24019
+ reason
24020
+ }
24021
+ });
24022
+ }
24023
+ #error(code, message) {
24024
+ return { ok: false, error: { code, message, retryable: false } };
24025
+ }
24026
+ };
24027
+
23726
24028
  // dist/acp-transport.js
23727
24029
  var GrokTransportError = class extends Error {
23728
24030
  kind;
@@ -23734,16 +24036,16 @@ var GrokTransportError = class extends Error {
23734
24036
  this.name = "GrokTransportError";
23735
24037
  }
23736
24038
  };
23737
- function isRecord14(value) {
24039
+ function isRecord15(value) {
23738
24040
  return typeof value === "object" && value !== null && !Array.isArray(value);
23739
24041
  }
23740
24042
  function acpToolName(update, metadata) {
23741
- if (!isRecord14(update))
24043
+ if (!isRecord15(update))
23742
24044
  return void 0;
23743
24045
  if (typeof update.name === "string" && update.name.length > 0)
23744
24046
  return update.name;
23745
- const meta3 = isRecord14(update._meta) ? update._meta : metadata;
23746
- const tool = meta3 && isRecord14(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
24047
+ const meta3 = isRecord15(update._meta) ? update._meta : metadata;
24048
+ const tool = meta3 && isRecord15(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
23747
24049
  return tool && typeof tool.name === "string" && tool.name.length > 0 ? tool.name : void 0;
23748
24050
  }
23749
24051
  function errorText(error53) {
@@ -23799,8 +24101,14 @@ function signalProcessTree(child, signal) {
23799
24101
  try {
23800
24102
  process.kill(-child.pid, signal);
23801
24103
  } catch (error53) {
23802
- if (!isRecord14(error53) || error53.code !== "ESRCH")
23803
- throw error53;
24104
+ if (!isRecord15(error53) || error53.code === "ESRCH")
24105
+ return;
24106
+ try {
24107
+ child.kill(signal);
24108
+ } catch (fallback) {
24109
+ if (!isRecord15(fallback) || fallback.code !== "ESRCH")
24110
+ throw fallback;
24111
+ }
23804
24112
  }
23805
24113
  }
23806
24114
  function transportEvent(update, metadata) {
@@ -23842,6 +24150,10 @@ function transportEvent(update, metadata) {
23842
24150
  const subagent = grokSubagentEventFromUpdate(extension);
23843
24151
  if (subagent)
23844
24152
  return subagent;
24153
+ if (extension.sessionUpdate === "interaction_resolved") {
24154
+ const toolCallId = extension.tool_call_id ?? extension.toolCallId;
24155
+ return typeof toolCallId === "string" && toolCallId.trim().length > 0 ? { type: "interaction.resolved", toolCallId, ...metadata ? { metadata } : {} } : null;
24156
+ }
23845
24157
  switch (update.sessionUpdate) {
23846
24158
  case "user_message_chunk":
23847
24159
  case "agent_message_chunk":
@@ -23890,13 +24202,13 @@ function transportEvent(update, metadata) {
23890
24202
  function grokHomeDir(options) {
23891
24203
  const environment = { ...process.env, ...options.environment };
23892
24204
  const home = environment.HOME ?? environment.USERPROFILE ?? os5.homedir();
23893
- return environment.GROK_HOME ?? path12.join(home, ".grok");
24205
+ return environment.GROK_HOME ?? path13.join(home, ".grok");
23894
24206
  }
23895
24207
  function grokNativeSessionDirectory(options, sessionId) {
23896
- return path12.join(grokHomeDir(options), "sessions", encodeURIComponent(path12.resolve(options.cwd)), sessionId);
24208
+ return path13.join(grokHomeDir(options), "sessions", encodeURIComponent(path13.resolve(options.cwd)), sessionId);
23897
24209
  }
23898
24210
  function nativeSessionFile(options, sessionId, fileName) {
23899
- return path12.join(grokNativeSessionDirectory(options, sessionId), fileName);
24211
+ return path13.join(grokNativeSessionDirectory(options, sessionId), fileName);
23900
24212
  }
23901
24213
  function nativeHistoryPath(options, sessionId) {
23902
24214
  return nativeSessionFile(options, sessionId, "updates.jsonl");
@@ -23909,14 +24221,14 @@ async function readNativeSignals(options, sessionId) {
23909
24221
  }
23910
24222
  }
23911
24223
  function isMissingFile(error53) {
23912
- return isRecord14(error53) && error53.code === "ENOENT";
24224
+ return isRecord15(error53) && error53.code === "ENOENT";
23913
24225
  }
23914
24226
  async function locateGrokNativeSession(options, sessionId) {
23915
24227
  if (sessionId.length === 0)
23916
24228
  return null;
23917
24229
  let entries;
23918
24230
  try {
23919
- entries = await readdir(path12.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
24231
+ entries = await readdir(path13.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
23920
24232
  } catch (error53) {
23921
24233
  if (isMissingFile(error53))
23922
24234
  return null;
@@ -23930,9 +24242,9 @@ async function locateGrokNativeSession(options, sessionId) {
23930
24242
  continue;
23931
24243
  let summaryRaw;
23932
24244
  try {
23933
- summaryRaw = await readFile3(path12.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
24245
+ summaryRaw = await readFile3(path13.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
23934
24246
  } catch (error53) {
23935
- if (isMissingFile(error53) || isRecord14(error53) && error53.code === "ENOTDIR")
24247
+ if (isMissingFile(error53) || isRecord15(error53) && error53.code === "ENOTDIR")
23936
24248
  continue;
23937
24249
  throw new GrokTransportError("unavailable", "Grok Native Session metadata could not be read", {
23938
24250
  cause: error53
@@ -23944,11 +24256,11 @@ async function locateGrokNativeSession(options, sessionId) {
23944
24256
  } catch {
23945
24257
  continue;
23946
24258
  }
23947
- if (!isRecord14(parsed))
24259
+ if (!isRecord15(parsed))
23948
24260
  continue;
23949
24261
  const info = parsed.info;
23950
- const cwd = isRecord14(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path12.resolve(info.cwd) : path12.resolve(decodeURIComponent(entry.name));
23951
- const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path12.resolve(parsed.source_workspace_dir) : void 0;
24262
+ const cwd = isRecord15(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path13.resolve(info.cwd) : path13.resolve(decodeURIComponent(entry.name));
24263
+ const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path13.resolve(parsed.source_workspace_dir) : void 0;
23952
24264
  matches.push({
23953
24265
  cwd,
23954
24266
  ...sourceWorkspaceDir ? { sourceWorkspaceDir } : {}
@@ -23958,7 +24270,7 @@ async function locateGrokNativeSession(options, sessionId) {
23958
24270
  }
23959
24271
  async function readGrokNativeHistory(options, sessionId) {
23960
24272
  try {
23961
- return parseNativeHistory(await readFile3(nativeHistoryPath({ ...options, cwd: path12.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
24273
+ return parseNativeHistory(await readFile3(nativeHistoryPath({ ...options, cwd: path13.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
23962
24274
  } catch (error53) {
23963
24275
  if (isMissingFile(error53))
23964
24276
  return [];
@@ -23980,12 +24292,12 @@ function parseNativeHistory(contents, sessionId) {
23980
24292
  } catch {
23981
24293
  throw new GrokTransportError("protocolError", "Grok Native history contains invalid JSON");
23982
24294
  }
23983
- if (!isRecord14(record2) || !isRecord14(record2.params))
24295
+ if (!isRecord15(record2) || !isRecord15(record2.params))
23984
24296
  continue;
23985
24297
  const params = record2.params;
23986
- if (params.sessionId !== sessionId || !isRecord14(params.update))
24298
+ if (params.sessionId !== sessionId || !isRecord15(params.update))
23987
24299
  continue;
23988
- const metadata = isRecord14(params._meta) ? params._meta : void 0;
24300
+ const metadata = isRecord15(params._meta) ? params._meta : void 0;
23989
24301
  const event = transportEvent(params.update, metadata);
23990
24302
  if (event)
23991
24303
  events.push(metadata ? { ...event, metadata } : event);
@@ -24049,7 +24361,7 @@ var GrokAcpTransport = class {
24049
24361
  if (!this.#connection)
24050
24362
  throw new GrokTransportError("unavailable", "Grok ACP is unavailable");
24051
24363
  const result = await withTimeout(this.#connection.request("_x.ai/session/usage", { sessionId: this.sessionId }), this.#options.commandTimeoutMs, "Grok Session usage");
24052
- return isRecord14(result) ? result.usage : void 0;
24364
+ return isRecord15(result) ? result.usage : void 0;
24053
24365
  }
24054
24366
  async readHistory(sessionId, cwd = this.#options.cwd) {
24055
24367
  return readGrokNativeHistory({ ...this.#options, cwd }, sessionId);
@@ -24244,7 +24556,7 @@ var GrokAcpTransport = class {
24244
24556
  this.#initialize = initialize;
24245
24557
  return initialize;
24246
24558
  }
24247
- async runTurn(text, onEvent, onPermission, onExtension) {
24559
+ async runTurn(text, onEvent, onPermission, onQuestion, onExtension = async ({ method }) => isGrokExitPlanModeMethod(method) ? grokPlanRejectedResponse() : grokSkipInterviewResponse()) {
24248
24560
  const connection = this.#connection;
24249
24561
  if (!connection || !this.#sessionId || this.#closed || this.#closing) {
24250
24562
  throw new GrokTransportError("unavailable", "Grok ACP Session is unavailable");
@@ -24253,7 +24565,7 @@ var GrokAcpTransport = class {
24253
24565
  throw new Error("Grok ACP Session already has an active Prompt");
24254
24566
  if (this.#permissionConfirmation)
24255
24567
  throw new GrokTransportError("unavailable", "Grok ACP Session has an active operation");
24256
- const active = { onEvent, onPermission, onExtension };
24568
+ const active = { onEvent, onPermission, onExtension, onQuestion };
24257
24569
  this.#activePrompt = active;
24258
24570
  try {
24259
24571
  return await connection.prompt({
@@ -24312,7 +24624,7 @@ var GrokAcpTransport = class {
24312
24624
  ...reasoningEffort ? { reasoningEffort } : {},
24313
24625
  ...contextWindowTokens !== void 0 ? { _meta: { contextWindow: contextWindowTokens } } : {}
24314
24626
  });
24315
- if (!isRecord14(response) || !isRecord14(response._meta) || !isRecord14(response._meta.model)) {
24627
+ if (!isRecord15(response) || !isRecord15(response._meta) || !isRecord15(response._meta.model)) {
24316
24628
  throw new GrokTransportError("protocolError", "Grok rejected Model configuration");
24317
24629
  }
24318
24630
  const selected = response._meta.model.Ok;
@@ -24352,7 +24664,7 @@ var GrokAcpTransport = class {
24352
24664
  permission_mode: mode
24353
24665
  });
24354
24666
  const response = await connection.request("_x.ai/session/info", { sessionId });
24355
- if (!isRecord14(response) || !isRecord14(response.result) || response.result.sessionId !== sessionId) {
24667
+ if (!isRecord15(response) || !isRecord15(response.result) || response.result.sessionId !== sessionId) {
24356
24668
  throw new Error("Grok did not confirm the target Session");
24357
24669
  }
24358
24670
  })()
@@ -24407,7 +24719,7 @@ var GrokAcpTransport = class {
24407
24719
  this.#availableCommands = parseGrokAvailableCommands(update.availableCommands);
24408
24720
  return;
24409
24721
  }
24410
- const metadata = isRecord14(notification._meta) ? notification._meta : void 0;
24722
+ const metadata = isRecord15(notification._meta) ? notification._meta : void 0;
24411
24723
  const event = transportEvent(notification.update, metadata);
24412
24724
  if (!event)
24413
24725
  return;
@@ -24422,7 +24734,7 @@ var GrokAcpTransport = class {
24422
24734
  #handleExtensionNotification(method, params) {
24423
24735
  if (!isGrokExtensionSessionUpdateMethod(method))
24424
24736
  return;
24425
- if (typeof params.sessionId !== "string" || !isRecord14(params.update))
24737
+ if (typeof params.sessionId !== "string" || !isRecord15(params.update))
24426
24738
  return;
24427
24739
  this.#handleUpdate(params);
24428
24740
  }
@@ -24432,8 +24744,34 @@ var GrokAcpTransport = class {
24432
24744
  }
24433
24745
  return this.#activePrompt.onPermission({ request: params, options: params.options });
24434
24746
  }
24435
- #handleExtensionRequest(method, params) {
24436
- if (this.#activePrompt) {
24747
+ async #handleExtensionRequest(method, params) {
24748
+ if (method === GROK_ASK_USER_QUESTION_METHOD) {
24749
+ const active = this.#activePrompt;
24750
+ let request = null;
24751
+ let parseError;
24752
+ try {
24753
+ request = parseGrokQuestionRequest(params);
24754
+ } catch (error53) {
24755
+ parseError = error53;
24756
+ }
24757
+ if (request) {
24758
+ if (!active || this.#closed || this.#closing || this.#replay !== null || this.#activeCompact !== null || request.sessionId !== this.#sessionId)
24759
+ return { outcome: "cancelled" };
24760
+ return { ...await active.onQuestion(request) };
24761
+ }
24762
+ if (!isRecord15(params) || "toolCallId" in params && "mode" in params) {
24763
+ throw RequestError.invalidParams(void 0, errorText(parseError));
24764
+ }
24765
+ const legacy = parseGrokAskUserQuestionParams(params);
24766
+ if (!legacy)
24767
+ throw RequestError.invalidParams(params, "Grok Question is invalid");
24768
+ if (legacy.sessionId && legacy.sessionId !== this.#sessionId)
24769
+ return { outcome: "cancelled" };
24770
+ if (active && !this.#closed && !this.#closing && this.#replay === null)
24771
+ return active.onExtension({ method, params });
24772
+ return grokSkipInterviewResponse();
24773
+ }
24774
+ if (this.#activePrompt && (isGrokAskUserQuestionMethod(method) || isGrokExitPlanModeMethod(method))) {
24437
24775
  return this.#activePrompt.onExtension({ method, params });
24438
24776
  }
24439
24777
  if (isGrokAskUserQuestionMethod(method))
@@ -24453,7 +24791,7 @@ var GrokAcpTransport = class {
24453
24791
  // dist/session-import.js
24454
24792
  import { createReadStream as createReadStream2 } from "node:fs";
24455
24793
  import { opendir as opendir2, readFile as readFile4, stat } from "node:fs/promises";
24456
- import path13 from "node:path";
24794
+ import path14 from "node:path";
24457
24795
  import { createInterface as createInterface2 } from "node:readline";
24458
24796
 
24459
24797
  // ../../harness-adapter/dist/session-import.js
@@ -24574,7 +24912,7 @@ var SessionImportScope = class {
24574
24912
  // dist/session-import.js
24575
24913
  var MAX_METADATA_BYTES = 4 * 1024 * 1024;
24576
24914
  var SUBAGENT_SESSION_KINDS = /* @__PURE__ */ new Set(["subagent", "subagent_resume"]);
24577
- function isRecord15(value) {
24915
+ function isRecord16(value) {
24578
24916
  return typeof value === "object" && value !== null && !Array.isArray(value);
24579
24917
  }
24580
24918
  async function readJson(file2, signal) {
@@ -24587,7 +24925,7 @@ function processAlive(pid) {
24587
24925
  process.kill(pid, 0);
24588
24926
  return true;
24589
24927
  } catch (error53) {
24590
- return isRecord15(error53) && error53.code === "EPERM";
24928
+ return isRecord16(error53) && error53.code === "EPERM";
24591
24929
  }
24592
24930
  }
24593
24931
  async function firstUserText(file2, signal) {
@@ -24604,10 +24942,10 @@ async function firstUserText(file2, signal) {
24604
24942
  } catch {
24605
24943
  continue;
24606
24944
  }
24607
- const update = isRecord15(entry) && isRecord15(entry.params) ? entry.params.update : null;
24608
- if (!isRecord15(update) || update.sessionUpdate !== "user_message_chunk")
24945
+ const update = isRecord16(entry) && isRecord16(entry.params) ? entry.params.update : null;
24946
+ if (!isRecord16(update) || update.sessionUpdate !== "user_message_chunk")
24609
24947
  continue;
24610
- const text = isRecord15(update.content) ? update.content.text : null;
24948
+ const text = isRecord16(update.content) ? update.content.text : null;
24611
24949
  return typeof text === "string" ? text : "";
24612
24950
  }
24613
24951
  return null;
@@ -24674,7 +25012,7 @@ var GrokSessionImport = class {
24674
25012
  const active = /* @__PURE__ */ new Set();
24675
25013
  let entries;
24676
25014
  try {
24677
- entries = await readJson(path13.join(this.#home(), "active_sessions.json"), signal);
25015
+ entries = await readJson(path14.join(this.#home(), "active_sessions.json"), signal);
24678
25016
  } catch (error53) {
24679
25017
  signal.throwIfAborted();
24680
25018
  if (isStorageAccessError(error53))
@@ -24684,14 +25022,14 @@ var GrokSessionImport = class {
24684
25022
  if (!Array.isArray(entries))
24685
25023
  return active;
24686
25024
  for (const entry of entries) {
24687
- if (isRecord15(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
25025
+ if (isRecord16(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
24688
25026
  active.add(entry.session_id);
24689
25027
  }
24690
25028
  return active;
24691
25029
  }
24692
25030
  /** Session ID to every directory claiming it. Enumerated links are not followed. */
24693
25031
  async #sessionDirectories(signal) {
24694
- const root = path13.join(this.#home(), "sessions");
25032
+ const root = path14.join(this.#home(), "sessions");
24695
25033
  const found = /* @__PURE__ */ new Map();
24696
25034
  const info = await optionalLstat(root);
24697
25035
  if (!info)
@@ -24702,7 +25040,7 @@ var GrokSessionImport = class {
24702
25040
  signal.throwIfAborted();
24703
25041
  if (!workspace.isDirectory())
24704
25042
  continue;
24705
- const workspaceDirectory = path13.join(root, workspace.name);
25043
+ const workspaceDirectory = path14.join(root, workspace.name);
24706
25044
  const sessions = await opendir2(workspaceDirectory).catch((error53) => {
24707
25045
  if (isMissingFileError(error53))
24708
25046
  return null;
@@ -24715,7 +25053,7 @@ var GrokSessionImport = class {
24715
25053
  if (!session.isDirectory())
24716
25054
  continue;
24717
25055
  const directories = found.get(session.name) ?? [];
24718
- directories.push(path13.join(workspaceDirectory, session.name));
25056
+ directories.push(path14.join(workspaceDirectory, session.name));
24719
25057
  found.set(session.name, directories);
24720
25058
  }
24721
25059
  }
@@ -24723,25 +25061,25 @@ var GrokSessionImport = class {
24723
25061
  }
24724
25062
  async #candidate(sessionDirectory, active, signal) {
24725
25063
  signal.throwIfAborted();
24726
- const nativeSessionId = path13.basename(sessionDirectory);
25064
+ const nativeSessionId = path14.basename(sessionDirectory);
24727
25065
  const files = [
24728
- path13.join(sessionDirectory, "summary.json"),
24729
- path13.join(sessionDirectory, "updates.jsonl")
25066
+ path14.join(sessionDirectory, "summary.json"),
25067
+ path14.join(sessionDirectory, "updates.jsonl")
24730
25068
  ];
24731
25069
  return readStableFiles(files, async ([summaryInfo, updates]) => {
24732
25070
  if (!summaryInfo?.isFile() || !updates?.isFile() || summaryInfo.size > MAX_METADATA_BYTES)
24733
25071
  return null;
24734
25072
  try {
24735
25073
  const summary = await readJson(files[0], signal);
24736
- if (!isRecord15(summary) || !isRecord15(summary.info) || summary.info.id !== nativeSessionId)
25074
+ if (!isRecord16(summary) || !isRecord16(summary.info) || summary.info.id !== nativeSessionId)
24737
25075
  return null;
24738
25076
  if (typeof summary.session_kind === "string" && SUBAGENT_SESSION_KINDS.has(summary.session_kind))
24739
25077
  return null;
24740
25078
  const nativeCwd = summary.info.cwd;
24741
- if (typeof nativeCwd !== "string" || !path13.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
25079
+ if (typeof nativeCwd !== "string" || !path14.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
24742
25080
  return null;
24743
- const cwd = path13.resolve(nativeCwd);
24744
- if (encodeURIComponent(cwd) !== path13.basename(path13.dirname(sessionDirectory)))
25081
+ const cwd = path14.resolve(nativeCwd);
25082
+ if (encodeURIComponent(cwd) !== path14.basename(path14.dirname(sessionDirectory)))
24745
25083
  return null;
24746
25084
  if (!(await stat(cwd)).isDirectory())
24747
25085
  return null;
@@ -24960,7 +25298,7 @@ var GrokSubagentLifecycle = class {
24960
25298
  };
24961
25299
 
24962
25300
  // dist/grok-models.js
24963
- function isRecord16(value) {
25301
+ function isRecord17(value) {
24964
25302
  return typeof value === "object" && value !== null && !Array.isArray(value);
24965
25303
  }
24966
25304
  function nonBlank(value) {
@@ -24993,7 +25331,7 @@ function thinkingOptions(value) {
24993
25331
  const seen = /* @__PURE__ */ new Set();
24994
25332
  const options = [];
24995
25333
  for (const candidate of value) {
24996
- if (!isRecord16(candidate) || !nonBlank(candidate.label))
25334
+ if (!isRecord17(candidate) || !nonBlank(candidate.label))
24997
25335
  continue;
24998
25336
  const id = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
24999
25337
  if (!id.success || seen.has(id.data))
@@ -25004,7 +25342,7 @@ function thinkingOptions(value) {
25004
25342
  return options;
25005
25343
  }
25006
25344
  function parseGrokModelState(value) {
25007
- if (!isRecord16(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
25345
+ if (!isRecord17(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
25008
25346
  return null;
25009
25347
  }
25010
25348
  const currentModel = encodeGrokModelRef(value.currentModelId);
@@ -25016,12 +25354,12 @@ function parseGrokModelState(value) {
25016
25354
  const models = [];
25017
25355
  let currentThinkingOptionId;
25018
25356
  for (const candidate of value.availableModels) {
25019
- if (!isRecord16(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
25357
+ if (!isRecord17(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
25020
25358
  continue;
25021
25359
  const ref = encodeGrokModelRef(candidate.modelId);
25022
25360
  if (!ref)
25023
25361
  continue;
25024
- const metadata = isRecord16(candidate._meta) ? candidate._meta : {};
25362
+ const metadata = isRecord17(candidate._meta) ? candidate._meta : {};
25025
25363
  const options2 = thinkingOptions(metadata.reasoningEfforts);
25026
25364
  if (Array.isArray(metadata.contextWindows) && metadata.contextWindows.includes(5e5)) {
25027
25365
  defaultContextWindowTokensByModel.set(ref.id, 5e5);
@@ -25060,10 +25398,10 @@ function parseGrokModelState(value) {
25060
25398
  };
25061
25399
  }
25062
25400
  function modelStateFromInitialize(response) {
25063
- return parseGrokModelState(isRecord16(response._meta) ? response._meta.modelState : void 0);
25401
+ return parseGrokModelState(isRecord17(response._meta) ? response._meta.modelState : void 0);
25064
25402
  }
25065
25403
  function modelStateFromSessionResponse(response) {
25066
- return parseGrokModelState(isRecord16(response) ? response.models : void 0);
25404
+ return parseGrokModelState(isRecord17(response) ? response.models : void 0);
25067
25405
  }
25068
25406
  function stateForGrokModel(modelState, nativeState, model2 = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
25069
25407
  const selectedModel = model2;
@@ -25084,10 +25422,18 @@ function stateForGrokModel(modelState, nativeState, model2 = modelState.currentM
25084
25422
  // dist/grok-credits.js
25085
25423
  import { readFile as readFile5 } from "node:fs/promises";
25086
25424
  import os6 from "node:os";
25087
- import path14 from "node:path";
25425
+ import path15 from "node:path";
25088
25426
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
25427
+ var GROK_SETTINGS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/settings";
25089
25428
  var REQUEST_TIMEOUT_MS = 15e3;
25090
- function isRecord17(value) {
25429
+ var PLAN_TIMEOUT_MS = 2e3;
25430
+ function parseGrokPlan(value) {
25431
+ if (!isRecord18(value) || typeof value.subscription_tier_display !== "string")
25432
+ return void 0;
25433
+ const plan = value.subscription_tier_display.trim();
25434
+ return plan && plan.length <= 128 && !/[\u0000-\u001f\u007f]/u.test(plan) ? plan : void 0;
25435
+ }
25436
+ function isRecord18(value) {
25091
25437
  return typeof value === "object" && value !== null && !Array.isArray(value);
25092
25438
  }
25093
25439
  function finitePercent(value) {
@@ -25096,7 +25442,7 @@ function finitePercent(value) {
25096
25442
  return Math.min(100, Math.max(0, value));
25097
25443
  }
25098
25444
  function nonNegativeCentValue(value) {
25099
- if (!isRecord17(value))
25445
+ if (!isRecord18(value))
25100
25446
  return void 0;
25101
25447
  const amount = value.val === void 0 ? 0 : value.val;
25102
25448
  if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
@@ -25104,7 +25450,7 @@ function nonNegativeCentValue(value) {
25104
25450
  return amount;
25105
25451
  }
25106
25452
  function grokHome2(environment) {
25107
- return environment.GROK_HOME ?? path14.join(environment.HOME ?? environment.USERPROFILE ?? os6.homedir(), ".grok");
25453
+ return environment.GROK_HOME ?? path15.join(environment.HOME ?? environment.USERPROFILE ?? os6.homedir(), ".grok");
25108
25454
  }
25109
25455
  function periodTypeFrom(value) {
25110
25456
  if (typeof value !== "string")
@@ -25120,7 +25466,7 @@ function productUsageFrom(value) {
25120
25466
  if (!Array.isArray(value))
25121
25467
  return void 0;
25122
25468
  const products = value.flatMap((entry) => {
25123
- if (!isRecord17(entry) || typeof entry.product !== "string")
25469
+ if (!isRecord18(entry) || typeof entry.product !== "string")
25124
25470
  return [];
25125
25471
  const usagePercent = finitePercent(entry.usagePercent);
25126
25472
  const labels = {
@@ -25141,10 +25487,10 @@ function productUsageFrom(value) {
25141
25487
  return products.length > 0 ? products : void 0;
25142
25488
  }
25143
25489
  function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
25144
- if (!isRecord17(value) || !isRecord17(value.config))
25490
+ if (!isRecord18(value) || !isRecord18(value.config))
25145
25491
  return null;
25146
25492
  const config2 = value.config;
25147
- const period = isRecord17(config2.currentPeriod) ? config2.currentPeriod : void 0;
25493
+ const period = isRecord18(config2.currentPeriod) ? config2.currentPeriod : void 0;
25148
25494
  const periodType = periodTypeFrom(period?.type);
25149
25495
  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);
25150
25496
  let usedPercent = finitePercent(config2.creditUsagePercent);
@@ -25171,11 +25517,11 @@ function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()
25171
25517
  };
25172
25518
  }
25173
25519
  function selectAccessToken(auth, now) {
25174
- if (!isRecord17(auth))
25520
+ if (!isRecord18(auth))
25175
25521
  return null;
25176
- const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord17(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")));
25522
+ const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord18(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")));
25177
25523
  for (const [, value] of entries) {
25178
- if (!isRecord17(value) || typeof value.key !== "string")
25524
+ if (!isRecord18(value) || typeof value.key !== "string")
25179
25525
  continue;
25180
25526
  if (typeof value.expires_at === "string") {
25181
25527
  const expiresAt = Date.parse(value.expires_at);
@@ -25196,26 +25542,30 @@ async function fetchGrokAccount(input = {}) {
25196
25542
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((value) => value?.trim()))
25197
25543
  return null;
25198
25544
  const now = input.now ?? /* @__PURE__ */ new Date();
25199
- const authPath = path14.join(grokHome2(environment), "auth.json");
25545
+ const authPath = path15.join(grokHome2(environment), "auth.json");
25200
25546
  const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile5(authPath, "utf8");
25201
25547
  const token = selectAccessToken(JSON.parse(raw), now);
25202
25548
  if (!token)
25203
25549
  return null;
25204
25550
  const fetchImpl = input.fetch ?? fetch;
25205
- const response = await fetchImpl(GROK_CREDITS_ENDPOINT, {
25551
+ const request = (url2, timeoutMs) => fetchImpl(url2, {
25206
25552
  method: "GET",
25207
25553
  headers: {
25208
25554
  Authorization: `Bearer ${token.key}`,
25209
25555
  "x-xai-token-auth": "xai-grok-cli",
25210
25556
  Accept: "application/json"
25211
25557
  },
25212
- signal: input.signal ? AbortSignal.any([input.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]) : AbortSignal.timeout(REQUEST_TIMEOUT_MS)
25558
+ signal: input.signal ? AbortSignal.any([input.signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs)
25213
25559
  });
25560
+ const credits = request(GROK_CREDITS_ENDPOINT, REQUEST_TIMEOUT_MS);
25561
+ const plan = input.includePlan === false ? Promise.resolve(void 0) : request(GROK_SETTINGS_ENDPOINT, input.planTimeoutMs ?? PLAN_TIMEOUT_MS).then(async (response2) => response2.ok ? parseGrokPlan(await response2.json()) : void 0).catch(() => void 0);
25562
+ const response = await credits;
25214
25563
  if (!response.ok)
25215
25564
  return null;
25216
25565
  const snapshot = parseGrokCreditsResponse(await response.json(), now.toISOString());
25217
25566
  if (!snapshot)
25218
25567
  return null;
25568
+ const planName = await plan;
25219
25569
  return {
25220
25570
  credits: {
25221
25571
  usedPercent: snapshot.usedPercent,
@@ -25224,14 +25574,15 @@ async function fetchGrokAccount(input = {}) {
25224
25574
  ...snapshot.productUsage ? { productUsage: [...snapshot.productUsage] } : {}
25225
25575
  },
25226
25576
  ...token.email ? { email: token.email } : {},
25227
- ...token.label ? { label: token.label } : {}
25577
+ ...token.label ? { label: token.label } : {},
25578
+ ...planName ? { plan: planName } : {}
25228
25579
  };
25229
25580
  } catch {
25230
25581
  return null;
25231
25582
  }
25232
25583
  }
25233
25584
  async function fetchGrokCredits(input = {}) {
25234
- const account = await fetchGrokAccount(input);
25585
+ const account = await fetchGrokAccount({ ...input, includePlan: false });
25235
25586
  const usedPercent = account?.credits?.usedPercent;
25236
25587
  if (!account?.credits || usedPercent === void 0)
25237
25588
  return null;
@@ -25247,7 +25598,7 @@ async function fetchGrokCredits(input = {}) {
25247
25598
 
25248
25599
  // dist/grok-usage.js
25249
25600
  var USD_TICKS_PER_DOLLAR = 1e10;
25250
- function isRecord18(value) {
25601
+ function isRecord19(value) {
25251
25602
  return typeof value === "object" && value !== null && !Array.isArray(value);
25252
25603
  }
25253
25604
  function optionalToken(value) {
@@ -25264,7 +25615,7 @@ function combineUsage(base, next) {
25264
25615
  return base === null ? next : parseHostUsage({ ...base, ...next });
25265
25616
  }
25266
25617
  function usageFromNative(value) {
25267
- if (!isRecord18(value))
25618
+ if (!isRecord19(value))
25268
25619
  return null;
25269
25620
  const nativeInputTokens = optionalToken(value.inputTokens);
25270
25621
  const cachedRead = optionalToken(value.cachedReadTokens);
@@ -25290,7 +25641,7 @@ function usageFromNative(value) {
25290
25641
  }
25291
25642
  }
25292
25643
  function usageFromResponse(value) {
25293
- if (!isRecord18(value))
25644
+ if (!isRecord19(value))
25294
25645
  return null;
25295
25646
  const buckets = [
25296
25647
  value.input_tokens,
@@ -25320,10 +25671,10 @@ var GrokTurnUsage = class {
25320
25671
  #latestCacheHit;
25321
25672
  #sessionInputTokens = 0;
25322
25673
  constructor(base, emptySession = false) {
25323
- for (const field of summedUsageFields) {
25324
- const value = base?.[field];
25674
+ for (const field2 of summedUsageFields) {
25675
+ const value = base?.[field2];
25325
25676
  if (value !== void 0)
25326
- this.#totals[field] = value;
25677
+ this.#totals[field2] = value;
25327
25678
  }
25328
25679
  this.#cacheComplete = base?.sessionCacheUsage !== void 0 || emptySession;
25329
25680
  this.#sessionInputTokens = base?.sessionCacheUsage?.inputTokens ?? 0;
@@ -25364,10 +25715,10 @@ var GrokTurnUsage = class {
25364
25715
  this.#cacheComplete = false;
25365
25716
  if (usage) {
25366
25717
  this.#sessionInputTokens += (usage.inputTokens ?? 0) + (usage.cachedInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0);
25367
- for (const field of summedUsageFields) {
25368
- const value = usage[field];
25718
+ for (const field2 of summedUsageFields) {
25719
+ const value = usage[field2];
25369
25720
  if (value !== void 0)
25370
- this.#totals[field] = (this.#totals[field] ?? 0) + value;
25721
+ this.#totals[field2] = (this.#totals[field2] ?? 0) + value;
25371
25722
  }
25372
25723
  if (duration3 > 0 && usage.outputTokens !== void 0) {
25373
25724
  this.#outputTokens += usage.outputTokens;
@@ -25393,7 +25744,7 @@ var GrokTurnUsage = class {
25393
25744
  }
25394
25745
  };
25395
25746
  function usageFromSignals(value) {
25396
- if (!isRecord18(value))
25747
+ if (!isRecord19(value))
25397
25748
  return null;
25398
25749
  try {
25399
25750
  return parseHostUsage({
@@ -25413,7 +25764,7 @@ var summedUsageFields = [
25413
25764
  "totalTokens"
25414
25765
  ];
25415
25766
  function nativeCostTicks(value) {
25416
- if (!isRecord18(value))
25767
+ if (!isRecord19(value))
25417
25768
  return void 0;
25418
25769
  const ticks = value.costUsdTicks;
25419
25770
  if (typeof ticks !== "number" || !Number.isSafeInteger(ticks) || ticks < 0)
@@ -25421,7 +25772,7 @@ function nativeCostTicks(value) {
25421
25772
  return ticks;
25422
25773
  }
25423
25774
  function sessionCostFromNative(value, initialCostUsd) {
25424
- if (!isRecord18(value))
25775
+ if (!isRecord19(value))
25425
25776
  return void 0;
25426
25777
  if (value.costIsPartial !== void 0 && value.costIsPartial !== false)
25427
25778
  return void 0;
@@ -25450,7 +25801,7 @@ function sessionUsageFromHistory(events) {
25450
25801
  continue;
25451
25802
  const usage = usageFromNative(event.usage);
25452
25803
  const ticks2 = nativeCostTicks(event.usage);
25453
- const complete = isRecord18(event.usage) && (event.usage.usageIsIncomplete === void 0 || event.usage.usageIsIncomplete === false) && usage?.inputTokens !== void 0 && usage.cachedInputTokens !== void 0 && typeof event.usage.inputTokens === "number" && usage.cachedInputTokens + (usage.cacheWriteInputTokens ?? 0) <= event.usage.inputTokens;
25804
+ const complete = isRecord19(event.usage) && (event.usage.usageIsIncomplete === void 0 || event.usage.usageIsIncomplete === false) && usage?.inputTokens !== void 0 && usage.cachedInputTokens !== void 0 && typeof event.usage.inputTokens === "number" && usage.cachedInputTokens + (usage.cacheWriteInputTokens ?? 0) <= event.usage.inputTokens;
25454
25805
  latestByKey.set(key, { usage, complete, ...ticks2 !== void 0 ? { ticks: ticks2 } : {} });
25455
25806
  }
25456
25807
  if (latestByKey.size === 0)
@@ -25462,11 +25813,11 @@ function sessionUsageFromHistory(events) {
25462
25813
  for (const entry of latestByKey.values()) {
25463
25814
  if (!entry.usage)
25464
25815
  continue;
25465
- for (const field of summedUsageFields) {
25466
- const value = entry.usage[field];
25816
+ for (const field2 of summedUsageFields) {
25817
+ const value = entry.usage[field2];
25467
25818
  if (value === void 0)
25468
25819
  continue;
25469
- totals2[field] = (totals2[field] ?? 0) + value;
25820
+ totals2[field2] = (totals2[field2] ?? 0) + value;
25470
25821
  }
25471
25822
  sessionInputTokens += (entry.usage.inputTokens ?? 0) + (entry.usage.cachedInputTokens ?? 0) + (entry.usage.cacheWriteInputTokens ?? 0);
25472
25823
  if (entry.ticks === void 0)
@@ -25506,7 +25857,7 @@ function usageFromCompact(tokensAfter, contextWindowTokens) {
25506
25857
  function usageFromUpdate(update, metadata, contextWindowTokens) {
25507
25858
  try {
25508
25859
  if (update?.sessionUpdate === "usage_update") {
25509
- const cost = isRecord18(update.cost) ? update.cost : null;
25860
+ const cost = isRecord19(update.cost) ? update.cost : null;
25510
25861
  return parseHostUsage({
25511
25862
  contextUsedTokens: update.used,
25512
25863
  contextWindowTokens: update.size,
@@ -25745,11 +26096,11 @@ var GrokHarnessSession = class {
25745
26096
  });
25746
26097
  const active = {
25747
26098
  command,
26099
+ questions: new GrokQuestions(command.turnId, this.#randomUUID, (output) => this.#channel.emit(output)),
25748
26100
  usage: new GrokTurnUsage(this.#usage, this.#snapshot.turns.length === 0),
25749
26101
  agent: null,
25750
26102
  agentMessageId: null,
25751
- rawAgentText: "",
25752
- projectedAgentText: "",
26103
+ agentMedia: null,
25753
26104
  reasoning: null,
25754
26105
  reasoningMessageId: null,
25755
26106
  compactionItem: null,
@@ -25759,7 +26110,7 @@ var GrokHarnessSession = class {
25759
26110
  subagents: this.#createSubagents(),
25760
26111
  completedItems: [],
25761
26112
  approvals: /* @__PURE__ */ new Map(),
25762
- questions: /* @__PURE__ */ new Map(),
26113
+ legacyQuestions: /* @__PURE__ */ new Map(),
25763
26114
  cancellationRequested: false,
25764
26115
  beforeNativeTurnKeys: new Set(this.#snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey)),
25765
26116
  completion,
@@ -25767,7 +26118,7 @@ var GrokHarnessSession = class {
25767
26118
  };
25768
26119
  this.#active = active;
25769
26120
  this.#event({ type: "turn.started", turnId: command.turnId });
25770
- void this.#transport.runTurn(text, (event) => this.#handleEvent(active, event), (request) => this.#requestPermission(active, request), (request) => this.#requestExtension(active, request)).then((response) => this.#settleFromHistory(active, terminalOutcome2(response, active.cancellationRequested), response), (error53) => this.#settleFromHistory(active, {
26121
+ void this.#transport.runTurn(text, (event) => this.#handleEvent(active, event), (request) => this.#requestPermission(active, request), (request) => this.#active === active && this.#phase === "open" && !active.cancellationRequested ? active.questions.ask(request) : Promise.resolve({ outcome: "cancelled" }), (request) => this.#requestExtension(active, request)).finally(() => active.questions.cancel()).then((response) => this.#settleFromHistory(active, terminalOutcome2(response, active.cancellationRequested), response), (error53) => this.#settleFromHistory(active, {
25771
26122
  status: "failed",
25772
26123
  error: normalizeError(error53, "nativeFailure")
25773
26124
  }));
@@ -25836,10 +26187,10 @@ var GrokHarnessSession = class {
25836
26187
  });
25837
26188
  const active = {
25838
26189
  command: { type: "turn.start", turnId: command.turnId, input: [] },
26190
+ questions: new GrokQuestions(command.turnId, this.#randomUUID, (output) => this.#channel.emit(output)),
25839
26191
  agent: null,
25840
26192
  agentMessageId: null,
25841
- rawAgentText: "",
25842
- projectedAgentText: "",
26193
+ agentMedia: null,
25843
26194
  reasoning: null,
25844
26195
  reasoningMessageId: null,
25845
26196
  compactionItem: null,
@@ -25849,7 +26200,7 @@ var GrokHarnessSession = class {
25849
26200
  subagents: this.#createSubagents(),
25850
26201
  completedItems: [],
25851
26202
  approvals: /* @__PURE__ */ new Map(),
25852
- questions: /* @__PURE__ */ new Map(),
26203
+ legacyQuestions: /* @__PURE__ */ new Map(),
25853
26204
  cancellationRequested: false,
25854
26205
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
25855
26206
  completion,
@@ -26016,6 +26367,7 @@ var GrokHarnessSession = class {
26016
26367
  if (active.cancellationRequested)
26017
26368
  return { ok: true, value: { cancellationRequested: true } };
26018
26369
  active.cancellationRequested = true;
26370
+ active.questions.cancel();
26019
26371
  this.#closePendingInteractions(active, "cancelled");
26020
26372
  try {
26021
26373
  await this.#transport.cancel();
@@ -26026,10 +26378,12 @@ var GrokHarnessSession = class {
26026
26378
  }
26027
26379
  async #respond(command) {
26028
26380
  const active = this.#active;
26381
+ if (active?.questions.has(command.interactionId))
26382
+ return active.questions.respond(command);
26029
26383
  const approval = active?.approvals.get(command.interactionId);
26030
26384
  if (active && approval)
26031
26385
  return this.#respondApproval(active, approval, command);
26032
- const question = active?.questions.get(command.interactionId);
26386
+ const question = active?.legacyQuestions.get(command.interactionId);
26033
26387
  if (active && question)
26034
26388
  return this.#respondQuestion(active, question, command);
26035
26389
  return { ok: false, error: invalidState("Grok Interaction is not pending") };
@@ -26083,7 +26437,7 @@ var GrokHarnessSession = class {
26083
26437
  if (validation)
26084
26438
  return { ok: false, error: validation };
26085
26439
  const native = pending.type === "planApproval" ? grokExitPlanModeResponse(pending.request, command.response) : grokAskUserQuestionResponse(pending.request, command.response);
26086
- active.questions.delete(command.interactionId);
26440
+ active.legacyQuestions.delete(command.interactionId);
26087
26441
  pending.resolve(native);
26088
26442
  this.#event({
26089
26443
  type: "interaction.closed",
@@ -26141,7 +26495,7 @@ var GrokHarnessSession = class {
26141
26495
  const interactionId = hostInteractionIdSchema.parse(this.#randomUUID());
26142
26496
  const interaction = createGrokQuestionInteraction(request, interactionId, active.command.turnId);
26143
26497
  return new Promise((resolve) => {
26144
- active.questions.set(interactionId, {
26498
+ active.legacyQuestions.set(interactionId, {
26145
26499
  type: "question",
26146
26500
  interaction,
26147
26501
  request,
@@ -26157,7 +26511,7 @@ var GrokHarnessSession = class {
26157
26511
  const interactionId = hostInteractionIdSchema.parse(this.#randomUUID());
26158
26512
  const interaction = createGrokPlanReview(request, interactionId, active.command.turnId);
26159
26513
  return new Promise((resolve) => {
26160
- active.questions.set(interactionId, {
26514
+ active.legacyQuestions.set(interactionId, {
26161
26515
  type: "planApproval",
26162
26516
  interaction,
26163
26517
  request,
@@ -26177,8 +26531,8 @@ var GrokHarnessSession = class {
26177
26531
  reason
26178
26532
  });
26179
26533
  }
26180
- for (const [interactionId, pending] of active.questions) {
26181
- active.questions.delete(interactionId);
26534
+ for (const [interactionId, pending] of active.legacyQuestions) {
26535
+ active.legacyQuestions.delete(interactionId);
26182
26536
  pending.resolve(pending.type === "planApproval" ? grokPlanRejectedResponse() : grokSkipInterviewResponse());
26183
26537
  this.#event({
26184
26538
  type: "interaction.closed",
@@ -26191,6 +26545,10 @@ var GrokHarnessSession = class {
26191
26545
  #handleEvent(active, event) {
26192
26546
  if (this.#active !== active || this.#phase !== "open")
26193
26547
  return;
26548
+ if (event.type === "interaction.resolved") {
26549
+ active.questions.withdraw(event.toolCallId);
26550
+ return;
26551
+ }
26194
26552
  const requestUsage = active.usage?.observe(event);
26195
26553
  if (requestUsage) {
26196
26554
  this.#publishUsage(requestUsage, active.command.turnId, true);
@@ -26286,19 +26644,16 @@ var GrokHarnessSession = class {
26286
26644
  itemId: hostItemIdSchema.parse(this.#randomUUID()),
26287
26645
  text: ""
26288
26646
  };
26289
- active.rawAgentText = "";
26290
- active.projectedAgentText = "";
26647
+ active.agentMedia = new LocalMediaMarkdownStream(this.#mediaRoots);
26291
26648
  this.#event({ type: "item.started", turnId: active.command.turnId, item: active.agent });
26292
26649
  }
26293
- active.rawAgentText += text;
26294
- const projected = rewriteLocalMediaMarkdown(active.rawAgentText, this.#mediaRoots, {
26295
- holdIncomplete: true
26296
- });
26297
- const delta = projected.startsWith(active.projectedAgentText) ? projected.slice(active.projectedAgentText.length) : text;
26298
- if (delta.length === 0)
26650
+ const delta = active.agentMedia?.append(text) ?? "";
26651
+ this.#publishAgent(active, delta);
26652
+ }
26653
+ #publishAgent(active, delta) {
26654
+ if (!active.agent || !active.agentMedia || !delta)
26299
26655
  return;
26300
- active.projectedAgentText += delta;
26301
- active.agent = { ...active.agent, text: active.projectedAgentText };
26656
+ active.agent = { ...active.agent, text: active.agentMedia.text };
26302
26657
  this.#event({
26303
26658
  type: "item.updated",
26304
26659
  turnId: active.command.turnId,
@@ -26519,25 +26874,12 @@ var GrokHarnessSession = class {
26519
26874
  }
26520
26875
  #completeAgent(active, outcome) {
26521
26876
  const item = active.agent;
26522
- if (item && active.rawAgentText.length > 0) {
26523
- const flushed = rewriteLocalMediaMarkdown(active.rawAgentText, this.#mediaRoots);
26524
- const delta = flushed.startsWith(item.text) ? flushed.slice(item.text.length) : "";
26525
- if (delta.length > 0) {
26526
- active.projectedAgentText = flushed;
26527
- active.agent = { ...item, text: flushed };
26528
- this.#event({
26529
- type: "item.updated",
26530
- turnId: active.command.turnId,
26531
- itemId: item.itemId,
26532
- update: { type: "text.append", text: delta }
26533
- });
26534
- }
26535
- }
26877
+ if (item && active.agentMedia)
26878
+ this.#publishAgent(active, active.agentMedia.flush());
26536
26879
  const completed = active.agent ?? item;
26537
26880
  active.agent = null;
26538
26881
  active.agentMessageId = null;
26539
- active.rawAgentText = "";
26540
- active.projectedAgentText = "";
26882
+ active.agentMedia = null;
26541
26883
  if (completed)
26542
26884
  this.#completeItem(active, completed, outcome);
26543
26885
  }
@@ -26587,6 +26929,7 @@ var GrokHarnessSession = class {
26587
26929
  #finish(active, outcome, usage = null, nativeTurnRef) {
26588
26930
  if (this.#active !== active)
26589
26931
  return;
26932
+ active.questions.cancel();
26590
26933
  const itemOutcome = outcome;
26591
26934
  this.#completeReasoning(active, itemOutcome);
26592
26935
  this.#completeAgent(active, itemOutcome);
@@ -26634,12 +26977,8 @@ var GrokHarnessSession = class {
26634
26977
  const active = this.#active;
26635
26978
  if (active) {
26636
26979
  active.cancellationRequested = true;
26637
- for (const approval of active.approvals.values()) {
26638
- approval.resolve({ outcome: { outcome: "cancelled" } });
26639
- }
26640
- for (const question of active.questions.values()) {
26641
- question.resolve(question.type === "planApproval" ? grokPlanRejectedResponse() : grokSkipInterviewResponse());
26642
- }
26980
+ active.questions.cancel();
26981
+ this.#closePendingInteractions(active, "cancelled");
26643
26982
  await this.#transport.cancel().catch(() => void 0);
26644
26983
  await Promise.race([
26645
26984
  active.completion,
@@ -26783,7 +27122,7 @@ var GrokAdapter = class {
26783
27122
  async inspect(input = {}) {
26784
27123
  if (this.#closePromise)
26785
27124
  return { status: "unavailable", error: invalidState("Grok Adapter is closed") };
26786
- const cwd = path15.resolve(input.cwd ?? process.cwd());
27125
+ const cwd = path16.resolve(input.cwd ?? process.cwd());
26787
27126
  if (!input.refresh) {
26788
27127
  const cached2 = this.#inspectionCache.get(cwd);
26789
27128
  if (cached2)
@@ -26845,7 +27184,7 @@ var GrokAdapter = class {
26845
27184
  }
26846
27185
  };
26847
27186
  }
26848
- const cwd = path15.resolve(input.cwd);
27187
+ const cwd = path16.resolve(input.cwd);
26849
27188
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
26850
27189
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
26851
27190
  return {