@karlorz/codexhost-cli-win32-x64 0.15.0-1 → 0.16.1-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -387,202 +387,10 @@ function createHarnessInstaller(environment, source) {
387
387
  };
388
388
  }
389
389
 
390
- // dist/usage-statistics.js
391
- import os2 from "node:os";
392
- import path5 from "node:path";
393
- import { readFile } from "node:fs/promises";
394
-
395
- // ../../harness-adapter/dist/usage-statistics.js
396
- import { createReadStream } from "node:fs";
397
- import { lstat, opendir } from "node:fs/promises";
390
+ // dist/grok-goals.js
391
+ import { readFile, stat } from "node:fs/promises";
398
392
  import path4 from "node:path";
399
- import { createInterface } from "node:readline";
400
- var MAX_SESSION_ID_LENGTH = 512;
401
- var MAX_CWD_LENGTH = 4096;
402
- var MAX_SESSION_TITLE_LENGTH = 200;
403
- function usageSessionTitle(value) {
404
- if (typeof value !== "string")
405
- return void 0;
406
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
407
- if (!normalized)
408
- return void 0;
409
- if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
410
- return normalized;
411
- let title = "";
412
- for (const character of normalized) {
413
- if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
414
- break;
415
- title += character;
416
- }
417
- return `${title.trimEnd()}…`;
418
- }
419
- function sessionIdOk(value) {
420
- return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
421
- }
422
- function cwdOk(value) {
423
- return typeof value === "string" && value.length > 0 && value.length <= MAX_CWD_LENGTH && !value.includes("\0") && (value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith("\\\\"));
424
- }
425
- function withUsageSession(entry, session) {
426
- const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
427
- const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
428
- const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
429
- if (sessionId === void 0 && cwd === void 0)
430
- return entry;
431
- return {
432
- ...entry,
433
- ...sessionId !== void 0 ? { sessionId } : {},
434
- ...cwd !== void 0 ? { cwd } : {},
435
- ...sessionTitle !== void 0 ? { sessionTitle } : {}
436
- };
437
- }
438
- async function jsonlUsageSources(root, maxDepth, signal) {
439
- const sources = [];
440
- const visit = async (directory, depth) => {
441
- signal.throwIfAborted();
442
- const entries = await opendir(directory).catch((error53) => {
443
- if (error53.code === "ENOENT")
444
- return null;
445
- throw error53;
446
- });
447
- if (!entries)
448
- return;
449
- for await (const entry of entries) {
450
- signal.throwIfAborted();
451
- const file2 = path4.join(directory, entry.name);
452
- if (entry.isDirectory()) {
453
- if (depth < maxDepth)
454
- await visit(file2, depth + 1);
455
- } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
456
- const info = await lstat(file2).catch(() => null);
457
- if (info?.isFile() && info.size > 0) {
458
- sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
459
- }
460
- }
461
- }
462
- };
463
- await visit(root, 0);
464
- return sources;
465
- }
466
- async function* jsonlRecords(file2, marker, signal) {
467
- const lines = createInterface({
468
- input: createReadStream(file2, { encoding: "utf8", signal }),
469
- crlfDelay: Infinity
470
- });
471
- for await (const line of lines) {
472
- if (!line.includes(marker))
473
- continue;
474
- let value;
475
- try {
476
- value = JSON.parse(line);
477
- } catch {
478
- continue;
479
- }
480
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
481
- yield value;
482
- }
483
- }
484
- }
485
- function nativeTimeMs(value) {
486
- const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
487
- return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
488
- }
489
-
490
- // dist/usage-statistics.js
491
- function isRecord(value) {
492
- return typeof value === "object" && value !== null && !Array.isArray(value);
493
- }
494
- var USD_TICKS = 1e10;
495
- function count(value) {
496
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
497
- }
498
- function grokHome(environment) {
499
- return environment.GROK_HOME || path5.join(environment.HOME || os2.homedir(), ".grok");
500
- }
501
- async function grokSummary(directory) {
502
- try {
503
- const summary = JSON.parse(await readFile(path5.join(directory, "summary.json"), "utf8"));
504
- if (!isRecord(summary))
505
- return { forkedAt: null };
506
- const title = usageSessionTitle(summary.generated_title) ?? usageSessionTitle(summary.session_summary);
507
- return {
508
- forkedAt: typeof summary.parent_session_id === "string" ? nativeTimeMs(summary.created_at) : null,
509
- ...title ? { title } : {}
510
- };
511
- } catch {
512
- return { forkedAt: null };
513
- }
514
- }
515
- function grokSession(file2) {
516
- const directory = path5.dirname(file2);
517
- let cwd;
518
- try {
519
- cwd = decodeURIComponent(path5.basename(path5.dirname(directory)));
520
- } catch {
521
- cwd = void 0;
522
- }
523
- return { sessionId: path5.basename(directory), cwd };
524
- }
525
- async function readGrokUsage(file2, signal) {
526
- const summary = await grokSummary(path5.dirname(file2));
527
- const forkedAt = summary.forkedAt;
528
- let title = summary.title;
529
- const session = grokSession(file2);
530
- const entries = [];
531
- for await (const line of jsonlRecords(file2, '"sessionUpdate"', signal)) {
532
- const params = isRecord(line.params) ? line.params : {};
533
- const update = isRecord(params.update) ? params.update : {};
534
- if (!title && update.sessionUpdate === "user_message_chunk") {
535
- title = usageSessionTitle(isRecord(update.content) ? update.content.text : void 0);
536
- continue;
537
- }
538
- const usage = isRecord(update.usage) ? update.usage : {};
539
- if (update.sessionUpdate !== "turn_completed" || typeof update.prompt_id !== "string")
540
- continue;
541
- const meta3 = isRecord(params._meta) ? params._meta : {};
542
- const at = nativeTimeMs(meta3.agentTimestampMs) ?? (typeof line.timestamp === "number" ? nativeTimeMs(line.timestamp * 1e3) : null);
543
- if (at === null || forkedAt !== null && at <= forkedAt)
544
- continue;
545
- for (const [model2, value] of Object.entries(isRecord(usage.modelUsage) ? usage.modelUsage : {})) {
546
- if (!isRecord(value))
547
- continue;
548
- const input = count(value.inputTokens);
549
- const output = count(value.outputTokens);
550
- const cached2 = count(value.cachedReadTokens);
551
- const written = count(value.cacheCreationTokens ?? 0);
552
- const reasoning = count(value.reasoningTokens);
553
- const ticks = count(value.costUsdTicks);
554
- if (input === null || output === null || value.totalTokens !== input + output)
555
- continue;
556
- const cacheKnown = cached2 !== null && cached2 <= input && written === 0;
557
- entries.push(withUsageSession({
558
- id: `${update.prompt_id}:${model2}`,
559
- occurredAtMs: at,
560
- model: model2,
561
- inputTokens: input,
562
- ...cacheKnown ? { cachedInputTokens: cached2, cacheWriteInputTokens: 0 } : {},
563
- outputTokens: output,
564
- ...reasoning !== null && reasoning <= output ? { reasoningOutputTokens: reasoning } : {},
565
- // A turn Grok marks incomplete has no cost of its own; it counts as free rather
566
- // than as a model without a price.
567
- ...ticks !== null ? { costUsd: ticks / USD_TICKS } : usage.usageIsIncomplete === true ? { costUsd: 0 } : {}
568
- }, { ...session, ...title ? { title } : {} }));
569
- }
570
- }
571
- return entries;
572
- }
573
- function createGrokUsageStatistics(environment) {
574
- return Object.freeze({
575
- // sessions/<url-encoded cwd>/<session>/updates.jsonl; subagents are sessions of their own.
576
- listSources: async (signal) => (await jsonlUsageSources(path5.join(grokHome(environment), "sessions"), 2, signal)).filter((source) => path5.basename(source.id) === "updates.jsonl"),
577
- readSource: (id, signal) => readGrokUsage(id, signal)
578
- });
579
- }
580
-
581
- // dist/grok-adapter.js
582
- import { randomUUID as randomUUID2 } from "node:crypto";
583
-
584
- // dist/grok-text-item-id.js
585
- import { createHash } from "node:crypto";
393
+ import { setTimeout as delay } from "node:timers/promises";
586
394
 
587
395
  // ../../../node_modules/zod/v4/classic/external.js
588
396
  var external_exports = {};
