@karlorz/codexhost-cli-win32-x64 0.16.1-2 → 0.16.1-3

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, path20) {
1162
- if (!path20)
1161
+ function getElementAtPath(obj, path21) {
1162
+ if (!path21)
1163
1163
  return obj;
1164
- return path20.reduce((acc, key) => acc?.[key], obj);
1164
+ return path21.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(path20, issues) {
1573
+ function prefixIssues(path21, issues) {
1574
1574
  return issues.map((iss) => {
1575
1575
  var _a3;
1576
1576
  (_a3 = iss).path ?? (_a3.path = []);
1577
- iss.path.unshift(path20);
1577
+ iss.path.unshift(path21);
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, path20 = []) => {
1724
+ const processError = (error54, path21 = []) => {
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 }, [...path20, ...issue2.path]));
1727
+ issue2.errors.map((issues) => processError({ issues }, [...path21, ...issue2.path]));
1728
1728
  } else if (issue2.code === "invalid_key") {
1729
- processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1729
+ processError({ issues: issue2.issues }, [...path21, ...issue2.path]);
1730
1730
  } else if (issue2.code === "invalid_element") {
1731
- processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1731
+ processError({ issues: issue2.issues }, [...path21, ...issue2.path]);
1732
1732
  } else {
1733
- const fullpath = [...path20, ...issue2.path];
1733
+ const fullpath = [...path21, ...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, path20 = []) => {
1760
+ const processError = (error54, path21 = []) => {
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 }, [...path20, ...issue2.path]));
1764
+ issue2.errors.map((issues) => processError({ issues }, [...path21, ...issue2.path]));
1765
1765
  } else if (issue2.code === "invalid_key") {
1766
- processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1766
+ processError({ issues: issue2.issues }, [...path21, ...issue2.path]);
1767
1767
  } else if (issue2.code === "invalid_element") {
1768
- processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1768
+ processError({ issues: issue2.issues }, [...path21, ...issue2.path]);
1769
1769
  } else {
1770
- const fullpath = [...path20, ...issue2.path];
1770
+ const fullpath = [...path21, ...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 path20 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1803
- for (const seg of path20) {
1802
+ const path21 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1803
+ for (const seg of path21) {
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 path20 = ref.slice(1).split("/").filter(Boolean);
14496
- if (path20.length === 0) {
14495
+ const path21 = ref.slice(1).split("/").filter(Boolean);
14496
+ if (path21.length === 0) {
14497
14497
  return ctx.rootSchema;
14498
14498
  }
14499
14499
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14500
- if (path20[0] === defsKey) {
14501
- const key = path20[1];
14500
+ if (path21[0] === defsKey) {
14501
+ const key = path21[1];
14502
14502
  if (!key || !ctx.defs[key]) {
14503
14503
  throw new Error(`Reference not found: ${ref}`);
14504
14504
  }
@@ -16525,6 +16525,37 @@ var voiceSettingsStateSchema = external_exports.strictObject({
16525
16525
  })
16526
16526
  });
16527
16527
 
16528
+ // ../../shared-contracts/dist/background-activity.js
16529
+ var backgroundActivitySchema = external_exports.strictObject({
16530
+ id: external_exports.string().min(1),
16531
+ kind: external_exports.enum(["task", "monitor", "loop", "subagent"]),
16532
+ label: external_exports.string(),
16533
+ status: external_exports.enum(["running", "scheduled", "completed", "failed", "cancelled", "unknown"]),
16534
+ canStop: external_exports.boolean(),
16535
+ /** Existing detached command Item presented by Desktop's native process UI. */
16536
+ commandItemId: hostItemIdSchema.optional(),
16537
+ schedule: external_exports.string().optional(),
16538
+ nextRunAt: external_exports.string().datetime({ offset: true }).optional(),
16539
+ relatedActivityId: external_exports.string().optional(),
16540
+ threadId: hostThreadIdSchema.optional()
16541
+ });
16542
+ var backgroundActivityDetailSchema = external_exports.strictObject({
16543
+ activity: backgroundActivitySchema,
16544
+ output: external_exports.string(),
16545
+ truncated: external_exports.boolean()
16546
+ });
16547
+ var threadActivityParamsSchema = external_exports.strictObject({ threadId: hostThreadIdSchema });
16548
+ var threadActivityItemParamsSchema = threadActivityParamsSchema.extend({
16549
+ activityId: external_exports.string().min(1)
16550
+ });
16551
+ var threadActivityListResultSchema = external_exports.strictObject({
16552
+ supported: external_exports.boolean(),
16553
+ activities: external_exports.array(backgroundActivitySchema)
16554
+ });
16555
+ var threadActivityStopResultSchema = external_exports.strictObject({
16556
+ outcome: external_exports.enum(["stopped", "alreadyStopped", "notFound"])
16557
+ });
16558
+
16528
16559
  // ../../shared-contracts/dist/index.js
16529
16560
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
16530
16561
 
@@ -17047,6 +17078,13 @@ var grokCommandCatalog = harnessCommandCatalogSchema.parse({
17047
17078
  }
17048
17079
  },
17049
17080
  argumentMode: "text"
17081
+ },
17082
+ {
17083
+ id: "grok.loop",
17084
+ invocation: "/loop",
17085
+ label: "Loop",
17086
+ description: "Create a native timed Loop; include the interval and task",
17087
+ argumentMode: "text"
17050
17088
  }
17051
17089
  ]
17052
17090
  });
@@ -17128,7 +17166,7 @@ async function readGrokCredentials(environment) {
17128
17166
  }
17129
17167
 
17130
17168
  // dist/grok-adapter.js
17131
- import path19 from "node:path";
17169
+ import path20 from "node:path";
17132
17170
 
17133
17171
  // ../../harness-plugin-files/dist/grok-computer-use.js
17134
17172
  import { randomUUID } from "node:crypto";
@@ -22015,8 +22053,8 @@ function parseGrokAvailableCommands(value) {
22015
22053
  });
22016
22054
  }
22017
22055
  function isGrokSkill(command) {
22018
- const path20 = command.meta?.path;
22019
- return typeof path20 === "string" && /(^|[\\/])SKILL\.md$/u.test(path20) || typeof command.meta?.qualifiedName === "string";
22056
+ const path21 = command.meta?.path;
22057
+ return typeof path21 === "string" && /(^|[\\/])SKILL\.md$/u.test(path21) || typeof command.meta?.qualifiedName === "string";
22020
22058
  }
22021
22059
  function grokLiveCommands(native) {
22022
22060
  return native.map((command) => ({
@@ -22315,16 +22353,16 @@ var Diff = class {
22315
22353
  }
22316
22354
  }
22317
22355
  }
22318
- addToPath(path20, added, removed, oldPosInc, options) {
22319
- const last = path20.lastComponent;
22356
+ addToPath(path21, added, removed, oldPosInc, options) {
22357
+ const last = path21.lastComponent;
22320
22358
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
22321
22359
  return {
22322
- oldPos: path20.oldPos + oldPosInc,
22360
+ oldPos: path21.oldPos + oldPosInc,
22323
22361
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
22324
22362
  };
22325
22363
  } else {
22326
22364
  return {
22327
- oldPos: path20.oldPos + oldPosInc,
22365
+ oldPos: path21.oldPos + oldPosInc,
22328
22366
  lastComponent: { count: 1, added, removed, previousComponent: last }
22329
22367
  };
22330
22368
  }
@@ -23076,7 +23114,13 @@ function grokGeneratedImageItem(image, itemId, sourceItemId) {
23076
23114
 
23077
23115
  // dist/grok-tool-output.js
23078
23116
  var DEFAULT_GROK_TOOL_OUTPUT_LIMIT = 64e3;
23079
- var EXECUTE_TOOL_NAMES = /* @__PURE__ */ new Set(["bash", "run_terminal_command", "shell", "cursor_shell"]);
23117
+ var EXECUTE_TOOL_NAMES = /* @__PURE__ */ new Set([
23118
+ "bash",
23119
+ "run_terminal_command",
23120
+ "shell",
23121
+ "cursor_shell",
23122
+ "monitor"
23123
+ ]);
23080
23124
  function isRecord7(value) {
23081
23125
  return typeof value === "object" && value !== null && !Array.isArray(value);
23082
23126
  }
@@ -24322,15 +24366,15 @@ function isRecord10(value) {
24322
24366
  function optionalNonNegativeInt(value) {
24323
24367
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
24324
24368
  }
24325
- function firstPresent(record2, keys) {
24369
+ function firstPresent(record3, keys) {
24326
24370
  for (const key of keys) {
24327
- if (record2[key] !== void 0)
24328
- return record2[key];
24371
+ if (record3[key] !== void 0)
24372
+ return record3[key];
24329
24373
  }
24330
24374
  return void 0;
24331
24375
  }
24332
- function optionalErrorMessage(record2) {
24333
- const value = firstPresent(record2, ["errorMessage", "error_message", "message"]);
24376
+ function optionalErrorMessage(record3) {
24377
+ const value = firstPresent(record3, ["errorMessage", "error_message", "message"]);
24334
24378
  return typeof value === "string" && value.length > 0 ? value : void 0;
24335
24379
  }
24336
24380
  function isGrokExtensionSessionUpdateMethod(method) {
@@ -24373,10 +24417,228 @@ function grokCompactionEventFromUpdate(update) {
24373
24417
  return null;
24374
24418
  }
24375
24419
 
24420
+ // dist/grok-background.js
24421
+ var GROK_TASK_KILL_METHOD = "x.ai/task/kill";
24422
+ var GROK_TASK_LIST_METHOD = "x.ai/task/list";
24423
+ var GROK_SCHEDULER_DELETE_METHOD = "x.ai/scheduler/delete";
24424
+ var GROK_BACKGROUND_NOTIFICATION_METHODS = [
24425
+ "x.ai/task_backgrounded",
24426
+ "_x.ai/task_backgrounded",
24427
+ "x.ai/task_completed",
24428
+ "_x.ai/task_completed",
24429
+ "x.ai/monitor_event",
24430
+ "_x.ai/monitor_event",
24431
+ "x.ai/scheduled_task_created",
24432
+ "_x.ai/scheduled_task_created",
24433
+ "x.ai/scheduled_task_fired",
24434
+ "_x.ai/scheduled_task_fired",
24435
+ "x.ai/scheduled_task_deleted",
24436
+ "_x.ai/scheduled_task_deleted"
24437
+ ];
24438
+ var BACKGROUND_SESSION_UPDATES = /* @__PURE__ */ new Set([
24439
+ "task_backgrounded",
24440
+ "task_completed",
24441
+ "monitor_event",
24442
+ "scheduled_task_created",
24443
+ "scheduled_task_fired",
24444
+ "scheduled_task_deleted"
24445
+ ]);
24446
+ function isRecord11(value) {
24447
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24448
+ }
24449
+ function firstPresent2(record3, keys) {
24450
+ for (const key of keys) {
24451
+ if (record3[key] !== void 0)
24452
+ return record3[key];
24453
+ }
24454
+ return void 0;
24455
+ }
24456
+ function stringField4(record3, keys) {
24457
+ const value = firstPresent2(record3, keys);
24458
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
24459
+ }
24460
+ function optionalString(record3, keys) {
24461
+ const value = firstPresent2(record3, keys);
24462
+ return typeof value === "string" && value.length > 0 ? value : void 0;
24463
+ }
24464
+ function numberField2(record3, keys) {
24465
+ const value = firstPresent2(record3, keys);
24466
+ if (value === null)
24467
+ return null;
24468
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
24469
+ }
24470
+ function booleanField(record3, keys) {
24471
+ const value = firstPresent2(record3, keys);
24472
+ return typeof value === "boolean" ? value : void 0;
24473
+ }
24474
+ function snapshotRecord(value) {
24475
+ if (!isRecord11(value))
24476
+ return void 0;
24477
+ const nested = value.task_snapshot ?? value.taskSnapshot;
24478
+ return isRecord11(nested) ? nested : value;
24479
+ }
24480
+ function backgroundKind(value, monitorDescription) {
24481
+ if (monitorDescription)
24482
+ return "monitor";
24483
+ if (typeof value === "string" && value.toLowerCase() === "monitor")
24484
+ return "monitor";
24485
+ return "run";
24486
+ }
24487
+ function isGrokBackgroundNotificationMethod(method) {
24488
+ return GROK_BACKGROUND_NOTIFICATION_METHODS.includes(method);
24489
+ }
24490
+ function fields(value) {
24491
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0));
24492
+ }
24493
+ function grokBackgroundEventFromUpdate(update) {
24494
+ if (!isRecord11(update) || typeof update.sessionUpdate !== "string" || !BACKGROUND_SESSION_UPDATES.has(update.sessionUpdate))
24495
+ return null;
24496
+ const taskId = stringField4(update, ["task_id", "taskId"]);
24497
+ if (update.sessionUpdate === "task_backgrounded") {
24498
+ const toolCallId = stringField4(update, ["tool_call_id", "toolCallId"]);
24499
+ const command = stringField4(update, ["command"]);
24500
+ if (!taskId || !toolCallId || !command)
24501
+ return null;
24502
+ const monitorDescription = optionalString(update, [
24503
+ "monitor_description",
24504
+ "monitorDescription"
24505
+ ]);
24506
+ return {
24507
+ type: "task.backgrounded",
24508
+ taskId,
24509
+ toolCallId,
24510
+ command,
24511
+ kind: backgroundKind(void 0, monitorDescription),
24512
+ ...fields({
24513
+ cwd: optionalString(update, ["cwd"]),
24514
+ outputFile: optionalString(update, ["output_file", "outputFile"]),
24515
+ description: monitorDescription ?? optionalString(update, ["description"])
24516
+ })
24517
+ };
24518
+ }
24519
+ if (update.sessionUpdate === "task_completed") {
24520
+ const snapshot = snapshotRecord(firstPresent2(update, ["task_snapshot", "taskSnapshot"]) ?? update);
24521
+ const id = snapshot && stringField4(snapshot, ["task_id", "taskId"]);
24522
+ if (!snapshot || !id)
24523
+ return null;
24524
+ return {
24525
+ type: "task.completed",
24526
+ taskId: id,
24527
+ kind: backgroundKind(snapshot.kind),
24528
+ ...fields({
24529
+ command: optionalString(snapshot, ["command"]),
24530
+ description: optionalString(snapshot, ["description", "display_command", "displayCommand"]),
24531
+ output: optionalString(snapshot, ["output"]),
24532
+ outputFile: optionalString(snapshot, ["output_file", "outputFile"]),
24533
+ truncated: booleanField(snapshot, ["truncated"]),
24534
+ exitCode: numberField2(snapshot, ["exit_code", "exitCode"]),
24535
+ signal: optionalString(snapshot, ["signal"]),
24536
+ explicitlyKilled: booleanField(snapshot, ["explicitly_killed", "explicitlyKilled"])
24537
+ })
24538
+ };
24539
+ }
24540
+ if (!taskId)
24541
+ return null;
24542
+ if (update.sessionUpdate === "monitor_event") {
24543
+ const text = optionalString(update, ["event_text", "eventText"]);
24544
+ return text === void 0 ? null : {
24545
+ type: "monitor.event",
24546
+ taskId,
24547
+ text,
24548
+ ...fields({ description: optionalString(update, ["description"]) })
24549
+ };
24550
+ }
24551
+ if (update.sessionUpdate === "scheduled_task_created" || update.sessionUpdate === "scheduled_task_fired") {
24552
+ const prompt = optionalString(update, ["prompt"]);
24553
+ const humanSchedule = optionalString(update, ["human_schedule", "humanSchedule"]);
24554
+ if (prompt === void 0 || !humanSchedule)
24555
+ return null;
24556
+ const next = optionalString(update, ["next_fire_at", "nextFireAt"]);
24557
+ const common = {
24558
+ taskId,
24559
+ prompt,
24560
+ humanSchedule,
24561
+ ...fields({ nextFireAt: next && Number.isFinite(Date.parse(next)) ? next : void 0 })
24562
+ };
24563
+ return update.sessionUpdate === "scheduled_task_created" ? { type: "scheduled.created", ...common } : {
24564
+ type: "scheduled.fired",
24565
+ ...common,
24566
+ ...fields({ subagentId: stringField4(update, ["subagent_id", "subagentId"]) })
24567
+ };
24568
+ }
24569
+ if (update.sessionUpdate === "scheduled_task_deleted")
24570
+ return {
24571
+ type: "scheduled.deleted",
24572
+ taskId,
24573
+ ...fields({ reason: optionalString(update, ["reason"]) })
24574
+ };
24575
+ return null;
24576
+ }
24577
+ function grokToolIsBackgrounded(rawOutput, rawInput) {
24578
+ const exitCode = isRecord11(rawOutput) ? numberField2(rawOutput, ["exit_code", "exitCode"]) : void 0;
24579
+ if (exitCode !== void 0 && exitCode !== null)
24580
+ return false;
24581
+ if (isRecord11(rawOutput) && optionalString(rawOutput, ["signal"]) === "backgrounded")
24582
+ return true;
24583
+ if (grokBackgroundTaskId(rawOutput, rawInput))
24584
+ return true;
24585
+ return Boolean(isRecord11(rawInput) && (rawInput.background === true || rawInput.is_background === true));
24586
+ }
24587
+ function grokBackgroundTaskId(rawOutput, rawInput) {
24588
+ if (isRecord11(rawOutput)) {
24589
+ const id = stringField4(rawOutput, ["task_id", "taskId"]);
24590
+ if (id)
24591
+ return id;
24592
+ }
24593
+ if (isRecord11(rawInput))
24594
+ return stringField4(rawInput, ["task_id", "taskId"]);
24595
+ return void 0;
24596
+ }
24597
+ function grokBackgroundCompletionOutcome(event) {
24598
+ if (event.explicitlyKilled || event.signal === "killed" || event.signal === "session_restart") {
24599
+ return { status: "cancelled", reason: "Background command stopped" };
24600
+ }
24601
+ if (event.exitCode === 0) {
24602
+ return { status: "succeeded" };
24603
+ }
24604
+ return {
24605
+ status: "failed",
24606
+ error: {
24607
+ code: "nativeFailure",
24608
+ message: event.signal ? `Grok background command ended with signal ${event.signal}` : `Grok background command exited ${event.exitCode}`,
24609
+ retryable: false
24610
+ }
24611
+ };
24612
+ }
24613
+ function applyGrokScheduledEvent(loops, event, observedIds) {
24614
+ observedIds?.add(event.taskId);
24615
+ if (event.type === "scheduled.deleted") {
24616
+ loops.delete(event.taskId);
24617
+ return;
24618
+ }
24619
+ const current = loops.get(event.taskId);
24620
+ loops.set(event.taskId, {
24621
+ taskId: event.taskId,
24622
+ prompt: event.prompt,
24623
+ humanSchedule: event.humanSchedule,
24624
+ ...event.nextFireAt ? { nextFireAt: event.nextFireAt } : {},
24625
+ ...event.type === "scheduled.fired" && event.subagentId ? { lastSubagentId: event.subagentId } : current?.lastSubagentId ? { lastSubagentId: current.lastSubagentId } : {}
24626
+ });
24627
+ }
24628
+ function collectGrokScheduledLoops(events) {
24629
+ const loops = /* @__PURE__ */ new Map();
24630
+ for (const event of events) {
24631
+ if (event.type === "scheduled.created" || event.type === "scheduled.fired" || event.type === "scheduled.deleted") {
24632
+ applyGrokScheduledEvent(loops, event);
24633
+ }
24634
+ }
24635
+ return loops;
24636
+ }
24637
+
24376
24638
  // dist/grok-manual-compaction.js
24377
24639
  var GROK_COMPACT_CONVERSATION_METHOD = "x.ai/compact_conversation";
24378
24640
  var GROK_COMPACT_CONVERSATION_FALLBACK_METHOD = "_x.ai/compact_conversation";
24379
- function isRecord11(value) {
24641
+ function isRecord12(value) {
24380
24642
  return typeof value === "object" && value !== null && !Array.isArray(value);
24381
24643
  }
24382
24644
  function optionalNonNegativeInt2(value) {
@@ -24388,7 +24650,7 @@ function optionalErrorMessage2(value) {
24388
24650
  function parseGrokCompactResult(value, cancelled = false) {
24389
24651
  if (cancelled)
24390
24652
  return { outcome: "cancelled" };
24391
- if (!isRecord11(value))
24653
+ if (!isRecord12(value))
24392
24654
  return { outcome: "succeeded" };
24393
24655
  const tokensBefore = optionalNonNegativeInt2(value.tokensBefore ?? value.tokens_before);
24394
24656
  const tokensAfter = optionalNonNegativeInt2(value.tokensAfter ?? value.tokens_after);
@@ -24426,7 +24688,7 @@ var GROK_REWIND_EXECUTE_METHOD = "_x.ai/rewind/execute";
24426
24688
  function error52(code, message, retryable = false) {
24427
24689
  return { code, message, retryable };
24428
24690
  }
24429
- function isRecord12(value) {
24691
+ function isRecord13(value) {
24430
24692
  return typeof value === "object" && value !== null && !Array.isArray(value);
24431
24693
  }
24432
24694
  function buildGrokRewindParams(input) {
@@ -24438,10 +24700,10 @@ function buildGrokRewindParams(input) {
24438
24700
  };
24439
24701
  }
24440
24702
  function parseGrokRewindResponse(value) {
24441
- if (!isRecord12(value))
24703
+ if (!isRecord13(value))
24442
24704
  return null;
24443
- const payload = typeof value.success !== "boolean" && isRecord12(value.result) ? value.result : value;
24444
- if (!isRecord12(payload) || typeof payload.success !== "boolean")
24705
+ const payload = typeof value.success !== "boolean" && isRecord13(value.result) ? value.result : value;
24706
+ if (!isRecord13(payload) || typeof payload.success !== "boolean")
24445
24707
  return null;
24446
24708
  return rewindPayload(payload);
24447
24709
  }
@@ -24607,14 +24869,14 @@ var GROK_CLOCK_ELICIT_PERSIST_FIXTURE = {
24607
24869
  ...GROK_CLOCK_ELICIT_FIXTURE,
24608
24870
  persist: ["session", "always"]
24609
24871
  };
24610
- function isRecord13(value) {
24872
+ function isRecord14(value) {
24611
24873
  return typeof value === "object" && value !== null && !Array.isArray(value);
24612
24874
  }
24613
24875
  function nonEmptyString(value) {
24614
24876
  return typeof value === "string" && value.trim().length > 0 ? value : void 0;
24615
24877
  }
24616
- function hasOnlyKeys(record2, allowed) {
24617
- return Object.keys(record2).every((key) => allowed.has(key));
24878
+ function hasOnlyKeys(record3, allowed) {
24879
+ return Object.keys(record3).every((key) => allowed.has(key));
24618
24880
  }
24619
24881
  function clampText(value, max) {
24620
24882
  return value.length <= max ? value : value.slice(0, max);
@@ -24648,11 +24910,11 @@ function parsePersistOffer(value) {
24648
24910
  return out.length > 0 ? out : "invalid";
24649
24911
  }
24650
24912
  function schemaIsSupportedEmptyObject(schema) {
24651
- if (!isRecord13(schema) || !hasOnlyKeys(schema, SCHEMA_KEYS) || schema.type !== "object") {
24913
+ if (!isRecord14(schema) || !hasOnlyKeys(schema, SCHEMA_KEYS) || schema.type !== "object") {
24652
24914
  return false;
24653
24915
  }
24654
24916
  if (schema.properties !== void 0) {
24655
- if (!isRecord13(schema.properties) || Object.keys(schema.properties).length !== 0)
24917
+ if (!isRecord14(schema.properties) || Object.keys(schema.properties).length !== 0)
24656
24918
  return false;
24657
24919
  }
24658
24920
  if (schema.required !== void 0) {
@@ -24662,7 +24924,7 @@ function schemaIsSupportedEmptyObject(schema) {
24662
24924
  return true;
24663
24925
  }
24664
24926
  function parseGrokMcpElicitParams(params) {
24665
- if (!isRecord13(params))
24927
+ if (!isRecord14(params))
24666
24928
  return { status: "invalid", message: "elicitation params must be an object" };
24667
24929
  const sessionId = nonEmptyString(params.sessionId);
24668
24930
  const toolCallId = nonEmptyString(params.toolCallId);
@@ -24690,7 +24952,7 @@ function parseGrokMcpElicitParams(params) {
24690
24952
  return { status: "invalid", message: "form elicitation contains unreviewed fields" };
24691
24953
  }
24692
24954
  if (params.requestedSchema !== void 0) {
24693
- if (!isRecord13(params.requestedSchema)) {
24955
+ if (!isRecord14(params.requestedSchema)) {
24694
24956
  return { status: "invalid", message: "requestedSchema must be an object" };
24695
24957
  }
24696
24958
  if (!schemaIsSupportedEmptyObject(params.requestedSchema))
@@ -24757,7 +25019,7 @@ function projectGrokMcpElicitApproval(input) {
24757
25019
  };
24758
25020
  }
24759
25021
  function grokElicitationResolvedToolCallId(update) {
24760
- if (!isRecord13(update) || update.sessionUpdate !== "interaction_resolved")
25022
+ if (!isRecord14(update) || update.sessionUpdate !== "interaction_resolved")
24761
25023
  return void 0;
24762
25024
  return nonEmptyString(update.tool_call_id) ?? nonEmptyString(update.toolCallId);
24763
25025
  }
@@ -24887,19 +25149,19 @@ var GrokPermissionConfirmation = class {
24887
25149
  // dist/grok-questions.js
24888
25150
  var GROK_ASK_USER_QUESTION_METHOD = "_x.ai/ask_user_question";
24889
25151
  var GROK_QUESTION_ACTIVITY_METHOD = "_x.ai/ask_user_question_activity";
24890
- function isRecord14(value) {
25152
+ function isRecord15(value) {
24891
25153
  return typeof value === "object" && value !== null && !Array.isArray(value);
24892
25154
  }
24893
25155
  function nonEmptyString2(value) {
24894
25156
  return typeof value === "string" && value.trim().length > 0;
24895
25157
  }
24896
25158
  function parseGrokQuestionRequest(value) {
24897
- if (!isRecord14(value) || !nonEmptyString2(value.sessionId) || !nonEmptyString2(value.toolCallId) || value.mode !== "default" && value.mode !== "plan" || !Array.isArray(value.questions) || value.questions.length === 0) {
25159
+ if (!isRecord15(value) || !nonEmptyString2(value.sessionId) || !nonEmptyString2(value.toolCallId) || value.mode !== "default" && value.mode !== "plan" || !Array.isArray(value.questions) || value.questions.length === 0) {
24898
25160
  throw new Error("Grok question requires sessionId, toolCallId, mode and nonempty questions");
24899
25161
  }
24900
25162
  const seen = /* @__PURE__ */ new Set();
24901
25163
  const questions = value.questions.map((question) => {
24902
- if (!isRecord14(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") {
25164
+ if (!isRecord15(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") {
24903
25165
  throw new Error("Grok question text must be unique and options/multiSelect must be valid");
24904
25166
  }
24905
25167
  if (question.multiSelect != null && question.multi_select != null && question.multiSelect !== question.multi_select)
@@ -24907,7 +25169,7 @@ function parseGrokQuestionRequest(value) {
24907
25169
  seen.add(question.question);
24908
25170
  const labels = /* @__PURE__ */ new Set();
24909
25171
  const options = question.options.map((option) => {
24910
- if (!isRecord14(option) || !nonEmptyString2(option.label) || labels.has(option.label) || typeof option.description !== "string" || option.preview != null && typeof option.preview !== "string") {
25172
+ if (!isRecord15(option) || !nonEmptyString2(option.label) || labels.has(option.label) || typeof option.description !== "string" || option.preview != null && typeof option.preview !== "string") {
24911
25173
  throw new Error("Grok question options require unique labels and text descriptions/previews");
24912
25174
  }
24913
25175
  labels.add(option.label);
@@ -25078,8 +25340,8 @@ function parseGrokInterjectResult(value) {
25078
25340
  return { status: "queued" };
25079
25341
  if (typeof value !== "object" || Array.isArray(value))
25080
25342
  return null;
25081
- const record2 = value;
25082
- const nested = record2.status === void 0 && typeof record2.result === "object" && record2.result !== null ? record2.result : record2;
25343
+ const record3 = value;
25344
+ const nested = record3.status === void 0 && typeof record3.result === "object" && record3.result !== null ? record3.result : record3;
25083
25345
  const status2 = nested.status ?? nested.ok;
25084
25346
  if (status2 === void 0 || status2 === "queued" || status2 === true)
25085
25347
  return { status: "queued" };
@@ -25097,16 +25359,16 @@ var GrokTransportError = class extends Error {
25097
25359
  this.name = "GrokTransportError";
25098
25360
  }
25099
25361
  };
25100
- function isRecord15(value) {
25362
+ function isRecord16(value) {
25101
25363
  return typeof value === "object" && value !== null && !Array.isArray(value);
25102
25364
  }
25103
25365
  function acpToolName(update, metadata) {
25104
- if (!isRecord15(update))
25366
+ if (!isRecord16(update))
25105
25367
  return void 0;
25106
25368
  if (typeof update.name === "string" && update.name.length > 0)
25107
25369
  return update.name;
25108
- const meta3 = isRecord15(update._meta) ? update._meta : metadata;
25109
- const tool = meta3 && isRecord15(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
25370
+ const meta3 = isRecord16(update._meta) ? update._meta : metadata;
25371
+ const tool = meta3 && isRecord16(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
25110
25372
  return tool && typeof tool.name === "string" && tool.name.length > 0 ? tool.name : void 0;
25111
25373
  }
25112
25374
  function errorText(error53) {
@@ -25162,14 +25424,14 @@ function signalProcessTree(child, signal) {
25162
25424
  try {
25163
25425
  process.kill(-child.pid, signal);
25164
25426
  } catch (error53) {
25165
- if (!isRecord15(error53) || error53.code !== "ESRCH")
25427
+ if (!isRecord16(error53) || error53.code !== "ESRCH")
25166
25428
  throw error53;
25167
25429
  }
25168
25430
  }
25169
25431
  function grokNotificationMetadata(envelope, update) {
25170
- if (!isRecord15(envelope) && !isRecord15(update))
25432
+ if (!isRecord16(envelope) && !isRecord16(update))
25171
25433
  return void 0;
25172
- return { ...isRecord15(update) ? update : {}, ...isRecord15(envelope) ? envelope : {} };
25434
+ return { ...isRecord16(update) ? update : {}, ...isRecord16(envelope) ? envelope : {} };
25173
25435
  }
25174
25436
  function transportEvent(update, metadata) {
25175
25437
  const extension = update;
@@ -25211,6 +25473,9 @@ function transportEvent(update, metadata) {
25211
25473
  const compaction = grokCompactionEventFromUpdate(extension);
25212
25474
  if (compaction)
25213
25475
  return compaction;
25476
+ const background = grokBackgroundEventFromUpdate(extension);
25477
+ if (background)
25478
+ return { ...background, ...metadata ? { metadata } : {} };
25214
25479
  const subagent = grokSubagentEventFromUpdate(extension);
25215
25480
  if (subagent)
25216
25481
  return subagent;
@@ -25289,7 +25554,7 @@ async function readNativeSignals(options, sessionId) {
25289
25554
  }
25290
25555
  }
25291
25556
  function isMissingFile(error53) {
25292
- return isRecord15(error53) && error53.code === "ENOENT";
25557
+ return isRecord16(error53) && error53.code === "ENOENT";
25293
25558
  }
25294
25559
  async function locateGrokNativeSession(options, sessionId) {
25295
25560
  if (sessionId.length === 0)
@@ -25312,7 +25577,7 @@ async function locateGrokNativeSession(options, sessionId) {
25312
25577
  try {
25313
25578
  summaryRaw = await readFile5(path16.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
25314
25579
  } catch (error53) {
25315
- if (isMissingFile(error53) || isRecord15(error53) && error53.code === "ENOTDIR")
25580
+ if (isMissingFile(error53) || isRecord16(error53) && error53.code === "ENOTDIR")
25316
25581
  continue;
25317
25582
  throw new GrokTransportError("unavailable", "Grok Native Session metadata could not be read", {
25318
25583
  cause: error53
@@ -25324,10 +25589,10 @@ async function locateGrokNativeSession(options, sessionId) {
25324
25589
  } catch {
25325
25590
  continue;
25326
25591
  }
25327
- if (!isRecord15(parsed))
25592
+ if (!isRecord16(parsed))
25328
25593
  continue;
25329
25594
  const info = parsed.info;
25330
- const cwd = isRecord15(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path16.resolve(info.cwd) : path16.resolve(decodeURIComponent(entry.name));
25595
+ const cwd = isRecord16(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path16.resolve(info.cwd) : path16.resolve(decodeURIComponent(entry.name));
25331
25596
  const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path16.resolve(parsed.source_workspace_dir) : void 0;
25332
25597
  matches.push({
25333
25598
  cwd,
@@ -25354,20 +25619,20 @@ function parseNativeHistory(contents, sessionId) {
25354
25619
  for (const line of contents.split("\n")) {
25355
25620
  if (line.length === 0)
25356
25621
  continue;
25357
- let record2;
25622
+ let record3;
25358
25623
  try {
25359
- record2 = JSON.parse(line);
25624
+ record3 = JSON.parse(line);
25360
25625
  } catch {
25361
25626
  throw new GrokTransportError("protocolError", "Grok Native history contains invalid JSON");
25362
25627
  }
25363
- if (!isRecord15(record2) || !isRecord15(record2.params))
25628
+ if (!isRecord16(record3) || !isRecord16(record3.params))
25364
25629
  continue;
25365
- const params = record2.params;
25366
- if (params.sessionId !== sessionId || !isRecord15(params.update))
25630
+ const params = record3.params;
25631
+ if (params.sessionId !== sessionId || !isRecord16(params.update))
25367
25632
  continue;
25368
25633
  let metadata = grokNotificationMetadata(params._meta, params.update._meta);
25369
- if (typeof record2.timestamp === "number" && Number.isFinite(record2.timestamp))
25370
- metadata = { nativeTimestampMs: record2.timestamp * 1e3, ...metadata };
25634
+ if (typeof record3.timestamp === "number" && Number.isFinite(record3.timestamp))
25635
+ metadata = { nativeTimestampMs: record3.timestamp * 1e3, ...metadata };
25371
25636
  const event = transportEvent(params.update, metadata);
25372
25637
  if (event)
25373
25638
  events.push(metadata ? { ...event, metadata } : event);
@@ -25433,7 +25698,7 @@ var GrokAcpTransport = class {
25433
25698
  if (!this.#connection)
25434
25699
  throw new GrokTransportError("unavailable", "Grok ACP is unavailable");
25435
25700
  const result = await withTimeout(this.#connection.request("_x.ai/session/usage", { sessionId: this.sessionId }), this.#options.commandTimeoutMs, "Grok Session usage");
25436
- return isRecord15(result) ? result.usage : void 0;
25701
+ return isRecord16(result) ? result.usage : void 0;
25437
25702
  }
25438
25703
  async readHistory(sessionId, cwd = this.#options.cwd) {
25439
25704
  return readGrokNativeHistory({ ...this.#options, cwd }, sessionId);
@@ -25538,7 +25803,7 @@ var GrokAcpTransport = class {
25538
25803
  sessionId: this.#sessionId,
25539
25804
  toolCallId
25540
25805
  }), 3e3, "Grok question activity");
25541
- if (!isRecord15(raw) || !("timeout" in raw))
25806
+ if (!isRecord16(raw) || !("timeout" in raw))
25542
25807
  throw new GrokTransportError("protocolError", "Invalid Grok activity acknowledgement");
25543
25808
  return raw.timeout === null ? null : questionAutoResolutionSchema.parse(raw.timeout);
25544
25809
  } catch (error53) {
@@ -25810,7 +26075,7 @@ var GrokAcpTransport = class {
25810
26075
  }
25811
26076
  } : {}
25812
26077
  });
25813
- if (!isRecord15(response) || !isRecord15(response._meta) || !isRecord15(response._meta.model)) {
26078
+ if (!isRecord16(response) || !isRecord16(response._meta) || !isRecord16(response._meta.model)) {
25814
26079
  throw new GrokTransportError("protocolError", "Grok rejected Model configuration");
25815
26080
  }
25816
26081
  const selected = response._meta.model.Ok;
@@ -25850,7 +26115,7 @@ var GrokAcpTransport = class {
25850
26115
  permission_mode: mode
25851
26116
  });
25852
26117
  const response = await connection.request("_x.ai/session/info", { sessionId });
25853
- if (!isRecord15(response) || !isRecord15(response.result) || response.result.sessionId !== sessionId) {
26118
+ if (!isRecord16(response) || !isRecord16(response.result) || response.result.sessionId !== sessionId) {
25854
26119
  throw new Error("Grok did not confirm the target Session");
25855
26120
  }
25856
26121
  })()
@@ -25922,12 +26187,62 @@ var GrokAcpTransport = class {
25922
26187
  this.#background?.onEvent(enriched);
25923
26188
  }
25924
26189
  #handleExtensionNotification(method, params) {
25925
- if (!isGrokExtensionSessionUpdateMethod(method))
26190
+ if (!isGrokExtensionSessionUpdateMethod(method) && !isGrokBackgroundNotificationMethod(method)) {
25926
26191
  return;
25927
- if (typeof params.sessionId !== "string" || !isRecord15(params.update))
26192
+ }
26193
+ if (typeof params.sessionId !== "string" || !isRecord16(params.update))
25928
26194
  return;
25929
26195
  this.#handleUpdate(params);
25930
26196
  }
26197
+ async killTask(taskId, source = "clientUi") {
26198
+ const result = await this.#extResult(GROK_TASK_KILL_METHOD, {
26199
+ sessionId: this.sessionId,
26200
+ taskId,
26201
+ source
26202
+ });
26203
+ if (!isRecord16(result) || result.taskId !== taskId || !["killed", "already_exited", "not_found"].includes(String(result.outcome)))
26204
+ throw new GrokTransportError("protocolError", "Malformed Grok task kill response");
26205
+ return result.outcome;
26206
+ }
26207
+ async listTasks() {
26208
+ return this.#extResult(GROK_TASK_LIST_METHOD, { sessionId: this.sessionId });
26209
+ }
26210
+ async getSubagent(id) {
26211
+ return this.#extResult("x.ai/subagent/get", { subagentId: id, block: false });
26212
+ }
26213
+ async deleteScheduledTask(taskId) {
26214
+ const result = await this.#extResult(GROK_SCHEDULER_DELETE_METHOD, {
26215
+ sessionId: this.sessionId,
26216
+ taskId
26217
+ });
26218
+ if (!isRecord16(result) || result.taskId !== taskId || typeof result.deleted !== "boolean")
26219
+ throw new GrokTransportError("protocolError", "Malformed Grok scheduler delete response");
26220
+ return result.deleted;
26221
+ }
26222
+ async #extResult(method, params) {
26223
+ if (!this.#connection || !this.#sessionId || this.#closed || this.#closing) {
26224
+ throw new GrokTransportError("unavailable", "Grok ACP Session is unavailable");
26225
+ }
26226
+ let raw;
26227
+ try {
26228
+ raw = await withTimeout(this.#connection.request(method, params), this.#options.commandTimeoutMs, `Grok ${method}`);
26229
+ } catch (error53) {
26230
+ if (!isRecord16(error53) || error53.code !== -32601)
26231
+ throw error53;
26232
+ try {
26233
+ raw = await withTimeout(this.#connection.request(`_${method}`, params), this.#options.commandTimeoutMs, `Grok _${method}`);
26234
+ } catch (fallback) {
26235
+ if (isRecord16(fallback) && fallback.code === -32601)
26236
+ throw new GrokTransportError("unsupported", `Grok does not support ${method}`);
26237
+ throw fallback;
26238
+ }
26239
+ }
26240
+ if (isRecord16(raw) && raw.error !== void 0 && raw.error !== null) {
26241
+ const message = typeof raw.error === "string" ? raw.error : isRecord16(raw.error) && typeof raw.error.message === "string" ? raw.error.message : `Grok ${method} failed`;
26242
+ throw new GrokTransportError("unavailable", message);
26243
+ }
26244
+ return isRecord16(raw) && "result" in raw ? raw.result : raw;
26245
+ }
25931
26246
  #handlePermission(params) {
25932
26247
  const observer = this.#activePrompt ?? this.#background;
25933
26248
  if (params.sessionId !== this.#sessionId || !observer) {
@@ -26098,7 +26413,7 @@ var SessionImportScope = class {
26098
26413
  // dist/session-import.js
26099
26414
  var MAX_METADATA_BYTES = 4 * 1024 * 1024;
26100
26415
  var SUBAGENT_SESSION_KINDS = /* @__PURE__ */ new Set(["subagent", "subagent_resume"]);
26101
- function isRecord16(value) {
26416
+ function isRecord17(value) {
26102
26417
  return typeof value === "object" && value !== null && !Array.isArray(value);
26103
26418
  }
26104
26419
  async function readJson(file2, signal) {
@@ -26111,7 +26426,7 @@ function processAlive(pid) {
26111
26426
  process.kill(pid, 0);
26112
26427
  return true;
26113
26428
  } catch (error53) {
26114
- return isRecord16(error53) && error53.code === "EPERM";
26429
+ return isRecord17(error53) && error53.code === "EPERM";
26115
26430
  }
26116
26431
  }
26117
26432
  async function firstUserText(file2, signal) {
@@ -26128,10 +26443,10 @@ async function firstUserText(file2, signal) {
26128
26443
  } catch {
26129
26444
  continue;
26130
26445
  }
26131
- const update = isRecord16(entry) && isRecord16(entry.params) ? entry.params.update : null;
26132
- if (!isRecord16(update) || update.sessionUpdate !== "user_message_chunk")
26446
+ const update = isRecord17(entry) && isRecord17(entry.params) ? entry.params.update : null;
26447
+ if (!isRecord17(update) || update.sessionUpdate !== "user_message_chunk")
26133
26448
  continue;
26134
- const text = isRecord16(update.content) ? update.content.text : null;
26449
+ const text = isRecord17(update.content) ? update.content.text : null;
26135
26450
  return typeof text === "string" ? text : "";
26136
26451
  }
26137
26452
  return null;
@@ -26208,7 +26523,7 @@ var GrokSessionImport = class {
26208
26523
  if (!Array.isArray(entries))
26209
26524
  return active;
26210
26525
  for (const entry of entries) {
26211
- if (isRecord16(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
26526
+ if (isRecord17(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
26212
26527
  active.add(entry.session_id);
26213
26528
  }
26214
26529
  return active;
@@ -26257,7 +26572,7 @@ var GrokSessionImport = class {
26257
26572
  return null;
26258
26573
  try {
26259
26574
  const summary = await readJson(files[0], signal);
26260
- if (!isRecord16(summary) || !isRecord16(summary.info) || summary.info.id !== nativeSessionId)
26575
+ if (!isRecord17(summary) || !isRecord17(summary.info) || summary.info.id !== nativeSessionId)
26261
26576
  return null;
26262
26577
  if (typeof summary.session_kind === "string" && SUBAGENT_SESSION_KINDS.has(summary.session_kind))
26263
26578
  return null;
@@ -26508,8 +26823,488 @@ var GrokSubagentLifecycle = class {
26508
26823
  }
26509
26824
  };
26510
26825
 
26826
+ // dist/grok-activity.js
26827
+ import { readFile as readFile7 } from "node:fs/promises";
26828
+ import path18 from "node:path";
26829
+ var record2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
26830
+ var fail = (code, message) => ({ ok: false, error: { code, message, retryable: false } });
26831
+ function parseGrokTaskList(value, sessionId) {
26832
+ if (!record2(value) || !Array.isArray(value.tasks))
26833
+ throw new Error("Malformed Grok task list");
26834
+ return value.tasks.map((entry) => {
26835
+ if (!record2(entry) || typeof entry.task_id !== "string" || typeof entry.command !== "string" || typeof entry.output !== "string" || typeof entry.completed !== "boolean" || typeof entry.truncated !== "boolean")
26836
+ throw new Error("Malformed Grok task snapshot");
26837
+ return entry;
26838
+ }).filter((entry) => (!entry.owner_session_id || entry.owner_session_id === sessionId) && entry.is_backgrounded === true);
26839
+ }
26840
+ async function readGrokScheduledLoops(directory) {
26841
+ let raw;
26842
+ try {
26843
+ raw = JSON.parse(await readFile7(path18.join(directory, "resources_state.json"), "utf8"));
26844
+ } catch (error53) {
26845
+ if (error53.code === "ENOENT")
26846
+ return null;
26847
+ throw error53;
26848
+ }
26849
+ if (!record2(raw) || !record2(raw.state))
26850
+ throw new Error("Malformed Grok resource state");
26851
+ const scheduler = raw.state["grok_build.Scheduler"];
26852
+ if (scheduler === void 0)
26853
+ return /* @__PURE__ */ new Map();
26854
+ if (!record2(scheduler) || !Array.isArray(scheduler.tasks))
26855
+ throw new Error("Malformed Grok scheduler state");
26856
+ const loops = /* @__PURE__ */ new Map();
26857
+ for (const task of scheduler.tasks) {
26858
+ if (!record2(task) || typeof task.id !== "string" || typeof task.prompt !== "string" || typeof task.intervalSecs !== "number" || task.intervalSecs <= 0)
26859
+ throw new Error("Malformed Grok scheduled task");
26860
+ const anchor = typeof task.lastFiredAt === "string" ? task.lastFiredAt : task.createdAt;
26861
+ const next = typeof anchor === "string" ? Date.parse(anchor) + task.intervalSecs * 1e3 : NaN;
26862
+ loops.set(task.id, {
26863
+ taskId: task.id,
26864
+ prompt: task.prompt,
26865
+ humanSchedule: `every ${task.intervalSecs} seconds`,
26866
+ ...(task.recurring !== false || task.lastFiredAt == null) && (typeof task.expiresAt !== "string" || Date.parse(task.expiresAt) > Date.now()) && Number.isFinite(next) ? { nextFireAt: new Date(next).toISOString() } : {},
26867
+ ...typeof task.lastSubagentId === "string" ? { lastSubagentId: task.lastSubagentId } : {}
26868
+ });
26869
+ }
26870
+ return loops;
26871
+ }
26872
+ function createGrokActivity(options) {
26873
+ let tasks = [];
26874
+ const summaries = () => [
26875
+ ...tasks.map((task) => {
26876
+ const commandItemId = options.commandItemId?.(task.task_id);
26877
+ return {
26878
+ id: `task:${task.task_id}`,
26879
+ kind: task.kind === "monitor" ? "monitor" : "task",
26880
+ label: task.description ?? task.command,
26881
+ status: !task.completed ? "running" : task.explicitly_killed ? "cancelled" : task.exit_code === 0 ? "completed" : task.exit_code != null || task.signal ? "failed" : "unknown",
26882
+ canStop: !task.completed && Boolean(options.killTask),
26883
+ ...commandItemId ? { commandItemId } : {}
26884
+ };
26885
+ }),
26886
+ ...[...options.loops.values()].map((loop) => ({
26887
+ id: `loop:${loop.taskId}`,
26888
+ kind: "loop",
26889
+ label: loop.prompt,
26890
+ status: "scheduled",
26891
+ canStop: Boolean(options.deleteLoop),
26892
+ schedule: loop.humanSchedule,
26893
+ ...loop.nextFireAt ? { nextRunAt: loop.nextFireAt } : {},
26894
+ ...loop.lastSubagentId ? { relatedActivityId: `subagent:${loop.lastSubagentId}` } : {}
26895
+ })),
26896
+ ...[...options.children.values()].map((child) => ({
26897
+ id: `subagent:${child.nativeSubagentId}`,
26898
+ kind: "subagent",
26899
+ label: child.description,
26900
+ status: child.status === "pending" || child.status === "running" ? "running" : child.status === "interrupted" ? "cancelled" : child.status,
26901
+ canStop: false
26902
+ }))
26903
+ ];
26904
+ const capability = {
26905
+ subagents: () => [...options.children.values()].map((state) => ({
26906
+ activityId: `subagent:${state.nativeSubagentId}`,
26907
+ state
26908
+ })),
26909
+ async list() {
26910
+ if (!options.isOpen())
26911
+ return fail("nativeFailure", "Grok Session is closed");
26912
+ try {
26913
+ const loops = await readGrokScheduledLoops(options.directory);
26914
+ if (!options.isOpen())
26915
+ return fail("nativeFailure", "Grok Session changed");
26916
+ if (loops) {
26917
+ for (const id of options.loops.keys())
26918
+ if (!options.observedLoopIds.has(id) && !loops.has(id))
26919
+ options.loops.delete(id);
26920
+ for (const [id, loop] of loops)
26921
+ if (!options.observedLoopIds.has(id))
26922
+ options.loops.set(id, loop);
26923
+ }
26924
+ for (const loop of options.loops.values()) {
26925
+ if (loop.lastSubagentId && !options.children.has(loop.lastSubagentId))
26926
+ options.children.set(loop.lastSubagentId, {
26927
+ subagentId: loop.lastSubagentId,
26928
+ nativeSubagentId: loop.lastSubagentId,
26929
+ description: loop.prompt,
26930
+ background: true,
26931
+ status: "pending"
26932
+ });
26933
+ }
26934
+ if (options.listTasks) {
26935
+ const nativeTasks = parseGrokTaskList(await options.listTasks(), options.sessionId);
26936
+ if (!options.isOpen())
26937
+ return fail("nativeFailure", "Grok Session changed");
26938
+ tasks = nativeTasks;
26939
+ options.observeTasks?.(tasks);
26940
+ }
26941
+ if (options.getChild)
26942
+ for (const [id, child] of options.children) {
26943
+ if (child.status !== "running" && child.status !== "pending")
26944
+ continue;
26945
+ const raw = await options.getChild(id);
26946
+ if (!options.isOpen())
26947
+ return fail("nativeFailure", "Grok Session changed");
26948
+ if (!record2(raw))
26949
+ throw new Error("Malformed native child response");
26950
+ const snapshot = raw.snapshot;
26951
+ if (snapshot === null)
26952
+ continue;
26953
+ if (!record2(snapshot) || snapshot.subagentId !== id || snapshot.parentSessionId !== options.sessionId)
26954
+ throw new Error("Native child owner mismatch");
26955
+ const status2 = snapshot.status;
26956
+ if (!["initializing", "running", "completed", "failed", "cancelled"].includes(String(status2)))
26957
+ throw new Error("Unknown native child status");
26958
+ options.children.set(id, {
26959
+ ...child,
26960
+ status: status2 === "initializing" ? "pending" : status2 === "cancelled" ? "interrupted" : status2
26961
+ });
26962
+ }
26963
+ return { ok: true, value: summaries() };
26964
+ } catch (error53) {
26965
+ return fail("nativeFailure", error53 instanceof Error ? error53.message : "Grok activity read failed");
26966
+ }
26967
+ },
26968
+ async read(id) {
26969
+ const listed = await capability.list();
26970
+ if (!listed.ok)
26971
+ return listed;
26972
+ const activity = listed.value.find((entry) => entry.id === id);
26973
+ if (!activity)
26974
+ return fail("invalidRequest", "Native background activity was not found");
26975
+ let output = "";
26976
+ let truncated = false;
26977
+ if (activity.kind === "task" || activity.kind === "monitor") {
26978
+ const task = tasks.find((entry) => `task:${entry.task_id}` === id);
26979
+ output = task?.output ?? "";
26980
+ truncated = task?.truncated ?? false;
26981
+ } else if (activity.kind === "loop") {
26982
+ output = activity.label;
26983
+ } else {
26984
+ const snapshot = await options.readChild(id.slice("subagent:".length));
26985
+ if (!snapshot.ok)
26986
+ return snapshot;
26987
+ output = snapshot.value.turns.flatMap((turn) => turn.items.flatMap(({ item }) => {
26988
+ if (item.type === "agentMessage" || item.type === "reasoning")
26989
+ return [item.text];
26990
+ if (item.type === "commandExecution")
26991
+ return [`$ ${item.command}
26992
+ ${item.output ?? ""}`];
26993
+ return [];
26994
+ })).join("\n\n");
26995
+ }
26996
+ if (output.length > options.outputLimit) {
26997
+ output = output.slice(0, options.outputLimit);
26998
+ truncated = true;
26999
+ }
27000
+ return { ok: true, value: { activity, output, truncated } };
27001
+ },
27002
+ async stop(id) {
27003
+ const listed = await capability.list();
27004
+ if (!listed.ok)
27005
+ return listed;
27006
+ const activity = listed.value.find((entry) => entry.id === id);
27007
+ if (!activity)
27008
+ return { ok: true, value: { outcome: "notFound" } };
27009
+ if (!activity.canStop)
27010
+ return fail("unsupported", "Native activity cannot be stopped through this interface");
27011
+ try {
27012
+ if (activity.kind === "loop" && options.deleteLoop) {
27013
+ const deleted = await options.deleteLoop(id.slice("loop:".length));
27014
+ const nativeId = id.slice("loop:".length);
27015
+ options.observedLoopIds.add(nativeId);
27016
+ options.loops.delete(nativeId);
27017
+ return { ok: true, value: { outcome: deleted ? "stopped" : "notFound" } };
27018
+ }
27019
+ if (options.killTask) {
27020
+ const result = await options.killTask(id.slice("task:".length));
27021
+ return {
27022
+ ok: true,
27023
+ value: {
27024
+ outcome: result === "killed" ? "stopped" : result === "already_exited" ? "alreadyStopped" : "notFound"
27025
+ }
27026
+ };
27027
+ }
27028
+ return fail("unsupported", "Native stop is unavailable");
27029
+ } catch (error53) {
27030
+ return fail("nativeFailure", error53 instanceof Error ? error53.message : "Grok activity stop failed");
27031
+ }
27032
+ }
27033
+ };
27034
+ return capability;
27035
+ }
27036
+
27037
+ // dist/grok-background-items.js
27038
+ import { open as open2 } from "node:fs/promises";
27039
+ import { StringDecoder } from "node:string_decoder";
27040
+ var POLL_INTERVAL_MS = 1e3;
27041
+ var READ_CHUNK_BYTES = 64 * 1024;
27042
+ var MAX_READ_BYTES_PER_TICK = 512 * 1024;
27043
+ var MAX_TOMBSTONES = 1e3;
27044
+ var GrokBackgroundItems = class {
27045
+ #byTaskId = /* @__PURE__ */ new Map();
27046
+ #byCallId = /* @__PURE__ */ new Map();
27047
+ #tombstones = /* @__PURE__ */ new Map();
27048
+ #tombstoneCallIds = /* @__PURE__ */ new Set();
27049
+ #emit;
27050
+ #outputLimit;
27051
+ constructor(options) {
27052
+ this.#emit = options.emit;
27053
+ this.#outputLimit = options.outputLimit;
27054
+ }
27055
+ running() {
27056
+ return [...this.#byTaskId.values()].filter((followed) => !followed.completed && !followed.outcome).map((followed) => followed.command);
27057
+ }
27058
+ taskIds() {
27059
+ return this.running().map((command) => command.taskId);
27060
+ }
27061
+ commandItemId(taskId) {
27062
+ return this.#byTaskId.get(taskId)?.command.item.itemId ?? this.#tombstones.get(taskId)?.itemId;
27063
+ }
27064
+ hasCallId(callId) {
27065
+ return this.#byCallId.has(callId) || this.#tombstoneCallIds.has(callId);
27066
+ }
27067
+ follow(command) {
27068
+ if (this.#tombstones.has(command.taskId) || this.#tombstoneCallIds.has(command.callId)) {
27069
+ return;
27070
+ }
27071
+ const existing = this.#byTaskId.get(command.taskId);
27072
+ if (existing?.completed)
27073
+ return;
27074
+ if (existing) {
27075
+ existing.command = command;
27076
+ this.#byCallId.set(command.callId, command.taskId);
27077
+ existing.outputFile ??= command.outputFile;
27078
+ if (existing.outputFile && !existing.timer && !existing.completed) {
27079
+ existing.timer = setInterval(() => void this.#poll(existing), POLL_INTERVAL_MS);
27080
+ existing.timer.unref();
27081
+ }
27082
+ return;
27083
+ }
27084
+ const followed = {
27085
+ command,
27086
+ outputFile: command.outputFile,
27087
+ offset: 0,
27088
+ decoder: new StringDecoder("utf8"),
27089
+ output: command.item.output ?? "",
27090
+ truncated: command.item.outputTruncated === true,
27091
+ timer: null,
27092
+ reading: Promise.resolve(),
27093
+ outcome: void 0,
27094
+ completed: false,
27095
+ exitCode: command.item.exitCode,
27096
+ fileOutput: "",
27097
+ nativeTruncated: false
27098
+ };
27099
+ this.#byTaskId.set(command.taskId, followed);
27100
+ this.#byCallId.set(command.callId, command.taskId);
27101
+ if (followed.outputFile) {
27102
+ followed.timer = setInterval(() => void this.#poll(followed), POLL_INTERVAL_MS);
27103
+ followed.timer.unref();
27104
+ }
27105
+ }
27106
+ replaceSnapshot(taskIdOrCallId, snapshotText) {
27107
+ const followed = this.#lookup(taskIdOrCallId);
27108
+ if (!followed || followed.completed || !snapshotText)
27109
+ return Boolean(followed);
27110
+ if (followed.outputFile) {
27111
+ return true;
27112
+ }
27113
+ this.#applySnapshot(followed, snapshotText);
27114
+ return true;
27115
+ }
27116
+ append(taskIdOrCallId, text) {
27117
+ const followed = this.#lookup(taskIdOrCallId);
27118
+ if (!followed || followed.completed || !text)
27119
+ return Boolean(followed);
27120
+ if (followed.outputFile) {
27121
+ return true;
27122
+ }
27123
+ this.#append(followed, text);
27124
+ return true;
27125
+ }
27126
+ settle(taskId, outcome, output, outputFile, exitCode, truncated) {
27127
+ const followed = this.#byTaskId.get(taskId);
27128
+ if (!followed) {
27129
+ if (this.#tombstones.has(taskId))
27130
+ return true;
27131
+ return false;
27132
+ }
27133
+ if (followed.outcome)
27134
+ return true;
27135
+ followed.outcome = outcome;
27136
+ followed.nativeTruncated ||= truncated === true;
27137
+ followed.outputFile ??= outputFile;
27138
+ if (exitCode !== void 0) {
27139
+ followed.exitCode = exitCode;
27140
+ }
27141
+ if (followed.timer)
27142
+ clearInterval(followed.timer);
27143
+ followed.timer = null;
27144
+ if (followed.outputFile) {
27145
+ void this.#poll(followed).then(() => this.#complete(followed, outcome));
27146
+ } else {
27147
+ if (output !== void 0 && output.length > 0) {
27148
+ this.#applySnapshot(followed, output);
27149
+ }
27150
+ this.#complete(followed, outcome);
27151
+ }
27152
+ return true;
27153
+ }
27154
+ abandonAll(reason) {
27155
+ for (const followed of this.#byTaskId.values()) {
27156
+ if (followed.timer) {
27157
+ clearInterval(followed.timer);
27158
+ followed.timer = null;
27159
+ }
27160
+ this.#complete(followed, followed.outcome ?? { status: "cancelled", reason });
27161
+ }
27162
+ this.#byTaskId.clear();
27163
+ this.#byCallId.clear();
27164
+ }
27165
+ #lookup(taskIdOrCallId) {
27166
+ return this.#byTaskId.get(taskIdOrCallId) ?? this.#byTaskId.get(this.#byCallId.get(taskIdOrCallId) ?? "");
27167
+ }
27168
+ #applySnapshot(followed, snapshotText) {
27169
+ if (followed.completed)
27170
+ return;
27171
+ if (snapshotText.startsWith(followed.output)) {
27172
+ const delta = snapshotText.slice(followed.output.length);
27173
+ if (delta.length > 0) {
27174
+ this.#append(followed, delta);
27175
+ }
27176
+ } else if (snapshotText !== followed.output) {
27177
+ const bounded2 = snapshotText.slice(0, this.#outputLimit);
27178
+ const wasTruncated = snapshotText.length > this.#outputLimit;
27179
+ followed.output = bounded2;
27180
+ followed.truncated ||= wasTruncated;
27181
+ followed.command = {
27182
+ ...followed.command,
27183
+ item: {
27184
+ ...followed.command.item,
27185
+ output: followed.output,
27186
+ outputTruncated: followed.truncated
27187
+ }
27188
+ };
27189
+ }
27190
+ }
27191
+ #append(followed, text) {
27192
+ if (followed.completed || text.length === 0)
27193
+ return;
27194
+ const remaining = Math.max(0, this.#outputLimit - followed.output.length);
27195
+ const chunk = remaining > 0 ? text.slice(0, remaining) : "";
27196
+ if (text.length > remaining)
27197
+ followed.truncated = true;
27198
+ if (!chunk)
27199
+ return;
27200
+ followed.output += chunk;
27201
+ followed.command = {
27202
+ ...followed.command,
27203
+ item: {
27204
+ ...followed.command.item,
27205
+ output: followed.output,
27206
+ outputTruncated: followed.truncated
27207
+ }
27208
+ };
27209
+ this.#emit({
27210
+ type: "item.updated",
27211
+ turnId: followed.command.turnId,
27212
+ itemId: followed.command.item.itemId,
27213
+ update: { type: "output.append", text: chunk }
27214
+ });
27215
+ }
27216
+ #complete(followed, outcome) {
27217
+ if (followed.completed)
27218
+ return;
27219
+ followed.completed = true;
27220
+ followed.outcome = outcome;
27221
+ if (followed.timer) {
27222
+ clearInterval(followed.timer);
27223
+ followed.timer = null;
27224
+ }
27225
+ const taskId = followed.command.taskId;
27226
+ const callId = followed.command.callId;
27227
+ this.#recordTombstone(taskId, callId, followed.command.item.itemId);
27228
+ this.#byTaskId.delete(taskId);
27229
+ this.#byCallId.delete(callId);
27230
+ const resolvedExitCode = followed.exitCode !== void 0 ? followed.exitCode : followed.command.item.exitCode;
27231
+ const item = {
27232
+ ...followed.command.item,
27233
+ output: followed.output,
27234
+ outputTruncated: followed.truncated || followed.nativeTruncated,
27235
+ ...resolvedExitCode !== void 0 ? { exitCode: resolvedExitCode } : {}
27236
+ };
27237
+ this.#emit({
27238
+ type: "item.completed",
27239
+ turnId: followed.command.turnId,
27240
+ snapshot: { item, outcome }
27241
+ });
27242
+ }
27243
+ #recordTombstone(taskId, callId, itemId) {
27244
+ if (this.#tombstones.size >= MAX_TOMBSTONES) {
27245
+ const oldestKey = this.#tombstones.keys().next().value;
27246
+ if (oldestKey !== void 0) {
27247
+ const oldest = this.#tombstones.get(oldestKey);
27248
+ if (oldest)
27249
+ this.#tombstoneCallIds.delete(oldest.callId);
27250
+ this.#tombstones.delete(oldestKey);
27251
+ }
27252
+ }
27253
+ this.#tombstones.set(taskId, { callId, itemId });
27254
+ this.#tombstoneCallIds.add(callId);
27255
+ }
27256
+ #poll(followed) {
27257
+ if (followed.completed || followed.truncated) {
27258
+ if (followed.timer) {
27259
+ clearInterval(followed.timer);
27260
+ followed.timer = null;
27261
+ }
27262
+ return followed.reading;
27263
+ }
27264
+ followed.reading = followed.reading.then(() => this.#read(followed));
27265
+ return followed.reading;
27266
+ }
27267
+ async #read(followed) {
27268
+ if (!followed.outputFile || followed.completed || followed.truncated)
27269
+ return;
27270
+ try {
27271
+ const handle = await open2(followed.outputFile, "r");
27272
+ try {
27273
+ let totalReadThisTick = 0;
27274
+ const buffer = Buffer.alloc(READ_CHUNK_BYTES);
27275
+ while (!followed.completed && !followed.truncated) {
27276
+ const toRead = Math.min(buffer.length, MAX_READ_BYTES_PER_TICK - totalReadThisTick);
27277
+ if (toRead <= 0)
27278
+ break;
27279
+ const { bytesRead } = await handle.read(buffer, 0, toRead, followed.offset);
27280
+ if (bytesRead === 0)
27281
+ break;
27282
+ followed.offset += bytesRead;
27283
+ totalReadThisTick += bytesRead;
27284
+ followed.fileOutput += followed.decoder.write(buffer.subarray(0, bytesRead));
27285
+ this.#applySnapshot(followed, followed.fileOutput);
27286
+ if (followed.fileOutput.length > this.#outputLimit) {
27287
+ followed.fileOutput = followed.fileOutput.slice(0, this.#outputLimit);
27288
+ followed.truncated = true;
27289
+ }
27290
+ if (totalReadThisTick >= MAX_READ_BYTES_PER_TICK)
27291
+ break;
27292
+ }
27293
+ } finally {
27294
+ await handle.close();
27295
+ }
27296
+ } catch (error53) {
27297
+ if (isRecord18(error53) && error53.code === "ENOENT")
27298
+ return;
27299
+ }
27300
+ }
27301
+ };
27302
+ function isRecord18(value) {
27303
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27304
+ }
27305
+
26511
27306
  // dist/grok-models.js
26512
- function isRecord17(value) {
27307
+ function isRecord19(value) {
26513
27308
  return typeof value === "object" && value !== null && !Array.isArray(value);
26514
27309
  }
26515
27310
  function nonBlank(value) {
@@ -26521,7 +27316,7 @@ function thinkingOptions(value) {
26521
27316
  const seen = /* @__PURE__ */ new Set();
26522
27317
  const options = [];
26523
27318
  for (const candidate of value) {
26524
- if (!isRecord17(candidate) || !nonBlank(candidate.label))
27319
+ if (!isRecord19(candidate) || !nonBlank(candidate.label))
26525
27320
  continue;
26526
27321
  const id = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
26527
27322
  if (!id.success || seen.has(id.data))
@@ -26532,7 +27327,7 @@ function thinkingOptions(value) {
26532
27327
  return options;
26533
27328
  }
26534
27329
  function parseGrokModelState(value) {
26535
- if (!isRecord17(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
27330
+ if (!isRecord19(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
26536
27331
  return null;
26537
27332
  }
26538
27333
  const currentModel = harnessModelRefSchema.safeParse({ id: value.currentModelId });
@@ -26544,12 +27339,12 @@ function parseGrokModelState(value) {
26544
27339
  const models = [];
26545
27340
  let currentThinkingOptionId;
26546
27341
  for (const candidate of value.availableModels) {
26547
- if (!isRecord17(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
27342
+ if (!isRecord19(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
26548
27343
  continue;
26549
27344
  const ref = harnessModelRefSchema.safeParse({ id: candidate.modelId });
26550
27345
  if (!ref.success)
26551
27346
  continue;
26552
- const metadata = isRecord17(candidate._meta) ? candidate._meta : {};
27347
+ const metadata = isRecord19(candidate._meta) ? candidate._meta : {};
26553
27348
  const options2 = thinkingOptions(metadata.reasoningEfforts);
26554
27349
  if (Array.isArray(metadata.contextWindows) && metadata.contextWindows.includes(5e5)) {
26555
27350
  defaultContextWindowTokensByModel.set(ref.data.id, 5e5);
@@ -26588,10 +27383,10 @@ function parseGrokModelState(value) {
26588
27383
  };
26589
27384
  }
26590
27385
  function modelStateFromInitialize(response) {
26591
- return parseGrokModelState(isRecord17(response._meta) ? response._meta.modelState : void 0);
27386
+ return parseGrokModelState(isRecord19(response._meta) ? response._meta.modelState : void 0);
26592
27387
  }
26593
27388
  function modelStateFromSessionResponse(response) {
26594
- return parseGrokModelState(isRecord17(response) ? response.models : void 0);
27389
+ return parseGrokModelState(isRecord19(response) ? response.models : void 0);
26595
27390
  }
26596
27391
  function stateForGrokModel(modelState, nativeState, model2 = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
26597
27392
  const selectedModel = model2;
@@ -26610,12 +27405,12 @@ function stateForGrokModel(modelState, nativeState, model2 = modelState.currentM
26610
27405
  }
26611
27406
 
26612
27407
  // dist/grok-credits.js
26613
- import { readFile as readFile7 } from "node:fs/promises";
27408
+ import { readFile as readFile8 } from "node:fs/promises";
26614
27409
  import os7 from "node:os";
26615
- import path18 from "node:path";
27410
+ import path19 from "node:path";
26616
27411
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
26617
27412
  var REQUEST_TIMEOUT_MS = 15e3;
26618
- function isRecord18(value) {
27413
+ function isRecord20(value) {
26619
27414
  return typeof value === "object" && value !== null && !Array.isArray(value);
26620
27415
  }
26621
27416
  function finitePercent(value) {
@@ -26624,7 +27419,7 @@ function finitePercent(value) {
26624
27419
  return Math.min(100, Math.max(0, value));
26625
27420
  }
26626
27421
  function nonNegativeCentValue(value) {
26627
- if (!isRecord18(value))
27422
+ if (!isRecord20(value))
26628
27423
  return void 0;
26629
27424
  const amount = value.val === void 0 ? 0 : value.val;
26630
27425
  if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
@@ -26632,7 +27427,7 @@ function nonNegativeCentValue(value) {
26632
27427
  return amount;
26633
27428
  }
26634
27429
  function grokHome3(environment) {
26635
- return environment.GROK_HOME ?? path18.join(environment.HOME ?? environment.USERPROFILE ?? os7.homedir(), ".grok");
27430
+ return environment.GROK_HOME ?? path19.join(environment.HOME ?? environment.USERPROFILE ?? os7.homedir(), ".grok");
26636
27431
  }
26637
27432
  function periodTypeFrom(value) {
26638
27433
  if (typeof value !== "string")
@@ -26648,7 +27443,7 @@ function productUsageFrom(value) {
26648
27443
  if (!Array.isArray(value))
26649
27444
  return void 0;
26650
27445
  const products = value.flatMap((entry) => {
26651
- if (!isRecord18(entry) || typeof entry.product !== "string")
27446
+ if (!isRecord20(entry) || typeof entry.product !== "string")
26652
27447
  return [];
26653
27448
  const usagePercent = finitePercent(entry.usagePercent);
26654
27449
  const labels = {
@@ -26669,10 +27464,10 @@ function productUsageFrom(value) {
26669
27464
  return products.length > 0 ? products : void 0;
26670
27465
  }
26671
27466
  function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
26672
- if (!isRecord18(value) || !isRecord18(value.config))
27467
+ if (!isRecord20(value) || !isRecord20(value.config))
26673
27468
  return null;
26674
27469
  const config2 = value.config;
26675
- const period = isRecord18(config2.currentPeriod) ? config2.currentPeriod : void 0;
27470
+ const period = isRecord20(config2.currentPeriod) ? config2.currentPeriod : void 0;
26676
27471
  const periodType = periodTypeFrom(period?.type);
26677
27472
  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);
26678
27473
  let usedPercent = finitePercent(config2.creditUsagePercent);
@@ -26699,11 +27494,11 @@ function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()
26699
27494
  };
26700
27495
  }
26701
27496
  function selectAccessToken(auth, now) {
26702
- if (!isRecord18(auth))
27497
+ if (!isRecord20(auth))
26703
27498
  return null;
26704
- 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")));
27499
+ const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord20(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
26705
27500
  for (const [, value] of entries) {
26706
- if (!isRecord18(value) || typeof value.key !== "string")
27501
+ if (!isRecord20(value) || typeof value.key !== "string")
26707
27502
  continue;
26708
27503
  if (typeof value.expires_at === "string") {
26709
27504
  const expiresAt = Date.parse(value.expires_at);
@@ -26724,8 +27519,8 @@ async function fetchGrokAccount(input = {}) {
26724
27519
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((value) => value?.trim()))
26725
27520
  return null;
26726
27521
  const now = input.now ?? /* @__PURE__ */ new Date();
26727
- const authPath = path18.join(grokHome3(environment), "auth.json");
26728
- const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile7(authPath, "utf8");
27522
+ const authPath = path19.join(grokHome3(environment), "auth.json");
27523
+ const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile8(authPath, "utf8");
26729
27524
  const token = selectAccessToken(JSON.parse(raw), now);
26730
27525
  if (!token)
26731
27526
  return null;
@@ -26774,7 +27569,7 @@ async function fetchGrokCredits(input = {}) {
26774
27569
 
26775
27570
  // dist/grok-usage.js
26776
27571
  var USD_TICKS_PER_DOLLAR = 1e10;
26777
- function isRecord19(value) {
27572
+ function isRecord21(value) {
26778
27573
  return typeof value === "object" && value !== null && !Array.isArray(value);
26779
27574
  }
26780
27575
  function optionalToken(value) {
@@ -26791,7 +27586,7 @@ function combineUsage(base, next) {
26791
27586
  return base === null ? next : parseHostUsage({ ...base, ...next });
26792
27587
  }
26793
27588
  function usageFromNative(value) {
26794
- if (!isRecord19(value))
27589
+ if (!isRecord21(value))
26795
27590
  return null;
26796
27591
  const inputTokens = optionalToken(value.inputTokens);
26797
27592
  const cachedRead = optionalToken(value.cachedReadTokens);
@@ -26815,7 +27610,7 @@ function usageFromNative(value) {
26815
27610
  }
26816
27611
  }
26817
27612
  function usageFromResponse(value) {
26818
- if (!isRecord19(value))
27613
+ if (!isRecord21(value))
26819
27614
  return null;
26820
27615
  const buckets = [
26821
27616
  value.input_tokens,
@@ -26915,7 +27710,7 @@ var GrokTurnUsage = class {
26915
27710
  }
26916
27711
  };
26917
27712
  function usageFromSignals(value) {
26918
- if (!isRecord19(value))
27713
+ if (!isRecord21(value))
26919
27714
  return null;
26920
27715
  try {
26921
27716
  return parseHostUsage({
@@ -26935,7 +27730,7 @@ var summedUsageFields = [
26935
27730
  "totalTokens"
26936
27731
  ];
26937
27732
  function nativeCostTicks(value) {
26938
- if (!isRecord19(value))
27733
+ if (!isRecord21(value))
26939
27734
  return void 0;
26940
27735
  const ticks = value.costUsdTicks;
26941
27736
  if (typeof ticks !== "number" || !Number.isSafeInteger(ticks) || ticks < 0)
@@ -26943,7 +27738,7 @@ function nativeCostTicks(value) {
26943
27738
  return ticks;
26944
27739
  }
26945
27740
  function sessionCostFromNative(value, initialCostUsd) {
26946
- if (!isRecord19(value))
27741
+ if (!isRecord21(value))
26947
27742
  return void 0;
26948
27743
  if (value.costIsPartial !== void 0 && value.costIsPartial !== false)
26949
27744
  return void 0;
@@ -26974,7 +27769,7 @@ function sessionUsageFromHistory(events) {
26974
27769
  continue;
26975
27770
  const usage = usageFromNative(event.usage);
26976
27771
  const ticks2 = nativeCostTicks(event.usage);
26977
- const complete = isRecord19(event.usage) && (event.usage.usageIsIncomplete === void 0 || event.usage.usageIsIncomplete === false) && usage?.inputTokens !== void 0 && usage.cachedInputTokens !== void 0 && usage.cachedInputTokens <= usage.inputTokens;
27772
+ const complete = isRecord21(event.usage) && (event.usage.usageIsIncomplete === void 0 || event.usage.usageIsIncomplete === false) && usage?.inputTokens !== void 0 && usage.cachedInputTokens !== void 0 && usage.cachedInputTokens <= usage.inputTokens;
26978
27773
  latestByKey.set(key, { usage, complete, ...ticks2 !== void 0 ? { ticks: ticks2 } : {} });
26979
27774
  }
26980
27775
  if (latestByKey.size === 0)
@@ -27028,7 +27823,7 @@ function usageFromCompact(tokensAfter, contextWindowTokens) {
27028
27823
  function usageFromUpdate(update, metadata, contextWindowTokens) {
27029
27824
  try {
27030
27825
  if (update?.sessionUpdate === "usage_update") {
27031
- const cost = isRecord19(update.cost) ? update.cost : null;
27826
+ const cost = isRecord21(update.cost) ? update.cost : null;
27032
27827
  return parseHostUsage({
27033
27828
  contextUsedTokens: update.used,
27034
27829
  contextWindowTokens: update.size,
@@ -27161,6 +27956,14 @@ var GrokHarnessSession = class {
27161
27956
  #costRequest = 0;
27162
27957
  #historyLength;
27163
27958
  #goalHelpers = [];
27959
+ backgroundActivity;
27960
+ #nativeTasksRunning = false;
27961
+ #backgroundItems;
27962
+ #loops;
27963
+ #observedLoopIds = /* @__PURE__ */ new Set();
27964
+ #activityChildren = /* @__PURE__ */ new Map();
27965
+ #earlyBackground = /* @__PURE__ */ new Map();
27966
+ #pendingBackground = /* @__PURE__ */ new Map();
27164
27967
  constructor(cwd, transport, opened, modelState, onClosed, options) {
27165
27968
  this.#cwd = cwd;
27166
27969
  this.#historyLength = options.history.length;
@@ -27173,12 +27976,44 @@ var GrokHarnessSession = class {
27173
27976
  this.#closeTimeoutMs = options.closeTimeoutMs;
27174
27977
  this.#randomUUID = options.randomUUID;
27175
27978
  this.#toolOutputLimit = options.toolOutputLimit;
27979
+ this.#backgroundItems = new GrokBackgroundItems({
27980
+ outputLimit: options.toolOutputLimit,
27981
+ emit: (event) => this.#event(event)
27982
+ });
27983
+ this.#loops = collectGrokScheduledLoops(options.history);
27984
+ for (const event of options.history)
27985
+ this.#observeActivityChild(event);
27986
+ this.backgroundActivity = createGrokActivity({
27987
+ sessionId: opened.sessionId,
27988
+ directory: options.sessionDirectory,
27989
+ loops: this.#loops,
27990
+ observedLoopIds: this.#observedLoopIds,
27991
+ children: this.#activityChildren,
27992
+ outputLimit: options.toolOutputLimit,
27993
+ commandItemId: (taskId) => this.#backgroundItems.commandItemId(taskId),
27994
+ observeTasks: (tasks) => {
27995
+ this.#nativeTasksRunning = tasks.some((task) => !task.completed);
27996
+ for (const task of tasks)
27997
+ if (task.completed)
27998
+ this.#backgroundItems.settle(task.task_id, grokBackgroundCompletionOutcome({
27999
+ ...task.exit_code !== void 0 ? { exitCode: task.exit_code } : {},
28000
+ ...task.signal ? { signal: task.signal } : {},
28001
+ ...task.explicitly_killed ? { explicitlyKilled: true } : {}
28002
+ }), task.output, void 0, task.exit_code, task.truncated);
28003
+ },
28004
+ readChild: options.readChild,
28005
+ isOpen: () => this.#phase === "open",
28006
+ ...transport.getSubagent ? { getChild: transport.getSubagent.bind(transport) } : {},
28007
+ ...transport.listTasks ? { listTasks: transport.listTasks.bind(transport) } : {},
28008
+ ...transport.killTask ? { killTask: transport.killTask.bind(transport) } : {},
28009
+ ...transport.deleteScheduledTask ? { deleteLoop: transport.deleteScheduledTask.bind(transport) } : {}
28010
+ });
27176
28011
  this.initialUsage = options.initialUsage ?? null;
27177
28012
  this.#usage = this.initialUsage;
27178
28013
  this.#initialCostUsd = this.initialUsage?.totalCostUsd ?? 0;
27179
28014
  this.capabilities = ((session) => ({
27180
28015
  ...capabilitiesForModels(modelState),
27181
- ...transport.goalControl && transport.observeBackground ? { autonomousTurns: { observe: true } } : {},
28016
+ ...transport.observeBackground ? { autonomousTurns: { observe: true } } : {},
27182
28017
  get steer() {
27183
28018
  return session.#canSteerActiveTurn();
27184
28019
  }
@@ -27241,12 +28076,19 @@ var GrokHarnessSession = class {
27241
28076
  return goalControl(prompt);
27242
28077
  }, (goal) => this.#event({ type: "goal.changed", goal }), 3e4, () => transport.getHistory());
27243
28078
  this.goals = goals;
28079
+ }
28080
+ if (transport.observeBackground) {
28081
+ const goals = this.goals;
27244
28082
  transport.observeBackground({
27245
28083
  onEvent: (event) => {
27246
28084
  if (event.type === "goal.changed") {
28085
+ if (!goals)
28086
+ return;
27247
28087
  void goals.observe(event.update).catch((error53) => this.handleTransportFault(new GrokTransportError("protocolError", String(error53))));
27248
28088
  return;
27249
28089
  }
28090
+ if (this.#applyBackgroundLifecycle(event))
28091
+ return;
27250
28092
  this.#backgroundQueue = this.#backgroundQueue.then(() => this.#backgroundEvent(event)).catch((error53) => this.handleTransportFault(new GrokTransportError("protocolError", String(error53))));
27251
28093
  },
27252
28094
  onPermission: async (request) => {
@@ -27262,7 +28104,7 @@ var GrokHarnessSession = class {
27262
28104
  return this.#active ? this.#active.questions.ask(request) : { outcome: "cancelled" };
27263
28105
  }
27264
28106
  });
27265
- void this.goals.read();
28107
+ void goals?.read();
27266
28108
  }
27267
28109
  }
27268
28110
  async questionActivity(interactionId) {
@@ -27443,7 +28285,147 @@ var GrokHarnessSession = class {
27443
28285
  return active;
27444
28286
  }
27445
28287
  hasBackgroundWork() {
27446
- return this.goals?.active === true;
28288
+ return this.goals?.active === true || this.#backgroundItems.taskIds().length > 0 || this.#nativeTasksRunning || this.#loops.size > 0 || this.#pendingBackground.size > 0 || [...this.#activityChildren.values()].some((child) => child.status === "running" || child.status === "pending");
28289
+ }
28290
+ async stopBackgroundWork() {
28291
+ const listed = await this.backgroundActivity.list();
28292
+ if (!listed.ok)
28293
+ return listed;
28294
+ const ids = [
28295
+ .../* @__PURE__ */ new Set([
28296
+ ...this.#backgroundItems.taskIds(),
28297
+ ...listed.value.filter((entry) => (entry.kind === "task" || entry.kind === "monitor") && entry.status === "running").map((entry) => entry.id.slice("task:".length))
28298
+ ])
28299
+ ];
28300
+ if (ids.length === 0)
28301
+ return { ok: true, value: void 0 };
28302
+ const kill = this.#transport.killTask?.bind(this.#transport);
28303
+ if (!kill) {
28304
+ return {
28305
+ ok: false,
28306
+ error: {
28307
+ code: "unsupported",
28308
+ message: "Grok cannot stop background tasks on this transport",
28309
+ retryable: false
28310
+ }
28311
+ };
28312
+ }
28313
+ try {
28314
+ await Promise.all(ids.map((taskId) => kill(taskId, "teardown")));
28315
+ return { ok: true, value: void 0 };
28316
+ } catch (error53) {
28317
+ return { ok: false, error: normalizeError(error53, "nativeFailure") };
28318
+ }
28319
+ }
28320
+ #observeActivityChild(event) {
28321
+ if (event.type === "subagent.spawned") {
28322
+ this.#activityChildren.set(event.nativeSubagentId, {
28323
+ subagentId: event.nativeSubagentId,
28324
+ nativeSubagentId: event.nativeSubagentId,
28325
+ description: event.description ?? "Grok Subagent",
28326
+ background: true,
28327
+ status: "running",
28328
+ ...event.role ? { role: event.role } : {},
28329
+ ...event.model ? { model: event.model } : {}
28330
+ });
28331
+ }
28332
+ if (event.type === "subagent.finished") {
28333
+ const child = this.#activityChildren.get(event.nativeSubagentId);
28334
+ if (child)
28335
+ this.#activityChildren.set(event.nativeSubagentId, {
28336
+ ...child,
28337
+ status: event.status,
28338
+ ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
28339
+ });
28340
+ }
28341
+ }
28342
+ #applyBackgroundLifecycle(event) {
28343
+ this.#observeActivityChild(event);
28344
+ if (event.type === "task.backgrounded") {
28345
+ this.#nativeTasksRunning = true;
28346
+ this.#acceptBackgrounded(event);
28347
+ return true;
28348
+ }
28349
+ if (event.type === "task.completed") {
28350
+ const outcome = grokBackgroundCompletionOutcome(event);
28351
+ this.#backgroundItems.settle(event.taskId, outcome, event.output, event.outputFile, event.exitCode, event.truncated);
28352
+ void this.backgroundActivity.list();
28353
+ return true;
28354
+ }
28355
+ if (event.type === "monitor.event") {
28356
+ this.#backgroundItems.append(event.taskId, event.text.endsWith("\n") ? event.text : `${event.text}
28357
+ `);
28358
+ return true;
28359
+ }
28360
+ if (event.type === "scheduled.created" || event.type === "scheduled.fired" || event.type === "scheduled.deleted") {
28361
+ if (event.type === "scheduled.fired" && event.subagentId && !this.#activityChildren.has(event.subagentId))
28362
+ this.#activityChildren.set(event.subagentId, {
28363
+ subagentId: event.subagentId,
28364
+ nativeSubagentId: event.subagentId,
28365
+ description: event.prompt,
28366
+ background: true,
28367
+ status: "running"
28368
+ });
28369
+ applyGrokScheduledEvent(this.#loops, event, this.#observedLoopIds);
28370
+ return true;
28371
+ }
28372
+ return false;
28373
+ }
28374
+ #holdBackgroundCommand(active, callId, item, rawOutput) {
28375
+ active.tools.delete(callId);
28376
+ this.#event({ type: "item.detached", turnId: active.command.turnId, itemId: item.itemId });
28377
+ const taskId = grokBackgroundTaskId(rawOutput);
28378
+ const held = { turnId: active.command.turnId, item };
28379
+ if (taskId) {
28380
+ this.#followBackground(callId, held, {
28381
+ taskId,
28382
+ kind: "run",
28383
+ description: item.command
28384
+ });
28385
+ return;
28386
+ }
28387
+ const early = this.#earlyBackground.get(callId);
28388
+ if (early) {
28389
+ this.#earlyBackground.delete(callId);
28390
+ this.#followBackground(callId, held, early);
28391
+ } else
28392
+ this.#pendingBackground.set(callId, held);
28393
+ }
28394
+ #acceptBackgrounded(event) {
28395
+ const active = this.#active;
28396
+ const tool = active?.tools.get(event.toolCallId);
28397
+ if (tool?.item.type === "commandExecution" && active) {
28398
+ active.tools.delete(event.toolCallId);
28399
+ this.#event({
28400
+ type: "item.detached",
28401
+ turnId: active.command.turnId,
28402
+ itemId: tool.item.itemId
28403
+ });
28404
+ this.#followBackground(event.toolCallId, { turnId: active.command.turnId, item: tool.item }, event);
28405
+ return;
28406
+ }
28407
+ const pending = this.#pendingBackground.get(event.toolCallId);
28408
+ if (pending)
28409
+ this.#followBackground(event.toolCallId, pending, event);
28410
+ else if (!this.#backgroundItems.hasCallId(event.toolCallId))
28411
+ this.#earlyBackground.set(event.toolCallId, event);
28412
+ else {
28413
+ const running = this.#backgroundItems.running().find((r) => r.callId === event.toolCallId);
28414
+ if (running)
28415
+ this.#followBackground(event.toolCallId, running, event);
28416
+ }
28417
+ }
28418
+ #followBackground(callId, held, event) {
28419
+ this.#pendingBackground.delete(callId);
28420
+ this.#backgroundItems.follow({
28421
+ turnId: held.turnId,
28422
+ callId,
28423
+ taskId: event.taskId,
28424
+ item: held.item,
28425
+ kind: event.kind,
28426
+ description: event.description ?? event.command ?? held.item.command,
28427
+ ...event.outputFile ? { outputFile: event.outputFile } : {}
28428
+ });
27447
28429
  }
27448
28430
  async #backgroundEvent(event) {
27449
28431
  await this.#goalCommand;
@@ -27509,6 +28491,23 @@ var GrokHarnessSession = class {
27509
28491
  async #executeHarnessCommand(command) {
27510
28492
  if (this.#phase !== "open")
27511
28493
  return { ok: false, error: invalidState("Grok Session is not open") };
28494
+ if (command.commandId === "grok.loop") {
28495
+ if (command.arguments && (Object.keys(command.arguments).some((key) => key !== "text") || command.arguments.text !== void 0 && typeof command.arguments.text !== "string"))
28496
+ return {
28497
+ ok: false,
28498
+ error: {
28499
+ code: "invalidRequest",
28500
+ message: "Grok loop accepts a text argument",
28501
+ retryable: false
28502
+ }
28503
+ };
28504
+ const text = String(command.arguments?.text ?? "").trim();
28505
+ return this.#startTurn({
28506
+ type: "turn.start",
28507
+ turnId: command.turnId,
28508
+ input: [{ type: "text", text: text ? `/loop ${text}` : "/loop" }]
28509
+ }, true);
28510
+ }
27512
28511
  if (command.commandId === "grok.goal" || command.commandId === "grok.desktop-goal") {
27513
28512
  const prompt = grokGoalPrompt(command.arguments);
27514
28513
  if (!prompt.ok)
@@ -27981,6 +28980,8 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
27981
28980
  const contextUsage = usageFromUpdate(event.type === "usage" ? event.update : void 0, event.metadata, this.#state.effectiveModel ? this.#modelState.contextWindowTokensByModel.get(this.#state.effectiveModel.id) : void 0);
27982
28981
  if (contextUsage)
27983
28982
  this.#publishUsage(contextUsage, active.command.turnId);
28983
+ if (this.#applyBackgroundLifecycle(event))
28984
+ return;
27984
28985
  if (event.type === "agent.text")
27985
28986
  this.#appendAgent(active, event.text, event.messageId);
27986
28987
  else if (event.type === "agent.thought")
@@ -28162,9 +29163,16 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
28162
29163
  active.tools.set(event.callId, {
28163
29164
  item,
28164
29165
  ...event.status ? { status: event.status } : {},
28165
- ...generatedImage ? { generatedImage } : {}
29166
+ ...generatedImage ? { generatedImage } : {},
29167
+ ...event.rawInput !== void 0 ? { rawInput: event.rawInput } : {}
28166
29168
  });
28167
29169
  this.#event({ type: "item.started", turnId: active.command.turnId, item });
29170
+ const background = this.#earlyBackground.get(event.callId);
29171
+ if (background) {
29172
+ this.#earlyBackground.delete(event.callId);
29173
+ this.#acceptBackgrounded(background);
29174
+ return;
29175
+ }
28168
29176
  if (event.status === "completed" || event.status === "failed") {
28169
29177
  this.#completeTool(active, event.callId, event.status, event.content, event.rawOutput);
28170
29178
  }
@@ -28198,6 +29206,13 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
28198
29206
  });
28199
29207
  return;
28200
29208
  }
29209
+ if (this.#backgroundItems.hasCallId(event.callId) || this.#pendingBackground.has(event.callId)) {
29210
+ const projection2 = projectGrokToolOutput(event.content, event.rawOutput, this.#toolOutputLimit);
29211
+ const text = projection2.output?.content.flatMap((entry) => entry.type === "text" ? [entry.text] : []).join("") ?? "";
29212
+ if (text)
29213
+ this.#backgroundItems.replaceSnapshot(event.callId, text);
29214
+ return;
29215
+ }
28201
29216
  const tool = active.tools.get(event.callId);
28202
29217
  if (!tool)
28203
29218
  return;
@@ -28240,11 +29255,15 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
28240
29255
  const tool = active.tools.get(callId);
28241
29256
  if (!tool)
28242
29257
  return;
28243
- active.tools.delete(callId);
28244
29258
  const projection = projectGrokToolOutput(content, rawOutput, this.#toolOutputLimit);
28245
29259
  if (hasGrokToolProjection(projection)) {
28246
29260
  tool.item = applyGrokToolProjection(tool.item, projection);
28247
29261
  }
29262
+ if (tool.item.type === "commandExecution" && status2 !== "failed" && grokToolIsBackgrounded(rawOutput, tool.rawInput)) {
29263
+ this.#holdBackgroundCommand(active, callId, tool.item, rawOutput);
29264
+ return;
29265
+ }
29266
+ active.tools.delete(callId);
28248
29267
  const outcome = status2 === "failed" ? {
28249
29268
  status: "failed",
28250
29269
  error: {
@@ -28456,8 +29475,11 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
28456
29475
  this.#completeItem(active, active.compactionItem, itemOutcome);
28457
29476
  active.compactionItem = null;
28458
29477
  }
28459
- for (const tool of active.tools.values())
29478
+ for (const [callId, tool] of active.tools) {
29479
+ if (this.#pendingBackground.has(callId) || this.#backgroundItems.hasCallId(callId))
29480
+ continue;
28460
29481
  this.#completeItem(active, tool.item, itemOutcome);
29482
+ }
28461
29483
  active.tools.clear();
28462
29484
  for (const item of persistedMessages) {
28463
29485
  if (item.itemId === pendingId)
@@ -28511,6 +29533,9 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
28511
29533
  return;
28512
29534
  this.#phase = "closing";
28513
29535
  this.goals?.close();
29536
+ this.#backgroundItems.abandonAll("Grok Session closed");
29537
+ this.#pendingBackground.clear();
29538
+ this.#loops.clear();
28514
29539
  const active = this.#active;
28515
29540
  if (active) {
28516
29541
  active.cancellationRequested = true;
@@ -28538,6 +29563,9 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
28538
29563
  return;
28539
29564
  const normalized = normalizeError(error53, "processExited");
28540
29565
  this.goals?.close();
29566
+ this.#backgroundItems.abandonAll(normalized.message);
29567
+ this.#pendingBackground.clear();
29568
+ this.#loops.clear();
28541
29569
  if (this.#active)
28542
29570
  this.#finish(this.#active, { status: "failed", error: normalized });
28543
29571
  this.#phase = "faulted";
@@ -28656,7 +29684,7 @@ var GrokAdapter = class {
28656
29684
  async inspect(input = {}) {
28657
29685
  if (this.#closePromise)
28658
29686
  return { status: "unavailable", error: invalidState("Grok Adapter is closed") };
28659
- const cwd = path19.resolve(input.cwd ?? process.cwd());
29687
+ const cwd = path20.resolve(input.cwd ?? process.cwd());
28660
29688
  if (!input.refresh) {
28661
29689
  const cached2 = this.#inspectionCache.get(cwd);
28662
29690
  if (cached2)
@@ -28731,7 +29759,7 @@ var GrokAdapter = class {
28731
29759
  }
28732
29760
  };
28733
29761
  }
28734
- const cwd = path19.resolve(input.cwd);
29762
+ const cwd = path20.resolve(input.cwd);
28735
29763
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
28736
29764
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
28737
29765
  return {
@@ -28902,9 +29930,15 @@ var GrokAdapter = class {
28902
29930
  randomUUID: this.#dependencies.randomUUID,
28903
29931
  refreshCredits: () => this.refreshCredits(),
28904
29932
  sessionDirectory,
29933
+ readChild: (id) => this.subagents.readSnapshot({
29934
+ parent: nativeRef(transport.sessionId),
29935
+ nativeSubagentId: id,
29936
+ cwd
29937
+ }),
28905
29938
  toolOutputLimit: this.#toolOutputLimit
28906
29939
  });
28907
29940
  session = openedSession;
29941
+ await openedSession.backgroundActivity.list();
28908
29942
  this.#sessions.add(openedSession);
28909
29943
  this.#scheduleCreditsRefresh();
28910
29944
  return { ok: true, value: openedSession };