@karlorz/codexhost-cli-win32-x64 0.17.4-7 → 0.17.4-8

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.
@@ -1158,10 +1158,10 @@ function mergeDefs(...defs) {
1158
1158
  function cloneDef(schema) {
1159
1159
  return mergeDefs(schema._zod.def);
1160
1160
  }
1161
- function getElementAtPath(obj, path22) {
1162
- if (!path22)
1161
+ function getElementAtPath(obj, path23) {
1162
+ if (!path23)
1163
1163
  return obj;
1164
- return path22.reduce((acc, key) => acc?.[key], obj);
1164
+ return path23.reduce((acc, key) => acc?.[key], obj);
1165
1165
  }
1166
1166
  function promiseAllObject(promisesObj) {
1167
1167
  const keys = Object.keys(promisesObj);
@@ -1570,11 +1570,11 @@ function explicitlyAborted(x, startIndex = 0) {
1570
1570
  }
1571
1571
  return false;
1572
1572
  }
1573
- function prefixIssues(path22, issues) {
1573
+ function prefixIssues(path23, issues) {
1574
1574
  return issues.map((iss) => {
1575
1575
  var _a3;
1576
1576
  (_a3 = iss).path ?? (_a3.path = []);
1577
- iss.path.unshift(path22);
1577
+ iss.path.unshift(path23);
1578
1578
  return iss;
1579
1579
  });
1580
1580
  }
@@ -1721,16 +1721,16 @@ function flattenError(error53, mapper = (issue2) => issue2.message) {
1721
1721
  }
1722
1722
  function formatError(error53, mapper = (issue2) => issue2.message) {
1723
1723
  const fieldErrors = { _errors: [] };
1724
- const processError = (error54, path22 = []) => {
1724
+ const processError = (error54, path23 = []) => {
1725
1725
  for (const issue2 of error54.issues) {
1726
1726
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1727
- issue2.errors.map((issues) => processError({ issues }, [...path22, ...issue2.path]));
1727
+ issue2.errors.map((issues) => processError({ issues }, [...path23, ...issue2.path]));
1728
1728
  } else if (issue2.code === "invalid_key") {
1729
- processError({ issues: issue2.issues }, [...path22, ...issue2.path]);
1729
+ processError({ issues: issue2.issues }, [...path23, ...issue2.path]);
1730
1730
  } else if (issue2.code === "invalid_element") {
1731
- processError({ issues: issue2.issues }, [...path22, ...issue2.path]);
1731
+ processError({ issues: issue2.issues }, [...path23, ...issue2.path]);
1732
1732
  } else {
1733
- const fullpath = [...path22, ...issue2.path];
1733
+ const fullpath = [...path23, ...issue2.path];
1734
1734
  if (fullpath.length === 0) {
1735
1735
  fieldErrors._errors.push(mapper(issue2));
1736
1736
  } else {
@@ -1757,17 +1757,17 @@ function formatError(error53, mapper = (issue2) => issue2.message) {
1757
1757
  }
1758
1758
  function treeifyError(error53, mapper = (issue2) => issue2.message) {
1759
1759
  const result = { errors: [] };
1760
- const processError = (error54, path22 = []) => {
1760
+ const processError = (error54, path23 = []) => {
1761
1761
  var _a3, _b;
1762
1762
  for (const issue2 of error54.issues) {
1763
1763
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1764
- issue2.errors.map((issues) => processError({ issues }, [...path22, ...issue2.path]));
1764
+ issue2.errors.map((issues) => processError({ issues }, [...path23, ...issue2.path]));
1765
1765
  } else if (issue2.code === "invalid_key") {
1766
- processError({ issues: issue2.issues }, [...path22, ...issue2.path]);
1766
+ processError({ issues: issue2.issues }, [...path23, ...issue2.path]);
1767
1767
  } else if (issue2.code === "invalid_element") {
1768
- processError({ issues: issue2.issues }, [...path22, ...issue2.path]);
1768
+ processError({ issues: issue2.issues }, [...path23, ...issue2.path]);
1769
1769
  } else {
1770
- const fullpath = [...path22, ...issue2.path];
1770
+ const fullpath = [...path23, ...issue2.path];
1771
1771
  if (fullpath.length === 0) {
1772
1772
  result.errors.push(mapper(issue2));
1773
1773
  continue;
@@ -1799,8 +1799,8 @@ function treeifyError(error53, mapper = (issue2) => issue2.message) {
1799
1799
  }
1800
1800
  function toDotPath(_path) {
1801
1801
  const segs = [];
1802
- const path22 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1803
- for (const seg of path22) {
1802
+ const path23 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1803
+ for (const seg of path23) {
1804
1804
  if (typeof seg === "number")
1805
1805
  segs.push(`[${seg}]`);
1806
1806
  else if (typeof seg === "symbol")
@@ -14492,13 +14492,13 @@ function resolveRef(ref, ctx) {
14492
14492
  if (!ref.startsWith("#")) {
14493
14493
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14494
14494
  }
14495
- const path22 = ref.slice(1).split("/").filter(Boolean);
14496
- if (path22.length === 0) {
14495
+ const path23 = ref.slice(1).split("/").filter(Boolean);
14496
+ if (path23.length === 0) {
14497
14497
  return ctx.rootSchema;
14498
14498
  }
14499
14499
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14500
- if (path22[0] === defsKey) {
14501
- const key = path22[1];
14500
+ if (path23[0] === defsKey) {
14501
+ const key = path23[1];
14502
14502
  if (!key || !ctx.defs[key]) {
14503
14503
  throw new Error(`Reference not found: ${ref}`);
14504
14504
  }
@@ -15379,44 +15379,73 @@ var CONSOLE_HOST_METHODS = Object.freeze([
15379
15379
  var WORKSPACE_CONTRACT_VERSION = 1;
15380
15380
 
15381
15381
  // ../../shared-contracts/dist/thread-questions.js
15382
- var threadQuestionsParamsSchema = external_exports.strictObject({ threadId: hostThreadIdSchema });
15382
+ var threadQuestionsParamsSchema = external_exports.strictObject({
15383
+ threadId: hostThreadIdSchema,
15384
+ unobserved: external_exports.literal(true).optional()
15385
+ });
15383
15386
  var field = { id: external_exports.string().min(1), prompt: external_exports.string(), optional: external_exports.boolean() };
15384
15387
  var questionAutoResolutionSchema = external_exports.strictObject({
15385
15388
  deadlineUnixMs: external_exports.number().int().min(0).max(864e13),
15386
15389
  action: external_exports.enum(["recommended", "decline"]),
15387
15390
  resetOnActivity: external_exports.boolean().optional()
15388
15391
  });
15392
+ var threadQuestionFieldSchema = external_exports.discriminatedUnion("type", [
15393
+ external_exports.strictObject({
15394
+ ...field,
15395
+ type: external_exports.literal("choice"),
15396
+ multiple: external_exports.boolean(),
15397
+ allowOther: external_exports.boolean(),
15398
+ options: external_exports.array(external_exports.strictObject({
15399
+ value: external_exports.string().min(1),
15400
+ label: external_exports.string(),
15401
+ description: external_exports.string().optional()
15402
+ })).min(1)
15403
+ }),
15404
+ external_exports.strictObject({
15405
+ ...field,
15406
+ type: external_exports.literal("text"),
15407
+ multiline: external_exports.boolean(),
15408
+ secret: external_exports.literal(false),
15409
+ placeholder: external_exports.string().optional(),
15410
+ prefill: external_exports.string().optional()
15411
+ })
15412
+ ]);
15389
15413
  var threadQuestionSchema = external_exports.strictObject({
15390
15414
  interactionId: hostInteractionIdSchema,
15391
15415
  turnId: hostTurnIdSchema,
15392
15416
  title: external_exports.string().optional(),
15393
15417
  expiresAt: external_exports.string().optional(),
15394
15418
  autoResolution: questionAutoResolutionSchema.optional(),
15395
- questions: external_exports.array(external_exports.discriminatedUnion("type", [
15396
- external_exports.strictObject({
15397
- ...field,
15398
- type: external_exports.literal("choice"),
15399
- multiple: external_exports.boolean(),
15400
- allowOther: external_exports.boolean(),
15401
- options: external_exports.array(external_exports.strictObject({
15402
- value: external_exports.string().min(1),
15403
- label: external_exports.string(),
15404
- description: external_exports.string().optional()
15405
- })).min(1)
15406
- }),
15407
- external_exports.strictObject({
15408
- ...field,
15409
- type: external_exports.literal("text"),
15410
- multiline: external_exports.boolean(),
15411
- secret: external_exports.literal(false),
15412
- placeholder: external_exports.string().optional(),
15413
- prefill: external_exports.string().optional()
15414
- })
15415
- ])).min(1)
15419
+ questions: external_exports.array(threadQuestionFieldSchema).min(1)
15416
15420
  });
15417
15421
  var threadQuestionsResultSchema = external_exports.strictObject({
15418
15422
  questions: external_exports.array(threadQuestionSchema)
15419
15423
  });
15424
+ var questionRecordOutcomeSchema = external_exports.enum([
15425
+ "answered",
15426
+ "skipped",
15427
+ "closedByHarness",
15428
+ "expired",
15429
+ "turnEnded"
15430
+ ]);
15431
+ var threadQuestionRecordSchema = external_exports.strictObject({
15432
+ interactionId: hostInteractionIdSchema,
15433
+ turnId: hostTurnIdSchema,
15434
+ itemId: hostItemIdSchema,
15435
+ title: external_exports.string().optional(),
15436
+ questions: external_exports.array(threadQuestionFieldSchema).min(1),
15437
+ outcome: questionRecordOutcomeSchema,
15438
+ answers: external_exports.record(external_exports.string(), external_exports.array(external_exports.string()))
15439
+ });
15440
+ var threadQuestionPendingAnchorSchema = external_exports.strictObject({
15441
+ interactionId: hostInteractionIdSchema,
15442
+ turnId: hostTurnIdSchema,
15443
+ itemId: hostItemIdSchema
15444
+ });
15445
+ var threadQuestionRecordsResultSchema = external_exports.strictObject({
15446
+ records: external_exports.array(threadQuestionRecordSchema),
15447
+ pendingAnchors: external_exports.array(threadQuestionPendingAnchorSchema)
15448
+ });
15420
15449
  var threadQuestionRespondParamsSchema = external_exports.strictObject({
15421
15450
  threadId: hostThreadIdSchema,
15422
15451
  interactionId: hostInteractionIdSchema,
@@ -17333,7 +17362,7 @@ async function readGrokCredentials(environment) {
17333
17362
  }
17334
17363
 
17335
17364
  // dist/grok-adapter.js
17336
- import path21 from "node:path";
17365
+ import path22 from "node:path";
17337
17366
 
17338
17367
  // ../../harness-plugin-files/dist/grok-computer-use.js
17339
17368
  import { randomUUID } from "node:crypto";
@@ -22580,8 +22609,8 @@ function parseGrokAvailableCommands(value) {
22580
22609
  });
22581
22610
  }
22582
22611
  function isGrokSkill(command) {
22583
- const path22 = command.meta?.path;
22584
- return typeof path22 === "string" && /(^|[\\/])SKILL\.md$/u.test(path22) || typeof command.meta?.qualifiedName === "string";
22612
+ const path23 = command.meta?.path;
22613
+ return typeof path23 === "string" && /(^|[\\/])SKILL\.md$/u.test(path23) || typeof command.meta?.qualifiedName === "string";
22585
22614
  }
22586
22615
  function grokLiveCommands(native) {
22587
22616
  return native.map((command) => ({
@@ -22907,16 +22936,16 @@ var Diff = class {
22907
22936
  }
22908
22937
  }
22909
22938
  }
22910
- addToPath(path22, added, removed, oldPosInc, options) {
22911
- const last = path22.lastComponent;
22939
+ addToPath(path23, added, removed, oldPosInc, options) {
22940
+ const last = path23.lastComponent;
22912
22941
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
22913
22942
  return {
22914
- oldPos: path22.oldPos + oldPosInc,
22943
+ oldPos: path23.oldPos + oldPosInc,
22915
22944
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
22916
22945
  };
22917
22946
  } else {
22918
22947
  return {
22919
- oldPos: path22.oldPos + oldPosInc,
22948
+ oldPos: path23.oldPos + oldPosInc,
22920
22949
  lastComponent: { count: 1, added, removed, previousComponent: last }
22921
22950
  };
22922
22951
  }
@@ -23906,6 +23935,306 @@ function extractText(value, depth = 0) {
23906
23935
  return void 0;
23907
23936
  }
23908
23937
 
23938
+ // dist/grok-questions.js
23939
+ var GROK_ASK_USER_QUESTION_METHOD = "_x.ai/ask_user_question";
23940
+ var GROK_QUESTION_ACTIVITY_METHOD = "_x.ai/ask_user_question_activity";
23941
+ function isRecord10(value) {
23942
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23943
+ }
23944
+ function nonEmptyString(value) {
23945
+ return typeof value === "string" && value.trim().length > 0;
23946
+ }
23947
+ function parseGrokQuestionRequest(value) {
23948
+ if (!isRecord10(value) || !nonEmptyString(value.sessionId) || !nonEmptyString(value.toolCallId) || value.mode !== "default" && value.mode !== "plan" || !Array.isArray(value.questions) || value.questions.length === 0) {
23949
+ throw new Error("Grok question requires sessionId, toolCallId, mode and nonempty questions");
23950
+ }
23951
+ const seen = /* @__PURE__ */ new Set();
23952
+ const questions = value.questions.map((question) => {
23953
+ if (!isRecord10(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") {
23954
+ throw new Error("Grok question text must be unique and options/multiSelect must be valid");
23955
+ }
23956
+ if (question.multiSelect != null && question.multi_select != null && question.multiSelect !== question.multi_select)
23957
+ throw new Error("Grok question contains conflicting multi-select flags");
23958
+ seen.add(question.question);
23959
+ const labels = /* @__PURE__ */ new Set();
23960
+ const options = question.options.map((option) => {
23961
+ if (!isRecord10(option) || !nonEmptyString(option.label) || labels.has(option.label) || typeof option.description !== "string" || option.preview != null && typeof option.preview !== "string") {
23962
+ throw new Error("Grok question options require unique labels and text descriptions/previews");
23963
+ }
23964
+ labels.add(option.label);
23965
+ return {
23966
+ label: option.label,
23967
+ description: option.description,
23968
+ ...typeof option.preview === "string" ? { preview: option.preview } : {}
23969
+ };
23970
+ });
23971
+ return {
23972
+ question: question.question,
23973
+ options,
23974
+ multiple: question.multiSelect === true || question.multi_select === true
23975
+ };
23976
+ });
23977
+ const timeout = value.timeout == null ? void 0 : questionAutoResolutionSchema.parse(value.timeout);
23978
+ return {
23979
+ sessionId: value.sessionId,
23980
+ toolCallId: value.toolCallId,
23981
+ mode: value.mode,
23982
+ questions,
23983
+ ...timeout ? { timeout } : {}
23984
+ };
23985
+ }
23986
+ function toGrokHostQuestions(questions) {
23987
+ return questions.map((question, index) => question.options.length ? {
23988
+ id: `q${index}`,
23989
+ type: "choice",
23990
+ prompt: question.question,
23991
+ options: question.options.map(({ label, description, preview }) => {
23992
+ const text = [description, preview].filter(Boolean).join("\n\n");
23993
+ return { value: label, label, ...text ? { description: text } : {} };
23994
+ }),
23995
+ multiple: question.multiple ?? false,
23996
+ allowOther: true,
23997
+ optional: true
23998
+ } : {
23999
+ id: `q${index}`,
24000
+ type: "text",
24001
+ prompt: question.question,
24002
+ multiline: true,
24003
+ secret: false,
24004
+ optional: true
24005
+ });
24006
+ }
24007
+ var GrokQuestions = class {
24008
+ turnId;
24009
+ randomUUID;
24010
+ emit;
24011
+ #pending = /* @__PURE__ */ new Map();
24012
+ #seenToolCalls = /* @__PURE__ */ new Set();
24013
+ #closed = false;
24014
+ constructor(turnId, randomUUID3, emit) {
24015
+ this.turnId = turnId;
24016
+ this.randomUUID = randomUUID3;
24017
+ this.emit = emit;
24018
+ }
24019
+ has(interactionId) {
24020
+ return this.#pending.has(interactionId);
24021
+ }
24022
+ async activity(interactionId, reset) {
24023
+ const pending = this.#pending.get(interactionId);
24024
+ if (!pending?.interaction.autoResolution?.resetOnActivity)
24025
+ return null;
24026
+ const timeout = await reset(pending.request.toolCallId);
24027
+ if (this.#pending.get(interactionId) !== pending)
24028
+ return null;
24029
+ return timeout;
24030
+ }
24031
+ ask(request) {
24032
+ if (this.#closed || this.#seenToolCalls.has(request.toolCallId))
24033
+ return Promise.resolve({ outcome: "cancelled" });
24034
+ this.#seenToolCalls.add(request.toolCallId);
24035
+ const interaction = {
24036
+ type: "question",
24037
+ interactionId: hostInteractionIdSchema.parse(this.randomUUID()),
24038
+ turnId: this.turnId,
24039
+ title: "Grok",
24040
+ ...request.timeout ? { autoResolution: request.timeout } : {},
24041
+ questions: toGrokHostQuestions(request.questions)
24042
+ };
24043
+ return new Promise((resolve) => {
24044
+ this.#pending.set(interaction.interactionId, { request, interaction, resolve });
24045
+ this.emit({ kind: "interaction", interaction });
24046
+ });
24047
+ }
24048
+ respond(command) {
24049
+ const pending = this.#pending.get(command.interactionId);
24050
+ if (!pending)
24051
+ return this.#error("invalidState", "Grok Question is not pending");
24052
+ if (command.response.type !== "question") {
24053
+ return this.#error("invalidRequest", "Grok Question requires a Question Response");
24054
+ }
24055
+ const response = command.response;
24056
+ const error53 = validateHostQuestionResponse(pending.interaction, response);
24057
+ if (error53)
24058
+ return { ok: false, error: error53 };
24059
+ if (response.cancelled) {
24060
+ this.#settle(pending, { outcome: "cancelled" }, "cancelled");
24061
+ return { ok: true, value: { accepted: true } };
24062
+ }
24063
+ const answers = /* @__PURE__ */ new Map();
24064
+ const annotations = /* @__PURE__ */ new Map();
24065
+ for (const [index, question] of pending.request.questions.entries()) {
24066
+ const values = response.answers[`q${index}`];
24067
+ if (!values?.length)
24068
+ continue;
24069
+ if (values.some((answer) => !nonEmptyString(answer)) || new Set(values).size !== values.length)
24070
+ return this.#error("invalidRequest", "Grok answers must be nonempty and unique");
24071
+ const selected = values.map((answer) => question.options.find(({ label }) => label === answer));
24072
+ const other = values.filter((_, position) => !selected[position]);
24073
+ if (other.length > 1)
24074
+ return this.#error("invalidRequest", "Grok question accepts only one Other response");
24075
+ answers.set(question.question, selected.map((option) => option?.label ?? "Other"));
24076
+ const previews = selected.flatMap((option) => option?.preview !== void 0 ? [option.preview] : []);
24077
+ if (previews.length || other.length)
24078
+ annotations.set(question.question, {
24079
+ ...previews.length ? { preview: previews.join("\n\n") } : {},
24080
+ ...other.length ? { notes: other[0] } : {}
24081
+ });
24082
+ }
24083
+ this.#settle(pending, {
24084
+ outcome: "accepted",
24085
+ answers: Object.fromEntries(answers),
24086
+ ...annotations.size ? { annotations: Object.fromEntries(annotations) } : {}
24087
+ }, "responded");
24088
+ return { ok: true, value: { accepted: true } };
24089
+ }
24090
+ withdraw(toolCallId) {
24091
+ for (const pending of this.#pending.values()) {
24092
+ if (pending.request.toolCallId === toolCallId)
24093
+ this.#settle(pending, { outcome: "cancelled" }, "cancelled");
24094
+ }
24095
+ }
24096
+ cancel() {
24097
+ this.#closed = true;
24098
+ for (const pending of this.#pending.values())
24099
+ this.#settle(pending, { outcome: "cancelled" }, "cancelled");
24100
+ }
24101
+ #settle(pending, response, reason) {
24102
+ if (!this.#pending.delete(pending.interaction.interactionId))
24103
+ return;
24104
+ pending.resolve(response);
24105
+ this.emit({
24106
+ kind: "event",
24107
+ event: {
24108
+ type: "interaction.closed",
24109
+ interactionId: pending.interaction.interactionId,
24110
+ turnId: this.turnId,
24111
+ reason
24112
+ }
24113
+ });
24114
+ }
24115
+ #error(code, message) {
24116
+ return { ok: false, error: { code, message, retryable: false } };
24117
+ }
24118
+ };
24119
+
24120
+ // dist/grok-question-record.js
24121
+ function isRecord11(value) {
24122
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24123
+ }
24124
+ function isAskUserQuestionName(name) {
24125
+ const normalized = name.trim().toLowerCase();
24126
+ return normalized === "askuserquestion" || normalized === "ask_user_question" || normalized === "_x.ai/ask_user_question";
24127
+ }
24128
+ function questionsFromInput(rawInput) {
24129
+ const questions = isRecord11(rawInput) ? rawInput.questions : void 0;
24130
+ if (!Array.isArray(questions) || questions.length === 0)
24131
+ return null;
24132
+ const native = [];
24133
+ for (const value of questions) {
24134
+ if (!isRecord11(value) || typeof value.question !== "string" || value.question.length === 0) {
24135
+ return null;
24136
+ }
24137
+ const options = Array.isArray(value.options) ? value.options.flatMap((option) => {
24138
+ if (!isRecord11(option) || typeof option.label !== "string" || option.label.length === 0) {
24139
+ return [];
24140
+ }
24141
+ return [
24142
+ {
24143
+ label: option.label,
24144
+ description: typeof option.description === "string" ? option.description : "",
24145
+ ...typeof option.preview === "string" ? { preview: option.preview } : {}
24146
+ }
24147
+ ];
24148
+ }) : [];
24149
+ native.push({
24150
+ question: value.question,
24151
+ options,
24152
+ multiple: value.multiSelect === true || value.multi_select === true
24153
+ });
24154
+ }
24155
+ return toGrokHostQuestions(native);
24156
+ }
24157
+ function asRecord(value) {
24158
+ if (isRecord11(value))
24159
+ return value;
24160
+ if (typeof value !== "string")
24161
+ return void 0;
24162
+ try {
24163
+ const parsed = JSON.parse(value);
24164
+ return isRecord11(parsed) ? parsed : void 0;
24165
+ } catch {
24166
+ return void 0;
24167
+ }
24168
+ }
24169
+ function userAnsweredMessage(rawOutput) {
24170
+ const parsed = asRecord(rawOutput);
24171
+ if (!parsed)
24172
+ return void 0;
24173
+ if (isRecord11(parsed.UserAnswered) && typeof parsed.UserAnswered.message === "string") {
24174
+ return parsed.UserAnswered.message;
24175
+ }
24176
+ return typeof parsed.message === "string" ? parsed.message : void 0;
24177
+ }
24178
+ function answersFromUserAnsweredMessage(message, questions) {
24179
+ const answers = {};
24180
+ for (const question of questions) {
24181
+ const escaped = question.prompt.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
24182
+ const match = message.match(new RegExp(`"${escaped}"\\s*=\\s*"([^"]*)"`, "u"));
24183
+ if (!match?.[1])
24184
+ continue;
24185
+ const labels = match[1].split(/\s*,\s*/u).map((label) => label.trim()).filter((label) => label.length > 0);
24186
+ const allowed = question.type === "choice" ? new Set(question.options.map((option) => option.value)) : null;
24187
+ const selected = allowed && question.type === "choice" && !question.allowOther ? labels.filter((label) => allowed.has(label)) : labels;
24188
+ if (selected.length)
24189
+ answers[question.id] = selected;
24190
+ }
24191
+ return answers;
24192
+ }
24193
+ function answersFromOutput(rawOutput, questions) {
24194
+ const parsed = asRecord(rawOutput);
24195
+ if (parsed?.outcome === "cancelled") {
24196
+ return { outcome: "skipped", answers: {} };
24197
+ }
24198
+ const message = userAnsweredMessage(rawOutput);
24199
+ if (message && /declined to answer/iu.test(message)) {
24200
+ return { outcome: "skipped", answers: {} };
24201
+ }
24202
+ const nativeAnswers = parsed && isRecord11(parsed.answers) ? parsed.answers : void 0;
24203
+ const answers = {};
24204
+ if (nativeAnswers) {
24205
+ for (const question of questions) {
24206
+ const values = nativeAnswers[question.prompt] ?? nativeAnswers[question.id];
24207
+ if (!Array.isArray(values) || values.some((value) => typeof value !== "string"))
24208
+ continue;
24209
+ const selected = values.filter((value) => typeof value === "string" && value.trim().length > 0);
24210
+ if (selected.length)
24211
+ answers[question.id] = selected;
24212
+ }
24213
+ }
24214
+ if (Object.keys(answers).length > 0)
24215
+ return { outcome: "answered", answers };
24216
+ if (message) {
24217
+ const fromMessage = answersFromUserAnsweredMessage(message, questions);
24218
+ if (Object.keys(fromMessage).length > 0)
24219
+ return { outcome: "answered", answers: fromMessage };
24220
+ if (/answered your questions/iu.test(message))
24221
+ return { outcome: "answered", answers: {} };
24222
+ }
24223
+ return { outcome: "closedByHarness", answers: {} };
24224
+ }
24225
+ function grokQuestionRecordFromTool(toolName, rawInput, rawOutput, status2) {
24226
+ if (!isAskUserQuestionName(toolName))
24227
+ return void 0;
24228
+ const questions = questionsFromInput(rawInput);
24229
+ if (!questions)
24230
+ return void 0;
24231
+ if (status2 === "failed") {
24232
+ return { title: "Grok", questions, outcome: "closedByHarness", answers: {} };
24233
+ }
24234
+ const { outcome, answers } = answersFromOutput(rawOutput, questions);
24235
+ return { title: "Grok", questions, outcome, answers };
24236
+ }
24237
+
23909
24238
  // dist/grok-history.js
23910
24239
  function stableId(kind, turn, index) {
23911
24240
  return hostItemIdSchema.parse(`grok-history-${kind}-${turn}-${index}`);
@@ -24117,7 +24446,11 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
24117
24446
  if (status2 === "completed") {
24118
24447
  settleWatchedSubagents(tool.type === "toolExecution" ? tool.toolName : tool.command, tool.type === "toolExecution" ? tool.arguments : void 0, content, rawOutput);
24119
24448
  }
24120
- items.push({ item: tool, outcome });
24449
+ const questionRecord = tool.type === "toolExecution" ? grokQuestionRecordFromTool(tool.toolName, tool.arguments, rawOutput, status2) : void 0;
24450
+ items.push({
24451
+ item: questionRecord && tool.type === "toolExecution" ? { ...tool, questionRecord } : tool,
24452
+ outcome
24453
+ });
24121
24454
  if (status2 !== "completed")
24122
24455
  return;
24123
24456
  const changes = projectGrokFileChanges(content, cwd);
@@ -24447,11 +24780,11 @@ var GROK_SESSION_DELETE_METHOD = "_x.ai/session/delete";
24447
24780
  function error51(code, message, retryable = false) {
24448
24781
  return { code, message, retryable };
24449
24782
  }
24450
- function isRecord10(value) {
24783
+ function isRecord12(value) {
24451
24784
  return typeof value === "object" && value !== null && !Array.isArray(value);
24452
24785
  }
24453
24786
  function isGrokMethodNotFound(error53) {
24454
- if (isRecord10(error53) && error53.code === -32601)
24787
+ if (isRecord12(error53) && error53.code === -32601)
24455
24788
  return true;
24456
24789
  const message = error53 instanceof Error ? error53.message : String(error53);
24457
24790
  return /method not found/iu.test(message);
@@ -24469,10 +24802,10 @@ function buildGrokForkParams(input) {
24469
24802
  };
24470
24803
  }
24471
24804
  function parseGrokForkResponse(value) {
24472
- if (!isRecord10(value) || value.error !== void 0)
24805
+ if (!isRecord12(value) || value.error !== void 0)
24473
24806
  return null;
24474
- const payload = typeof value.newSessionId !== "string" && isRecord10(value.result) ? value.result : value;
24475
- if (!isRecord10(payload) || payload.error !== void 0)
24807
+ const payload = typeof value.newSessionId !== "string" && isRecord12(value.result) ? value.result : value;
24808
+ if (!isRecord12(payload) || payload.error !== void 0)
24476
24809
  return null;
24477
24810
  if (typeof payload.newSessionId !== "string" || payload.newSessionId.length === 0)
24478
24811
  return null;
@@ -24636,7 +24969,7 @@ var GROK_SESSION_UPDATE_EXTENSION_METHODS = [
24636
24969
  "x.ai/session_notification",
24637
24970
  "_x.ai/session_notification"
24638
24971
  ];
24639
- function isRecord11(value) {
24972
+ function isRecord13(value) {
24640
24973
  return typeof value === "object" && value !== null && !Array.isArray(value);
24641
24974
  }
24642
24975
  function optionalNonNegativeInt(value) {
@@ -24657,7 +24990,7 @@ function isGrokExtensionSessionUpdateMethod(method) {
24657
24990
  return GROK_SESSION_UPDATE_EXTENSION_METHODS.includes(method);
24658
24991
  }
24659
24992
  function grokCompactionEventFromUpdate(update) {
24660
- if (!isRecord11(update) || typeof update.sessionUpdate !== "string")
24993
+ if (!isRecord13(update) || typeof update.sessionUpdate !== "string")
24661
24994
  return null;
24662
24995
  const tokensUsed = optionalNonNegativeInt(firstPresent(update, ["tokensUsed", "tokens_used"]));
24663
24996
  const contextWindowTokens = optionalNonNegativeInt(firstPresent(update, ["contextWindowTokens", "contextWindow", "context_window"]));
@@ -24719,7 +25052,7 @@ var BACKGROUND_SESSION_UPDATES = /* @__PURE__ */ new Set([
24719
25052
  "scheduled_task_fired",
24720
25053
  "scheduled_task_deleted"
24721
25054
  ]);
24722
- function isRecord12(value) {
25055
+ function isRecord14(value) {
24723
25056
  return typeof value === "object" && value !== null && !Array.isArray(value);
24724
25057
  }
24725
25058
  function firstPresent2(record3, keys) {
@@ -24748,10 +25081,10 @@ function booleanField(record3, keys) {
24748
25081
  return typeof value === "boolean" ? value : void 0;
24749
25082
  }
24750
25083
  function snapshotRecord(value) {
24751
- if (!isRecord12(value))
25084
+ if (!isRecord14(value))
24752
25085
  return void 0;
24753
25086
  const nested = value.task_snapshot ?? value.taskSnapshot;
24754
- return isRecord12(nested) ? nested : value;
25087
+ return isRecord14(nested) ? nested : value;
24755
25088
  }
24756
25089
  function backgroundKind(value, monitorDescription) {
24757
25090
  if (monitorDescription)
@@ -24767,7 +25100,7 @@ function fields(value) {
24767
25100
  return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0));
24768
25101
  }
24769
25102
  function grokBackgroundEventFromUpdate(update) {
24770
- if (!isRecord12(update) || typeof update.sessionUpdate !== "string" || !BACKGROUND_SESSION_UPDATES.has(update.sessionUpdate))
25103
+ if (!isRecord14(update) || typeof update.sessionUpdate !== "string" || !BACKGROUND_SESSION_UPDATES.has(update.sessionUpdate))
24771
25104
  return null;
24772
25105
  const taskId = stringField4(update, ["task_id", "taskId"]);
24773
25106
  if (update.sessionUpdate === "task_backgrounded") {
@@ -24851,22 +25184,22 @@ function grokBackgroundEventFromUpdate(update) {
24851
25184
  return null;
24852
25185
  }
24853
25186
  function grokToolIsBackgrounded(rawOutput, rawInput) {
24854
- const exitCode = isRecord12(rawOutput) ? numberField2(rawOutput, ["exit_code", "exitCode"]) : void 0;
25187
+ const exitCode = isRecord14(rawOutput) ? numberField2(rawOutput, ["exit_code", "exitCode"]) : void 0;
24855
25188
  if (exitCode !== void 0 && exitCode !== null)
24856
25189
  return false;
24857
- if (isRecord12(rawOutput) && optionalString(rawOutput, ["signal"]) === "backgrounded")
25190
+ if (isRecord14(rawOutput) && optionalString(rawOutput, ["signal"]) === "backgrounded")
24858
25191
  return true;
24859
25192
  if (grokBackgroundTaskId(rawOutput, rawInput))
24860
25193
  return true;
24861
- return Boolean(isRecord12(rawInput) && (rawInput.background === true || rawInput.is_background === true));
25194
+ return Boolean(isRecord14(rawInput) && (rawInput.background === true || rawInput.is_background === true));
24862
25195
  }
24863
25196
  function grokBackgroundTaskId(rawOutput, rawInput) {
24864
- if (isRecord12(rawOutput)) {
25197
+ if (isRecord14(rawOutput)) {
24865
25198
  const id = stringField4(rawOutput, ["task_id", "taskId"]);
24866
25199
  if (id)
24867
25200
  return id;
24868
25201
  }
24869
- if (isRecord12(rawInput))
25202
+ if (isRecord14(rawInput))
24870
25203
  return stringField4(rawInput, ["task_id", "taskId"]);
24871
25204
  return void 0;
24872
25205
  }
@@ -24901,6 +25234,15 @@ function applyGrokScheduledEvent(loops, event, observedIds) {
24901
25234
  ...event.type === "scheduled.fired" && event.subagentId ? { lastSubagentId: event.subagentId } : current?.lastSubagentId ? { lastSubagentId: current.lastSubagentId } : {}
24902
25235
  });
24903
25236
  }
25237
+ function collectGrokScheduledTaskIds(events) {
25238
+ const ids = /* @__PURE__ */ new Set();
25239
+ for (const event of events) {
25240
+ if ((event.type === "scheduled.created" || event.type === "scheduled.fired") && typeof event.taskId === "string") {
25241
+ ids.add(event.taskId);
25242
+ }
25243
+ }
25244
+ return ids;
25245
+ }
24904
25246
  function collectGrokScheduledLoops(events) {
24905
25247
  const loops = /* @__PURE__ */ new Map();
24906
25248
  for (const event of events) {
@@ -24914,7 +25256,7 @@ function collectGrokScheduledLoops(events) {
24914
25256
  // dist/grok-manual-compaction.js
24915
25257
  var GROK_COMPACT_CONVERSATION_METHOD = "x.ai/compact_conversation";
24916
25258
  var GROK_COMPACT_CONVERSATION_FALLBACK_METHOD = "_x.ai/compact_conversation";
24917
- function isRecord13(value) {
25259
+ function isRecord15(value) {
24918
25260
  return typeof value === "object" && value !== null && !Array.isArray(value);
24919
25261
  }
24920
25262
  function optionalNonNegativeInt2(value) {
@@ -24926,7 +25268,7 @@ function optionalErrorMessage2(value) {
24926
25268
  function parseGrokCompactResult(value, cancelled = false) {
24927
25269
  if (cancelled)
24928
25270
  return { outcome: "cancelled" };
24929
- if (!isRecord13(value))
25271
+ if (!isRecord15(value))
24930
25272
  return { outcome: "succeeded" };
24931
25273
  const tokensBefore = optionalNonNegativeInt2(value.tokensBefore ?? value.tokens_before);
24932
25274
  const tokensAfter = optionalNonNegativeInt2(value.tokensAfter ?? value.tokens_after);
@@ -24964,7 +25306,7 @@ var GROK_REWIND_EXECUTE_METHOD = "_x.ai/rewind/execute";
24964
25306
  function error52(code, message, retryable = false) {
24965
25307
  return { code, message, retryable };
24966
25308
  }
24967
- function isRecord14(value) {
25309
+ function isRecord16(value) {
24968
25310
  return typeof value === "object" && value !== null && !Array.isArray(value);
24969
25311
  }
24970
25312
  function buildGrokRewindParams(input) {
@@ -24976,10 +25318,10 @@ function buildGrokRewindParams(input) {
24976
25318
  };
24977
25319
  }
24978
25320
  function parseGrokRewindResponse(value) {
24979
- if (!isRecord14(value))
25321
+ if (!isRecord16(value))
24980
25322
  return null;
24981
- const payload = typeof value.success !== "boolean" && isRecord14(value.result) ? value.result : value;
24982
- if (!isRecord14(payload) || typeof payload.success !== "boolean")
25323
+ const payload = typeof value.success !== "boolean" && isRecord16(value.result) ? value.result : value;
25324
+ if (!isRecord16(payload) || typeof payload.success !== "boolean")
24983
25325
  return null;
24984
25326
  return rewindPayload(payload);
24985
25327
  }
@@ -25145,10 +25487,10 @@ var GROK_CLOCK_ELICIT_PERSIST_FIXTURE = {
25145
25487
  ...GROK_CLOCK_ELICIT_FIXTURE,
25146
25488
  persist: ["session", "always"]
25147
25489
  };
25148
- function isRecord15(value) {
25490
+ function isRecord17(value) {
25149
25491
  return typeof value === "object" && value !== null && !Array.isArray(value);
25150
25492
  }
25151
- function nonEmptyString(value) {
25493
+ function nonEmptyString2(value) {
25152
25494
  return typeof value === "string" && value.trim().length > 0 ? value : void 0;
25153
25495
  }
25154
25496
  function hasOnlyKeys(record3, allowed) {
@@ -25186,11 +25528,11 @@ function parsePersistOffer(value) {
25186
25528
  return out.length > 0 ? out : "invalid";
25187
25529
  }
25188
25530
  function schemaIsSupportedEmptyObject(schema) {
25189
- if (!isRecord15(schema) || !hasOnlyKeys(schema, SCHEMA_KEYS) || schema.type !== "object") {
25531
+ if (!isRecord17(schema) || !hasOnlyKeys(schema, SCHEMA_KEYS) || schema.type !== "object") {
25190
25532
  return false;
25191
25533
  }
25192
25534
  if (schema.properties !== void 0) {
25193
- if (!isRecord15(schema.properties) || Object.keys(schema.properties).length !== 0)
25535
+ if (!isRecord17(schema.properties) || Object.keys(schema.properties).length !== 0)
25194
25536
  return false;
25195
25537
  }
25196
25538
  if (schema.required !== void 0) {
@@ -25200,12 +25542,12 @@ function schemaIsSupportedEmptyObject(schema) {
25200
25542
  return true;
25201
25543
  }
25202
25544
  function parseGrokMcpElicitParams(params) {
25203
- if (!isRecord15(params))
25545
+ if (!isRecord17(params))
25204
25546
  return { status: "invalid", message: "elicitation params must be an object" };
25205
- const sessionId = nonEmptyString(params.sessionId);
25206
- const toolCallId = nonEmptyString(params.toolCallId);
25207
- const serverName = nonEmptyString(params.serverName);
25208
- const message = nonEmptyString(params.message);
25547
+ const sessionId = nonEmptyString2(params.sessionId);
25548
+ const toolCallId = nonEmptyString2(params.toolCallId);
25549
+ const serverName = nonEmptyString2(params.serverName);
25550
+ const message = nonEmptyString2(params.message);
25209
25551
  if (!sessionId || !toolCallId || !serverName || !message) {
25210
25552
  return {
25211
25553
  status: "invalid",
@@ -25216,7 +25558,7 @@ function parseGrokMcpElicitParams(params) {
25216
25558
  if (!hasOnlyKeys(params, URL_KEYS)) {
25217
25559
  return { status: "invalid", message: "URL elicitation contains unreviewed fields" };
25218
25560
  }
25219
- if (!nonEmptyString(params.url) || !nonEmptyString(params.elicitationId)) {
25561
+ if (!nonEmptyString2(params.url) || !nonEmptyString2(params.elicitationId)) {
25220
25562
  return { status: "invalid", message: "URL elicitation requires url and elicitationId" };
25221
25563
  }
25222
25564
  return { status: "unsupported" };
@@ -25228,7 +25570,7 @@ function parseGrokMcpElicitParams(params) {
25228
25570
  return { status: "invalid", message: "form elicitation contains unreviewed fields" };
25229
25571
  }
25230
25572
  if (params.requestedSchema !== void 0) {
25231
- if (!isRecord15(params.requestedSchema)) {
25573
+ if (!isRecord17(params.requestedSchema)) {
25232
25574
  return { status: "invalid", message: "requestedSchema must be an object" };
25233
25575
  }
25234
25576
  if (!schemaIsSupportedEmptyObject(params.requestedSchema))
@@ -25295,9 +25637,9 @@ function projectGrokMcpElicitApproval(input) {
25295
25637
  };
25296
25638
  }
25297
25639
  function grokElicitationResolvedToolCallId(update) {
25298
- if (!isRecord15(update) || update.sessionUpdate !== "interaction_resolved")
25640
+ if (!isRecord17(update) || update.sessionUpdate !== "interaction_resolved")
25299
25641
  return void 0;
25300
- return nonEmptyString(update.tool_call_id) ?? nonEmptyString(update.toolCallId);
25642
+ return nonEmptyString2(update.tool_call_id) ?? nonEmptyString2(update.toolCallId);
25301
25643
  }
25302
25644
 
25303
25645
  // dist/permission-modes.js
@@ -25447,191 +25789,11 @@ var GrokPermissionConfirmation = class {
25447
25789
  }
25448
25790
  };
25449
25791
 
25450
- // dist/grok-questions.js
25451
- var GROK_ASK_USER_QUESTION_METHOD = "_x.ai/ask_user_question";
25452
- var GROK_QUESTION_ACTIVITY_METHOD = "_x.ai/ask_user_question_activity";
25453
- function isRecord16(value) {
25454
- return typeof value === "object" && value !== null && !Array.isArray(value);
25455
- }
25456
- function nonEmptyString2(value) {
25457
- return typeof value === "string" && value.trim().length > 0;
25458
- }
25459
- function parseGrokQuestionRequest(value) {
25460
- if (!isRecord16(value) || !nonEmptyString2(value.sessionId) || !nonEmptyString2(value.toolCallId) || value.mode !== "default" && value.mode !== "plan" || !Array.isArray(value.questions) || value.questions.length === 0) {
25461
- throw new Error("Grok question requires sessionId, toolCallId, mode and nonempty questions");
25462
- }
25463
- const seen = /* @__PURE__ */ new Set();
25464
- const questions = value.questions.map((question) => {
25465
- if (!isRecord16(question) || !nonEmptyString2(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") {
25466
- throw new Error("Grok question text must be unique and options/multiSelect must be valid");
25467
- }
25468
- if (question.multiSelect != null && question.multi_select != null && question.multiSelect !== question.multi_select)
25469
- throw new Error("Grok question contains conflicting multi-select flags");
25470
- seen.add(question.question);
25471
- const labels = /* @__PURE__ */ new Set();
25472
- const options = question.options.map((option) => {
25473
- if (!isRecord16(option) || !nonEmptyString2(option.label) || labels.has(option.label) || typeof option.description !== "string" || option.preview != null && typeof option.preview !== "string") {
25474
- throw new Error("Grok question options require unique labels and text descriptions/previews");
25475
- }
25476
- labels.add(option.label);
25477
- return {
25478
- label: option.label,
25479
- description: option.description,
25480
- ...typeof option.preview === "string" ? { preview: option.preview } : {}
25481
- };
25482
- });
25483
- return {
25484
- question: question.question,
25485
- options,
25486
- multiple: question.multiSelect === true || question.multi_select === true
25487
- };
25488
- });
25489
- const timeout = value.timeout == null ? void 0 : questionAutoResolutionSchema.parse(value.timeout);
25490
- return {
25491
- sessionId: value.sessionId,
25492
- toolCallId: value.toolCallId,
25493
- mode: value.mode,
25494
- questions,
25495
- ...timeout ? { timeout } : {}
25496
- };
25497
- }
25498
- var GrokQuestions = class {
25499
- turnId;
25500
- randomUUID;
25501
- emit;
25502
- #pending = /* @__PURE__ */ new Map();
25503
- #seenToolCalls = /* @__PURE__ */ new Set();
25504
- #closed = false;
25505
- constructor(turnId, randomUUID3, emit) {
25506
- this.turnId = turnId;
25507
- this.randomUUID = randomUUID3;
25508
- this.emit = emit;
25509
- }
25510
- has(interactionId) {
25511
- return this.#pending.has(interactionId);
25512
- }
25513
- async activity(interactionId, reset) {
25514
- const pending = this.#pending.get(interactionId);
25515
- if (!pending?.interaction.autoResolution?.resetOnActivity)
25516
- return null;
25517
- const timeout = await reset(pending.request.toolCallId);
25518
- if (this.#pending.get(interactionId) !== pending)
25519
- return null;
25520
- return timeout;
25521
- }
25522
- ask(request) {
25523
- if (this.#closed || this.#seenToolCalls.has(request.toolCallId))
25524
- return Promise.resolve({ outcome: "cancelled" });
25525
- this.#seenToolCalls.add(request.toolCallId);
25526
- const interaction = {
25527
- type: "question",
25528
- interactionId: hostInteractionIdSchema.parse(this.randomUUID()),
25529
- turnId: this.turnId,
25530
- title: "Grok",
25531
- ...request.timeout ? { autoResolution: request.timeout } : {},
25532
- questions: request.questions.map((question, index) => question.options.length ? {
25533
- id: `q${index}`,
25534
- type: "choice",
25535
- prompt: question.question,
25536
- options: question.options.map(({ label, description, preview }) => ({
25537
- value: label,
25538
- label,
25539
- description: [description, preview].filter(Boolean).join("\n\n")
25540
- })),
25541
- multiple: question.multiple ?? false,
25542
- allowOther: true,
25543
- optional: true
25544
- } : {
25545
- id: `q${index}`,
25546
- type: "text",
25547
- prompt: question.question,
25548
- multiline: true,
25549
- secret: false,
25550
- optional: true
25551
- })
25552
- };
25553
- return new Promise((resolve) => {
25554
- this.#pending.set(interaction.interactionId, { request, interaction, resolve });
25555
- this.emit({ kind: "interaction", interaction });
25556
- });
25557
- }
25558
- respond(command) {
25559
- const pending = this.#pending.get(command.interactionId);
25560
- if (!pending)
25561
- return this.#error("invalidState", "Grok Question is not pending");
25562
- if (command.response.type !== "question") {
25563
- return this.#error("invalidRequest", "Grok Question requires a Question Response");
25564
- }
25565
- const response = command.response;
25566
- const error53 = validateHostQuestionResponse(pending.interaction, response);
25567
- if (error53)
25568
- return { ok: false, error: error53 };
25569
- if (response.cancelled) {
25570
- this.#settle(pending, { outcome: "cancelled" }, "cancelled");
25571
- return { ok: true, value: { accepted: true } };
25572
- }
25573
- const answers = /* @__PURE__ */ new Map();
25574
- const annotations = /* @__PURE__ */ new Map();
25575
- for (const [index, question] of pending.request.questions.entries()) {
25576
- const values = response.answers[`q${index}`];
25577
- if (!values?.length)
25578
- continue;
25579
- if (values.some((answer) => !nonEmptyString2(answer)) || new Set(values).size !== values.length)
25580
- return this.#error("invalidRequest", "Grok answers must be nonempty and unique");
25581
- const selected = values.map((answer) => question.options.find(({ label }) => label === answer));
25582
- const other = values.filter((_, position) => !selected[position]);
25583
- if (other.length > 1)
25584
- return this.#error("invalidRequest", "Grok question accepts only one Other response");
25585
- answers.set(question.question, selected.map((option) => option?.label ?? "Other"));
25586
- const previews = selected.flatMap((option) => option?.preview !== void 0 ? [option.preview] : []);
25587
- if (previews.length || other.length)
25588
- annotations.set(question.question, {
25589
- ...previews.length ? { preview: previews.join("\n\n") } : {},
25590
- ...other.length ? { notes: other[0] } : {}
25591
- });
25592
- }
25593
- this.#settle(pending, {
25594
- outcome: "accepted",
25595
- answers: Object.fromEntries(answers),
25596
- ...annotations.size ? { annotations: Object.fromEntries(annotations) } : {}
25597
- }, "responded");
25598
- return { ok: true, value: { accepted: true } };
25599
- }
25600
- withdraw(toolCallId) {
25601
- for (const pending of this.#pending.values()) {
25602
- if (pending.request.toolCallId === toolCallId)
25603
- this.#settle(pending, { outcome: "cancelled" }, "cancelled");
25604
- }
25605
- }
25606
- cancel() {
25607
- this.#closed = true;
25608
- for (const pending of this.#pending.values())
25609
- this.#settle(pending, { outcome: "cancelled" }, "cancelled");
25610
- }
25611
- #settle(pending, response, reason) {
25612
- if (!this.#pending.delete(pending.interaction.interactionId))
25613
- return;
25614
- pending.resolve(response);
25615
- this.emit({
25616
- kind: "event",
25617
- event: {
25618
- type: "interaction.closed",
25619
- interactionId: pending.interaction.interactionId,
25620
- turnId: this.turnId,
25621
- reason
25622
- }
25623
- });
25624
- }
25625
- #error(code, message) {
25626
- return { ok: false, error: { code, message, retryable: false } };
25627
- }
25628
- };
25629
-
25630
25792
  // dist/grok-plan-approval.js
25631
25793
  var GROK_EXIT_PLAN_MODE_METHODS = ["_x.ai/exit_plan_mode", "x.ai/exit_plan_mode"];
25632
25794
  var DECISION_ID = "plan-decision";
25633
25795
  var FEEDBACK_ID = "plan-feedback";
25634
- function isRecord17(value) {
25796
+ function isRecord18(value) {
25635
25797
  return typeof value === "object" && value !== null && !Array.isArray(value);
25636
25798
  }
25637
25799
  function nonEmptyString3(value) {
@@ -25641,7 +25803,7 @@ function isGrokExitPlanModeMethod(method) {
25641
25803
  return GROK_EXIT_PLAN_MODE_METHODS.includes(method);
25642
25804
  }
25643
25805
  function parseGrokPlanApprovalRequest(value) {
25644
- if (!isRecord17(value) || !nonEmptyString3(value.sessionId) || !nonEmptyString3(value.toolCallId)) {
25806
+ if (!isRecord18(value) || !nonEmptyString3(value.sessionId) || !nonEmptyString3(value.toolCallId)) {
25645
25807
  throw new Error("Grok plan approval requires sessionId and toolCallId");
25646
25808
  }
25647
25809
  const raw = value.planContent ?? value.plan_content;
@@ -25817,16 +25979,16 @@ var GrokTransportError = class extends Error {
25817
25979
  this.name = "GrokTransportError";
25818
25980
  }
25819
25981
  };
25820
- function isRecord18(value) {
25982
+ function isRecord19(value) {
25821
25983
  return typeof value === "object" && value !== null && !Array.isArray(value);
25822
25984
  }
25823
25985
  function acpToolName(update, metadata) {
25824
- if (!isRecord18(update))
25986
+ if (!isRecord19(update))
25825
25987
  return void 0;
25826
25988
  if (typeof update.name === "string" && update.name.length > 0)
25827
25989
  return update.name;
25828
- const meta3 = isRecord18(update._meta) ? update._meta : metadata;
25829
- const tool = meta3 && isRecord18(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
25990
+ const meta3 = isRecord19(update._meta) ? update._meta : metadata;
25991
+ const tool = meta3 && isRecord19(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
25830
25992
  return tool && typeof tool.name === "string" && tool.name.length > 0 ? tool.name : void 0;
25831
25993
  }
25832
25994
  function errorText(error53) {
@@ -25882,20 +26044,20 @@ function signalProcessTree(child, signal) {
25882
26044
  try {
25883
26045
  process.kill(-child.pid, signal);
25884
26046
  } catch (error53) {
25885
- if (!isRecord18(error53) || error53.code === "ESRCH")
26047
+ if (!isRecord19(error53) || error53.code === "ESRCH")
25886
26048
  return;
25887
26049
  try {
25888
26050
  child.kill(signal);
25889
26051
  } catch (fallback) {
25890
- if (!isRecord18(fallback) || fallback.code !== "ESRCH")
26052
+ if (!isRecord19(fallback) || fallback.code !== "ESRCH")
25891
26053
  throw fallback;
25892
26054
  }
25893
26055
  }
25894
26056
  }
25895
26057
  function grokNotificationMetadata(envelope, update) {
25896
- if (!isRecord18(envelope) && !isRecord18(update))
26058
+ if (!isRecord19(envelope) && !isRecord19(update))
25897
26059
  return void 0;
25898
- return { ...isRecord18(update) ? update : {}, ...isRecord18(envelope) ? envelope : {} };
26060
+ return { ...isRecord19(update) ? update : {}, ...isRecord19(envelope) ? envelope : {} };
25899
26061
  }
25900
26062
  function transportEvent(update, metadata) {
25901
26063
  const extension = update;
@@ -26024,7 +26186,7 @@ async function readNativeSignals(options, sessionId) {
26024
26186
  }
26025
26187
  }
26026
26188
  function isMissingFile(error53) {
26027
- return isRecord18(error53) && error53.code === "ENOENT";
26189
+ return isRecord19(error53) && error53.code === "ENOENT";
26028
26190
  }
26029
26191
  async function locateGrokNativeSession(options, sessionId) {
26030
26192
  if (sessionId.length === 0)
@@ -26047,7 +26209,7 @@ async function locateGrokNativeSession(options, sessionId) {
26047
26209
  try {
26048
26210
  summaryRaw = await readFile5(path17.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
26049
26211
  } catch (error53) {
26050
- if (isMissingFile(error53) || isRecord18(error53) && error53.code === "ENOTDIR")
26212
+ if (isMissingFile(error53) || isRecord19(error53) && error53.code === "ENOTDIR")
26051
26213
  continue;
26052
26214
  throw new GrokTransportError("unavailable", "Grok Native Session metadata could not be read", {
26053
26215
  cause: error53
@@ -26059,10 +26221,10 @@ async function locateGrokNativeSession(options, sessionId) {
26059
26221
  } catch {
26060
26222
  continue;
26061
26223
  }
26062
- if (!isRecord18(parsed))
26224
+ if (!isRecord19(parsed))
26063
26225
  continue;
26064
26226
  const info = parsed.info;
26065
- const cwd = isRecord18(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path17.resolve(info.cwd) : path17.resolve(decodeURIComponent(entry.name));
26227
+ const cwd = isRecord19(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path17.resolve(info.cwd) : path17.resolve(decodeURIComponent(entry.name));
26066
26228
  const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path17.resolve(parsed.source_workspace_dir) : void 0;
26067
26229
  matches.push({
26068
26230
  cwd,
@@ -26095,10 +26257,10 @@ function parseNativeHistory(contents, sessionId) {
26095
26257
  } catch {
26096
26258
  throw new GrokTransportError("protocolError", "Grok Native history contains invalid JSON");
26097
26259
  }
26098
- if (!isRecord18(record3) || !isRecord18(record3.params))
26260
+ if (!isRecord19(record3) || !isRecord19(record3.params))
26099
26261
  continue;
26100
26262
  const params = record3.params;
26101
- if (params.sessionId !== sessionId || !isRecord18(params.update))
26263
+ if (params.sessionId !== sessionId || !isRecord19(params.update))
26102
26264
  continue;
26103
26265
  let metadata = grokNotificationMetadata(params._meta, params.update._meta);
26104
26266
  if (typeof record3.timestamp === "number" && Number.isFinite(record3.timestamp))
@@ -26168,7 +26330,7 @@ var GrokAcpTransport = class {
26168
26330
  if (!this.#connection)
26169
26331
  throw new GrokTransportError("unavailable", "Grok ACP is unavailable");
26170
26332
  const result = await withTimeout(this.#connection.request("_x.ai/session/usage", { sessionId: this.sessionId }), this.#options.commandTimeoutMs, "Grok Session usage");
26171
- return isRecord18(result) ? result.usage : void 0;
26333
+ return isRecord19(result) ? result.usage : void 0;
26172
26334
  }
26173
26335
  async readHistory(sessionId, cwd = this.#options.cwd) {
26174
26336
  return readGrokNativeHistory({ ...this.#options, cwd }, sessionId);
@@ -26273,7 +26435,7 @@ var GrokAcpTransport = class {
26273
26435
  sessionId: this.#sessionId,
26274
26436
  toolCallId
26275
26437
  }), 3e3, "Grok question activity");
26276
- if (!isRecord18(raw) || !("timeout" in raw))
26438
+ if (!isRecord19(raw) || !("timeout" in raw))
26277
26439
  throw new GrokTransportError("protocolError", "Invalid Grok activity acknowledgement");
26278
26440
  return raw.timeout === null ? null : questionAutoResolutionSchema.parse(raw.timeout);
26279
26441
  } catch (error53) {
@@ -26545,7 +26707,7 @@ var GrokAcpTransport = class {
26545
26707
  }
26546
26708
  } : {}
26547
26709
  });
26548
- if (!isRecord18(response) || !isRecord18(response._meta) || !isRecord18(response._meta.model)) {
26710
+ if (!isRecord19(response) || !isRecord19(response._meta) || !isRecord19(response._meta.model)) {
26549
26711
  throw new GrokTransportError("protocolError", "Grok rejected Model configuration");
26550
26712
  }
26551
26713
  const selected = response._meta.model.Ok;
@@ -26585,7 +26747,7 @@ var GrokAcpTransport = class {
26585
26747
  permission_mode: mode
26586
26748
  });
26587
26749
  const response = await connection.request("_x.ai/session/info", { sessionId });
26588
- if (!isRecord18(response) || !isRecord18(response.result) || response.result.sessionId !== sessionId) {
26750
+ if (!isRecord19(response) || !isRecord19(response.result) || response.result.sessionId !== sessionId) {
26589
26751
  throw new Error("Grok did not confirm the target Session");
26590
26752
  }
26591
26753
  })()
@@ -26671,7 +26833,7 @@ var GrokAcpTransport = class {
26671
26833
  if (!isGrokExtensionSessionUpdateMethod(method) && !isGrokBackgroundNotificationMethod(method)) {
26672
26834
  return;
26673
26835
  }
26674
- if (typeof params.sessionId !== "string" || !isRecord18(params.update))
26836
+ if (typeof params.sessionId !== "string" || !isRecord19(params.update))
26675
26837
  return;
26676
26838
  this.#handleUpdate(params);
26677
26839
  }
@@ -26681,7 +26843,7 @@ var GrokAcpTransport = class {
26681
26843
  taskId,
26682
26844
  source
26683
26845
  });
26684
- if (!isRecord18(result) || result.taskId !== taskId || !["killed", "already_exited", "not_found"].includes(String(result.outcome)))
26846
+ if (!isRecord19(result) || result.taskId !== taskId || !["killed", "already_exited", "not_found"].includes(String(result.outcome)))
26685
26847
  throw new GrokTransportError("protocolError", "Malformed Grok task kill response");
26686
26848
  return result.outcome;
26687
26849
  }
@@ -26696,7 +26858,7 @@ var GrokAcpTransport = class {
26696
26858
  sessionId: this.sessionId,
26697
26859
  taskId
26698
26860
  });
26699
- if (!isRecord18(result) || result.taskId !== taskId || typeof result.deleted !== "boolean")
26861
+ if (!isRecord19(result) || result.taskId !== taskId || typeof result.deleted !== "boolean")
26700
26862
  throw new GrokTransportError("protocolError", "Malformed Grok scheduler delete response");
26701
26863
  return result.deleted;
26702
26864
  }
@@ -26708,21 +26870,21 @@ var GrokAcpTransport = class {
26708
26870
  try {
26709
26871
  raw = await withTimeout(this.#connection.request(method, params), this.#options.commandTimeoutMs, `Grok ${method}`);
26710
26872
  } catch (error53) {
26711
- if (!isRecord18(error53) || error53.code !== -32601)
26873
+ if (!isRecord19(error53) || error53.code !== -32601)
26712
26874
  throw error53;
26713
26875
  try {
26714
26876
  raw = await withTimeout(this.#connection.request(`_${method}`, params), this.#options.commandTimeoutMs, `Grok _${method}`);
26715
26877
  } catch (fallback) {
26716
- if (isRecord18(fallback) && fallback.code === -32601)
26878
+ if (isRecord19(fallback) && fallback.code === -32601)
26717
26879
  throw new GrokTransportError("unsupported", `Grok does not support ${method}`);
26718
26880
  throw fallback;
26719
26881
  }
26720
26882
  }
26721
- if (isRecord18(raw) && raw.error !== void 0 && raw.error !== null) {
26722
- const message = typeof raw.error === "string" ? raw.error : isRecord18(raw.error) && typeof raw.error.message === "string" ? raw.error.message : `Grok ${method} failed`;
26883
+ if (isRecord19(raw) && raw.error !== void 0 && raw.error !== null) {
26884
+ const message = typeof raw.error === "string" ? raw.error : isRecord19(raw.error) && typeof raw.error.message === "string" ? raw.error.message : `Grok ${method} failed`;
26723
26885
  throw new GrokTransportError("unavailable", message);
26724
26886
  }
26725
- return isRecord18(raw) && "result" in raw ? raw.result : raw;
26887
+ return isRecord19(raw) && "result" in raw ? raw.result : raw;
26726
26888
  }
26727
26889
  #handlePermission(params) {
26728
26890
  const observer = this.#activePrompt ?? this.#background;
@@ -26907,7 +27069,7 @@ var SessionImportScope = class {
26907
27069
  // dist/session-import.js
26908
27070
  var MAX_METADATA_BYTES = 4 * 1024 * 1024;
26909
27071
  var SUBAGENT_SESSION_KINDS = /* @__PURE__ */ new Set(["subagent", "subagent_resume"]);
26910
- function isRecord19(value) {
27072
+ function isRecord20(value) {
26911
27073
  return typeof value === "object" && value !== null && !Array.isArray(value);
26912
27074
  }
26913
27075
  async function readJson(file2, signal) {
@@ -26920,7 +27082,7 @@ function processAlive(pid) {
26920
27082
  process.kill(pid, 0);
26921
27083
  return true;
26922
27084
  } catch (error53) {
26923
- return isRecord19(error53) && error53.code === "EPERM";
27085
+ return isRecord20(error53) && error53.code === "EPERM";
26924
27086
  }
26925
27087
  }
26926
27088
  async function firstUserText(file2, signal) {
@@ -26937,10 +27099,10 @@ async function firstUserText(file2, signal) {
26937
27099
  } catch {
26938
27100
  continue;
26939
27101
  }
26940
- const update = isRecord19(entry) && isRecord19(entry.params) ? entry.params.update : null;
26941
- if (!isRecord19(update) || update.sessionUpdate !== "user_message_chunk")
27102
+ const update = isRecord20(entry) && isRecord20(entry.params) ? entry.params.update : null;
27103
+ if (!isRecord20(update) || update.sessionUpdate !== "user_message_chunk")
26942
27104
  continue;
26943
- const text = isRecord19(update.content) ? update.content.text : null;
27105
+ const text = isRecord20(update.content) ? update.content.text : null;
26944
27106
  return typeof text === "string" ? text : "";
26945
27107
  }
26946
27108
  return null;
@@ -27017,7 +27179,7 @@ var GrokSessionImport = class {
27017
27179
  if (!Array.isArray(entries))
27018
27180
  return active;
27019
27181
  for (const entry of entries) {
27020
- if (isRecord19(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
27182
+ if (isRecord20(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
27021
27183
  active.add(entry.session_id);
27022
27184
  }
27023
27185
  return active;
@@ -27066,7 +27228,7 @@ var GrokSessionImport = class {
27066
27228
  return null;
27067
27229
  try {
27068
27230
  const summary = await readJson(files[0], signal);
27069
- if (!isRecord19(summary) || !isRecord19(summary.info) || summary.info.id !== nativeSessionId)
27231
+ if (!isRecord20(summary) || !isRecord20(summary.info) || summary.info.id !== nativeSessionId)
27070
27232
  return null;
27071
27233
  if (typeof summary.session_kind === "string" && SUBAGENT_SESSION_KINDS.has(summary.session_kind))
27072
27234
  return null;
@@ -27318,9 +27480,65 @@ var GrokSubagentLifecycle = class {
27318
27480
  };
27319
27481
 
27320
27482
  // dist/grok-activity.js
27483
+ import { readFile as readFile8 } from "node:fs/promises";
27484
+ import path20 from "node:path";
27485
+
27486
+ // dist/grok-scheduled-origin.js
27321
27487
  import { readFile as readFile7 } from "node:fs/promises";
27322
27488
  import path19 from "node:path";
27489
+ var SCHEDULED_PROMPT_HEADER = /^<system-reminder>\nScheduled task (\S+) \(/;
27490
+ function grokScheduledTaskIdFromPrompt(prompt) {
27491
+ if (typeof prompt !== "string")
27492
+ return void 0;
27493
+ return prompt.match(SCHEDULED_PROMPT_HEADER)?.[1];
27494
+ }
27495
+ async function readGrokSubagentPrompt(sessionDirectory, nativeSubagentId) {
27496
+ try {
27497
+ const raw = JSON.parse(await readFile7(path19.join(sessionDirectory, "subagents", nativeSubagentId, "meta.json"), "utf8"));
27498
+ return typeof raw === "object" && raw !== null && "prompt" in raw && typeof raw.prompt === "string" ? raw.prompt : void 0;
27499
+ } catch {
27500
+ return void 0;
27501
+ }
27502
+ }
27503
+ async function tagGrokScheduledActivityChildren(input) {
27504
+ const scheduledChildIds = input.scheduledChildIds;
27505
+ const scheduledTaskIds = input.scheduledTaskIds;
27506
+ const pendingMeta = [];
27507
+ for (const [id, child] of input.children) {
27508
+ if (child.origin === "scheduled") {
27509
+ input.attempted.add(id);
27510
+ continue;
27511
+ }
27512
+ if (scheduledChildIds?.has(id)) {
27513
+ input.children.set(id, { ...child, origin: "scheduled" });
27514
+ input.attempted.add(id);
27515
+ continue;
27516
+ }
27517
+ if (input.attempted.has(id) || !scheduledTaskIds?.size)
27518
+ continue;
27519
+ pendingMeta.push(id);
27520
+ input.attempted.add(id);
27521
+ }
27522
+ if (pendingMeta.length === 0 || !scheduledTaskIds?.size)
27523
+ return;
27524
+ const prompts = await Promise.all(pendingMeta.map((id) => readGrokSubagentPrompt(input.directory, id)));
27525
+ for (const [index, id] of pendingMeta.entries()) {
27526
+ const current = input.children.get(id);
27527
+ if (!current || current.origin === "scheduled")
27528
+ continue;
27529
+ const taskId = grokScheduledTaskIdFromPrompt(prompts[index]);
27530
+ if (taskId && scheduledTaskIds.has(taskId)) {
27531
+ input.children.set(id, { ...current, origin: "scheduled" });
27532
+ }
27533
+ }
27534
+ }
27535
+
27536
+ // dist/grok-activity.js
27537
+ var SETTLED_SUBAGENT_ACTIVITY_LIMIT = 20;
27323
27538
  var record2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
27539
+ function isActiveChild(status2) {
27540
+ return status2 === "pending" || status2 === "running";
27541
+ }
27324
27542
  var fail = (code, message) => ({ ok: false, error: { code, message, retryable: false } });
27325
27543
  function parseGrokTaskList(value, sessionId) {
27326
27544
  if (!record2(value) || !Array.isArray(value.tasks))
@@ -27334,7 +27552,7 @@ function parseGrokTaskList(value, sessionId) {
27334
27552
  async function readGrokScheduledLoops(directory) {
27335
27553
  let raw;
27336
27554
  try {
27337
- raw = JSON.parse(await readFile7(path19.join(directory, "resources_state.json"), "utf8"));
27555
+ raw = JSON.parse(await readFile8(path20.join(directory, "resources_state.json"), "utf8"));
27338
27556
  } catch (error53) {
27339
27557
  if (error53.code === "ENOENT")
27340
27558
  return null;
@@ -27365,6 +27583,33 @@ async function readGrokScheduledLoops(directory) {
27365
27583
  }
27366
27584
  function createGrokActivity(options) {
27367
27585
  let tasks = [];
27586
+ const classifiedChildIds = /* @__PURE__ */ new Set();
27587
+ const listedChildren = () => {
27588
+ const keep = /* @__PURE__ */ new Set();
27589
+ for (const loop of options.loops.values()) {
27590
+ if (loop.lastSubagentId)
27591
+ keep.add(loop.lastSubagentId);
27592
+ }
27593
+ const active = [];
27594
+ const settled = [];
27595
+ for (const child of options.children.values()) {
27596
+ if (!child.nativeSubagentId)
27597
+ continue;
27598
+ if (isActiveChild(child.status))
27599
+ active.push(child);
27600
+ else
27601
+ settled.push(child);
27602
+ }
27603
+ const newestSettled = settled.reverse();
27604
+ for (const child of newestSettled.slice(0, SETTLED_SUBAGENT_ACTIVITY_LIMIT)) {
27605
+ if (child.nativeSubagentId)
27606
+ keep.add(child.nativeSubagentId);
27607
+ }
27608
+ return [
27609
+ ...active,
27610
+ ...newestSettled.filter((child) => child.nativeSubagentId && keep.has(child.nativeSubagentId))
27611
+ ];
27612
+ };
27368
27613
  const summaries = () => [
27369
27614
  ...tasks.map((task) => {
27370
27615
  const commandItemId = options.commandItemId?.(task.task_id);
@@ -27387,7 +27632,7 @@ function createGrokActivity(options) {
27387
27632
  ...loop.nextFireAt ? { nextRunAt: loop.nextFireAt } : {},
27388
27633
  ...loop.lastSubagentId ? { relatedActivityId: `subagent:${loop.lastSubagentId}` } : {}
27389
27634
  })),
27390
- ...[...options.children.values()].map((child) => ({
27635
+ ...listedChildren().map((child) => ({
27391
27636
  id: `subagent:${child.nativeSubagentId}`,
27392
27637
  kind: "subagent",
27393
27638
  label: child.description,
@@ -27454,6 +27699,15 @@ function createGrokActivity(options) {
27454
27699
  status: status2 === "initializing" ? "pending" : status2 === "cancelled" ? "interrupted" : status2
27455
27700
  });
27456
27701
  }
27702
+ await tagGrokScheduledActivityChildren({
27703
+ directory: options.directory,
27704
+ children: options.children,
27705
+ attempted: classifiedChildIds,
27706
+ ...options.scheduledTaskIds ? { scheduledTaskIds: options.scheduledTaskIds } : {},
27707
+ ...options.scheduledChildIds ? { scheduledChildIds: options.scheduledChildIds } : {}
27708
+ });
27709
+ if (!options.isOpen())
27710
+ return fail("nativeFailure", "Grok Session changed");
27457
27711
  return { ok: true, value: summaries() };
27458
27712
  } catch (error53) {
27459
27713
  return fail("nativeFailure", error53 instanceof Error ? error53.message : "Grok activity read failed");
@@ -27788,17 +28042,17 @@ var GrokBackgroundItems = class {
27788
28042
  await handle.close();
27789
28043
  }
27790
28044
  } catch (error53) {
27791
- if (isRecord20(error53) && error53.code === "ENOENT")
28045
+ if (isRecord21(error53) && error53.code === "ENOENT")
27792
28046
  return;
27793
28047
  }
27794
28048
  }
27795
28049
  };
27796
- function isRecord20(value) {
28050
+ function isRecord21(value) {
27797
28051
  return typeof value === "object" && value !== null && !Array.isArray(value);
27798
28052
  }
27799
28053
 
27800
28054
  // dist/grok-models.js
27801
- function isRecord21(value) {
28055
+ function isRecord22(value) {
27802
28056
  return typeof value === "object" && value !== null && !Array.isArray(value);
27803
28057
  }
27804
28058
  function nonBlank(value) {
@@ -27810,7 +28064,7 @@ function thinkingOptions(value) {
27810
28064
  const seen = /* @__PURE__ */ new Set();
27811
28065
  const options = [];
27812
28066
  for (const candidate of value) {
27813
- if (!isRecord21(candidate) || !nonBlank(candidate.label))
28067
+ if (!isRecord22(candidate) || !nonBlank(candidate.label))
27814
28068
  continue;
27815
28069
  const id = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
27816
28070
  if (!id.success || seen.has(id.data))
@@ -27821,7 +28075,7 @@ function thinkingOptions(value) {
27821
28075
  return options;
27822
28076
  }
27823
28077
  function parseGrokModelState(value) {
27824
- if (!isRecord21(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
28078
+ if (!isRecord22(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
27825
28079
  return null;
27826
28080
  }
27827
28081
  const currentModel = harnessModelRefSchema.safeParse({ id: value.currentModelId });
@@ -27833,12 +28087,12 @@ function parseGrokModelState(value) {
27833
28087
  const models = [];
27834
28088
  let currentThinkingOptionId;
27835
28089
  for (const candidate of value.availableModels) {
27836
- if (!isRecord21(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
28090
+ if (!isRecord22(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
27837
28091
  continue;
27838
28092
  const ref = harnessModelRefSchema.safeParse({ id: candidate.modelId });
27839
28093
  if (!ref.success)
27840
28094
  continue;
27841
- const metadata = isRecord21(candidate._meta) ? candidate._meta : {};
28095
+ const metadata = isRecord22(candidate._meta) ? candidate._meta : {};
27842
28096
  const options2 = thinkingOptions(metadata.reasoningEfforts);
27843
28097
  if (Array.isArray(metadata.contextWindows) && metadata.contextWindows.includes(5e5)) {
27844
28098
  defaultContextWindowTokensByModel.set(ref.data.id, 5e5);
@@ -27877,10 +28131,10 @@ function parseGrokModelState(value) {
27877
28131
  };
27878
28132
  }
27879
28133
  function modelStateFromInitialize(response) {
27880
- return parseGrokModelState(isRecord21(response._meta) ? response._meta.modelState : void 0);
28134
+ return parseGrokModelState(isRecord22(response._meta) ? response._meta.modelState : void 0);
27881
28135
  }
27882
28136
  function modelStateFromSessionResponse(response) {
27883
- return parseGrokModelState(isRecord21(response) ? response.models : void 0);
28137
+ return parseGrokModelState(isRecord22(response) ? response.models : void 0);
27884
28138
  }
27885
28139
  function stateForGrokModel(modelState, nativeState, model2 = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
27886
28140
  const selectedModel = model2;
@@ -27899,20 +28153,20 @@ function stateForGrokModel(modelState, nativeState, model2 = modelState.currentM
27899
28153
  }
27900
28154
 
27901
28155
  // dist/grok-credits.js
27902
- import { readFile as readFile8 } from "node:fs/promises";
28156
+ import { readFile as readFile9 } from "node:fs/promises";
27903
28157
  import os7 from "node:os";
27904
- import path20 from "node:path";
28158
+ import path21 from "node:path";
27905
28159
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
27906
28160
  var GROK_SETTINGS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/settings";
27907
28161
  var REQUEST_TIMEOUT_MS = 15e3;
27908
28162
  var PLAN_TIMEOUT_MS = 2e3;
27909
28163
  function parseGrokPlan(value) {
27910
- if (!isRecord22(value) || typeof value.subscription_tier_display !== "string")
28164
+ if (!isRecord23(value) || typeof value.subscription_tier_display !== "string")
27911
28165
  return void 0;
27912
28166
  const plan = value.subscription_tier_display.trim();
27913
28167
  return plan && plan.length <= 128 && !/[\u0000-\u001f\u007f]/u.test(plan) ? plan : void 0;
27914
28168
  }
27915
- function isRecord22(value) {
28169
+ function isRecord23(value) {
27916
28170
  return typeof value === "object" && value !== null && !Array.isArray(value);
27917
28171
  }
27918
28172
  function finitePercent(value) {
@@ -27921,7 +28175,7 @@ function finitePercent(value) {
27921
28175
  return Math.min(100, Math.max(0, value));
27922
28176
  }
27923
28177
  function nonNegativeCentValue(value) {
27924
- if (!isRecord22(value))
28178
+ if (!isRecord23(value))
27925
28179
  return void 0;
27926
28180
  const amount = value.val === void 0 ? 0 : value.val;
27927
28181
  if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
@@ -27929,7 +28183,7 @@ function nonNegativeCentValue(value) {
27929
28183
  return amount;
27930
28184
  }
27931
28185
  function grokHome3(environment) {
27932
- return environment.GROK_HOME ?? path20.join(environment.HOME ?? environment.USERPROFILE ?? os7.homedir(), ".grok");
28186
+ return environment.GROK_HOME ?? path21.join(environment.HOME ?? environment.USERPROFILE ?? os7.homedir(), ".grok");
27933
28187
  }
27934
28188
  function periodTypeFrom(value) {
27935
28189
  if (typeof value !== "string")
@@ -27945,7 +28199,7 @@ function productUsageFrom(value) {
27945
28199
  if (!Array.isArray(value))
27946
28200
  return void 0;
27947
28201
  const products = value.flatMap((entry) => {
27948
- if (!isRecord22(entry) || typeof entry.product !== "string")
28202
+ if (!isRecord23(entry) || typeof entry.product !== "string")
27949
28203
  return [];
27950
28204
  const usagePercent = finitePercent(entry.usagePercent);
27951
28205
  const labels = {
@@ -27966,10 +28220,10 @@ function productUsageFrom(value) {
27966
28220
  return products.length > 0 ? products : void 0;
27967
28221
  }
27968
28222
  function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
27969
- if (!isRecord22(value) || !isRecord22(value.config))
28223
+ if (!isRecord23(value) || !isRecord23(value.config))
27970
28224
  return null;
27971
28225
  const config2 = value.config;
27972
- const period = isRecord22(config2.currentPeriod) ? config2.currentPeriod : void 0;
28226
+ const period = isRecord23(config2.currentPeriod) ? config2.currentPeriod : void 0;
27973
28227
  const periodType = periodTypeFrom(period?.type);
27974
28228
  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);
27975
28229
  let usedPercent = finitePercent(config2.creditUsagePercent);
@@ -27996,11 +28250,11 @@ function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()
27996
28250
  };
27997
28251
  }
27998
28252
  function selectAccessToken(auth, now) {
27999
- if (!isRecord22(auth))
28253
+ if (!isRecord23(auth))
28000
28254
  return null;
28001
- const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord22(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")));
28255
+ const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord23(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")));
28002
28256
  for (const [, value] of entries) {
28003
- if (!isRecord22(value) || typeof value.key !== "string")
28257
+ if (!isRecord23(value) || typeof value.key !== "string")
28004
28258
  continue;
28005
28259
  if (typeof value.expires_at === "string") {
28006
28260
  const expiresAt = Date.parse(value.expires_at);
@@ -28021,8 +28275,8 @@ async function fetchGrokAccount(input = {}) {
28021
28275
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((value) => value?.trim()))
28022
28276
  return null;
28023
28277
  const now = input.now ?? /* @__PURE__ */ new Date();
28024
- const authPath = path20.join(grokHome3(environment), "auth.json");
28025
- const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile8(authPath, "utf8");
28278
+ const authPath = path21.join(grokHome3(environment), "auth.json");
28279
+ const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile9(authPath, "utf8");
28026
28280
  const token = selectAccessToken(JSON.parse(raw), now);
28027
28281
  if (!token)
28028
28282
  return null;
@@ -28076,7 +28330,7 @@ async function fetchGrokCredits(input = {}) {
28076
28330
 
28077
28331
  // dist/grok-usage.js
28078
28332
  var USD_TICKS_PER_DOLLAR = 1e10;
28079
- function isRecord23(value) {
28333
+ function isRecord24(value) {
28080
28334
  return typeof value === "object" && value !== null && !Array.isArray(value);
28081
28335
  }
28082
28336
  function optionalToken(value) {
@@ -28093,7 +28347,7 @@ function combineUsage(base, next) {
28093
28347
  return base === null ? next : parseHostUsage({ ...base, ...next });
28094
28348
  }
28095
28349
  function usageFromNative(value) {
28096
- if (!isRecord23(value))
28350
+ if (!isRecord24(value))
28097
28351
  return null;
28098
28352
  const inputTokens = optionalToken(value.inputTokens);
28099
28353
  const cachedRead = optionalToken(value.cachedReadTokens);
@@ -28117,7 +28371,7 @@ function usageFromNative(value) {
28117
28371
  }
28118
28372
  }
28119
28373
  function usageFromResponse(value) {
28120
- if (!isRecord23(value))
28374
+ if (!isRecord24(value))
28121
28375
  return null;
28122
28376
  const buckets = [
28123
28377
  value.input_tokens,
@@ -28217,7 +28471,7 @@ var GrokTurnUsage = class {
28217
28471
  }
28218
28472
  };
28219
28473
  function usageFromSignals(value) {
28220
- if (!isRecord23(value))
28474
+ if (!isRecord24(value))
28221
28475
  return null;
28222
28476
  try {
28223
28477
  return parseHostUsage({
@@ -28237,7 +28491,7 @@ var summedUsageFields = [
28237
28491
  "totalTokens"
28238
28492
  ];
28239
28493
  function nativeCostTicks(value) {
28240
- if (!isRecord23(value))
28494
+ if (!isRecord24(value))
28241
28495
  return void 0;
28242
28496
  const ticks = value.costUsdTicks;
28243
28497
  if (typeof ticks !== "number" || !Number.isSafeInteger(ticks) || ticks < 0)
@@ -28245,7 +28499,7 @@ function nativeCostTicks(value) {
28245
28499
  return ticks;
28246
28500
  }
28247
28501
  function sessionCostFromNative(value, initialCostUsd) {
28248
- if (!isRecord23(value))
28502
+ if (!isRecord24(value))
28249
28503
  return void 0;
28250
28504
  if (value.costIsPartial !== void 0 && value.costIsPartial !== false)
28251
28505
  return void 0;
@@ -28276,7 +28530,7 @@ function sessionUsageFromHistory(events) {
28276
28530
  continue;
28277
28531
  const usage = usageFromNative(event.usage);
28278
28532
  const ticks2 = nativeCostTicks(event.usage);
28279
- const complete = isRecord23(event.usage) && (event.usage.usageIsIncomplete === void 0 || event.usage.usageIsIncomplete === false) && usage?.inputTokens !== void 0 && usage.cachedInputTokens !== void 0 && usage.cachedInputTokens <= usage.inputTokens;
28533
+ const complete = isRecord24(event.usage) && (event.usage.usageIsIncomplete === void 0 || event.usage.usageIsIncomplete === false) && usage?.inputTokens !== void 0 && usage.cachedInputTokens !== void 0 && usage.cachedInputTokens <= usage.inputTokens;
28280
28534
  latestByKey.set(key, { usage, complete, ...ticks2 !== void 0 ? { ticks: ticks2 } : {} });
28281
28535
  }
28282
28536
  if (latestByKey.size === 0)
@@ -28330,7 +28584,7 @@ function usageFromCompact(tokensAfter, contextWindowTokens) {
28330
28584
  function usageFromUpdate(update, metadata, contextWindowTokens) {
28331
28585
  try {
28332
28586
  if (update?.sessionUpdate === "usage_update") {
28333
- const cost = isRecord23(update.cost) ? update.cost : null;
28587
+ const cost = isRecord24(update.cost) ? update.cost : null;
28334
28588
  return parseHostUsage({
28335
28589
  contextUsedTokens: update.used,
28336
28590
  contextWindowTokens: update.size,
@@ -28465,6 +28719,8 @@ var GrokHarnessSession = class {
28465
28719
  #backgroundItems;
28466
28720
  #loops;
28467
28721
  #observedLoopIds = /* @__PURE__ */ new Set();
28722
+ #scheduledTaskIds;
28723
+ #scheduledChildIds = /* @__PURE__ */ new Set();
28468
28724
  #activityChildren = /* @__PURE__ */ new Map();
28469
28725
  #earlyBackground = /* @__PURE__ */ new Map();
28470
28726
  #pendingBackground = /* @__PURE__ */ new Map();
@@ -28485,14 +28741,21 @@ var GrokHarnessSession = class {
28485
28741
  emit: (event) => this.#event(event)
28486
28742
  });
28487
28743
  this.#loops = collectGrokScheduledLoops(options.history);
28488
- for (const event of options.history)
28744
+ this.#scheduledTaskIds = collectGrokScheduledTaskIds(options.history);
28745
+ for (const event of options.history) {
28746
+ if (event.type === "scheduled.fired" && event.subagentId) {
28747
+ this.#scheduledChildIds.add(event.subagentId);
28748
+ }
28489
28749
  this.#observeActivityChild(event);
28750
+ }
28490
28751
  this.backgroundActivity = createGrokActivity({
28491
28752
  sessionId: opened.sessionId,
28492
28753
  directory: options.sessionDirectory,
28493
28754
  loops: this.#loops,
28494
28755
  observedLoopIds: this.#observedLoopIds,
28495
28756
  children: this.#activityChildren,
28757
+ scheduledTaskIds: this.#scheduledTaskIds,
28758
+ scheduledChildIds: this.#scheduledChildIds,
28496
28759
  outputLimit: options.toolOutputLimit,
28497
28760
  commandItemId: (taskId) => this.#backgroundItems.commandItemId(taskId),
28498
28761
  observeTasks: (tasks) => {
@@ -28832,14 +29095,18 @@ var GrokHarnessSession = class {
28832
29095
  }
28833
29096
  #observeActivityChild(event) {
28834
29097
  if (event.type === "subagent.spawned") {
29098
+ const existing = this.#activityChildren.get(event.nativeSubagentId);
29099
+ const scheduled = existing?.origin === "scheduled" || this.#scheduledChildIds.has(event.nativeSubagentId);
28835
29100
  this.#activityChildren.set(event.nativeSubagentId, {
29101
+ ...existing,
28836
29102
  subagentId: event.nativeSubagentId,
28837
29103
  nativeSubagentId: event.nativeSubagentId,
28838
- description: event.description ?? "Grok Subagent",
29104
+ description: event.description ?? existing?.description ?? "Grok Subagent",
28839
29105
  background: true,
28840
29106
  status: "running",
28841
29107
  ...event.role ? { role: event.role } : {},
28842
- ...event.model ? { model: event.model } : {}
29108
+ ...event.model ? { model: event.model } : {},
29109
+ ...scheduled ? { origin: "scheduled" } : {}
28843
29110
  });
28844
29111
  }
28845
29112
  if (event.type === "subagent.finished") {
@@ -28871,14 +29138,23 @@ var GrokHarnessSession = class {
28871
29138
  return true;
28872
29139
  }
28873
29140
  if (event.type === "scheduled.created" || event.type === "scheduled.fired" || event.type === "scheduled.deleted") {
28874
- if (event.type === "scheduled.fired" && event.subagentId && !this.#activityChildren.has(event.subagentId))
29141
+ if (event.type === "scheduled.created" || event.type === "scheduled.fired") {
29142
+ this.#scheduledTaskIds.add(event.taskId);
29143
+ }
29144
+ if (event.type === "scheduled.fired" && event.subagentId) {
29145
+ this.#scheduledChildIds.add(event.subagentId);
29146
+ const existing = this.#activityChildren.get(event.subagentId);
28875
29147
  this.#activityChildren.set(event.subagentId, {
28876
- subagentId: event.subagentId,
28877
- nativeSubagentId: event.subagentId,
28878
- description: event.prompt,
28879
- background: true,
28880
- status: "running"
29148
+ ...existing ?? {
29149
+ subagentId: event.subagentId,
29150
+ nativeSubagentId: event.subagentId,
29151
+ description: event.prompt,
29152
+ background: true,
29153
+ status: "running"
29154
+ },
29155
+ origin: "scheduled"
28881
29156
  });
29157
+ }
28882
29158
  applyGrokScheduledEvent(this.#loops, event, this.#observedLoopIds);
28883
29159
  return true;
28884
29160
  }
@@ -30256,7 +30532,7 @@ var GrokAdapter = class {
30256
30532
  async inspect(input = {}) {
30257
30533
  if (this.#closePromise)
30258
30534
  return { status: "unavailable", error: invalidState("Grok Adapter is closed") };
30259
- const cwd = path21.resolve(input.cwd ?? process.cwd());
30535
+ const cwd = path22.resolve(input.cwd ?? process.cwd());
30260
30536
  if (!input.refresh) {
30261
30537
  const cached2 = this.#inspectionCache.get(cwd);
30262
30538
  if (cached2)
@@ -30331,7 +30607,7 @@ var GrokAdapter = class {
30331
30607
  }
30332
30608
  };
30333
30609
  }
30334
- const cwd = path21.resolve(input.cwd);
30610
+ const cwd = path22.resolve(input.cwd);
30335
30611
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
30336
30612
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
30337
30613
  return {