@@ -1350,10 +1158,10 @@ function mergeDefs(...defs) {
1350
1158
  function cloneDef(schema) {
1351
1159
  return mergeDefs(schema._zod.def);
1352
1160
  }
1353
- function getElementAtPath(obj, path19) {
1354
- if (!path19)
1161
+ function getElementAtPath(obj, path20) {
1162
+ if (!path20)
1355
1163
  return obj;
1356
- return path19.reduce((acc, key) => acc?.[key], obj);
1164
+ return path20.reduce((acc, key) => acc?.[key], obj);
1357
1165
  }
1358
1166
  function promiseAllObject(promisesObj) {
1359
1167
  const keys = Object.keys(promisesObj);
@@ -1762,11 +1570,11 @@ function explicitlyAborted(x, startIndex = 0) {
1762
1570
  }
1763
1571
  return false;
1764
1572
  }
1765
- function prefixIssues(path19, issues) {
1573
+ function prefixIssues(path20, issues) {
1766
1574
  return issues.map((iss) => {
1767
1575
  var _a3;
1768
1576
  (_a3 = iss).path ?? (_a3.path = []);
1769
- iss.path.unshift(path19);
1577
+ iss.path.unshift(path20);
1770
1578
  return iss;
1771
1579
  });
1772
1580
  }
@@ -1913,16 +1721,16 @@ function flattenError(error53, mapper = (issue2) => issue2.message) {
1913
1721
  }
1914
1722
  function formatError(error53, mapper = (issue2) => issue2.message) {
1915
1723
  const fieldErrors = { _errors: [] };
1916
- const processError = (error54, path19 = []) => {
1724
+ const processError = (error54, path20 = []) => {
1917
1725
  for (const issue2 of error54.issues) {
1918
1726
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1919
- issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1727
+ issue2.errors.map((issues) => processError({ issues }, [...path20, ...issue2.path]));
1920
1728
  } else if (issue2.code === "invalid_key") {
1921
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1729
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1922
1730
  } else if (issue2.code === "invalid_element") {
1923
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1731
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1924
1732
  } else {
1925
- const fullpath = [...path19, ...issue2.path];
1733
+ const fullpath = [...path20, ...issue2.path];
1926
1734
  if (fullpath.length === 0) {
1927
1735
  fieldErrors._errors.push(mapper(issue2));
1928
1736
  } else {
@@ -1949,17 +1757,17 @@ function formatError(error53, mapper = (issue2) => issue2.message) {
1949
1757
  }
1950
1758
  function treeifyError(error53, mapper = (issue2) => issue2.message) {
1951
1759
  const result = { errors: [] };
1952
- const processError = (error54, path19 = []) => {
1760
+ const processError = (error54, path20 = []) => {
1953
1761
  var _a3, _b;
1954
1762
  for (const issue2 of error54.issues) {
1955
1763
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1956
- issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1764
+ issue2.errors.map((issues) => processError({ issues }, [...path20, ...issue2.path]));
1957
1765
  } else if (issue2.code === "invalid_key") {
1958
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1766
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1959
1767
  } else if (issue2.code === "invalid_element") {
1960
- processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1768
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
1961
1769
  } else {
1962
- const fullpath = [...path19, ...issue2.path];
1770
+ const fullpath = [...path20, ...issue2.path];
1963
1771
  if (fullpath.length === 0) {
1964
1772
  result.errors.push(mapper(issue2));
1965
1773
  continue;
@@ -1991,8 +1799,8 @@ function treeifyError(error53, mapper = (issue2) => issue2.message) {
1991
1799
  }
1992
1800
  function toDotPath(_path) {
1993
1801
  const segs = [];
1994
- const path19 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1995
- for (const seg of path19) {
1802
+ const path20 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1803
+ for (const seg of path20) {
1996
1804
  if (typeof seg === "number")
1997
1805
  segs.push(`[${seg}]`);
1998
1806
  else if (typeof seg === "symbol")
@@ -5220,8 +5028,8 @@ function az_default() {
5220
5028
  }
5221
5029
 
5222
5030
  // ../../../node_modules/zod/v4/locales/be.js
5223
- function getBelarusianPlural(count3, one, few, many) {
5224
- const absCount = Math.abs(count3);
5031
+ function getBelarusianPlural(count4, one, few, many) {
5032
+ const absCount = Math.abs(count4);
5225
5033
  const lastDigit = absCount % 10;
5226
5034
  const lastTwoDigits = absCount % 100;
5227
5035
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -7299,8 +7107,8 @@ function hu_default() {
7299
7107
  }
7300
7108
 
7301
7109
  // ../../../node_modules/zod/v4/locales/hy.js
7302
- function getArmenianPlural(count3, one, many) {
7303
- return Math.abs(count3) === 1 ? one : many;
7110
+ function getArmenianPlural(count4, one, many) {
7111
+ return Math.abs(count4) === 1 ? one : many;
7304
7112
  }
7305
7113
  function withDefiniteArticle(word) {
7306
7114
  if (!word)
@@ -9428,8 +9236,8 @@ function ro_default() {
9428
9236
  }
9429
9237
 
9430
9238
  // ../../../node_modules/zod/v4/locales/ru.js
9431
- function getRussianPlural(count3, one, few, many) {
9432
- const absCount = Math.abs(count3);
9239
+ function getRussianPlural(count4, one, few, many) {
9240
+ const absCount = Math.abs(count4);
9433
9241
  const lastDigit = absCount % 10;
9434
9242
  const lastTwoDigits = absCount % 100;
9435
9243
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -14684,13 +14492,13 @@ function resolveRef(ref, ctx) {
14684
14492
  if (!ref.startsWith("#")) {
14685
14493
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14686
14494
  }
14687
- const path19 = ref.slice(1).split("/").filter(Boolean);
14688
- if (path19.length === 0) {
14495
+ const path20 = ref.slice(1).split("/").filter(Boolean);
14496
+ if (path20.length === 0) {
14689
14497
  return ctx.rootSchema;
14690
14498
  }
14691
14499
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14692
- if (path19[0] === defsKey) {
14693
- const key = path19[1];
14500
+ if (path20[0] === defsKey) {
14501
+ const key = path20[1];
14694
14502
  if (!key || !ctx.defs[key]) {
14695
14503
  throw new Error(`Reference not found: ${ref}`);
14696
14504
  }
@@ -15098,6 +14906,33 @@ function date4(params) {
15098
14906
  // ../../../node_modules/zod/v4/classic/external.js
15099
14907
  config(en_default());
15100
14908
 
14909
+ // ../../shared-contracts/dist/goals.js
14910
+ var harnessGoalStatusSchema = external_exports.enum([
14911
+ "active",
14912
+ "paused",
14913
+ "blocked",
14914
+ "usageLimited",
14915
+ "budgetLimited",
14916
+ "complete"
14917
+ ]);
14918
+ var count = external_exports.number().int().nonnegative().safe();
14919
+ var harnessGoalSchema = external_exports.object({
14920
+ objective: external_exports.string().min(1),
14921
+ status: harnessGoalStatusSchema,
14922
+ tokenBudget: count.positive().nullable(),
14923
+ tokensUsed: count,
14924
+ timeUsedSeconds: count,
14925
+ createdAt: count,
14926
+ updatedAt: count
14927
+ });
14928
+ var goalOriginSchema = external_exports.enum(["user", "automatic"]).nullable();
14929
+ var harnessGoalSetSchema = external_exports.object({
14930
+ objective: external_exports.string().min(1).optional(),
14931
+ status: external_exports.enum(["active", "paused"]).optional(),
14932
+ tokenBudget: count.positive().nullable().optional(),
14933
+ origin: goalOriginSchema
14934
+ });
14935
+
15101
14936
  // ../../shared-contracts/dist/delegation-read.js
15102
14937
  var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
15103
14938
  var delegationReadParamsSchema = external_exports.strictObject({
@@ -15256,6 +15091,8 @@ var usageStatisticsTotalsSchema = external_exports.strictObject({
15256
15091
  cachedInputTokens: count2,
15257
15092
  cacheWriteInputTokens: count2,
15258
15093
  cacheKnownInputTokens: count2,
15094
+ cacheHitCachedInputTokens: count2,
15095
+ cacheHitInputTokens: count2,
15259
15096
  outputTokens: count2,
15260
15097
  reasoningOutputTokens: count2,
15261
15098
  /** USD at the public price, summed over the priced requests only. */
@@ -15948,7 +15785,9 @@ var harnessModelCatalogSchema = external_exports.object({
15948
15785
  var harnessHistoryCapabilitiesSchema = external_exports.object({
15949
15786
  fork: external_exports.boolean(),
15950
15787
  forkAcrossCwd: external_exports.boolean(),
15951
- rollbackLastTurn: external_exports.boolean()
15788
+ rollbackLastTurn: external_exports.boolean(),
15789
+ /** Remove the selected checkpoint's Turn and every later Turn, without restoring files. */
15790
+ rollbackToCheckpoint: external_exports.boolean().optional()
15952
15791
  }).strict().refine((history) => history.fork || !history.forkAcrossCwd, {
15953
15792
  path: ["forkAcrossCwd"],
15954
15793
  message: "Cross-cwd Fork requires exact history Fork support"
@@ -16186,7 +16025,10 @@ var harnessPluginRouteSchema = external_exports.object({
16186
16025
  harnessId: harnessPluginIdSchema,
16187
16026
  model: harnessModelRefSchema.optional(),
16188
16027
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
16189
- permissionModeId: harnessPermissionModeIdSchema.optional()
16028
+ permissionModeId: harnessPermissionModeIdSchema.optional(),
16029
+ /** A draft prewarm create: stays unsubmitted until the user's first Turn.
16030
+ * Desktop forwards only the Model of a main-process prewarm to thread/start. */
16031
+ prewarm: external_exports.literal(true).optional()
16190
16032
  }).strict();
16191
16033
 
16192
16034
  // ../../shared-contracts/dist/harness-launch-settings.js
@@ -16529,8 +16371,8 @@ var updateStatusSchema = external_exports.strictObject({
16529
16371
  downloadedBytes: external_exports.number().int().nonnegative().optional(),
16530
16372
  totalBytes: external_exports.number().int().positive().optional(),
16531
16373
  error: external_exports.string().min(1).max(UPDATE_ERROR_MAX_LENGTH).nullable()
16532
- }).superRefine((status, context) => {
16533
- if (status.downloadedBytes !== void 0 && status.totalBytes !== void 0 && status.downloadedBytes > status.totalBytes) {
16374
+ }).superRefine((status2, context) => {
16375
+ if (status2.downloadedBytes !== void 0 && status2.totalBytes !== void 0 && status2.downloadedBytes > status2.totalBytes) {
16534
16376
  context.addIssue({
16535
16377
  code: "custom",
16536
16378
  path: ["downloadedBytes"],
@@ -16686,73 +16528,630 @@ var voiceSettingsStateSchema = external_exports.strictObject({
16686
16528
  // ../../shared-contracts/dist/index.js
16687
16529
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
16688
16530
 
16689
- // dist/grok-text-item-id.js
16690
- function grokTextItemId(sessionId, turnIndex, kind, ordinal) {
16691
- const identity = JSON.stringify([sessionId, turnIndex, kind, ordinal]);
16692
- return hostItemIdSchema.parse(`grok-text-${createHash("sha256").update(identity).digest("hex")}`);
16531
+ // dist/grok-goal-history.js
16532
+ function grokEventTimestamp(event) {
16533
+ const value = event.metadata?.agentTimestampMs ?? event.metadata?.nativeTimestampMs;
16534
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
16535
+ }
16536
+ function lastCompletedGrokGoal(events) {
16537
+ let identity;
16538
+ let createdAt;
16539
+ let completed = null;
16540
+ for (const event of events) {
16541
+ if (event.type === "rewind.marker") {
16542
+ identity = void 0;
16543
+ createdAt = void 0;
16544
+ completed = null;
16545
+ }
16546
+ if (event.type !== "goal.changed" || event.update === null)
16547
+ continue;
16548
+ const update = event.update;
16549
+ if (update.status === "cleared")
16550
+ continue;
16551
+ if (typeof update.goal_id !== "string" || update.goal_id.length === 0) {
16552
+ identity = void 0;
16553
+ createdAt = void 0;
16554
+ completed = null;
16555
+ continue;
16556
+ }
16557
+ if (identity !== update.goal_id) {
16558
+ identity = update.goal_id;
16559
+ createdAt = void 0;
16560
+ completed = null;
16561
+ }
16562
+ const timestamp = grokEventTimestamp(event);
16563
+ if (createdAt === void 0 && update.last_event === "goal_created" && timestamp !== void 0)
16564
+ createdAt = Math.floor(timestamp / 1e3);
16565
+ if (update.status !== "complete") {
16566
+ completed = null;
16567
+ continue;
16568
+ }
16569
+ const parsed = harnessGoalSchema.safeParse({
16570
+ objective: update.objective,
16571
+ status: "complete",
16572
+ tokenBudget: update.token_budget ?? null,
16573
+ tokensUsed: update.tokens_used,
16574
+ timeUsedSeconds: typeof update.elapsed_ms === "number" ? Math.floor(update.elapsed_ms / 1e3) : void 0,
16575
+ createdAt,
16576
+ updatedAt: timestamp === void 0 ? void 0 : Math.floor(timestamp / 1e3)
16577
+ });
16578
+ completed = parsed.success ? parsed.data : null;
16579
+ }
16580
+ return completed;
16693
16581
  }
16694
16582
 
16695
- // dist/grok-credential-export.js
16696
- import { createHash as createHash2 } from "node:crypto";
16697
- import { readFile as readFile2 } from "node:fs/promises";
16698
- import os3 from "node:os";
16699
- import path6 from "node:path";
16700
- async function readGrokCredentials(environment) {
16701
- if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((v) => v?.trim()))
16702
- return [];
16583
+ // dist/grok-goals.js
16584
+ var status = {
16585
+ active: "active",
16586
+ paused: "paused",
16587
+ user_paused: "paused",
16588
+ back_off_paused: "paused",
16589
+ no_progress_paused: "paused",
16590
+ infra_paused: "paused",
16591
+ blocked: "blocked",
16592
+ budget_limited: "budgetLimited",
16593
+ complete: "complete"
16594
+ };
16595
+ function projectGrokGoal(state, updatedAt, update) {
16596
+ const source = update ?? state;
16597
+ return harnessGoalSchema.parse({
16598
+ objective: source.objective,
16599
+ status: status[String(source.status)],
16600
+ tokenBudget: source.token_budget ?? null,
16601
+ tokensUsed: update ? source.tokens_used : state.tokens_used_high_water,
16602
+ timeUsedSeconds: typeof source.elapsed_ms === "number" ? Math.floor(source.elapsed_ms / 1e3) : void 0,
16603
+ createdAt: Math.floor(Date.parse(String(state.created_at)) / 1e3),
16604
+ updatedAt: Math.floor(updatedAt / 1e3)
16605
+ });
16606
+ }
16607
+ async function readGrokGoal(directory) {
16608
+ const filename = path4.join(directory, "goal", "state.json");
16703
16609
  try {
16704
- const home = environment.GROK_HOME ?? path6.join(environment.HOME ?? os3.homedir(), ".grok");
16705
- const auth = JSON.parse(await readFile2(path6.join(home, "auth.json"), "utf8"));
16706
- const client2 = "b1a00492-073a-47ea-816f-4c329264a828";
16707
- const entry = auth[`https://auth.x.ai::${client2}`] ?? auth["https://auth.x.ai"];
16708
- if (!entry || entry.oidc_issuer !== "https://auth.x.ai" || entry.oidc_client_id !== client2)
16709
- return [];
16710
- if (![entry.key, entry.refresh_token, entry.user_id].every((v) => typeof v === "string" && v.length))
16711
- return [];
16712
- const expires = Date.parse(entry.expires_at);
16713
- if (!Number.isFinite(expires))
16714
- return [];
16715
- return [
16716
- {
16717
- source: {
16718
- id: `grok:${createHash2("sha256").update(entry.user_id).digest("hex")}`,
16719
- harnessId: "grok",
16720
- provider: "xai",
16721
- label: typeof entry.email === "string" && entry.email ? entry.email : "Grok"
16722
- },
16723
- oauth: { access: entry.key, refresh: entry.refresh_token, expires: expires - 3e5 }
16724
- }
16725
- ];
16726
- } catch {
16727
- return [];
16610
+ const state = JSON.parse(await readFile(filename, "utf8"));
16611
+ return { state, updatedAt: (await stat(filename)).mtimeMs };
16612
+ } catch (error53) {
16613
+ if (error53.code === "ENOENT")
16614
+ return null;
16615
+ throw error53;
16728
16616
  }
16729
16617
  }
16730
-
16731
- // dist/grok-adapter.js
16732
- import path18 from "node:path";
16733
-
16734
- // ../../harness-plugin-files/dist/grok-computer-use.js
16735
- import { randomUUID } from "node:crypto";
16736
- import { access, mkdir as mkdir2, readFile as readFile3, rename, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
16737
- import os4 from "node:os";
16738
- import path8 from "node:path";
16739
-
16740
- // ../../harness-plugin-files/dist/grok-computer-use-lock.js
16741
- import { mkdir, rm as rm2 } from "node:fs/promises";
16742
- import path7 from "node:path";
16743
- import { setTimeout as delay } from "node:timers/promises";
16744
- async function withGrokComputerUseLock(dataDirectory2, grokHome4, operation) {
16745
- const locks = [
16746
- .../* @__PURE__ */ new Set([
16747
- path7.join(dataDirectory2, ".grok-computer-use.lock"),
16748
- path7.join(grokHome4, ".codexhost-cua.lock")
16749
- ])
16750
- ].sort();
16751
- const acquired = [];
16752
- const deadline = Date.now() + 5e3;
16753
- try {
16618
+ var failure = (message) => ({
16619
+ ok: false,
16620
+ error: { code: "unavailable", message, retryable: false }
16621
+ });
16622
+ var GrokGoals = class {
16623
+ directory;
16624
+ control;
16625
+ changed;
16626
+ timeoutMs;
16627
+ history;
16628
+ #mutating = false;
16629
+ #active = false;
16630
+ #closed = false;
16631
+ #version = 0;
16632
+ #creation = null;
16633
+ #latest = null;
16634
+ constructor(directory, control, changed, timeoutMs = 3e4, history) {
16635
+ this.directory = directory;
16636
+ this.control = control;
16637
+ this.changed = changed;
16638
+ this.timeoutMs = timeoutMs;
16639
+ this.history = history;
16640
+ }
16641
+ get busy() {
16642
+ return this.#mutating;
16643
+ }
16644
+ get active() {
16645
+ return this.#active;
16646
+ }
16647
+ close() {
16648
+ this.#closed = true;
16649
+ this.#active = false;
16650
+ this.#creation = null;
16651
+ this.#version++;
16652
+ }
16653
+ async observe(update) {
16654
+ const version2 = ++this.#version;
16655
+ if (update === null) {
16656
+ this.#active = false;
16657
+ this.#latest = null;
16658
+ this.#creation = null;
16659
+ if (!this.#closed)
16660
+ this.changed(null);
16661
+ return;
16662
+ }
16663
+ this.#active = update.status === "active";
16664
+ for (let attempt = 0; attempt < 20 && !this.#closed && version2 === this.#version; attempt++) {
16665
+ const stored = await readGrokGoal(this.directory);
16666
+ if (stored && stored.state.goal_id === update.goal_id) {
16667
+ const goal = projectGrokGoal(stored.state, Date.now(), update);
16668
+ if (!this.#closed && version2 === this.#version) {
16669
+ this.#latest = { id: update.goal_id, goal, observedAt: Date.now() };
16670
+ this.changed(goal);
16671
+ }
16672
+ return;
16673
+ }
16674
+ await delay(50);
16675
+ }
16676
+ }
16677
+ async read() {
16678
+ if (this.#closed)
16679
+ return failure("Grok goal Session is closed");
16680
+ try {
16681
+ const stored = await readGrokGoal(this.directory);
16682
+ const goal = this.#projectStored(stored);
16683
+ this.#active = goal?.status === "active";
16684
+ return { ok: true, value: goal };
16685
+ } catch {
16686
+ return failure("Grok native goal accounting is unavailable");
16687
+ }
16688
+ }
16689
+ async readLastCompleted() {
16690
+ if (this.#closed)
16691
+ return failure("Grok goal Session is closed");
16692
+ try {
16693
+ return { ok: true, value: this.history ? lastCompletedGrokGoal(await this.history()) : null };
16694
+ } catch {
16695
+ return failure("Grok native goal completion history is unavailable");
16696
+ }
16697
+ }
16698
+ #projectStored(stored) {
16699
+ const latest = this.#latest;
16700
+ return stored ? latest && latest.id === stored.state.goal_id && latest.observedAt >= stored.updatedAt ? latest.goal : projectGrokGoal(stored.state, stored.updatedAt) : null;
16701
+ }
16702
+ async set(input) {
16703
+ if (input.objective !== void 0 && (input.status === "paused" || /[\r\n]/u.test(input.objective) || /^(?:status|pause|resume|clear)$/u.test(input.objective.trim())))
16704
+ return {
16705
+ ok: false,
16706
+ error: {
16707
+ code: "unsupported",
16708
+ message: "Grok cannot create a paused, multiline or reserved-control objective",
16709
+ retryable: false
16710
+ }
16711
+ };
16712
+ if (input.objective !== void 0 && /(?:^|\s)--budget(?:\s|$)/u.test(input.objective))
16713
+ return {
16714
+ ok: false,
16715
+ error: {
16716
+ code: "unsupported",
16717
+ message: "Set the native goal budget through tokenBudget, not objective command syntax",
16718
+ retryable: false
16719
+ }
16720
+ };
16721
+ if (input.tokenBudget !== void 0 && !input.objective)
16722
+ return {
16723
+ ok: false,
16724
+ error: {
16725
+ code: "unsupported",
16726
+ message: "Grok only accepts a token budget when creating a goal",
16727
+ retryable: false
16728
+ }
16729
+ };
16730
+ if (!input.objective && !input.status)
16731
+ return failure("Grok goal mutation has no supported change");
16732
+ if (this.#closed)
16733
+ return failure("Grok goal Session is closed");
16734
+ if (!input.objective)
16735
+ return this.#setNative(input);
16736
+ const creation = this.#creation;
16737
+ if (creation?.objective === input.objective && creation.tokenBudget === (input.tokenBudget ?? null)) {
16738
+ if (!creation.nativeId)
16739
+ return creation.promise;
16740
+ try {
16741
+ const stored = await readGrokGoal(this.directory);
16742
+ if (stored?.state.goal_id === creation.nativeId && stored.state.status === "active" && stored.state.objective === input.objective && (stored.state.token_budget ?? null) === creation.tokenBudget) {
16743
+ const goal = this.#projectStored(stored);
16744
+ if (goal?.status === "active" && goal.objective === input.objective && goal.tokenBudget === creation.tokenBudget)
16745
+ return { ok: true, value: goal };
16746
+ }
16747
+ } catch {
16748
+ return failure("Grok native goal accounting is unavailable");
16749
+ }
16750
+ }
16751
+ if (this.#mutating)
16752
+ return failure("Grok goal operation is unavailable");
16753
+ const pending = {
16754
+ objective: input.objective,
16755
+ tokenBudget: input.tokenBudget ?? null,
16756
+ promise: this.#setNative(input).catch(() => failure("Grok native goal accounting is unavailable")),
16757
+ nativeId: void 0
16758
+ };
16759
+ this.#creation = pending;
16760
+ const result = await pending.promise;
16761
+ if (result.ok && this.#creation === pending) {
16762
+ try {
16763
+ const id = (await readGrokGoal(this.directory))?.state.goal_id;
16764
+ if (typeof id === "string")
16765
+ pending.nativeId = id;
16766
+ else
16767
+ this.#creation = null;
16768
+ } catch {
16769
+ this.#creation = null;
16770
+ }
16771
+ } else if (this.#creation === pending)
16772
+ this.#creation = null;
16773
+ return result;
16774
+ }
16775
+ async #setNative(input) {
16776
+ const prompt = input.objective ? `/goal ${input.objective}${input.tokenBudget == null ? "" : ` --budget ${input.tokenBudget}`}` : `/goal ${input.status === "paused" ? "pause" : "resume"}`;
16777
+ const result = await this.#mutate(prompt, (goal, before) => goal !== null && (input.objective !== void 0 ? goal.objective === input.objective && (input.tokenBudget === void 0 || goal.tokenBudget === input.tokenBudget) && goal.createdAt >= (before?.createdAt ?? 0) : goal.status === input.status));
16778
+ return result.ok && result.value !== null ? { ok: true, value: result.value } : result.ok ? failure("Grok did not confirm a goal") : result;
16779
+ }
16780
+ async clear() {
16781
+ const before = await this.read();
16782
+ if (!before.ok)
16783
+ return before;
16784
+ if (before.value === null)
16785
+ return { ok: true, value: { cleared: false } };
16786
+ const result = await this.#mutate("/goal clear", (goal) => goal === null);
16787
+ return result.ok ? { ok: true, value: { cleared: true } } : result;
16788
+ }
16789
+ async #mutate(prompt, matches) {
16790
+ if (this.#mutating || this.#closed)
16791
+ return failure("Grok goal operation is unavailable");
16792
+ this.#mutating = true;
16793
+ const controller = new AbortController();
16794
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
16795
+ try {
16796
+ const before = await this.read();
16797
+ if (!before.ok)
16798
+ return before;
16799
+ const beforeIdentity = (await readGrokGoal(this.directory))?.state.goal_id;
16800
+ const creating = !["/goal pause", "/goal resume", "/goal clear"].includes(prompt);
16801
+ let error53;
16802
+ let settled = false;
16803
+ const version2 = this.#version;
16804
+ void this.control(prompt, controller.signal).then(() => {
16805
+ settled = true;
16806
+ }, (cause) => {
16807
+ error53 = cause;
16808
+ });
16809
+ const deadline = Date.now() + this.timeoutMs;
16810
+ while (!this.#closed && Date.now() < deadline) {
16811
+ if (error53)
16812
+ return failure("Grok rejected the goal control");
16813
+ const current = await this.read();
16814
+ if ((settled || creating && this.#version > version2) && current.ok && matches(current.value, before.value) && (!creating || (await readGrokGoal(this.directory))?.state.goal_id !== beforeIdentity)) {
16815
+ this.changed(current.value);
16816
+ return current;
16817
+ }
16818
+ await delay(50);
16819
+ }
16820
+ return failure("Grok goal change was not confirmed; re-read native state before retrying");
16821
+ } finally {
16822
+ clearTimeout(timer);
16823
+ controller.abort();
16824
+ this.#mutating = false;
16825
+ }
16826
+ }
16827
+ };
16828
+
16829
+ // dist/usage-statistics.js
16830
+ import os2 from "node:os";
16831
+ import path6 from "node:path";
16832
+ import { readFile as readFile2 } from "node:fs/promises";
16833
+
16834
+ // ../../harness-adapter/dist/usage-statistics.js
16835
+ import { createReadStream } from "node:fs";
16836
+ import { lstat, opendir } from "node:fs/promises";
16837
+ import path5 from "node:path";
16838
+ import { createInterface } from "node:readline";
16839
+ var MAX_SESSION_ID_LENGTH = 512;
16840
+ var MAX_CWD_LENGTH = 4096;
16841
+ var MAX_SESSION_TITLE_LENGTH = 200;
16842
+ function usageSessionTitle(value) {
16843
+ if (typeof value !== "string")
16844
+ return void 0;
16845
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
16846
+ if (!normalized)
16847
+ return void 0;
16848
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
16849
+ return normalized;
16850
+ let title = "";
16851
+ for (const character of normalized) {
16852
+ if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
16853
+ break;
16854
+ title += character;
16855
+ }
16856
+ return `${title.trimEnd()}…`;
16857
+ }
16858
+ function sessionIdOk(value) {
16859
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
16860
+ }
16861
+ function cwdOk(value) {
16862
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_CWD_LENGTH && !value.includes("\0") && (value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith("\\\\"));
16863
+ }
16864
+ function withUsageSession(entry, session) {
16865
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
16866
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
16867
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
16868
+ if (sessionId === void 0 && cwd === void 0)
16869
+ return entry;
16870
+ return {
16871
+ ...entry,
16872
+ ...sessionId !== void 0 ? { sessionId } : {},
16873
+ ...cwd !== void 0 ? { cwd } : {},
16874
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
16875
+ };
16876
+ }
16877
+ async function jsonlUsageSources(root, maxDepth, signal) {
16878
+ const sources = [];
16879
+ const visit = async (directory, depth) => {
16880
+ signal.throwIfAborted();
16881
+ const entries = await opendir(directory).catch((error53) => {
16882
+ if (error53.code === "ENOENT")
16883
+ return null;
16884
+ throw error53;
16885
+ });
16886
+ if (!entries)
16887
+ return;
16888
+ for await (const entry of entries) {
16889
+ signal.throwIfAborted();
16890
+ const file2 = path5.join(directory, entry.name);
16891
+ if (entry.isDirectory()) {
16892
+ if (depth < maxDepth)
16893
+ await visit(file2, depth + 1);
16894
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
16895
+ const info = await lstat(file2).catch(() => null);
16896
+ if (info?.isFile() && info.size > 0) {
16897
+ sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
16898
+ }
16899
+ }
16900
+ }
16901
+ };
16902
+ await visit(root, 0);
16903
+ return sources;
16904
+ }
16905
+ async function* jsonlRecords(file2, marker, signal) {
16906
+ const lines = createInterface({
16907
+ input: createReadStream(file2, { encoding: "utf8", signal }),
16908
+ crlfDelay: Infinity
16909
+ });
16910
+ for await (const line of lines) {
16911
+ if (!line.includes(marker))
16912
+ continue;
16913
+ let value;
16914
+ try {
16915
+ value = JSON.parse(line);
16916
+ } catch {
16917
+ continue;
16918
+ }
16919
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
16920
+ yield value;
16921
+ }
16922
+ }
16923
+ }
16924
+ function nativeTimeMs(value) {
16925
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
16926
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
16927
+ }
16928
+
16929
+ // dist/usage-statistics.js
16930
+ function isRecord(value) {
16931
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16932
+ }
16933
+ var USD_TICKS = 1e10;
16934
+ function count3(value) {
16935
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
16936
+ }
16937
+ function grokHome(environment) {
16938
+ return environment.GROK_HOME || path6.join(environment.HOME || os2.homedir(), ".grok");
16939
+ }
16940
+ async function grokSummary(directory) {
16941
+ try {
16942
+ const summary = JSON.parse(await readFile2(path6.join(directory, "summary.json"), "utf8"));
16943
+ if (!isRecord(summary))
16944
+ return { forkedAt: null };
16945
+ const title = usageSessionTitle(summary.generated_title) ?? usageSessionTitle(summary.session_summary);
16946
+ return {
16947
+ forkedAt: typeof summary.parent_session_id === "string" ? nativeTimeMs(summary.created_at) : null,
16948
+ ...title ? { title } : {}
16949
+ };
16950
+ } catch {
16951
+ return { forkedAt: null };
16952
+ }
16953
+ }
16954
+ function grokSession(file2) {
16955
+ const directory = path6.dirname(file2);
16956
+ let cwd;
16957
+ try {
16958
+ cwd = decodeURIComponent(path6.basename(path6.dirname(directory)));
16959
+ } catch {
16960
+ cwd = void 0;
16961
+ }
16962
+ return { sessionId: path6.basename(directory), cwd };
16963
+ }
16964
+ async function readGrokUsage(file2, signal) {
16965
+ const summary = await grokSummary(path6.dirname(file2));
16966
+ const forkedAt = summary.forkedAt;
16967
+ let title = summary.title;
16968
+ const session = grokSession(file2);
16969
+ const entries = [];
16970
+ for await (const line of jsonlRecords(file2, '"sessionUpdate"', signal)) {
16971
+ const params = isRecord(line.params) ? line.params : {};
16972
+ const update = isRecord(params.update) ? params.update : {};
16973
+ if (!title && update.sessionUpdate === "user_message_chunk") {
16974
+ title = usageSessionTitle(isRecord(update.content) ? update.content.text : void 0);
16975
+ continue;
16976
+ }
16977
+ const usage = isRecord(update.usage) ? update.usage : {};
16978
+ if (update.sessionUpdate !== "turn_completed" || typeof update.prompt_id !== "string")
16979
+ continue;
16980
+ const meta3 = isRecord(params._meta) ? params._meta : {};
16981
+ const at = nativeTimeMs(meta3.agentTimestampMs) ?? (typeof line.timestamp === "number" ? nativeTimeMs(line.timestamp * 1e3) : null);
16982
+ if (at === null || forkedAt !== null && at <= forkedAt)
16983
+ continue;
16984
+ for (const [model2, value] of Object.entries(isRecord(usage.modelUsage) ? usage.modelUsage : {})) {
16985
+ if (!isRecord(value))
16986
+ continue;
16987
+ const input = count3(value.inputTokens);
16988
+ const output = count3(value.outputTokens);
16989
+ const cached2 = count3(value.cachedReadTokens);
16990
+ const written = count3(value.cacheCreationTokens ?? 0);
16991
+ const reasoning = count3(value.reasoningTokens);
16992
+ const ticks = count3(value.costUsdTicks);
16993
+ if (input === null || output === null || value.totalTokens !== input + output)
16994
+ continue;
16995
+ const cacheKnown = cached2 !== null && cached2 <= input && written === 0;
16996
+ entries.push(withUsageSession({
16997
+ id: `${update.prompt_id}:${model2}`,
16998
+ occurredAtMs: at,
16999
+ model: model2,
17000
+ inputTokens: input,
17001
+ ...cacheKnown ? { cachedInputTokens: cached2, cacheWriteInputTokens: 0 } : {},
17002
+ outputTokens: output,
17003
+ ...reasoning !== null && reasoning <= output ? { reasoningOutputTokens: reasoning } : {},
17004
+ // A turn Grok marks incomplete has no cost of its own; it counts as free rather
17005
+ // than as a model without a price.
17006
+ ...ticks !== null ? { costUsd: ticks / USD_TICKS } : usage.usageIsIncomplete === true ? { costUsd: 0 } : {}
17007
+ }, { ...session, ...title ? { title } : {} }));
17008
+ }
17009
+ }
17010
+ return entries;
17011
+ }
17012
+ function createGrokUsageStatistics(environment) {
17013
+ return Object.freeze({
17014
+ // sessions/<url-encoded cwd>/<session>/updates.jsonl; subagents are sessions of their own.
17015
+ listSources: async (signal) => (await jsonlUsageSources(path6.join(grokHome(environment), "sessions"), 2, signal)).filter((source) => path6.basename(source.id) === "updates.jsonl"),
17016
+ readSource: (id, signal) => readGrokUsage(id, signal)
17017
+ });
17018
+ }
17019
+
17020
+ // dist/grok-commands.js
17021
+ var grokCommandCatalog = harnessCommandCatalogSchema.parse({
17022
+ commands: [
17023
+ {
17024
+ id: "grok.compact",
17025
+ invocation: "/compact",
17026
+ localizations: { "zh-CN": { label: "压缩上下文", description: "压缩当前对话上下文" } },
17027
+ label: "Compact context",
17028
+ description: "Compact the current conversation context",
17029
+ argumentMode: "text"
17030
+ },
17031
+ {
17032
+ id: "grok.desktop-goal",
17033
+ invocation: "/goal",
17034
+ label: "Goal",
17035
+ description: "Start a native goal through Desktop Goal mode",
17036
+ argumentMode: "text"
17037
+ },
17038
+ {
17039
+ id: "grok.goal",
17040
+ invocation: "/grok-goal",
17041
+ label: "Grok goal",
17042
+ description: "Set an objective [--budget tokens], or status / pause / resume / clear",
17043
+ localizations: {
17044
+ "zh-CN": {
17045
+ label: "Grok 目标",
17046
+ description: "设置原生目标与可选 token 预算,或 status / pause / resume / clear"
17047
+ }
17048
+ },
17049
+ argumentMode: "text"
17050
+ }
17051
+ ]
17052
+ });
17053
+ var GROK_GOAL_CONTROL_PATTERN = /^\/goal(?:\s+(?:status|pause|clear|resume))?\s*$/u;
17054
+ function isGrokGoalControlPrompt(value) {
17055
+ return GROK_GOAL_CONTROL_PATTERN.test(value.trim());
17056
+ }
17057
+ function grokGoalPrompt(arguments_) {
17058
+ if (arguments_ && (Object.keys(arguments_).some((key) => key !== "text") || arguments_.text !== void 0 && typeof arguments_.text !== "string")) {
17059
+ return {
17060
+ ok: false,
17061
+ error: {
17062
+ code: "invalidRequest",
17063
+ message: "Grok goal accepts only a text argument",
17064
+ retryable: false
17065
+ }
17066
+ };
17067
+ }
17068
+ const text = typeof arguments_?.text === "string" ? arguments_.text.trim() : "";
17069
+ return { ok: true, value: text ? `/goal ${text}` : "/goal" };
17070
+ }
17071
+
17072
+ // dist/grok-adapter.js
17073
+ import { randomUUID as randomUUID2 } from "node:crypto";
17074
+
17075
+ // dist/grok-text-item-id.js
17076
+ import { createHash } from "node:crypto";
17077
+ function grokTextItemId(sessionId, turnIndex, kind, ordinal) {
17078
+ const identity = JSON.stringify([sessionId, turnIndex, kind, ordinal]);
17079
+ return hostItemIdSchema.parse(`grok-text-${createHash("sha256").update(identity).digest("hex")}`);
17080
+ }
17081
+
17082
+ // dist/grok-agent-messages.js
17083
+ function settledGrokAgentMessages(persisted, completedItems) {
17084
+ const messages = persisted.flatMap(({ item }) => item.type === "agentMessage" ? [item] : []);
17085
+ const completed = new Set(completedItems.map(({ item }) => item.itemId));
17086
+ return messages.flatMap((item, index) => {
17087
+ const phase = index === messages.length - 1 ? "final_answer" : "commentary";
17088
+ if (completed.has(item.itemId))
17089
+ return [];
17090
+ return [{ ...item, phase }];
17091
+ });
17092
+ }
17093
+
17094
+ // dist/grok-credential-export.js
17095
+ import { createHash as createHash2 } from "node:crypto";
17096
+ import { readFile as readFile3 } from "node:fs/promises";
17097
+ import os3 from "node:os";
17098
+ import path7 from "node:path";
17099
+ async function readGrokCredentials(environment) {
17100
+ if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((v) => v?.trim()))
17101
+ return [];
17102
+ try {
17103
+ const home = environment.GROK_HOME ?? path7.join(environment.HOME ?? os3.homedir(), ".grok");
17104
+ const auth = JSON.parse(await readFile3(path7.join(home, "auth.json"), "utf8"));
17105
+ const client2 = "b1a00492-073a-47ea-816f-4c329264a828";
17106
+ const entry = auth[`https://auth.x.ai::${client2}`] ?? auth["https://auth.x.ai"];
17107
+ if (!entry || entry.oidc_issuer !== "https://auth.x.ai" || entry.oidc_client_id !== client2)
17108
+ return [];
17109
+ if (![entry.key, entry.refresh_token, entry.user_id].every((v) => typeof v === "string" && v.length))
17110
+ return [];
17111
+ const expires = Date.parse(entry.expires_at);
17112
+ if (!Number.isFinite(expires))
17113
+ return [];
17114
+ return [
17115
+ {
17116
+ source: {
17117
+ id: `grok:${createHash2("sha256").update(entry.user_id).digest("hex")}`,
17118
+ harnessId: "grok",
17119
+ provider: "xai",
17120
+ label: typeof entry.email === "string" && entry.email ? entry.email : "Grok"
17121
+ },
17122
+ oauth: { access: entry.key, refresh: entry.refresh_token, expires: expires - 3e5 }
17123
+ }
17124
+ ];
17125
+ } catch {
17126
+ return [];
17127
+ }
17128
+ }
17129
+
17130
+ // dist/grok-adapter.js
17131
+ import path19 from "node:path";
17132
+
17133
+ // ../../harness-plugin-files/dist/grok-computer-use.js
17134
+ import { randomUUID } from "node:crypto";
17135
+ import { access, mkdir as mkdir2, readFile as readFile4, rename, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
17136
+ import os4 from "node:os";
17137
+ import path9 from "node:path";
17138
+
17139
+ // ../../harness-plugin-files/dist/grok-computer-use-lock.js
17140
+ import { mkdir, rm as rm2 } from "node:fs/promises";
17141
+ import path8 from "node:path";
17142
+ import { setTimeout as delay2 } from "node:timers/promises";
17143
+ async function withGrokComputerUseLock(dataDirectory2, grokHome4, operation) {
17144
+ const locks = [
17145
+ .../* @__PURE__ */ new Set([
17146
+ path8.join(dataDirectory2, ".grok-computer-use.lock"),
17147
+ path8.join(grokHome4, ".codexhost-cua.lock")
17148
+ ])
17149
+ ].sort();
17150
+ const acquired = [];
17151
+ const deadline = Date.now() + 5e3;
17152
+ try {
16754
17153
  for (const lock of locks) {
16755
- await mkdir(path7.dirname(lock), { recursive: true, mode: 448 });
17154
+ await mkdir(path8.dirname(lock), { recursive: true, mode: 448 });
16756
17155
  for (; ; ) {
16757
17156
  try {
16758
17157
  await mkdir(lock, { mode: 448 });
@@ -16763,7 +17162,7 @@ async function withGrokComputerUseLock(dataDirectory2, grokHome4, operation) {
16763
17162
  throw error53;
16764
17163
  if (Date.now() >= deadline)
16765
17164
  throw new Error("Grok Computer Use settings are locked");
16766
- await delay(25);
17165
+ await delay2(25);
16767
17166
  }
16768
17167
  }
16769
17168
  }
@@ -16787,14 +17186,14 @@ var GrokComputerUseError = class extends Error {
16787
17186
  }
16788
17187
  };
16789
17188
  function dataDirectory(environment) {
16790
- return environment.CODEXHOST_DATA_DIR ? path8.resolve(environment.CODEXHOST_DATA_DIR) : path8.join(os4.homedir(), ".codexhost");
17189
+ return environment.CODEXHOST_DATA_DIR ? path9.resolve(environment.CODEXHOST_DATA_DIR) : path9.join(os4.homedir(), ".codexhost");
16791
17190
  }
16792
17191
  function grokHome2(environment) {
16793
- return environment.GROK_HOME ? path8.resolve(environment.GROK_HOME) : path8.join(environment.HOME ?? os4.homedir(), ".grok");
17192
+ return environment.GROK_HOME ? path9.resolve(environment.GROK_HOME) : path9.join(environment.HOME ?? os4.homedir(), ".grok");
16794
17193
  }
16795
17194
  function chatgptApp(environment, platform) {
16796
17195
  if (environment.CODEXHOST_CHATGPT_APP)
16797
- return path8.resolve(environment.CODEXHOST_CHATGPT_APP);
17196
+ return path9.resolve(environment.CODEXHOST_CHATGPT_APP);
16798
17197
  if (platform === "darwin")
16799
17198
  return "/Applications/ChatGPT.app";
16800
17199
  return void 0;
@@ -16811,7 +17210,7 @@ function isNotFound(error53) {
16811
17210
  return Boolean(error53 && typeof error53 === "object" && "code" in error53 && error53.code === "ENOENT");
16812
17211
  }
16813
17212
  async function writeAtomically(file2, content) {
16814
- await mkdir2(path8.dirname(file2), { recursive: true, mode: 448 });
17213
+ await mkdir2(path9.dirname(file2), { recursive: true, mode: 448 });
16815
17214
  const temporary = `${file2}.${randomUUID()}.tmp`;
16816
17215
  try {
16817
17216
  await writeFile2(temporary, content, { mode: 384, flag: "wx" });
@@ -16824,17 +17223,17 @@ function launchPaths(environment, platform) {
16824
17223
  const app = chatgptApp(environment, platform);
16825
17224
  if (!app)
16826
17225
  return void 0;
16827
- const resources = path8.join(app, "Contents", "Resources");
16828
- const cuaNode = path8.join(resources, "cua_node");
17226
+ const resources = path9.join(app, "Contents", "Resources");
17227
+ const cuaNode = path9.join(resources, "cua_node");
16829
17228
  return {
16830
- node: path8.join(cuaNode, "bin", "node"),
16831
- cuaRepl: path8.join(cuaNode, "lib", "node_modules", "@oai", "cua-repl", "bin", "cua-repl.mjs"),
16832
- nodeRepl: path8.join(cuaNode, "bin", "node_repl"),
16833
- nodeModules: path8.join(cuaNode, "lib", "node_modules"),
16834
- codexCli: path8.join(resources, "codex-cli", "bin", "codex"),
16835
- skyApp: path8.join(environment.HOME ?? os4.homedir(), ".codex", "computer-use", "Codex Computer Use.app"),
16836
- codexHome: path8.join(environment.HOME ?? os4.homedir(), ".codex"),
16837
- browserDesktop: path8.join(cuaNode, "lib", "node_modules", "@oai", "browser-desktop")
17229
+ node: path9.join(cuaNode, "bin", "node"),
17230
+ cuaRepl: path9.join(cuaNode, "lib", "node_modules", "@oai", "cua-repl", "bin", "cua-repl.mjs"),
17231
+ nodeRepl: path9.join(cuaNode, "bin", "node_repl"),
17232
+ nodeModules: path9.join(cuaNode, "lib", "node_modules"),
17233
+ codexCli: path9.join(resources, "codex-cli", "bin", "codex"),
17234
+ skyApp: path9.join(environment.HOME ?? os4.homedir(), ".codex", "computer-use", "Codex Computer Use.app"),
17235
+ codexHome: path9.join(environment.HOME ?? os4.homedir(), ".codex"),
17236
+ browserDesktop: path9.join(cuaNode, "lib", "node_modules", "@oai", "browser-desktop")
16838
17237
  };
16839
17238
  }
16840
17239
  async function sharedRuntimePresent(launch) {
@@ -16846,7 +17245,7 @@ async function computerFilesPresent(launch) {
16846
17245
  return present.every(Boolean);
16847
17246
  }
16848
17247
  async function browserFilesPresent(launch) {
16849
- return isFile(path8.join(launch.browserDesktop, "package.json"));
17248
+ return isFile(path9.join(launch.browserDesktop, "package.json"));
16850
17249
  }
16851
17250
  async function discoverGrokComputerUseLaunch(environment = process.env, platform = process.platform) {
16852
17251
  const launch = launchPaths(environment, platform);
@@ -16942,7 +17341,7 @@ ${backends}CUA_REPL_ENABLED_SURFACES = ${JSON.stringify(surfaces)}
16942
17341
  }
16943
17342
  async function readPreference(environment) {
16944
17343
  try {
16945
- const document = JSON.parse(await readFile3(path8.join(dataDirectory(environment), PREFERENCE_FILE), "utf8"));
17344
+ const document = JSON.parse(await readFile4(path9.join(dataDirectory(environment), PREFERENCE_FILE), "utf8"));
16946
17345
  return {
16947
17346
  ...typeof document.enabled === "boolean" ? { enabled: document.enabled } : {},
16948
17347
  ...typeof document.browser === "boolean" ? { browser: document.browser } : {},
@@ -16960,12 +17359,12 @@ async function writePreference(environment, state) {
16960
17359
  ...typeof state.browser === "boolean" ? { browser: state.browser } : {},
16961
17360
  ...state.applyError ? { applyError: state.applyError } : {}
16962
17361
  };
16963
- await writeAtomically(path8.join(dataDirectory(environment), PREFERENCE_FILE), `${JSON.stringify(document)}
17362
+ await writeAtomically(path9.join(dataDirectory(environment), PREFERENCE_FILE), `${JSON.stringify(document)}
16964
17363
  `);
16965
17364
  }
16966
17365
  async function readGrokConfig(environment) {
16967
17366
  try {
16968
- return await readFile3(path8.join(grokHome2(environment), "config.toml"), "utf8");
17367
+ return await readFile4(path9.join(grokHome2(environment), "config.toml"), "utf8");
16969
17368
  } catch (error53) {
16970
17369
  if (isNotFound(error53))
16971
17370
  return "";
@@ -16973,7 +17372,7 @@ async function readGrokConfig(environment) {
16973
17372
  }
16974
17373
  }
16975
17374
  async function writeGrokConfig(environment, text) {
16976
- await writeAtomically(path8.join(grokHome2(environment), "config.toml"), text.endsWith("\n") ? text : `${text}
17375
+ await writeAtomically(path9.join(grokHome2(environment), "config.toml"), text.endsWith("\n") ? text : `${text}
16977
17376
  `);
16978
17377
  }
16979
17378
  async function currentState(environment, preference) {
@@ -17425,10 +17824,11 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17425
17824
 
17426
17825
  // dist/acp-transport.js
17427
17826
  import { spawn, spawnSync } from "node:child_process";
17428
- import { readdir, readFile as readFile4 } from "node:fs/promises";
17827
+ import { readdir, readFile as readFile5 } from "node:fs/promises";
17429
17828
  import os6 from "node:os";
17430
- import path15 from "node:path";
17829
+ import path16 from "node:path";
17431
17830
  import { Readable, Writable } from "node:stream";
17831
+ import { setTimeout as delay3 } from "node:timers/promises";
17432
17832
 
17433
17833
  // ../../../node_modules/@agentclientprotocol/sdk/dist/schema/index.js
17434
17834
  var AGENT_METHODS = {
@@ -19714,9 +20114,9 @@ var Connection = class {
19714
20114
  return;
19715
20115
  }
19716
20116
  const responseBatch = isResponseBatch(batch);
19717
- const responseCount = responseBatch ? 0 : batch.reduce((count3, message) => count3 + (isNotificationMessage(message) ? 0 : 1), 0);
20117
+ const responseCount = responseBatch ? 0 : batch.reduce((count4, message) => count4 + (isNotificationMessage(message) ? 0 : 1), 0);
19718
20118
  let remaining = responseCount;
19719
- let remainingNotifications = batch.reduce((count3, message) => count3 + (isNotificationMessage(message) ? 1 : 0), 0);
20119
+ let remainingNotifications = batch.reduce((count4, message) => count4 + (isNotificationMessage(message) ? 1 : 0), 0);
19720
20120
  let responseSent = false;
19721
20121
  const responses = [];
19722
20122
  const sendResponsesIfReady = async () => {
@@ -21615,8 +22015,8 @@ function parseGrokAvailableCommands(value) {
21615
22015
  });
21616
22016
  }
21617
22017
  function isGrokSkill(command) {
21618
- const path19 = command.meta?.path;
21619
- return typeof path19 === "string" && /(^|[\\/])SKILL\.md$/u.test(path19) || typeof command.meta?.qualifiedName === "string";
22018
+ const path20 = command.meta?.path;
22019
+ return typeof path20 === "string" && /(^|[\\/])SKILL\.md$/u.test(path20) || typeof command.meta?.qualifiedName === "string";
21620
22020
  }
21621
22021
  function grokLiveCommands(native) {
21622
22022
  return native.map((command) => ({
@@ -21627,7 +22027,7 @@ function grokLiveCommands(native) {
21627
22027
  }
21628
22028
 
21629
22029
  // dist/command.js
21630
- import path9 from "node:path";
22030
+ import path10 from "node:path";
21631
22031
  var GrokExecutableError = class extends Error {
21632
22032
  code = "GROK_NOT_FOUND";
21633
22033
  };
@@ -21656,7 +22056,7 @@ function resolveGrokExecutable(input = {}) {
21656
22056
  });
21657
22057
  if (!resolution)
21658
22058
  throw new GrokExecutableError("Grok CLI is not installed");
21659
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path9.resolve(resolution.executable);
22059
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path10.resolve(resolution.executable);
21660
22060
  }
21661
22061
  function grokInvocation(command, platform = process.platform, modelId) {
21662
22062
  const arguments_ = ["agent", "--no-leader"];
@@ -21669,11 +22069,151 @@ function grokInvocation(command, platform = process.platform, modelId) {
21669
22069
 
21670
22070
  // dist/grok-fork.js
21671
22071
  import { isDeepStrictEqual } from "node:util";
21672
- import path13 from "node:path";
22072
+ import path14 from "node:path";
22073
+
22074
+ // dist/grok-history-groups.js
22075
+ function grokPromptIndex(event) {
22076
+ const value = event.metadata?.promptIndex ?? event.metadata?.prompt_index;
22077
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
22078
+ }
22079
+ function grokHiddenInput(event) {
22080
+ return event.metadata?.hideFromScrollback === true || /^\s*<system-reminder>/u.test(event.text);
22081
+ }
22082
+ function grokHostTurn(event) {
22083
+ return event.metadata?.hostTurn === true || event.metadata?.host_turn === true;
22084
+ }
22085
+ var GrokNativeIdentityReuseError = class extends Error {
22086
+ constructor(key) {
22087
+ super(`Grok Native terminal identity reused by a new prompt: ${key}`);
22088
+ }
22089
+ };
22090
+ function hasUsage(usage) {
22091
+ if (!usage || typeof usage !== "object")
22092
+ return false;
22093
+ return Object.entries(usage).some(([key, value]) => /^(?:inputTokens|outputTokens|totalTokens|reasoningTokens|thoughtTokens|cachedReadTokens|cacheCreationTokens|costUsdTicks)$/u.test(key) && typeof value === "number" && value > 0);
22094
+ }
22095
+ function classifyGrokHistory(events) {
22096
+ const groups = [];
22097
+ const retained = /* @__PURE__ */ new Map();
22098
+ let user;
22099
+ let userIndex;
22100
+ let evidence = false;
22101
+ let goalPresent = false;
22102
+ let goalWorker = false;
22103
+ let promptIndex = 0;
22104
+ for (const [terminalIndex, event] of events.entries()) {
22105
+ if (event.type === "goal.changed")
22106
+ goalPresent = event.update !== null;
22107
+ if (event.type === "rewind.marker") {
22108
+ for (const [key, index] of retained)
22109
+ if (index >= event.targetPromptIndex)
22110
+ retained.delete(key);
22111
+ promptIndex = event.targetPromptIndex;
22112
+ user = void 0;
22113
+ userIndex = void 0;
22114
+ evidence = false;
22115
+ } else if (event.type === "user.text") {
22116
+ if (!user || grokHiddenInput(user) && grokPromptIndex(user) === null && !grokHiddenInput(event)) {
22117
+ user = event;
22118
+ userIndex = terminalIndex;
22119
+ evidence = false;
22120
+ goalWorker = goalPresent;
22121
+ }
22122
+ } else if (event.type === "agent.text" || event.type === "agent.thought") {
22123
+ evidence ||= event.text.length > 0;
22124
+ } else if (event.type === "tool.call")
22125
+ evidence = true;
22126
+ else if (event.type === "turn.completed") {
22127
+ const hidden = user && grokHiddenInput(user);
22128
+ const host = user ? grokHostTurn(user) : false;
22129
+ const index = user ? grokPromptIndex(user) ?? promptIndex : promptIndex;
22130
+ const executed = evidence || hasUsage(event.usage) || goalWorker && event.stopReason === "cancelled";
22131
+ const eligible = !host && (!hidden || user && grokPromptIndex(user) !== null && executed);
22132
+ const reused = retained.has(event.nativeTurnKey);
22133
+ const disposition = !eligible || reused && (!user || hidden && !executed) ? "ephemeral" : reused ? "reused" : "durable";
22134
+ groups.push({
22135
+ ...user ? { user } : {},
22136
+ ...userIndex !== void 0 ? { userIndex } : {},
22137
+ terminal: event,
22138
+ terminalIndex,
22139
+ disposition
22140
+ });
22141
+ if (disposition === "durable")
22142
+ retained.set(event.nativeTurnKey, index);
22143
+ if (user && !host)
22144
+ promptIndex = index + 1;
22145
+ user = void 0;
22146
+ userIndex = void 0;
22147
+ evidence = false;
22148
+ goalWorker = false;
22149
+ }
22150
+ }
22151
+ return groups;
22152
+ }
22153
+
22154
+ // dist/grok-goal-helpers.js
22155
+ function placeGrokGoalHelpers(replay, groups) {
22156
+ const nextRewind = /* @__PURE__ */ new Map();
22157
+ let boundary = replay.length;
22158
+ for (let i = replay.length - 1; i >= 0; i--) {
22159
+ if (replay[i]?.type === "rewind.marker")
22160
+ boundary = i;
22161
+ if (replay[i]?.type === "turn.completed")
22162
+ nextRewind.set(i, boundary);
22163
+ }
22164
+ const owners = /* @__PURE__ */ new Map();
22165
+ let start = 0;
22166
+ for (const group of groups) {
22167
+ if (group.disposition !== "durable" || group.userIndex === void 0)
22168
+ continue;
22169
+ const terminal = group.terminalIndex;
22170
+ const entries = owners.get(group.terminal.nativeTurnKey) ?? [];
22171
+ entries.push({
22172
+ start: group.userIndex,
22173
+ end: nextRewind.get(terminal) ?? replay.length,
22174
+ terminal
22175
+ });
22176
+ owners.set(group.terminal.nativeTurnKey, entries);
22177
+ }
22178
+ const pending = /* @__PURE__ */ new Map();
22179
+ const inserts = /* @__PURE__ */ new Map();
22180
+ const moved = /* @__PURE__ */ new Set();
22181
+ for (const [index, event] of replay.entries()) {
22182
+ if (event.type === "rewind.marker") {
22183
+ pending.clear();
22184
+ start = index + 1;
22185
+ }
22186
+ if (event.type === "subagent.spawned" && event.parentPromptId) {
22187
+ const owner = owners.get(event.parentPromptId)?.find((g) => g.terminal >= start && index < g.end);
22188
+ if (!owner) {
22189
+ moved.add(event);
22190
+ continue;
22191
+ }
22192
+ pending.set(event.nativeSubagentId, {
22193
+ at: Math.max(owner.start + 1, Math.min(index, owner.terminal)),
22194
+ end: owner.terminal
22195
+ });
22196
+ }
22197
+ if (event.type !== "subagent.spawned" && event.type !== "subagent.finished")
22198
+ continue;
22199
+ const placement = pending.get(event.nativeSubagentId);
22200
+ if (!placement)
22201
+ continue;
22202
+ const at = Math.max(placement.at, Math.min(index, placement.end));
22203
+ const list = inserts.get(at) ?? [];
22204
+ list.push(event);
22205
+ inserts.set(at, list);
22206
+ moved.add(event);
22207
+ }
22208
+ return replay.flatMap((event, index) => [
22209
+ ...inserts.get(index) ?? [],
22210
+ ...moved.has(event) ? [] : [event]
22211
+ ]);
22212
+ }
21673
22213
 
21674
22214
  // dist/grok-file-change.js
21675
22215
  import { Buffer as Buffer2 } from "node:buffer";
21676
- import path10 from "node:path";
22216
+ import path11 from "node:path";
21677
22217
 
21678
22218
  // ../../../node_modules/diff/libesm/diff/base.js
21679
22219
  var Diff = class {
@@ -21775,16 +22315,16 @@ var Diff = class {
21775
22315
  }
21776
22316
  }
21777
22317
  }
21778
- addToPath(path19, added, removed, oldPosInc, options) {
21779
- const last = path19.lastComponent;
22318
+ addToPath(path20, added, removed, oldPosInc, options) {
22319
+ const last = path20.lastComponent;
21780
22320
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
21781
22321
  return {
21782
- oldPos: path19.oldPos + oldPosInc,
22322
+ oldPos: path20.oldPos + oldPosInc,
21783
22323
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
21784
22324
  };
21785
22325
  } else {
21786
22326
  return {
21787
- oldPos: path19.oldPos + oldPosInc,
22327
+ oldPos: path20.oldPos + oldPosInc,
21788
22328
  lastComponent: { count: 1, added, removed, previousComponent: last }
21789
22329
  };
21790
22330
  }
@@ -22097,13 +22637,13 @@ function isRecord5(value) {
22097
22637
  return typeof value === "object" && value !== null && !Array.isArray(value);
22098
22638
  }
22099
22639
  function validAbsolutePath(value) {
22100
- return typeof value === "string" && path10.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
22640
+ return typeof value === "string" && path11.isAbsolute(value) && value.trim().length > 0 && !value.includes("\0") && !value.includes("\n") && !value.includes("\r");
22101
22641
  }
22102
22642
  function displayPath(nativePath, cwd) {
22103
- const resolvedCwd = path10.resolve(cwd);
22104
- const resolvedPath = path10.resolve(nativePath);
22105
- const relative = path10.relative(resolvedCwd, resolvedPath);
22106
- const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path10.sep}`);
22643
+ const resolvedCwd = path11.resolve(cwd);
22644
+ const resolvedPath = path11.resolve(nativePath);
22645
+ const relative = path11.relative(resolvedCwd, resolvedPath);
22646
+ const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path11.sep}`);
22107
22647
  const selected = inside ? relative : resolvedPath;
22108
22648
  const normalized = selected.replaceAll("\\", "/");
22109
22649
  if (normalized.length === 0 || normalized === ".")
@@ -22164,12 +22704,12 @@ function projectGrokFileChanges(content, cwd, textLimit = DEFAULT_GROK_FILE_CHAN
22164
22704
  }
22165
22705
 
22166
22706
  // dist/grok-generated-image.js
22167
- import path12 from "node:path";
22707
+ import path13 from "node:path";
22168
22708
 
22169
22709
  // dist/local-media-markdown.js
22170
22710
  import { existsSync, statSync } from "node:fs";
22171
22711
  import os5 from "node:os";
22172
- import path11 from "node:path";
22712
+ import path12 from "node:path";
22173
22713
  var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
22174
22714
  ".aac",
22175
22715
  ".gif",
@@ -22188,14 +22728,14 @@ var MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
22188
22728
  ".webp"
22189
22729
  ]);
22190
22730
  function grokMediaResolveRoots(cwd, sessionDirectory) {
22191
- const roots = [path11.resolve(cwd)];
22731
+ const roots = [path12.resolve(cwd)];
22192
22732
  if (sessionDirectory) {
22193
- const session = path11.resolve(sessionDirectory);
22194
- roots.push(session, path11.join(session, "videos"), path11.join(session, "images"));
22733
+ const session = path12.resolve(sessionDirectory);
22734
+ roots.push(session, path12.join(session, "videos"), path12.join(session, "images"));
22195
22735
  }
22196
22736
  const home = process.env.HOME ?? process.env.USERPROFILE ?? os5.homedir();
22197
22737
  if (home)
22198
- roots.push(path11.join(home, "Downloads"));
22738
+ roots.push(path12.join(home, "Downloads"));
22199
22739
  return roots;
22200
22740
  }
22201
22741
  function rewriteLocalMediaMarkdown(text, roots, options = {}) {
@@ -22296,7 +22836,7 @@ function parseInlineCode(text, start) {
22296
22836
  return { closed: false, content: text.slice(start + 1), end: text.length };
22297
22837
  }
22298
22838
  function mediaMarkdownImage(absolutePath) {
22299
- const name = path11.basename(absolutePath).replaceAll("]", "\\]");
22839
+ const name = path12.basename(absolutePath).replaceAll("]", "\\]");
22300
22840
  return `![${name}](${formatMarkdownDestination(absolutePath, false)})`;
22301
22841
  }
22302
22842
  function parseMarkdownImage(text, start) {
@@ -22421,11 +22961,11 @@ function resolveLocalMediaPath(raw, roots, exists = mediaFileExists) {
22421
22961
  if (!hasMediaExtension(stripped))
22422
22962
  return null;
22423
22963
  if (isAbsoluteMediaPath(stripped)) {
22424
- const absolute = path11.resolve(stripped);
22964
+ const absolute = path12.resolve(stripped);
22425
22965
  return exists(absolute) ? absolute : null;
22426
22966
  }
22427
22967
  for (const root of roots) {
22428
- const absolute = path11.resolve(root, stripped);
22968
+ const absolute = path12.resolve(root, stripped);
22429
22969
  if (exists(absolute))
22430
22970
  return absolute;
22431
22971
  }
@@ -22447,11 +22987,11 @@ function stripFileUrl(value) {
22447
22987
  }
22448
22988
  }
22449
22989
  function isAbsoluteMediaPath(value) {
22450
- return path11.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
22990
+ return path12.isAbsolute(value) || /^[a-zA-Z]:[\\/]/.test(value);
22451
22991
  }
22452
22992
  function hasMediaExtension(value) {
22453
22993
  const pathname = value.split(/[?#]/, 1)[0] ?? value;
22454
- return MEDIA_EXTENSIONS.has(path11.extname(pathname).toLowerCase());
22994
+ return MEDIA_EXTENSIONS.has(path12.extname(pathname).toLowerCase());
22455
22995
  }
22456
22996
  function mediaFileExists(absolutePath) {
22457
22997
  try {
@@ -22481,7 +23021,7 @@ function fromNativeRecord(value, exists) {
22481
23021
  const savedPath = stringField(value, "path");
22482
23022
  if (!validAbsolutePath(savedPath))
22483
23023
  return null;
22484
- const resolved = path12.resolve(savedPath);
23024
+ const resolved = path13.resolve(savedPath);
22485
23025
  if (!exists(resolved))
22486
23026
  return null;
22487
23027
  const filename = stringField(value, "filename");
@@ -22868,11 +23408,18 @@ function grokSubagentEventFromUpdate(update) {
22868
23408
  return null;
22869
23409
  if (update.sessionUpdate === "subagent_spawned") {
22870
23410
  const description = bounded(stringField3(update, "description"), DESCRIPTION_LIMIT);
22871
- const role = bounded(stringField3(update, "subagent_type") ?? stringField3(update, "role"), DESCRIPTION_LIMIT);
23411
+ const nativeType = stringField3(update, "subagent_type");
23412
+ const role = bounded(stringField3(update, "role") ?? (nativeType === "general-purpose" ? void 0 : nativeType), DESCRIPTION_LIMIT);
22872
23413
  const model2 = bounded(stringField3(update, "model"), DESCRIPTION_LIMIT);
23414
+ const parentPromptId = idField(update, "parent_prompt_id");
23415
+ const childSessionId = idField(update, "child_session_id");
23416
+ const attemptId = idField(update, "attempt_id");
22873
23417
  return {
22874
23418
  type: "subagent.spawned",
22875
23419
  nativeSubagentId,
23420
+ ...parentPromptId ? { parentPromptId } : {},
23421
+ ...childSessionId ? { childSessionId } : {},
23422
+ ...attemptId ? { attemptId } : {},
22876
23423
  ...description ? { description } : {},
22877
23424
  ...role ? { role } : {},
22878
23425
  ...model2 ? { model: model2 } : {}
@@ -22882,13 +23429,14 @@ function grokSubagentEventFromUpdate(update) {
22882
23429
  const mapped = mapTaskStatus(typeof update.status === "string" ? update.status : void 0);
22883
23430
  if (!mapped || mapped === "running" || mapped === "pending")
22884
23431
  return null;
22885
- const status = mapped === "failed" ? "failed" : mapped === "interrupted" ? "interrupted" : "completed";
23432
+ const status2 = mapped === "failed" ? "failed" : mapped === "interrupted" ? "interrupted" : "completed";
22886
23433
  const resultSummary = bounded(typeof update.output === "string" ? update.output.trim() : void 0, SUMMARY_LIMIT);
22887
23434
  return {
22888
23435
  type: "subagent.finished",
22889
23436
  nativeSubagentId,
22890
- status,
22891
- ...resultSummary ? { resultSummary } : {}
23437
+ status: status2,
23438
+ ...resultSummary ? { resultSummary } : {},
23439
+ ...typeof update.output === "string" ? { output: update.output } : {}
22892
23440
  };
22893
23441
  }
22894
23442
  return null;
@@ -22905,11 +23453,11 @@ function grokSubagentWaitSettlements(input) {
22905
23453
  const settled = [];
22906
23454
  for (const result of resultEntries) {
22907
23455
  const id = idField(result, "task_id") ?? idField(result, "subagent_id");
22908
- const status = mapTaskStatus(typeof result.status === "string" ? result.status : void 0);
22909
- if (!id || !status || status === "running" || status === "pending")
23456
+ const status2 = mapTaskStatus(typeof result.status === "string" ? result.status : void 0);
23457
+ if (!id || !status2 || status2 === "running" || status2 === "pending")
22910
23458
  continue;
22911
23459
  const resultSummary = bounded(typeof result.output === "string" ? result.output.trim() : void 0, SUMMARY_LIMIT);
22912
- settled.push({ id, status, ...resultSummary ? { resultSummary } : {} });
23460
+ settled.push({ id, status: status2, ...resultSummary ? { resultSummary } : {} });
22913
23461
  }
22914
23462
  return settled;
22915
23463
  }
@@ -22953,12 +23501,12 @@ function taskOutputTextSettlements(rawOutput, content, ids) {
22953
23501
  const pattern = /---\s*Task\s+(\S+)\s+\[(completed|failed|interrupted|cancelled|canceled)\]\s*---/gi;
22954
23502
  for (const match of text.matchAll(pattern)) {
22955
23503
  const id = match[1]?.trim();
22956
- const status = mapTaskStatus(match[2]);
22957
- if (!id || !status || status === "running" || status === "pending")
23504
+ const status2 = mapTaskStatus(match[2]);
23505
+ if (!id || !status2 || status2 === "running" || status2 === "pending")
22958
23506
  continue;
22959
23507
  if (!ids.includes(id))
22960
23508
  continue;
22961
- settled.push({ id, status });
23509
+ settled.push({ id, status: status2 });
22962
23510
  }
22963
23511
  return settled;
22964
23512
  }
@@ -22982,10 +23530,10 @@ function taskOutputStatus(rawOutput, content) {
22982
23530
  }
22983
23531
  return void 0;
22984
23532
  }
22985
- function mapTaskStatus(status) {
22986
- if (!status)
23533
+ function mapTaskStatus(status2) {
23534
+ if (!status2)
22987
23535
  return void 0;
22988
- switch (status.toLowerCase()) {
23536
+ switch (status2.toLowerCase()) {
22989
23537
  case "completed":
22990
23538
  case "succeeded":
22991
23539
  case "success":
@@ -23052,27 +23600,12 @@ function terminalOutcome(stopReason) {
23052
23600
  }
23053
23601
  };
23054
23602
  }
23055
- var systemReminderPattern = /^\s*<system-reminder>[\s\S]*$/u;
23056
- var taskCompletedTurnKeyPattern = /^task-completed-/u;
23057
- function isSyntheticGrokUserText(text) {
23058
- return systemReminderPattern.test(text);
23059
- }
23060
- function isSyntheticGrokTurnKey(nativeTurnKey) {
23061
- return taskCompletedTurnKeyPattern.test(nativeTurnKey);
23062
- }
23063
- function isHostTurnEvent(event) {
23064
- return event.metadata?.hostTurn === true || event.metadata?.host_turn === true;
23065
- }
23066
23603
  function userEventIdentity(event) {
23067
23604
  const eventId = event.metadata?.eventId;
23068
23605
  if (typeof eventId === "string" && eventId.length > 0)
23069
23606
  return eventId;
23070
23607
  return event.messageId && event.messageId.length > 0 ? event.messageId : null;
23071
23608
  }
23072
- function explicitPromptIndex(event) {
23073
- const value = event.metadata?.promptIndex ?? event.metadata?.prompt_index;
23074
- return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
23075
- }
23076
23609
  function grokCheckpointId(promptIndex) {
23077
23610
  return String(promptIndex);
23078
23611
  }
@@ -23086,6 +23619,10 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23086
23619
  const knownByNativeKey = new Map(knownTurnRefs.filter((ref) => ref.harnessId === harnessId && ref.nativeSessionId === sessionId).map((ref) => [ref.nativeTurnKey, ref]));
23087
23620
  let turns = [];
23088
23621
  let input = "";
23622
+ let hiddenInput = false;
23623
+ let openingGoal;
23624
+ let displayInput;
23625
+ let startedAtMs;
23089
23626
  let items = [];
23090
23627
  let turnIndex = 0;
23091
23628
  let messageIndex = 0;
@@ -23103,12 +23640,14 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23103
23640
  const mediaRoots = grokMediaResolveRoots(cwd, sessionDirectory);
23104
23641
  const subagents = /* @__PURE__ */ new Map();
23105
23642
  const subagentAliases = /* @__PURE__ */ new Map();
23643
+ const goalSummarizers = /* @__PURE__ */ new Set();
23644
+ const goalSummaries = [];
23106
23645
  const rememberSubagentAlias = (callId, nativeId) => {
23107
23646
  subagentAliases.set(callId, callId);
23108
23647
  if (nativeId)
23109
23648
  subagentAliases.set(nativeId, callId);
23110
23649
  };
23111
- const completeHistorySubagent = (callId, status, content, rawOutput, rawInput) => {
23650
+ const completeHistorySubagent = (callId, status2, content, rawOutput, rawInput) => {
23112
23651
  const current = subagents.get(callId);
23113
23652
  const currentAgent = current?.subagents[0];
23114
23653
  if (!current || !currentAgent)
@@ -23116,7 +23655,7 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23116
23655
  const nativeSubagentId = grokNativeSubagentId(rawInput, rawOutput, content) ?? currentAgent.nativeSubagentId;
23117
23656
  rememberSubagentAlias(callId, nativeSubagentId);
23118
23657
  const summary = grokSubagentResultSummary(content, rawOutput);
23119
- const failed = status === "failed";
23658
+ const failed = status2 === "failed";
23120
23659
  const keepRunning = !failed && (currentAgent.background === true || current.operation === "send");
23121
23660
  const item = {
23122
23661
  ...current,
@@ -23188,10 +23727,26 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23188
23727
  const completeAgent = () => {
23189
23728
  if (!agent || agent.text.length === 0)
23190
23729
  return;
23730
+ const summary = goalSummaries.find((value) => agent !== null && agent.text.endsWith(value) && agent.text.length > value.length);
23731
+ const head = summary ? agent.text.slice(0, -summary.length) : agent.text;
23732
+ const split = summary !== void 0 && head.trim().length > 0;
23191
23733
  items.push({
23192
- item: { ...agent, text: rewriteLocalMediaMarkdown(agent.text, mediaRoots) },
23734
+ item: {
23735
+ ...agent,
23736
+ text: rewriteLocalMediaMarkdown(split ? head : agent.text, mediaRoots)
23737
+ },
23193
23738
  outcome: { status: "succeeded" }
23194
23739
  });
23740
+ if (split) {
23741
+ items.push({
23742
+ item: {
23743
+ ...agent,
23744
+ itemId: grokTextItemId(sessionId, turnIndex, "agentMessage", ++agentIndex),
23745
+ text: rewriteLocalMediaMarkdown(summary, mediaRoots)
23746
+ },
23747
+ outcome: { status: "succeeded" }
23748
+ });
23749
+ }
23195
23750
  agent = null;
23196
23751
  };
23197
23752
  const completeReasoning = () => {
@@ -23223,7 +23778,7 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23223
23778
  if (image)
23224
23779
  generatedImages.set(callId, image);
23225
23780
  };
23226
- const completeTool = (callId, status, content, rawOutput) => {
23781
+ const completeTool = (callId, status2, content, rawOutput) => {
23227
23782
  applyToolProjection(callId, content, rawOutput);
23228
23783
  const tool = tools.get(callId);
23229
23784
  if (!tool)
@@ -23231,7 +23786,7 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23231
23786
  tools.delete(callId);
23232
23787
  const generatedImage = generatedImages.get(callId);
23233
23788
  generatedImages.delete(callId);
23234
- const outcome = status === "failed" ? {
23789
+ const outcome = status2 === "failed" ? {
23235
23790
  status: "failed",
23236
23791
  error: {
23237
23792
  code: "nativeFailure",
@@ -23239,11 +23794,11 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23239
23794
  retryable: false
23240
23795
  }
23241
23796
  } : { status: "succeeded" };
23242
- if (status === "completed") {
23797
+ if (status2 === "completed") {
23243
23798
  settleWatchedSubagents(tool.type === "toolExecution" ? tool.toolName : tool.command, tool.type === "toolExecution" ? tool.arguments : void 0, content, rawOutput);
23244
23799
  }
23245
23800
  items.push({ item: tool, outcome });
23246
- if (status !== "completed")
23801
+ if (status2 !== "completed")
23247
23802
  return;
23248
23803
  const changes = projectGrokFileChanges(content, cwd);
23249
23804
  if (changes) {
@@ -23262,7 +23817,7 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23262
23817
  outcome: { status: "succeeded" }
23263
23818
  });
23264
23819
  };
23265
- const completeTurn = (outcome, terminalKey) => {
23820
+ const completeTurn = (outcome, terminalKey, completedAtMs) => {
23266
23821
  if (input.length === 0)
23267
23822
  return;
23268
23823
  const reconstructedKey = terminalKey ?? nativeTurnKey;
@@ -23289,9 +23844,10 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23289
23844
  checkpointId: grokCheckpointId(currentPromptIndex),
23290
23845
  formatVersion: 1
23291
23846
  }),
23292
- input: [{ type: "text", text: input }],
23847
+ input: displayInput ? [{ type: "text", text: displayInput }] : hiddenInput ? [] : [{ type: "text", text: input }],
23293
23848
  items,
23294
- outcome
23849
+ outcome,
23850
+ ...startedAtMs !== void 0 && completedAtMs !== void 0 && completedAtMs >= startedAtMs ? { startedAtMs, completedAtMs } : {}
23295
23851
  });
23296
23852
  turnIndex += 1;
23297
23853
  messageIndex = 0;
@@ -23300,9 +23856,25 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23300
23856
  nativeTurnKey = null;
23301
23857
  currentPromptIndex = null;
23302
23858
  input = "";
23859
+ displayInput = void 0;
23860
+ startedAtMs = void 0;
23303
23861
  items = [];
23304
- };
23305
- for (const event of replay) {
23862
+ goalSummarizers.clear();
23863
+ goalSummaries.length = 0;
23864
+ };
23865
+ const groups = classifyGrokHistory(replay);
23866
+ const durableSynthetic = new Set(groups.filter((g) => g.disposition === "durable").map((g) => g.user));
23867
+ const reused = groups.find((g) => g.disposition === "reused");
23868
+ if (reused)
23869
+ throw new GrokNativeIdentityReuseError(reused.terminal.nativeTurnKey);
23870
+ for (const event of placeGrokGoalHelpers(replay, groups)) {
23871
+ if (event.type === "goal.changed") {
23872
+ const update = event.update;
23873
+ if (update === null || update.status === "cleared")
23874
+ openingGoal = void 0;
23875
+ else if (update.last_event === "goal_created" && typeof update.goal_id === "string" && typeof update.objective === "string" && update.objective.length > 0 && update.goal_id !== openingGoal?.id)
23876
+ openingGoal = { id: update.goal_id, objective: update.objective, pending: true };
23877
+ }
23306
23878
  if (event.type === "rewind.marker") {
23307
23879
  turns = turns.filter((turn) => {
23308
23880
  const index = turn.checkpoint ? parseGrokPromptIndex(turn.checkpoint.checkpointId) : null;
@@ -23316,6 +23888,9 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23316
23888
  nativePromptIndex = event.targetPromptIndex;
23317
23889
  currentPromptIndex = null;
23318
23890
  input = "";
23891
+ openingGoal = void 0;
23892
+ displayInput = void 0;
23893
+ startedAtMs = void 0;
23319
23894
  items = [];
23320
23895
  agent = null;
23321
23896
  reasoning = null;
@@ -23323,37 +23898,43 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23323
23898
  generatedImages.clear();
23324
23899
  subagents.clear();
23325
23900
  subagentAliases.clear();
23901
+ goalSummarizers.clear();
23902
+ goalSummaries.length = 0;
23326
23903
  continue;
23327
23904
  }
23328
23905
  if (event.type === "user.text") {
23329
- if (isHostTurnEvent(event))
23906
+ if (grokHostTurn(event))
23330
23907
  continue;
23331
- if (isSyntheticGrokUserText(event.text)) {
23908
+ if (grokHiddenInput(event) && !durableSynthetic.has(event)) {
23332
23909
  if (input.length > 0) {
23333
23910
  completeTurn({
23334
23911
  status: "unknown",
23335
23912
  reason: "Grok Native history has no terminal signal"
23336
23913
  });
23337
23914
  }
23338
- nativePromptIndex = (explicitPromptIndex(event) ?? nativePromptIndex) + 1;
23915
+ nativePromptIndex = (grokPromptIndex(event) ?? nativePromptIndex) + 1;
23339
23916
  continue;
23340
23917
  }
23341
23918
  if (input.length > 0) {
23342
23919
  input += event.text;
23343
23920
  continue;
23344
23921
  }
23345
- currentPromptIndex = explicitPromptIndex(event) ?? nativePromptIndex;
23922
+ currentPromptIndex = grokPromptIndex(event) ?? nativePromptIndex;
23346
23923
  nativePromptIndex = currentPromptIndex + 1;
23347
23924
  input = event.text;
23925
+ hiddenInput = grokHiddenInput(event);
23926
+ startedAtMs = grokEventTimestamp(event);
23927
+ if (hiddenInput && durableSynthetic.has(event) && openingGoal?.pending) {
23928
+ displayInput = `/goal ${openingGoal.objective}`;
23929
+ openingGoal.pending = false;
23930
+ }
23348
23931
  nativeTurnKey = userEventIdentity(event);
23349
23932
  continue;
23350
23933
  }
23351
23934
  if (input.length === 0)
23352
23935
  continue;
23353
23936
  if (event.type === "turn.completed") {
23354
- if (isSyntheticGrokTurnKey(event.nativeTurnKey))
23355
- continue;
23356
- completeTurn(terminalOutcome(event.stopReason), event.nativeTurnKey);
23937
+ completeTurn(terminalOutcome(event.stopReason), event.nativeTurnKey, grokEventTimestamp(event));
23357
23938
  } else if (event.type === "compaction.started") {
23358
23939
  completeReasoning();
23359
23940
  completeAgent();
@@ -23473,12 +24054,15 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23473
24054
  }
23474
24055
  }
23475
24056
  } else if (event.type === "subagent.spawned") {
24057
+ if (event.description === "goal summarizer")
24058
+ goalSummarizers.add(event.nativeSubagentId);
24059
+ let bound = false;
23476
24060
  for (const [callId, current] of subagents) {
23477
24061
  const agent2 = current.subagents[0];
23478
24062
  if (!agent2)
23479
24063
  continue;
23480
24064
  const matchesId = agent2.nativeSubagentId === event.nativeSubagentId;
23481
- const matchesDescription = !agent2.nativeSubagentId && event.description !== void 0 && agent2.description === event.description;
24065
+ const matchesDescription = !event.parentPromptId && !agent2.nativeSubagentId && event.description !== void 0 && agent2.description === event.description;
23482
24066
  if (!matchesId && !matchesDescription)
23483
24067
  continue;
23484
24068
  rememberSubagentAlias(callId, event.nativeSubagentId);
@@ -23494,9 +24078,36 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
23494
24078
  }
23495
24079
  ]
23496
24080
  });
24081
+ bound = true;
23497
24082
  break;
23498
24083
  }
24084
+ if (!bound && event.parentPromptId && !items.some((s) => s.item.type === "subagentDelegation" && s.item.subagents.some((a) => a.nativeSubagentId === event.nativeSubagentId))) {
24085
+ completeReasoning();
24086
+ completeAgent();
24087
+ const callId = `grok-helper-${event.nativeSubagentId}`;
24088
+ rememberSubagentAlias(callId, event.nativeSubagentId);
24089
+ subagents.set(callId, {
24090
+ type: "subagentDelegation",
24091
+ itemId: hostItemIdSchema.parse(callId),
24092
+ operation: "spawn",
24093
+ subagents: [
24094
+ {
24095
+ subagentId: event.nativeSubagentId,
24096
+ nativeSubagentId: event.nativeSubagentId,
24097
+ description: event.description ?? "Grok Subagent",
24098
+ ...event.model ? { model: event.model } : {},
24099
+ ...event.role ? { role: event.role } : {},
24100
+ background: true,
24101
+ status: "running"
24102
+ }
24103
+ ]
24104
+ });
24105
+ }
23499
24106
  } else if (event.type === "subagent.finished") {
24107
+ const output = event.output ?? event.resultSummary;
24108
+ if (goalSummarizers.has(event.nativeSubagentId) && event.status === "completed" && output) {
24109
+ goalSummaries.push(output);
24110
+ }
23500
24111
  settleWatchedSubagents("get_command_or_subagent_output", { task_ids: [event.nativeSubagentId] }, event.resultSummary ? [event.resultSummary] : void 0, { task_id: event.nativeSubagentId, status: event.status, output: event.resultSummary });
23501
24112
  }
23502
24113
  }
@@ -23509,12 +24120,6 @@ function resolveGrokTargetPromptIndex(snapshot, checkpointId) {
23509
24120
  return null;
23510
24121
  return parseGrokPromptIndex(turn.checkpoint.checkpointId);
23511
24122
  }
23512
- function resolveGrokLastTurnPromptIndex(snapshot) {
23513
- const last = snapshot.turns.at(-1);
23514
- if (!last?.checkpoint)
23515
- return null;
23516
- return parseGrokPromptIndex(last.checkpoint.checkpointId);
23517
- }
23518
24123
 
23519
24124
  // dist/grok-fork.js
23520
24125
  var GROK_SESSION_FORK_METHOD = "_x.ai/session/fork";
@@ -23563,11 +24168,11 @@ function parseGrokForkResponse(value) {
23563
24168
  }
23564
24169
  function projectRelativePath(value, cwds) {
23565
24170
  const normalized = value.replaceAll("\\", "/");
23566
- if (!path13.isAbsolute(value))
24171
+ if (!path14.isAbsolute(value))
23567
24172
  return normalized;
23568
24173
  for (const cwd of cwds) {
23569
- const relative = path13.relative(path13.resolve(cwd), path13.resolve(value));
23570
- if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path13.sep}`)) {
24174
+ const relative = path14.relative(path14.resolve(cwd), path14.resolve(value));
24175
+ if (relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path14.sep}`)) {
23571
24176
  return relative.replaceAll("\\", "/");
23572
24177
  }
23573
24178
  }
@@ -23632,8 +24237,8 @@ async function forkGrokSession(input) {
23632
24237
  error: error51("sessionNotFound", "Grok Native Session is unavailable")
23633
24238
  };
23634
24239
  }
23635
- const sourceCwd = path13.resolve(located.cwd);
23636
- const targetCwd = path13.resolve(input.cwd);
24240
+ const sourceCwd = path14.resolve(located.cwd);
24241
+ const targetCwd = path14.resolve(input.cwd);
23637
24242
  const source = await readSnapshot({ ...input, cwd: sourceCwd }, sourceRef.data.nativeSessionId);
23638
24243
  if (!source.ok)
23639
24244
  return source;
@@ -23816,7 +24421,7 @@ function parseGrokCompactResult(value, cancelled = false) {
23816
24421
  }
23817
24422
 
23818
24423
  // dist/grok-rewind.js
23819
- import path14 from "node:path";
24424
+ import path15 from "node:path";
23820
24425
  var GROK_REWIND_EXECUTE_METHOD = "_x.ai/rewind/execute";
23821
24426
  function error52(code, message, retryable = false) {
23822
24427
  return { code, message, retryable };
@@ -23874,12 +24479,19 @@ async function readSnapshot2(input, sessionId) {
23874
24479
  };
23875
24480
  }
23876
24481
  }
23877
- async function rewindGrokLastTurn(input) {
24482
+ async function rewindGrokSession(input) {
23878
24483
  const sourceRef = nativeSessionRefSchema.safeParse(input.sourceRef);
23879
24484
  if (!sourceRef.success || sourceRef.data.harnessId !== input.harnessId) {
23880
24485
  return {
23881
24486
  ok: false,
23882
- error: error52("invalidRequest", "Grok last-Turn Rewind identity does not belong to Grok")
24487
+ error: error52("invalidRequest", "Grok Rewind identity does not belong to Grok")
24488
+ };
24489
+ }
24490
+ const checkpoint = input.checkpoint ? nativeCheckpointRefSchema.safeParse(input.checkpoint) : null;
24491
+ if (checkpoint && (!checkpoint.success || checkpoint.data.harnessId !== input.harnessId || checkpoint.data.nativeSessionId !== sourceRef.data.nativeSessionId)) {
24492
+ return {
24493
+ ok: false,
24494
+ error: error52("checkpointNotFound", "Grok Rewind Checkpoint does not belong to the source Session")
23883
24495
  };
23884
24496
  }
23885
24497
  const located = await input.locateSource(sourceRef.data.nativeSessionId);
@@ -23889,22 +24501,39 @@ async function rewindGrokLastTurn(input) {
23889
24501
  error: error52("sessionNotFound", "Grok Native Session is unavailable")
23890
24502
  };
23891
24503
  }
23892
- const sourceCwd = path14.resolve(located.cwd);
23893
- const targetCwd = path14.resolve(input.cwd);
24504
+ const sourceCwd = path15.resolve(located.cwd);
24505
+ const targetCwd = path15.resolve(input.cwd);
23894
24506
  if (sourceCwd !== targetCwd) {
23895
24507
  return {
23896
24508
  ok: false,
23897
- error: error52("invalidRequest", "Grok last-Turn Rewind must stay in the source cwd")
24509
+ error: error52("invalidRequest", "Grok Rewind must stay in the source cwd")
24510
+ };
24511
+ }
24512
+ let sourceHistory;
24513
+ try {
24514
+ sourceHistory = await input.readHistory(sourceCwd, sourceRef.data.nativeSessionId);
24515
+ } catch {
24516
+ return {
24517
+ ok: false,
24518
+ error: error52("nativeFailure", "Grok Native Session history could not be read", true)
24519
+ };
24520
+ }
24521
+ if (sourceHistory.some((event) => event.type === "user.text" && isGrokGoalControlPrompt(event.text) && event.metadata?.hostTurn !== true && event.metadata?.host_turn !== true)) {
24522
+ return {
24523
+ ok: false,
24524
+ error: error52("unsupported", "Grok history contains legacy goal controls without native rewind boundaries; use a newer Grok build")
23898
24525
  };
23899
24526
  }
23900
- const source = await readSnapshot2({ ...input, cwd: sourceCwd }, sourceRef.data.nativeSessionId);
24527
+ const source = await readSnapshot2({ ...input, cwd: sourceCwd, readHistory: async () => sourceHistory }, sourceRef.data.nativeSessionId);
23901
24528
  if (!source.ok)
23902
24529
  return source;
23903
- const targetPromptIndex = resolveGrokLastTurnPromptIndex(source.value);
23904
- if (source.value.turns.length === 0 || targetPromptIndex === null) {
24530
+ const checkpointId = checkpoint?.success ? checkpoint.data.checkpointId : source.value.turns.at(-1)?.checkpoint?.checkpointId;
24531
+ const retainedCount = source.value.turns.findIndex((turn) => turn.checkpoint?.checkpointId === checkpointId);
24532
+ const targetPromptIndex = checkpointId === void 0 ? null : resolveGrokTargetPromptIndex(source.value, checkpointId);
24533
+ if (retainedCount < 0 || targetPromptIndex === null) {
23905
24534
  return {
23906
24535
  ok: false,
23907
- error: error52("invalidState", "Grok Native Session has no Turn to rewind")
24536
+ error: error52(input.checkpoint ? "checkpointNotFound" : "invalidState", "Grok Rewind boundary is unavailable")
23908
24537
  };
23909
24538
  }
23910
24539
  let sessionId;
@@ -23933,9 +24562,9 @@ async function rewindGrokLastTurn(input) {
23933
24562
  const derived = await readSnapshot2({ ...input, cwd: targetCwd }, sessionId);
23934
24563
  if (!derived.ok)
23935
24564
  return derived;
23936
- const expectedKeys = source.value.turns.slice(0, -1).map((turn) => turn.nativeTurnRef.nativeTurnKey);
24565
+ const expectedKeys = source.value.turns.slice(0, retainedCount).map((turn) => turn.nativeTurnRef.nativeTurnKey);
23937
24566
  const actualKeys = derived.value.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey);
23938
- if (derived.value.turns.length !== source.value.turns.length - 1 || actualKeys.some((key, index) => key !== expectedKeys[index]) || derived.value.turns.some((turn) => turn.nativeTurnRef.nativeSessionId !== sessionId)) {
24567
+ if (derived.value.turns.length !== retainedCount || actualKeys.some((key, index) => key !== expectedKeys[index]) || derived.value.turns.some((turn) => turn.nativeTurnRef.nativeSessionId !== sessionId)) {
23939
24568
  return {
23940
24569
  ok: false,
23941
24570
  error: error52("protocolError", "Grok Native Rewind history is invalid")
@@ -24515,8 +25144,17 @@ function signalProcessTree(child, signal) {
24515
25144
  throw error53;
24516
25145
  }
24517
25146
  }
25147
+ function grokNotificationMetadata(envelope, update) {
25148
+ if (!isRecord15(envelope) && !isRecord15(update))
25149
+ return void 0;
25150
+ return { ...isRecord15(update) ? update : {}, ...isRecord15(envelope) ? envelope : {} };
25151
+ }
24518
25152
  function transportEvent(update, metadata) {
24519
25153
  const extension = update;
25154
+ if (extension.sessionUpdate === "goal_updated")
25155
+ return { type: "goal.changed", update: extension };
25156
+ if (extension.sessionUpdate === "goal_cleared")
25157
+ return { type: "goal.changed", update: null };
24520
25158
  if (extension.sessionUpdate === "response_completed") {
24521
25159
  return {
24522
25160
  type: "response.completed",
@@ -24610,20 +25248,20 @@ function transportEvent(update, metadata) {
24610
25248
  function grokHomeDir(options) {
24611
25249
  const environment = { ...process.env, ...options.environment };
24612
25250
  const home = environment.HOME ?? environment.USERPROFILE ?? os6.homedir();
24613
- return environment.GROK_HOME ?? path15.join(home, ".grok");
25251
+ return environment.GROK_HOME ?? path16.join(home, ".grok");
24614
25252
  }
24615
25253
  function grokNativeSessionDirectory(options, sessionId) {
24616
- return path15.join(grokHomeDir(options), "sessions", encodeURIComponent(path15.resolve(options.cwd)), sessionId);
25254
+ return path16.join(grokHomeDir(options), "sessions", encodeURIComponent(path16.resolve(options.cwd)), sessionId);
24617
25255
  }
24618
25256
  function nativeSessionFile(options, sessionId, fileName) {
24619
- return path15.join(grokNativeSessionDirectory(options, sessionId), fileName);
25257
+ return path16.join(grokNativeSessionDirectory(options, sessionId), fileName);
24620
25258
  }
24621
25259
  function nativeHistoryPath(options, sessionId) {
24622
25260
  return nativeSessionFile(options, sessionId, "updates.jsonl");
24623
25261
  }
24624
25262
  async function readNativeSignals(options, sessionId) {
24625
25263
  try {
24626
- return JSON.parse(await readFile4(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
25264
+ return JSON.parse(await readFile5(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
24627
25265
  } catch {
24628
25266
  return void 0;
24629
25267
  }
@@ -24636,7 +25274,7 @@ async function locateGrokNativeSession(options, sessionId) {
24636
25274
  return null;
24637
25275
  let entries;
24638
25276
  try {
24639
- entries = await readdir(path15.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
25277
+ entries = await readdir(path16.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
24640
25278
  } catch (error53) {
24641
25279
  if (isMissingFile(error53))
24642
25280
  return null;
@@ -24650,7 +25288,7 @@ async function locateGrokNativeSession(options, sessionId) {
24650
25288
  continue;
24651
25289
  let summaryRaw;
24652
25290
  try {
24653
- summaryRaw = await readFile4(path15.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
25291
+ summaryRaw = await readFile5(path16.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
24654
25292
  } catch (error53) {
24655
25293
  if (isMissingFile(error53) || isRecord15(error53) && error53.code === "ENOTDIR")
24656
25294
  continue;
@@ -24667,8 +25305,8 @@ async function locateGrokNativeSession(options, sessionId) {
24667
25305
  if (!isRecord15(parsed))
24668
25306
  continue;
24669
25307
  const info = parsed.info;
24670
- const cwd = isRecord15(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path15.resolve(info.cwd) : path15.resolve(decodeURIComponent(entry.name));
24671
- const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path15.resolve(parsed.source_workspace_dir) : void 0;
25308
+ const cwd = isRecord15(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path16.resolve(info.cwd) : path16.resolve(decodeURIComponent(entry.name));
25309
+ const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path16.resolve(parsed.source_workspace_dir) : void 0;
24672
25310
  matches.push({
24673
25311
  cwd,
24674
25312
  ...sourceWorkspaceDir ? { sourceWorkspaceDir } : {}
@@ -24678,7 +25316,7 @@ async function locateGrokNativeSession(options, sessionId) {
24678
25316
  }
24679
25317
  async function readGrokNativeHistory(options, sessionId) {
24680
25318
  try {
24681
- return parseNativeHistory(await readFile4(nativeHistoryPath({ ...options, cwd: path15.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
25319
+ return parseNativeHistory(await readFile5(nativeHistoryPath({ ...options, cwd: path16.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
24682
25320
  } catch (error53) {
24683
25321
  if (isMissingFile(error53))
24684
25322
  return [];
@@ -24705,7 +25343,9 @@ function parseNativeHistory(contents, sessionId) {
24705
25343
  const params = record2.params;
24706
25344
  if (params.sessionId !== sessionId || !isRecord15(params.update))
24707
25345
  continue;
24708
- const metadata = isRecord15(params._meta) ? params._meta : void 0;
25346
+ let metadata = grokNotificationMetadata(params._meta, params.update._meta);
25347
+ if (typeof record2.timestamp === "number" && Number.isFinite(record2.timestamp))
25348
+ metadata = { nativeTimestampMs: record2.timestamp * 1e3, ...metadata };
24709
25349
  const event = transportEvent(params.update, metadata);
24710
25350
  if (event)
24711
25351
  events.push(metadata ? { ...event, metadata } : event);
@@ -24716,6 +25356,8 @@ var GrokAcpTransport = class {
24716
25356
  #options;
24717
25357
  #activeCompact = null;
24718
25358
  #activePrompt = null;
25359
+ #background = null;
25360
+ #goalPrompts = 0;
24719
25361
  #child = null;
24720
25362
  #closed = false;
24721
25363
  #closing = false;
@@ -24867,7 +25509,7 @@ var GrokAcpTransport = class {
24867
25509
  }
24868
25510
  }
24869
25511
  async questionActivity(toolCallId) {
24870
- if (!this.#connection || !this.#sessionId || !this.#activePrompt || this.#closed || this.#closing)
25512
+ if (!this.#connection || !this.#sessionId || !this.#activePrompt && !this.#background || this.#closed || this.#closing)
24871
25513
  return null;
24872
25514
  try {
24873
25515
  const raw = await withTimeout(this.#connection.request(GROK_QUESTION_ACTIVITY_METHOD, {
@@ -24887,6 +25529,8 @@ var GrokAcpTransport = class {
24887
25529
  if (!this.#connection)
24888
25530
  throw new GrokTransportError("unavailable", "Grok ACP is unavailable");
24889
25531
  try {
25532
+ const before = await this.readHistory(params.sessionId);
25533
+ const markerCount = before.filter((event) => event.type === "rewind.marker").length;
24890
25534
  const raw = await withTimeout(this.#connection.request(GROK_REWIND_EXECUTE_METHOD, params), this.#options.commandTimeoutMs, "Grok Session rewind");
24891
25535
  const parsed = parseGrokRewindResponse(raw);
24892
25536
  if (!parsed) {
@@ -24895,6 +25539,19 @@ var GrokAcpTransport = class {
24895
25539
  if (!parsed.success) {
24896
25540
  throw new GrokTransportError("unavailable", parsed.error && parsed.error.length > 0 ? `Grok Native Rewind failed: ${parsed.error}` : "Grok Native Rewind did not truncate history");
24897
25541
  }
25542
+ if (parsed.targetPromptIndex !== params.targetPromptIndex || parsed.mode !== void 0 && parsed.mode !== params.mode) {
25543
+ throw new GrokTransportError("protocolError", "Grok Rewind did not confirm the requested conversation boundary");
25544
+ }
25545
+ const deadline = Date.now() + 3e3;
25546
+ for (; ; ) {
25547
+ const markers = (await this.readHistory(params.sessionId)).filter((event) => event.type === "rewind.marker");
25548
+ if (markers.length > markerCount && markers.at(-1)?.targetPromptIndex === params.targetPromptIndex)
25549
+ break;
25550
+ if (this.#closing || this.#closed || Date.now() >= deadline) {
25551
+ throw new GrokTransportError("protocolError", "Grok Rewind marker is not available in Native history");
25552
+ }
25553
+ await delay3(25);
25554
+ }
24898
25555
  } catch (error53) {
24899
25556
  if (error53 instanceof GrokTransportError)
24900
25557
  throw error53;
@@ -24982,6 +25639,25 @@ var GrokAcpTransport = class {
24982
25639
  this.#initialize = initialize;
24983
25640
  return initialize;
24984
25641
  }
25642
+ observeBackground(observer) {
25643
+ this.#background = observer;
25644
+ }
25645
+ async goalControl(text) {
25646
+ if (!this.#connection || !this.#sessionId || this.#closed || this.#closing)
25647
+ throw new GrokTransportError("unavailable", "Grok goal Session is unavailable");
25648
+ if (this.#goalPrompts > 0 && ["/goal pause", "/goal clear"].includes(text)) {
25649
+ await this.#connection.cancel({ sessionId: this.#sessionId });
25650
+ }
25651
+ this.#goalPrompts++;
25652
+ try {
25653
+ return await this.#connection.prompt({
25654
+ sessionId: this.#sessionId,
25655
+ prompt: [{ type: "text", text }]
25656
+ });
25657
+ } finally {
25658
+ this.#goalPrompts--;
25659
+ }
25660
+ }
24985
25661
  async runTurn(text, onEvent, onPermission, onElicitation, onQuestion = async () => ({ outcome: "cancelled" })) {
24986
25662
  const connection = this.#connection;
24987
25663
  if (!connection || !this.#sessionId || this.#closed || this.#closing) {
@@ -24994,10 +25670,25 @@ var GrokAcpTransport = class {
24994
25670
  const active = { onEvent, onPermission, onElicitation, onQuestion };
24995
25671
  this.#activePrompt = active;
24996
25672
  try {
24997
- return await connection.prompt({
25673
+ const historyStart = (await this.getHistory()).length;
25674
+ const response = await connection.prompt({
24998
25675
  sessionId: this.#sessionId,
24999
25676
  prompt: [{ type: "text", text }]
25000
25677
  });
25678
+ const promptId = response._meta?.promptId;
25679
+ if (response.stopReason === "end_turn" && typeof promptId === "string" && promptId.length > 0) {
25680
+ const deadline = Date.now() + 3e3;
25681
+ for (; ; ) {
25682
+ const history = await this.getHistory();
25683
+ if (history.slice(historyStart).some((event) => event.type === "turn.completed" && event.nativeTurnKey === promptId))
25684
+ break;
25685
+ if (this.#closing || this.#closed || Date.now() >= deadline) {
25686
+ throw new GrokTransportError("protocolError", "Grok completed Prompt is not available in Native history");
25687
+ }
25688
+ await delay3(25);
25689
+ }
25690
+ }
25691
+ return response;
25001
25692
  } finally {
25002
25693
  await yieldToEventLoop();
25003
25694
  if (this.#activePrompt === active)
@@ -25064,7 +25755,7 @@ var GrokAcpTransport = class {
25064
25755
  }
25065
25756
  cancel() {
25066
25757
  const connection = this.#connection;
25067
- if (!connection || !this.#sessionId || !this.#activePrompt && !this.#activeCompact) {
25758
+ if (!connection || !this.#sessionId || !this.#activePrompt && !this.#activeCompact && !this.#background && !this.#goalPrompts) {
25068
25759
  return Promise.reject(new Error("Grok ACP Session has no cancellable operation"));
25069
25760
  }
25070
25761
  if (this.#activeCompact)
@@ -25149,7 +25840,7 @@ var GrokAcpTransport = class {
25149
25840
  this.#availableCommands = parseGrokAvailableCommands(update.availableCommands);
25150
25841
  return;
25151
25842
  }
25152
- const metadata = isRecord15(notification._meta) ? notification._meta : void 0;
25843
+ const metadata = grokNotificationMetadata(notification._meta, notification.update._meta);
25153
25844
  const event = transportEvent(notification.update, metadata);
25154
25845
  if (!event)
25155
25846
  return;
@@ -25158,8 +25849,12 @@ var GrokAcpTransport = class {
25158
25849
  this.#replay.push(enriched);
25159
25850
  else if (this.#activePrompt)
25160
25851
  this.#activePrompt.onEvent(enriched);
25852
+ else if (this.#activeCompact)
25853
+ this.#activeCompact.onEvent(enriched);
25161
25854
  else
25162
- this.#activeCompact?.onEvent(enriched);
25855
+ this.#background?.onEvent(enriched);
25856
+ if (event.type === "goal.changed" && (this.#activePrompt || this.#activeCompact))
25857
+ this.#background?.onEvent(enriched);
25163
25858
  }
25164
25859
  #handleExtensionNotification(method, params) {
25165
25860
  if (!isGrokExtensionSessionUpdateMethod(method))
@@ -25169,13 +25864,17 @@ var GrokAcpTransport = class {
25169
25864
  this.#handleUpdate(params);
25170
25865
  }
25171
25866
  #handlePermission(params) {
25172
- if (params.sessionId !== this.#sessionId || !this.#activePrompt) {
25867
+ const observer = this.#activePrompt ?? this.#background;
25868
+ if (params.sessionId !== this.#sessionId || !observer) {
25173
25869
  return Promise.resolve({ outcome: { outcome: "cancelled" } });
25174
25870
  }
25175
- return this.#activePrompt.onPermission({ request: params, options: params.options });
25871
+ return observer.onPermission({
25872
+ request: params,
25873
+ options: params.options
25874
+ });
25176
25875
  }
25177
25876
  async #handleExtMethod(method, params) {
25178
- const activePrompt = !this.#closed && !this.#closing && this.#replay === null && this.#activeCompact === null ? this.#activePrompt : null;
25877
+ const activePrompt = !this.#closed && !this.#closing && this.#replay === null && this.#activeCompact === null ? this.#activePrompt ?? this.#background : null;
25179
25878
  if (method === GROK_ASK_USER_QUESTION_METHOD) {
25180
25879
  let request;
25181
25880
  try {
@@ -25212,8 +25911,8 @@ var GrokAcpTransport = class {
25212
25911
 
25213
25912
  // dist/session-import.js
25214
25913
  import { createReadStream as createReadStream2 } from "node:fs";
25215
- import { opendir as opendir2, readFile as readFile5, stat } from "node:fs/promises";
25216
- import path16 from "node:path";
25914
+ import { opendir as opendir2, readFile as readFile6, stat as stat2 } from "node:fs/promises";
25915
+ import path17 from "node:path";
25217
25916
  import { createInterface as createInterface2 } from "node:readline";
25218
25917
 
25219
25918
  // ../../harness-adapter/dist/session-import.js
@@ -25338,7 +26037,7 @@ function isRecord16(value) {
25338
26037
  return typeof value === "object" && value !== null && !Array.isArray(value);
25339
26038
  }
25340
26039
  async function readJson(file2, signal) {
25341
- return JSON.parse(await readFile5(file2, { encoding: "utf8", signal }));
26040
+ return JSON.parse(await readFile6(file2, { encoding: "utf8", signal }));
25342
26041
  }
25343
26042
  function processAlive(pid) {
25344
26043
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
@@ -25434,7 +26133,7 @@ var GrokSessionImport = class {
25434
26133
  const active = /* @__PURE__ */ new Set();
25435
26134
  let entries;
25436
26135
  try {
25437
- entries = await readJson(path16.join(this.#home(), "active_sessions.json"), signal);
26136
+ entries = await readJson(path17.join(this.#home(), "active_sessions.json"), signal);
25438
26137
  } catch (error53) {
25439
26138
  signal.throwIfAborted();
25440
26139
  if (isStorageAccessError(error53))
@@ -25451,7 +26150,7 @@ var GrokSessionImport = class {
25451
26150
  }
25452
26151
  /** Session ID to every directory claiming it. Enumerated links are not followed. */
25453
26152
  async #sessionDirectories(signal) {
25454
- const root = path16.join(this.#home(), "sessions");
26153
+ const root = path17.join(this.#home(), "sessions");
25455
26154
  const found = /* @__PURE__ */ new Map();
25456
26155
  const info = await optionalLstat(root);
25457
26156
  if (!info)
@@ -25462,7 +26161,7 @@ var GrokSessionImport = class {
25462
26161
  signal.throwIfAborted();
25463
26162
  if (!workspace.isDirectory())
25464
26163
  continue;
25465
- const workspaceDirectory = path16.join(root, workspace.name);
26164
+ const workspaceDirectory = path17.join(root, workspace.name);
25466
26165
  const sessions = await opendir2(workspaceDirectory).catch((error53) => {
25467
26166
  if (isMissingFileError(error53))
25468
26167
  return null;
@@ -25475,7 +26174,7 @@ var GrokSessionImport = class {
25475
26174
  if (!session.isDirectory())
25476
26175
  continue;
25477
26176
  const directories = found.get(session.name) ?? [];
25478
- directories.push(path16.join(workspaceDirectory, session.name));
26177
+ directories.push(path17.join(workspaceDirectory, session.name));
25479
26178
  found.set(session.name, directories);
25480
26179
  }
25481
26180
  }
@@ -25483,10 +26182,10 @@ var GrokSessionImport = class {
25483
26182
  }
25484
26183
  async #candidate(sessionDirectory, active, signal) {
25485
26184
  signal.throwIfAborted();
25486
- const nativeSessionId = path16.basename(sessionDirectory);
26185
+ const nativeSessionId = path17.basename(sessionDirectory);
25487
26186
  const files = [
25488
- path16.join(sessionDirectory, "summary.json"),
25489
- path16.join(sessionDirectory, "updates.jsonl")
26187
+ path17.join(sessionDirectory, "summary.json"),
26188
+ path17.join(sessionDirectory, "updates.jsonl")
25490
26189
  ];
25491
26190
  return readStableFiles(files, async ([summaryInfo, updates]) => {
25492
26191
  if (!summaryInfo?.isFile() || !updates?.isFile() || summaryInfo.size > MAX_METADATA_BYTES)
@@ -25498,12 +26197,12 @@ var GrokSessionImport = class {
25498
26197
  if (typeof summary.session_kind === "string" && SUBAGENT_SESSION_KINDS.has(summary.session_kind))
25499
26198
  return null;
25500
26199
  const nativeCwd = summary.info.cwd;
25501
- if (typeof nativeCwd !== "string" || !path16.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
26200
+ if (typeof nativeCwd !== "string" || !path17.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
25502
26201
  return null;
25503
- const cwd = path16.resolve(nativeCwd);
25504
- if (encodeURIComponent(cwd) !== path16.basename(path16.dirname(sessionDirectory)))
26202
+ const cwd = path17.resolve(nativeCwd);
26203
+ if (encodeURIComponent(cwd) !== path17.basename(path17.dirname(sessionDirectory)))
25505
26204
  return null;
25506
- if (!(await stat(cwd)).isDirectory())
26205
+ if (!(await stat2(cwd)).isDirectory())
25507
26206
  return null;
25508
26207
  const prompt = await firstUserText(files[1], signal);
25509
26208
  if (prompt === null)
@@ -25540,6 +26239,7 @@ var GrokSubagentLifecycle = class {
25540
26239
  #newItemId;
25541
26240
  #delegations = /* @__PURE__ */ new Map();
25542
26241
  #callIdByNativeId = /* @__PURE__ */ new Map();
26242
+ #completedNativeIds = /* @__PURE__ */ new Set();
25543
26243
  constructor(options) {
25544
26244
  this.#emit = options.emit;
25545
26245
  this.#newItemId = options.newItemId;
@@ -25595,12 +26295,23 @@ var GrokSubagentLifecycle = class {
25595
26295
  }
25596
26296
  for (const [callId, active] of this.#delegations) {
25597
26297
  const current = active.item.subagents[0];
25598
- if (!current || current.nativeSubagentId)
26298
+ if (input.parentPromptId || !current || current.nativeSubagentId)
25599
26299
  continue;
25600
26300
  if (input.description && current.description === input.description) {
25601
26301
  return this.update(turnId, callId, input);
25602
26302
  }
25603
26303
  }
26304
+ if (input.parentPromptId) {
26305
+ if (this.#completedNativeIds.has(input.nativeSubagentId))
26306
+ return void 0;
26307
+ return this.start(turnId, {
26308
+ ...input,
26309
+ callId: `grok-helper-${input.nativeSubagentId}`,
26310
+ operation: "spawn",
26311
+ description: input.description ?? "Grok Subagent",
26312
+ background: true
26313
+ });
26314
+ }
25604
26315
  return void 0;
25605
26316
  }
25606
26317
  update(turnId, callId, patch) {
@@ -25647,11 +26358,11 @@ var GrokSubagentLifecycle = class {
25647
26358
  if (callId && this.#delegations.has(callId)) {
25648
26359
  return this.complete(turnId, callId, { ...input, nativeSubagentId });
25649
26360
  }
25650
- const status = input.status ?? (input.cancellationRequested ? "interrupted" : input.failed ? "failed" : "completed");
26361
+ const status2 = input.status ?? (input.cancellationRequested ? "interrupted" : input.failed ? "failed" : "completed");
25651
26362
  this.#emit({
25652
26363
  type: "subagent.state.changed",
25653
26364
  nativeSubagentId,
25654
- status,
26365
+ status: status2,
25655
26366
  ...input.resultSummary ? { resultSummary: input.resultSummary } : {}
25656
26367
  });
25657
26368
  return void 0;
@@ -25664,13 +26375,15 @@ var GrokSubagentLifecycle = class {
25664
26375
  const current = active.item.subagents[0];
25665
26376
  if (!current)
25666
26377
  throw new Error("Grok Subagent delegation has no Agent state");
25667
- const status = input.status ?? (input.cancellationRequested ? "interrupted" : input.failed ? "failed" : input.keepRunning ? "running" : "completed");
26378
+ const status2 = input.status ?? (input.cancellationRequested ? "interrupted" : input.failed ? "failed" : input.keepRunning ? "running" : "completed");
25668
26379
  const nativeSubagentId = input.nativeSubagentId ?? current.nativeSubagentId;
25669
26380
  if (nativeSubagentId)
25670
26381
  this.#callIdByNativeId.set(nativeSubagentId, callId);
26382
+ if (nativeSubagentId)
26383
+ this.#completedNativeIds.add(nativeSubagentId);
25671
26384
  const subagent = {
25672
26385
  ...current,
25673
- status,
26386
+ status: status2,
25674
26387
  ...nativeSubagentId ? { nativeSubagentId, subagentId: nativeSubagentId } : {},
25675
26388
  ...input.resultSummary ? { resultSummary: input.resultSummary } : {}
25676
26389
  };
@@ -25688,14 +26401,14 @@ var GrokSubagentLifecycle = class {
25688
26401
  const current = active.item.subagents[0];
25689
26402
  if (!current)
25690
26403
  continue;
25691
- const status = outcome.status === "succeeded" ? current.status : outcome.status === "cancelled" ? "interrupted" : "failed";
25692
- const item = { ...active.item, subagents: [{ ...current, status }] };
26404
+ const status2 = outcome.status === "succeeded" ? current.status : outcome.status === "cancelled" ? "interrupted" : "failed";
26405
+ const item = { ...active.item, subagents: [{ ...current, status: status2 }] };
25693
26406
  if (!active.published) {
25694
26407
  active.item = item;
25695
26408
  this.#publish(turnId, active);
25696
26409
  }
25697
26410
  this.#emit({ type: "item.completed", turnId, snapshot: { item, outcome } });
25698
- this.#emitState({ ...current, status });
26411
+ this.#emitState({ ...current, status: status2 });
25699
26412
  }
25700
26413
  }
25701
26414
  #publish(turnId, active) {
@@ -25832,9 +26545,9 @@ function stateForGrokModel(modelState, nativeState, model2 = modelState.currentM
25832
26545
  }
25833
26546
 
25834
26547
  // dist/grok-credits.js
25835
- import { readFile as readFile6 } from "node:fs/promises";
26548
+ import { readFile as readFile7 } from "node:fs/promises";
25836
26549
  import os7 from "node:os";
25837
- import path17 from "node:path";
26550
+ import path18 from "node:path";
25838
26551
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
25839
26552
  var REQUEST_TIMEOUT_MS = 15e3;
25840
26553
  function isRecord18(value) {
@@ -25854,7 +26567,7 @@ function nonNegativeCentValue(value) {
25854
26567
  return amount;
25855
26568
  }
25856
26569
  function grokHome3(environment) {
25857
- return environment.GROK_HOME ?? path17.join(environment.HOME ?? environment.USERPROFILE ?? os7.homedir(), ".grok");
26570
+ return environment.GROK_HOME ?? path18.join(environment.HOME ?? environment.USERPROFILE ?? os7.homedir(), ".grok");
25858
26571
  }
25859
26572
  function periodTypeFrom(value) {
25860
26573
  if (typeof value !== "string")
@@ -25946,8 +26659,8 @@ async function fetchGrokAccount(input = {}) {
25946
26659
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((value) => value?.trim()))
25947
26660
  return null;
25948
26661
  const now = input.now ?? /* @__PURE__ */ new Date();
25949
- const authPath = path17.join(grokHome3(environment), "auth.json");
25950
- const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile6(authPath, "utf8");
26662
+ const authPath = path18.join(grokHome3(environment), "auth.json");
26663
+ const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile7(authPath, "utf8");
25951
26664
  const token = selectAccessToken(JSON.parse(raw), now);
25952
26665
  if (!token)
25953
26666
  return null;
@@ -26176,14 +26889,16 @@ function sessionCostFromNative(value, initialCostUsd) {
26176
26889
  }
26177
26890
  function historyTurnKey(event, index) {
26178
26891
  const key = event.nativeTurnKey;
26179
- if (typeof key === "string" && key.startsWith("task-completed-"))
26180
- return null;
26181
26892
  return typeof key === "string" && key.length > 0 ? key : `anon-${index}`;
26182
26893
  }
26183
26894
  function sessionUsageFromHistory(events) {
26184
26895
  const latestByKey = /* @__PURE__ */ new Map();
26185
26896
  let index = 0;
26186
- for (const event of events) {
26897
+ const groups = classifyGrokHistory(events);
26898
+ for (const group of groups) {
26899
+ if (group.disposition !== "durable" && (group.user || !latestByKey.has(group.terminal.nativeTurnKey)))
26900
+ continue;
26901
+ const event = group.terminal;
26187
26902
  if (event?.type !== "turn.completed")
26188
26903
  continue;
26189
26904
  const key = historyTurnKey(event, index);
@@ -26270,18 +26985,6 @@ function usageFromUpdate(update, metadata, contextWindowTokens) {
26270
26985
 
26271
26986
  // dist/grok-adapter.js
26272
26987
  var grokHarnessId = harnessIdSchema.parse("grok");
26273
- var grokCommandCatalog = harnessCommandCatalogSchema.parse({
26274
- commands: [
26275
- {
26276
- id: "grok.compact",
26277
- invocation: "/compact",
26278
- localizations: { "zh-CN": { label: "压缩上下文", description: "压缩当前对话上下文" } },
26279
- label: "Compact context",
26280
- description: "Compact the current conversation context",
26281
- argumentMode: "text"
26282
- }
26283
- ]
26284
- });
26285
26988
  function capabilitiesForModels(modelState) {
26286
26989
  return {
26287
26990
  configuration: {
@@ -26290,7 +26993,12 @@ function capabilitiesForModels(modelState) {
26290
26993
  selectPermissionMode: true,
26291
26994
  permissionModeScope: "live"
26292
26995
  },
26293
- history: { fork: true, forkAcrossCwd: true, rollbackLastTurn: true },
26996
+ history: {
26997
+ fork: true,
26998
+ forkAcrossCwd: true,
26999
+ rollbackLastTurn: true,
27000
+ rollbackToCheckpoint: true
27001
+ },
26294
27002
  subagents: { observe: true, readTranscript: true }
26295
27003
  };
26296
27004
  }
@@ -26359,6 +27067,9 @@ var GrokHarnessSession = class {
26359
27067
  harnessId = grokHarnessId;
26360
27068
  capabilities;
26361
27069
  commands;
27070
+ goals;
27071
+ #backgroundQueue = Promise.resolve();
27072
+ #goalCommand = null;
26362
27073
  initialState;
26363
27074
  initialUsage;
26364
27075
  outputs;
@@ -26382,8 +27093,11 @@ var GrokHarnessSession = class {
26382
27093
  #usage = null;
26383
27094
  #initialCostUsd;
26384
27095
  #costRequest = 0;
27096
+ #historyLength;
27097
+ #goalHelpers = [];
26385
27098
  constructor(cwd, transport, opened, modelState, onClosed, options) {
26386
27099
  this.#cwd = cwd;
27100
+ this.#historyLength = options.history.length;
26387
27101
  this.#sessionDirectory = options.sessionDirectory;
26388
27102
  this.#mediaRoots = grokMediaResolveRoots(cwd, options.sessionDirectory);
26389
27103
  this.#transport = transport;
@@ -26408,6 +27122,72 @@ var GrokHarnessSession = class {
26408
27122
  state: this.#state
26409
27123
  };
26410
27124
  this.outputs = this.#channel.outputs;
27125
+ const goalControl = transport.goalControl?.bind(transport);
27126
+ if (goalControl && transport.observeBackground) {
27127
+ const goals = new GrokGoals(options.sessionDirectory, async (prompt, signal) => {
27128
+ if (this.#phase !== "open" || this.#configuring)
27129
+ throw new Error("Grok Session cannot control goals during configuration");
27130
+ const active = this.#active;
27131
+ if (active) {
27132
+ if (!["/goal pause", "/goal clear"].includes(prompt))
27133
+ throw new Error("Pause the active Grok worker before changing its goal");
27134
+ const before = await readGrokGoal(this.#sessionDirectory);
27135
+ const current = await goals.read();
27136
+ if (!current.ok)
27137
+ throw new Error(current.error.message);
27138
+ signal.throwIfAborted();
27139
+ if (prompt !== "/goal clear" || current.value?.status !== "complete") {
27140
+ const cancelled = await this.#cancel({
27141
+ type: "turn.cancel",
27142
+ turnId: active.command.turnId
27143
+ });
27144
+ if (!cancelled.ok)
27145
+ throw new Error(cancelled.error.message);
27146
+ }
27147
+ await new Promise((resolve, reject) => {
27148
+ const aborted2 = () => reject(new Error("Grok goal control timed out waiting for its worker"));
27149
+ signal.addEventListener("abort", aborted2, { once: true });
27150
+ if (signal.aborted)
27151
+ aborted2();
27152
+ void active.completion.then(() => {
27153
+ signal.removeEventListener("abort", aborted2);
27154
+ resolve();
27155
+ });
27156
+ });
27157
+ const after = await readGrokGoal(this.#sessionDirectory);
27158
+ if (before?.state.goal_id !== after?.state.goal_id)
27159
+ throw new Error("Grok goal changed while waiting for its worker");
27160
+ }
27161
+ signal.throwIfAborted();
27162
+ if (this.#phase !== "open" || this.#active)
27163
+ throw new Error("Grok Session changed while controlling its goal");
27164
+ return goalControl(prompt);
27165
+ }, (goal) => this.#event({ type: "goal.changed", goal }), 3e4, () => transport.getHistory());
27166
+ this.goals = goals;
27167
+ this.capabilities = { ...this.capabilities, autonomousTurns: { observe: true } };
27168
+ transport.observeBackground({
27169
+ onEvent: (event) => {
27170
+ if (event.type === "goal.changed") {
27171
+ void goals.observe(event.update).catch((error53) => this.handleTransportFault(new GrokTransportError("protocolError", String(error53))));
27172
+ return;
27173
+ }
27174
+ this.#backgroundQueue = this.#backgroundQueue.then(() => this.#backgroundEvent(event)).catch((error53) => this.handleTransportFault(new GrokTransportError("protocolError", String(error53))));
27175
+ },
27176
+ onPermission: async (request) => {
27177
+ await this.#backgroundQueue;
27178
+ return this.#active ? this.#requestPermission(this.#active, request) : { outcome: { outcome: "cancelled" } };
27179
+ },
27180
+ onElicitation: async (request) => {
27181
+ await this.#backgroundQueue;
27182
+ return this.#active ? this.#requestElicitation(this.#active, request) : grokMcpElicitCancel();
27183
+ },
27184
+ onQuestion: async (request) => {
27185
+ await this.#backgroundQueue;
27186
+ return this.#active ? this.#active.questions.ask(request) : { outcome: "cancelled" };
27187
+ }
27188
+ });
27189
+ void this.goals.read();
27190
+ }
26411
27191
  }
26412
27192
  async questionActivity(interactionId) {
26413
27193
  const active = this.#active;
@@ -26434,7 +27214,7 @@ var GrokHarnessSession = class {
26434
27214
  if (this.#phase !== "open") {
26435
27215
  return { ok: false, error: invalidState("Grok Session is not open") };
26436
27216
  }
26437
- if (this.#active || this.#configuring) {
27217
+ if (this.#active || this.#configuring || this.#goalCommand || this.goals?.busy) {
26438
27218
  return {
26439
27219
  ok: false,
26440
27220
  error: {
@@ -26468,7 +27248,10 @@ var GrokHarnessSession = class {
26468
27248
  return this.#selectThinking(command);
26469
27249
  if (command.type === "permissionMode.select")
26470
27250
  return this.#selectPermissionMode(command);
26471
- if (this.#active || this.#configuring) {
27251
+ return this.#startTurn(command);
27252
+ }
27253
+ async #startTurn(command, catalogCommand = false) {
27254
+ if (this.#active || this.#configuring || this.#goalCommand || this.goals?.busy) {
26472
27255
  return {
26473
27256
  ok: false,
26474
27257
  error: {
@@ -26478,6 +27261,15 @@ var GrokHarnessSession = class {
26478
27261
  }
26479
27262
  };
26480
27263
  }
27264
+ if (this.goals?.active)
27265
+ return {
27266
+ ok: false,
27267
+ error: {
27268
+ code: "sessionBusy",
27269
+ message: "Pause the native Grok goal before starting a user Turn",
27270
+ retryable: true
27271
+ }
27272
+ };
26481
27273
  const text = command.input.map(({ text: text2 }) => text2).join("\n");
26482
27274
  if (text.length === 0) {
26483
27275
  return {
@@ -26494,6 +27286,16 @@ var GrokHarnessSession = class {
26494
27286
  } catch (error53) {
26495
27287
  return { ok: false, error: normalizeError(error53, "nativeFailure") };
26496
27288
  }
27289
+ const active = this.#newActive(command, catalogCommand);
27290
+ this.#active = active;
27291
+ this.#event({ type: "turn.started", turnId: command.turnId });
27292
+ void this.#transport.runTurn(text, (event) => this.#handleEvent(active, event), (request) => this.#requestPermission(active, request), (request) => this.#requestElicitation(active, request), (request) => this.#active === active && this.#phase === "open" && !active.cancellationRequested ? active.questions.ask(request) : Promise.resolve({ outcome: "cancelled" })).finally(() => active.questions.cancel()).then((response) => this.#settleFromHistory(active, terminalOutcome2(response, active.cancellationRequested), response), (error53) => this.#settleFromHistory(active, {
27293
+ status: "failed",
27294
+ error: normalizeError(error53, "nativeFailure")
27295
+ }));
27296
+ return { ok: true, value: { turnId: command.turnId } };
27297
+ }
27298
+ #newActive(command, catalogCommand = false) {
26497
27299
  let resolveCompletion = () => void 0;
26498
27300
  const completion = new Promise((resolve) => {
26499
27301
  resolveCompletion = resolve;
@@ -26519,16 +27321,71 @@ var GrokHarnessSession = class {
26519
27321
  questions: new GrokQuestions(command.turnId, this.#randomUUID, (output) => this.#channel.emit(output)),
26520
27322
  cancellationRequested: false,
26521
27323
  beforeNativeTurnKeys: new Set(this.#snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey)),
27324
+ historyStart: this.#historyLength,
27325
+ catalogCommand,
26522
27326
  completion,
26523
27327
  resolveCompletion
26524
27328
  };
26525
- this.#active = active;
26526
- this.#event({ type: "turn.started", turnId: command.turnId });
26527
- void this.#transport.runTurn(text, (event) => this.#handleEvent(active, event), (request) => this.#requestPermission(active, request), (request) => this.#requestElicitation(active, request), (request) => this.#active === active && this.#phase === "open" && !active.cancellationRequested ? active.questions.ask(request) : Promise.resolve({ outcome: "cancelled" })).finally(() => active.questions.cancel()).then((response) => this.#settleFromHistory(active, terminalOutcome2(response, active.cancellationRequested), response), (error53) => this.#settleFromHistory(active, {
26528
- status: "failed",
26529
- error: normalizeError(error53, "nativeFailure")
26530
- }));
26531
- return { ok: true, value: { turnId: command.turnId } };
27329
+ return active;
27330
+ }
27331
+ hasBackgroundWork() {
27332
+ return this.goals?.active === true;
27333
+ }
27334
+ async #backgroundEvent(event) {
27335
+ await this.#goalCommand;
27336
+ if (this.#phase !== "open")
27337
+ return;
27338
+ if (this.#bufferGoalHelper(event))
27339
+ return;
27340
+ if (!this.#active && event.type === "subagent.finished") {
27341
+ this.#event({
27342
+ type: "subagent.state.changed",
27343
+ nativeSubagentId: event.nativeSubagentId,
27344
+ status: event.status,
27345
+ ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
27346
+ });
27347
+ return;
27348
+ }
27349
+ let user = event.type === "user.text" ? event : void 0;
27350
+ if (!this.#active && this.goals && !user && ["agent.text", "agent.thought", "tool.call", "tool.update", "turn.completed"].includes(event.type)) {
27351
+ const history = await this.#transport.getHistory();
27352
+ const candidate = history.findLast((entry) => entry.type === "user.text" && entry.metadata?.host_turn !== true && entry.metadata?.hostTurn !== true);
27353
+ const latestIndex = Math.max(-1, ...this.#snapshot.turns.map((turn) => Number(turn.checkpoint?.checkpointId ?? -1)));
27354
+ if (candidate?.type === "user.text" && typeof candidate.metadata?.promptIndex === "number" && candidate.metadata.promptIndex > latestIndex)
27355
+ user = candidate;
27356
+ }
27357
+ if (user && !this.#active && user.metadata?.host_turn !== true && user.metadata?.hostTurn !== true && (this.goals?.active === true || typeof user.metadata?.promptIndex === "number")) {
27358
+ const command = {
27359
+ type: "turn.start",
27360
+ turnId: hostTurnIdSchema.parse(`grok-autonomous-${this.#randomUUID()}`),
27361
+ input: [{ type: "text", text: user.text }]
27362
+ };
27363
+ const active2 = this.#newActive(command);
27364
+ const promptIndex = grokPromptIndex(user);
27365
+ if (promptIndex !== null)
27366
+ active2.backgroundPromptIndex = promptIndex;
27367
+ this.#active = active2;
27368
+ this.#event({
27369
+ type: "turn.autonomous.started",
27370
+ turnId: command.turnId,
27371
+ input: /^\s*<system-reminder>/u.test(user.text) ? [] : command.input
27372
+ });
27373
+ this.#event({ type: "turn.started", turnId: command.turnId });
27374
+ }
27375
+ const active = this.#active;
27376
+ if (!active)
27377
+ return;
27378
+ this.#handleEvent(active, event);
27379
+ if (event.type === "turn.completed") {
27380
+ const deadline = Date.now() + 3e3;
27381
+ while (Date.now() < deadline && this.#phase === "open") {
27382
+ const history = await this.#transport.getHistory();
27383
+ if (history.slice(active.historyStart).some((entry) => entry.type === "turn.completed" && entry.nativeTurnKey === event.nativeTurnKey))
27384
+ break;
27385
+ await new Promise((resolve) => setTimeout(resolve, 50));
27386
+ }
27387
+ await this.#settleFromHistory(active, terminalOutcome2({ stopReason: event.stopReason }, active.cancellationRequested), void 0, event.nativeTurnKey);
27388
+ }
26532
27389
  }
26533
27390
  /** Built-ins plus the commands, workflows and skills the open Session advertises. */
26534
27391
  #liveCommandCatalog() {
@@ -26536,13 +27393,90 @@ var GrokHarnessSession = class {
26536
27393
  return mergeLiveHarnessCommands(grokCommandCatalog, GROK_LIVE_COMMAND_ID_PREFIX, native ? grokLiveCommands(native) : null);
26537
27394
  }
26538
27395
  async #executeHarnessCommand(command) {
27396
+ if (this.#phase !== "open")
27397
+ return { ok: false, error: invalidState("Grok Session is not open") };
27398
+ if (command.commandId === "grok.goal" || command.commandId === "grok.desktop-goal") {
27399
+ const prompt = grokGoalPrompt(command.arguments);
27400
+ if (!prompt.ok)
27401
+ return prompt;
27402
+ const goals = this.goals;
27403
+ const goalControl = this.#transport.goalControl?.bind(this.#transport);
27404
+ if (goals && goalControl) {
27405
+ if (this.#active || this.#goalCommand || this.#configuring || this.goals?.busy)
27406
+ return {
27407
+ ok: false,
27408
+ error: {
27409
+ code: "sessionBusy",
27410
+ message: "Grok Session already has an active operation",
27411
+ retryable: true
27412
+ }
27413
+ };
27414
+ const argument = prompt.value.slice("/goal ".length).trim();
27415
+ this.#event({ type: "turn.started", turnId: command.turnId });
27416
+ this.#goalCommand = (async () => {
27417
+ const budget = /^(.*) --budget (\d+)$/su.exec(argument);
27418
+ const existing = await goals.read();
27419
+ const emptyControl = existing.ok && existing.value === null && ["pause", "resume"].includes(argument);
27420
+ const result = emptyControl ? await goalControl(prompt.value).then(() => ({ ok: true, value: null }), (error53) => ({
27421
+ ok: false,
27422
+ error: normalizeError(error53, "nativeFailure")
27423
+ })) : argument === "clear" ? await goals.clear() : argument === "status" || !argument ? await goals.read() : argument === "pause" || argument === "resume" ? await goals.set({
27424
+ status: argument === "pause" ? "paused" : "active",
27425
+ origin: "user"
27426
+ }) : await goals.set({
27427
+ objective: budget?.[1] ?? argument,
27428
+ ...budget ? { tokenBudget: Number(budget[2]) } : {},
27429
+ origin: "user"
27430
+ });
27431
+ if (result.ok && command.commandId !== "grok.desktop-goal") {
27432
+ const value = result.value;
27433
+ const text = value && typeof value === "object" && "objective" in value ? `Goal: ${value.objective}
27434
+ Status: ${value.status}
27435
+ Goal tokens used: ${value.tokensUsed}
27436
+ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleared." : "No goal is currently set.";
27437
+ const item = {
27438
+ type: "agentMessage",
27439
+ itemId: hostItemIdSchema.parse(this.#randomUUID()),
27440
+ text
27441
+ };
27442
+ this.#event({ type: "item.started", turnId: command.turnId, item });
27443
+ this.#event({
27444
+ type: "item.completed",
27445
+ turnId: command.turnId,
27446
+ snapshot: { item, outcome: { status: "succeeded" } }
27447
+ });
27448
+ }
27449
+ this.#event({
27450
+ type: "turn.completed",
27451
+ turnId: command.turnId,
27452
+ ephemeral: true,
27453
+ outcome: result.ok ? { status: "succeeded" } : { status: "failed", error: result.error }
27454
+ });
27455
+ })().catch((error53) => {
27456
+ this.#event({
27457
+ type: "turn.completed",
27458
+ turnId: command.turnId,
27459
+ ephemeral: true,
27460
+ outcome: { status: "failed", error: normalizeError(error53, "nativeFailure") }
27461
+ });
27462
+ }).finally(() => {
27463
+ this.#goalCommand = null;
27464
+ });
27465
+ return { ok: true, value: { turnId: command.turnId } };
27466
+ }
27467
+ return this.#startTurn({
27468
+ type: "turn.start",
27469
+ turnId: command.turnId,
27470
+ input: [{ type: "text", text: prompt.value }]
27471
+ }, true);
27472
+ }
26539
27473
  const livePrompt = liveHarnessCommandPrompt(this.#liveCommandCatalog(), GROK_LIVE_COMMAND_ID_PREFIX, command.commandId, command.arguments?.text);
26540
27474
  if (livePrompt !== null) {
26541
- const started = await this.execute({
27475
+ const started = await this.#startTurn({
26542
27476
  type: "turn.start",
26543
27477
  turnId: command.turnId,
26544
27478
  input: [{ type: "text", text: livePrompt }]
26545
- });
27479
+ }, true);
26546
27480
  return started.ok ? { ok: true, value: { turnId: command.turnId } } : started;
26547
27481
  }
26548
27482
  if (command.commandId !== "grok.compact") {
@@ -26555,7 +27489,7 @@ var GrokHarnessSession = class {
26555
27489
  }
26556
27490
  };
26557
27491
  }
26558
- if (this.#active || this.#configuring) {
27492
+ if (this.#active || this.#configuring || this.#goalCommand || this.goals?.busy || this.goals?.active) {
26559
27493
  return {
26560
27494
  ok: false,
26561
27495
  error: {
@@ -26611,6 +27545,8 @@ var GrokHarnessSession = class {
26611
27545
  questions: new GrokQuestions(command.turnId, this.#randomUUID, (output) => this.#channel.emit(output)),
26612
27546
  cancellationRequested: false,
26613
27547
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
27548
+ historyStart: this.#historyLength,
27549
+ catalogCommand: true,
26614
27550
  completion,
26615
27551
  resolveCompletion
26616
27552
  };
@@ -26668,6 +27604,7 @@ var GrokHarnessSession = class {
26668
27604
  const knownTurnRefs = this.#snapshot.turns.map((turn) => turn.nativeTurnRef);
26669
27605
  const refreshed = mapGrokReplay(history, this.harnessId, this.#transport.sessionId, this.#cwd, knownTurnRefs, this.#toolOutputLimit, this.#sessionDirectory);
26670
27606
  this.#snapshot.turns = refreshed.turns;
27607
+ this.#historyLength = history.length;
26671
27608
  return history;
26672
27609
  }
26673
27610
  async #selectModel(command) {
@@ -26697,7 +27634,7 @@ var GrokHarnessSession = class {
26697
27634
  return this.#configure(model2, parsed.data);
26698
27635
  }
26699
27636
  async #configure(model2, thinkingOptionId) {
26700
- if (this.#configuring) {
27637
+ if (this.#configuring || this.#goalCommand || this.goals?.busy || this.goals?.active) {
26701
27638
  return {
26702
27639
  ok: false,
26703
27640
  error: {
@@ -26743,7 +27680,7 @@ var GrokHarnessSession = class {
26743
27680
  }
26744
27681
  };
26745
27682
  }
26746
- if (this.#active || this.#configuring) {
27683
+ if (this.#active || this.#configuring || this.#goalCommand || this.goals?.busy || this.goals?.active) {
26747
27684
  return {
26748
27685
  ok: false,
26749
27686
  error: {
@@ -27185,7 +28122,7 @@ var GrokHarnessSession = class {
27185
28122
  this.#completeTool(active, event.callId, event.status, event.content, event.rawOutput);
27186
28123
  }
27187
28124
  }
27188
- #completeTool(active, callId, status, content, rawOutput) {
28125
+ #completeTool(active, callId, status2, content, rawOutput) {
27189
28126
  const tool = active.tools.get(callId);
27190
28127
  if (!tool)
27191
28128
  return;
@@ -27194,7 +28131,7 @@ var GrokHarnessSession = class {
27194
28131
  if (hasGrokToolProjection(projection)) {
27195
28132
  tool.item = applyGrokToolProjection(tool.item, projection);
27196
28133
  }
27197
- const outcome = status === "failed" ? {
28134
+ const outcome = status2 === "failed" ? {
27198
28135
  status: "failed",
27199
28136
  error: {
27200
28137
  code: "nativeFailure",
@@ -27203,7 +28140,7 @@ var GrokHarnessSession = class {
27203
28140
  }
27204
28141
  } : { status: "succeeded" };
27205
28142
  this.#completeItem(active, tool.item, outcome);
27206
- if (status !== "completed")
28143
+ if (status2 !== "completed")
27207
28144
  return;
27208
28145
  this.#completeWatchedSubagents(active, tool.item, content, rawOutput);
27209
28146
  const changes = projectGrokFileChanges(content, this.#cwd);
@@ -27223,11 +28160,11 @@ var GrokHarnessSession = class {
27223
28160
  this.#event({ type: "item.started", turnId: active.command.turnId, item: imageItem });
27224
28161
  this.#completeItem(active, imageItem, { status: "succeeded" });
27225
28162
  }
27226
- #completeSubagentTool(active, callId, status, event) {
28163
+ #completeSubagentTool(active, callId, status2, event) {
27227
28164
  const nativeSubagentId = grokNativeSubagentId(event.rawInput, event.rawOutput, event.content);
27228
28165
  const resultSummary = grokSubagentResultSummary(event.content, event.rawOutput);
27229
28166
  active.subagents.completeSpawn(active.command.turnId, callId, {
27230
- failed: status === "failed",
28167
+ failed: status2 === "failed",
27231
28168
  cancellationRequested: active.cancellationRequested,
27232
28169
  ...nativeSubagentId ? { nativeSubagentId } : {},
27233
28170
  ...resultSummary ? { resultSummary } : {}
@@ -27253,6 +28190,8 @@ var GrokHarnessSession = class {
27253
28190
  }
27254
28191
  }
27255
28192
  #bindSpawnedSubagent(active, event) {
28193
+ if (this.#bufferGoalHelper(event))
28194
+ return;
27256
28195
  active.subagents.bindNativeId(active.command.turnId, {
27257
28196
  nativeSubagentId: event.nativeSubagentId,
27258
28197
  ...event.description ? { description: event.description } : {},
@@ -27261,6 +28200,8 @@ var GrokHarnessSession = class {
27261
28200
  });
27262
28201
  }
27263
28202
  #finishNativeSubagent(active, event) {
28203
+ if (this.#bufferGoalHelper(event))
28204
+ return;
27264
28205
  active.subagents.completeByNativeId(active.command.turnId, event.nativeSubagentId, {
27265
28206
  failed: event.status === "failed",
27266
28207
  cancellationRequested: active.cancellationRequested || event.status === "interrupted",
@@ -27268,6 +28209,29 @@ var GrokHarnessSession = class {
27268
28209
  ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
27269
28210
  });
27270
28211
  }
28212
+ #bufferGoalHelper(event) {
28213
+ if (event.type === "subagent.spawned" && event.parentPromptId) {
28214
+ if (!this.#snapshot.turns.some((t) => t.nativeTurnRef.nativeTurnKey === event.parentPromptId))
28215
+ this.#goalHelpers.push(event);
28216
+ return true;
28217
+ }
28218
+ if (event.type === "subagent.finished" && this.#goalHelpers.some((e) => e.type === "subagent.spawned" && e.nativeSubagentId === event.nativeSubagentId)) {
28219
+ this.#goalHelpers.push(event);
28220
+ return true;
28221
+ }
28222
+ return false;
28223
+ }
28224
+ #publishGoalHelpers(active, key) {
28225
+ const ids = new Set(this.#goalHelpers.filter((e) => e.type === "subagent.spawned" && e.parentPromptId === key).map((e) => e.nativeSubagentId));
28226
+ const events = this.#goalHelpers.filter((e) => ids.has(e.nativeSubagentId));
28227
+ this.#goalHelpers = this.#goalHelpers.filter((e) => !ids.has(e.nativeSubagentId));
28228
+ for (const event of events) {
28229
+ if (event.type === "subagent.spawned")
28230
+ active.subagents.bindNativeId(active.command.turnId, event);
28231
+ else
28232
+ this.#finishNativeSubagent(active, event);
28233
+ }
28234
+ }
27271
28235
  #completeAgent(active, outcome) {
27272
28236
  const item = active.agent;
27273
28237
  if (item && active.rawAgentText.length > 0) {
@@ -27308,20 +28272,32 @@ var GrokHarnessSession = class {
27308
28272
  snapshot
27309
28273
  });
27310
28274
  }
27311
- async #settleFromHistory(active, outcome, response) {
28275
+ async #settleFromHistory(active, outcome, response, terminalKey) {
27312
28276
  let history = [];
27313
28277
  let nativeTurnRef;
27314
28278
  let checkpoint;
28279
+ let ephemeral = false;
28280
+ let persistedItems;
27315
28281
  try {
27316
28282
  history = await this.#refreshSnapshot();
28283
+ const expectedKey = terminalKey ?? (typeof response?._meta?.promptId === "string" ? response._meta.promptId : void 0);
28284
+ const group = expectedKey ? classifyGrokHistory(history).findLast((g) => g.terminalIndex >= active.historyStart && g.terminal.nativeTurnKey === expectedKey && (active.backgroundPromptIndex === void 0 || g.user && grokPromptIndex(g.user) === active.backgroundPromptIndex)) : void 0;
27317
28285
  const created = this.#snapshot.turns.filter((turn) => !active.beforeNativeTurnKeys.has(turn.nativeTurnRef.nativeTurnKey));
27318
- if (created.length !== 1) {
28286
+ const lastUser = history.findLast((event) => event.type === "user.text");
28287
+ ephemeral = terminalKey !== void 0 && group?.disposition === "ephemeral" && created.length === 0 || created.length === 0 && active.catalogCommand && outcome.status === "succeeded" && response?.stopReason === "end_turn" && response._meta?.totalTokens === 0 && lastUser?.type === "user.text" && lastUser.text === active.command.input.map(({ text }) => text).join("\n") && (lastUser?.metadata?.hostTurn === true || lastUser?.metadata?.host_turn === true);
28288
+ if (created.length !== 1 && !ephemeral) {
27319
28289
  throw new Error(`Grok Turn persisted ${created.length} new Native Turns; exactly one is required`);
27320
28290
  }
28291
+ if (!ephemeral && expectedKey && (created[0]?.nativeTurnRef.nativeTurnKey !== expectedKey || terminalKey && !group))
28292
+ throw new Error("Grok persisted terminal does not match the live Turn occurrence");
27321
28293
  nativeTurnRef = created[0]?.nativeTurnRef;
27322
28294
  checkpoint = created[0]?.checkpoint;
28295
+ if (nativeTurnRef)
28296
+ this.#publishGoalHelpers(active, nativeTurnRef.nativeTurnKey);
28297
+ if (active.backgroundPromptIndex !== void 0 && !ephemeral)
28298
+ persistedItems = created[0]?.items;
27323
28299
  } catch (error53) {
27324
- if (outcome.status === "succeeded") {
28300
+ if (outcome.status === "succeeded" || error53 instanceof GrokNativeIdentityReuseError) {
27325
28301
  outcome = { status: "failed", error: normalizeError(error53, "protocolError") };
27326
28302
  }
27327
28303
  }
@@ -27336,12 +28312,29 @@ var GrokHarnessSession = class {
27336
28312
  }
27337
28313
  const usage = sessionUsageFromHistory(history);
27338
28314
  await this.#refreshCredits().catch(() => void 0);
27339
- this.#finish(active, checkpoint ? { ...outcome, checkpoint } : outcome, usage, nativeTurnRef);
28315
+ this.#finish(active, checkpoint ? { ...outcome, checkpoint } : outcome, usage, nativeTurnRef, ephemeral, outcome.status === "succeeded" ? persistedItems : void 0);
27340
28316
  }
27341
- #finish(active, outcome, usage = null, nativeTurnRef) {
28317
+ #finish(active, outcome, usage = null, nativeTurnRef, ephemeral = false, persistedItems) {
27342
28318
  if (this.#active !== active)
27343
28319
  return;
27344
28320
  const itemOutcome = outcome;
28321
+ const persistedMessages = persistedItems ? settledGrokAgentMessages(persistedItems, active.completedItems) : [];
28322
+ const pendingId = active.agent?.itemId;
28323
+ const pendingMessage = persistedMessages.find((item) => item.itemId === pendingId);
28324
+ if (pendingMessage && active.agent) {
28325
+ const text = pendingMessage.text.startsWith(active.agent.text) ? pendingMessage.text : active.agent.text;
28326
+ const delta = text.slice(active.agent.text.length);
28327
+ if (delta)
28328
+ this.#event({
28329
+ type: "item.updated",
28330
+ turnId: active.command.turnId,
28331
+ itemId: pendingMessage.itemId,
28332
+ update: { type: "text.append", text: delta }
28333
+ });
28334
+ active.agent = { ...pendingMessage, text };
28335
+ active.rawAgentText = text;
28336
+ active.projectedAgentText = text;
28337
+ }
27345
28338
  this.#completeReasoning(active, itemOutcome);
27346
28339
  this.#completeAgent(active, itemOutcome);
27347
28340
  active.subagents.finalize(active.command.turnId, itemOutcome);
@@ -27352,6 +28345,12 @@ var GrokHarnessSession = class {
27352
28345
  for (const tool of active.tools.values())
27353
28346
  this.#completeItem(active, tool.item, itemOutcome);
27354
28347
  active.tools.clear();
28348
+ for (const item of persistedMessages) {
28349
+ if (item.itemId === pendingId)
28350
+ continue;
28351
+ this.#event({ type: "item.started", turnId: active.command.turnId, item });
28352
+ this.#completeItem(active, item, itemOutcome);
28353
+ }
27355
28354
  for (const [interactionId, pending] of active.approvals) {
27356
28355
  active.approvals.delete(interactionId);
27357
28356
  pending.resolve({ outcome: { outcome: "cancelled" } });
@@ -27371,6 +28370,7 @@ var GrokHarnessSession = class {
27371
28370
  type: "turn.completed",
27372
28371
  turnId: active.command.turnId,
27373
28372
  ...nativeTurnRef ? { nativeTurnRef } : {},
28373
+ ...ephemeral ? { ephemeral: true } : {},
27374
28374
  outcome
27375
28375
  });
27376
28376
  active.resolveCompletion();
@@ -27396,6 +28396,7 @@ var GrokHarnessSession = class {
27396
28396
  if (this.#phase === "closed")
27397
28397
  return;
27398
28398
  this.#phase = "closing";
28399
+ this.goals?.close();
27399
28400
  const active = this.#active;
27400
28401
  if (active) {
27401
28402
  active.cancellationRequested = true;
@@ -27422,6 +28423,7 @@ var GrokHarnessSession = class {
27422
28423
  if (this.#phase !== "open")
27423
28424
  return;
27424
28425
  const normalized = normalizeError(error53, "processExited");
28426
+ this.goals?.close();
27425
28427
  if (this.#active)
27426
28428
  this.#finish(this.#active, { status: "failed", error: normalized });
27427
28429
  this.#phase = "faulted";
@@ -27540,7 +28542,7 @@ var GrokAdapter = class {
27540
28542
  async inspect(input = {}) {
27541
28543
  if (this.#closePromise)
27542
28544
  return { status: "unavailable", error: invalidState("Grok Adapter is closed") };
27543
- const cwd = path18.resolve(input.cwd ?? process.cwd());
28545
+ const cwd = path19.resolve(input.cwd ?? process.cwd());
27544
28546
  if (!input.refresh) {
27545
28547
  const cached2 = this.#inspectionCache.get(cwd);
27546
28548
  if (cached2)
@@ -27615,7 +28617,7 @@ var GrokAdapter = class {
27615
28617
  }
27616
28618
  };
27617
28619
  }
27618
- const cwd = path18.resolve(input.cwd);
28620
+ const cwd = path19.resolve(input.cwd);
27619
28621
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
27620
28622
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
27621
28623
  return {
@@ -27633,7 +28635,7 @@ var GrokAdapter = class {
27633
28635
  let initialPermissionModeId = requestedPermissionModeId;
27634
28636
  try {
27635
28637
  let opened;
27636
- if (input.kind === "rollbackLastTurn") {
28638
+ if (input.kind === "rollbackLastTurn" || input.kind === "rollbackToCheckpoint") {
27637
28639
  const sourceRef = nativeSessionRefSchema.safeParse(input.sourceRef);
27638
28640
  if (!sourceRef.success || sourceRef.data.harnessId !== this.harnessId) {
27639
28641
  await transport.close().catch(() => void 0);
@@ -27648,10 +28650,11 @@ var GrokAdapter = class {
27648
28650
  }
27649
28651
  const sourceSession = [...this.#sessions].find((entry) => entry.initialState.nativeRef?.nativeSessionId === sourceRef.data.nativeSessionId);
27650
28652
  sourceConfiguration = sourceSession?.currentConfiguration();
27651
- const rewound = await rewindGrokLastTurn({
28653
+ const rewound = await rewindGrokSession({
27652
28654
  cwd,
27653
28655
  harnessId: this.harnessId,
27654
28656
  sourceRef: sourceRef.data,
28657
+ ...input.kind === "rollbackToCheckpoint" ? { checkpoint: input.checkpoint } : {},
27655
28658
  locateSource: (sessionId) => transport.locateSession(sessionId),
27656
28659
  readHistory: (historyCwd, sessionId) => transport.readHistory(sessionId, historyCwd),
27657
28660
  rewindAndLoad: async (params) => {
@@ -27711,7 +28714,7 @@ var GrokAdapter = class {
27711
28714
  ok: false,
27712
28715
  error: {
27713
28716
  code: "nativeFailure",
27714
- message: input.kind === "rollbackLastTurn" ? "Grok Native Rewind did not open a Session" : "Grok Native Fork did not open a Session",
28717
+ message: input.kind === "rollbackLastTurn" || input.kind === "rollbackToCheckpoint" ? "Grok Native Rewind did not open a Session" : "Grok Native Fork did not open a Session",
27715
28718
  retryable: true
27716
28719
  }
27717
28720
  };
@@ -27722,8 +28725,8 @@ var GrokAdapter = class {
27722
28725
  const nativeModelId = modelState.currentModel.id;
27723
28726
  const nativeThinkingOptionId = modelState.currentThinkingOptionId;
27724
28727
  const retainedConfiguration = sourceConfiguration;
27725
- if ((input.kind === "rollbackLastTurn" || input.kind === "fork") && retainedConfiguration) {
27726
- const operation = input.kind === "rollbackLastTurn" ? "Rewind" : "Fork";
28728
+ if ((input.kind === "rollbackLastTurn" || input.kind === "rollbackToCheckpoint" || input.kind === "fork") && retainedConfiguration) {
28729
+ const operation = input.kind === "fork" ? "Fork" : "Rewind";
27727
28730
  initialPermissionModeId = retainedConfiguration.permissionModeId ?? GROK_DEFAULT_PERMISSION_MODE_ID;
27728
28731
  const catalogModel = modelState.catalog.models.find(({ ref }) => ref.id === retainedConfiguration.model.id);
27729
28732
  if (!catalogModel) {
@@ -27770,7 +28773,7 @@ var GrokAdapter = class {
27770
28773
  }
27771
28774
  await transport.setPermissionMode(initialPermissionModeId);
27772
28775
  const history = await transport.getHistory();
27773
- let initialUsage = input.kind === "resume" || input.kind === "fork" || input.kind === "rollbackLastTurn" ? combineUsage(sessionUsageFromHistory(history), usageFromSignals(opened.signals)) : null;
28776
+ let initialUsage = input.kind === "resume" || input.kind === "fork" || input.kind === "rollbackLastTurn" || input.kind === "rollbackToCheckpoint" ? combineUsage(sessionUsageFromHistory(history), usageFromSignals(opened.signals)) : null;
27774
28777
  if (contextWindow !== void 0 && initialUsage?.contextUsedTokens !== void 0) {
27775
28778
  initialUsage = combineUsage(initialUsage, { contextWindowTokens: contextWindow });
27776
28779
  }