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

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")
23898
24510
  };
23899
24511
  }
23900
- const source = await readSnapshot2({ ...input, cwd: sourceCwd }, sourceRef.data.nativeSessionId);
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")
24525
+ };
24526
+ }
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")
@@ -24435,6 +25064,28 @@ var GrokQuestions = class {
24435
25064
  }
24436
25065
  };
24437
25066
 
25067
+ // dist/grok-interject.js
25068
+ var GROK_INTERJECT_METHOD = "x.ai/interject";
25069
+ var GROK_INTERJECT_FALLBACK_METHOD = "_x.ai/interject";
25070
+ var GrokSteerMissedTurnError = class extends Error {
25071
+ constructor(message = "Grok steer missed the active Turn") {
25072
+ super(message);
25073
+ this.name = "GrokSteerMissedTurnError";
25074
+ }
25075
+ };
25076
+ function parseGrokInterjectResult(value) {
25077
+ if (value === void 0 || value === null)
25078
+ return { status: "queued" };
25079
+ if (typeof value !== "object" || Array.isArray(value))
25080
+ return null;
25081
+ const record2 = value;
25082
+ const nested = record2.status === void 0 && typeof record2.result === "object" && record2.result !== null ? record2.result : record2;
25083
+ const status2 = nested.status ?? nested.ok;
25084
+ if (status2 === void 0 || status2 === "queued" || status2 === true)
25085
+ return { status: "queued" };
25086
+ return null;
25087
+ }
25088
+
24438
25089
  // dist/acp-transport.js
24439
25090
  var GrokTransportError = class extends Error {
24440
25091
  kind;
@@ -24515,8 +25166,17 @@ function signalProcessTree(child, signal) {
24515
25166
  throw error53;
24516
25167
  }
24517
25168
  }
25169
+ function grokNotificationMetadata(envelope, update) {
25170
+ if (!isRecord15(envelope) && !isRecord15(update))
25171
+ return void 0;
25172
+ return { ...isRecord15(update) ? update : {}, ...isRecord15(envelope) ? envelope : {} };
25173
+ }
24518
25174
  function transportEvent(update, metadata) {
24519
25175
  const extension = update;
25176
+ if (extension.sessionUpdate === "goal_updated")
25177
+ return { type: "goal.changed", update: extension };
25178
+ if (extension.sessionUpdate === "goal_cleared")
25179
+ return { type: "goal.changed", update: null };
24520
25180
  if (extension.sessionUpdate === "response_completed") {
24521
25181
  return {
24522
25182
  type: "response.completed",
@@ -24610,20 +25270,20 @@ function transportEvent(update, metadata) {
24610
25270
  function grokHomeDir(options) {
24611
25271
  const environment = { ...process.env, ...options.environment };
24612
25272
  const home = environment.HOME ?? environment.USERPROFILE ?? os6.homedir();
24613
- return environment.GROK_HOME ?? path15.join(home, ".grok");
25273
+ return environment.GROK_HOME ?? path16.join(home, ".grok");
24614
25274
  }
24615
25275
  function grokNativeSessionDirectory(options, sessionId) {
24616
- return path15.join(grokHomeDir(options), "sessions", encodeURIComponent(path15.resolve(options.cwd)), sessionId);
25276
+ return path16.join(grokHomeDir(options), "sessions", encodeURIComponent(path16.resolve(options.cwd)), sessionId);
24617
25277
  }
24618
25278
  function nativeSessionFile(options, sessionId, fileName) {
24619
- return path15.join(grokNativeSessionDirectory(options, sessionId), fileName);
25279
+ return path16.join(grokNativeSessionDirectory(options, sessionId), fileName);
24620
25280
  }
24621
25281
  function nativeHistoryPath(options, sessionId) {
24622
25282
  return nativeSessionFile(options, sessionId, "updates.jsonl");
24623
25283
  }
24624
25284
  async function readNativeSignals(options, sessionId) {
24625
25285
  try {
24626
- return JSON.parse(await readFile4(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
25286
+ return JSON.parse(await readFile5(nativeSessionFile(options, sessionId, "signals.json"), "utf8"));
24627
25287
  } catch {
24628
25288
  return void 0;
24629
25289
  }
@@ -24636,7 +25296,7 @@ async function locateGrokNativeSession(options, sessionId) {
24636
25296
  return null;
24637
25297
  let entries;
24638
25298
  try {
24639
- entries = await readdir(path15.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
25299
+ entries = await readdir(path16.join(grokHomeDir(options), "sessions"), { withFileTypes: true });
24640
25300
  } catch (error53) {
24641
25301
  if (isMissingFile(error53))
24642
25302
  return null;
@@ -24650,7 +25310,7 @@ async function locateGrokNativeSession(options, sessionId) {
24650
25310
  continue;
24651
25311
  let summaryRaw;
24652
25312
  try {
24653
- summaryRaw = await readFile4(path15.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
25313
+ summaryRaw = await readFile5(path16.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
24654
25314
  } catch (error53) {
24655
25315
  if (isMissingFile(error53) || isRecord15(error53) && error53.code === "ENOTDIR")
24656
25316
  continue;
@@ -24667,8 +25327,8 @@ async function locateGrokNativeSession(options, sessionId) {
24667
25327
  if (!isRecord15(parsed))
24668
25328
  continue;
24669
25329
  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;
25330
+ const cwd = isRecord15(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path16.resolve(info.cwd) : path16.resolve(decodeURIComponent(entry.name));
25331
+ const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path16.resolve(parsed.source_workspace_dir) : void 0;
24672
25332
  matches.push({
24673
25333
  cwd,
24674
25334
  ...sourceWorkspaceDir ? { sourceWorkspaceDir } : {}
@@ -24678,7 +25338,7 @@ async function locateGrokNativeSession(options, sessionId) {
24678
25338
  }
24679
25339
  async function readGrokNativeHistory(options, sessionId) {
24680
25340
  try {
24681
- return parseNativeHistory(await readFile4(nativeHistoryPath({ ...options, cwd: path15.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
25341
+ return parseNativeHistory(await readFile5(nativeHistoryPath({ ...options, cwd: path16.resolve(options.cwd) }, sessionId), "utf8"), sessionId);
24682
25342
  } catch (error53) {
24683
25343
  if (isMissingFile(error53))
24684
25344
  return [];
@@ -24705,7 +25365,9 @@ function parseNativeHistory(contents, sessionId) {
24705
25365
  const params = record2.params;
24706
25366
  if (params.sessionId !== sessionId || !isRecord15(params.update))
24707
25367
  continue;
24708
- const metadata = isRecord15(params._meta) ? params._meta : void 0;
25368
+ let metadata = grokNotificationMetadata(params._meta, params.update._meta);
25369
+ if (typeof record2.timestamp === "number" && Number.isFinite(record2.timestamp))
25370
+ metadata = { nativeTimestampMs: record2.timestamp * 1e3, ...metadata };
24709
25371
  const event = transportEvent(params.update, metadata);
24710
25372
  if (event)
24711
25373
  events.push(metadata ? { ...event, metadata } : event);
@@ -24716,6 +25378,8 @@ var GrokAcpTransport = class {
24716
25378
  #options;
24717
25379
  #activeCompact = null;
24718
25380
  #activePrompt = null;
25381
+ #background = null;
25382
+ #goalPrompts = 0;
24719
25383
  #child = null;
24720
25384
  #closed = false;
24721
25385
  #closing = false;
@@ -24867,7 +25531,7 @@ var GrokAcpTransport = class {
24867
25531
  }
24868
25532
  }
24869
25533
  async questionActivity(toolCallId) {
24870
- if (!this.#connection || !this.#sessionId || !this.#activePrompt || this.#closed || this.#closing)
25534
+ if (!this.#connection || !this.#sessionId || !this.#activePrompt && !this.#background || this.#closed || this.#closing)
24871
25535
  return null;
24872
25536
  try {
24873
25537
  const raw = await withTimeout(this.#connection.request(GROK_QUESTION_ACTIVITY_METHOD, {
@@ -24887,6 +25551,8 @@ var GrokAcpTransport = class {
24887
25551
  if (!this.#connection)
24888
25552
  throw new GrokTransportError("unavailable", "Grok ACP is unavailable");
24889
25553
  try {
25554
+ const before = await this.readHistory(params.sessionId);
25555
+ const markerCount = before.filter((event) => event.type === "rewind.marker").length;
24890
25556
  const raw = await withTimeout(this.#connection.request(GROK_REWIND_EXECUTE_METHOD, params), this.#options.commandTimeoutMs, "Grok Session rewind");
24891
25557
  const parsed = parseGrokRewindResponse(raw);
24892
25558
  if (!parsed) {
@@ -24895,6 +25561,19 @@ var GrokAcpTransport = class {
24895
25561
  if (!parsed.success) {
24896
25562
  throw new GrokTransportError("unavailable", parsed.error && parsed.error.length > 0 ? `Grok Native Rewind failed: ${parsed.error}` : "Grok Native Rewind did not truncate history");
24897
25563
  }
25564
+ if (parsed.targetPromptIndex !== params.targetPromptIndex || parsed.mode !== void 0 && parsed.mode !== params.mode) {
25565
+ throw new GrokTransportError("protocolError", "Grok Rewind did not confirm the requested conversation boundary");
25566
+ }
25567
+ const deadline = Date.now() + 3e3;
25568
+ for (; ; ) {
25569
+ const markers = (await this.readHistory(params.sessionId)).filter((event) => event.type === "rewind.marker");
25570
+ if (markers.length > markerCount && markers.at(-1)?.targetPromptIndex === params.targetPromptIndex)
25571
+ break;
25572
+ if (this.#closing || this.#closed || Date.now() >= deadline) {
25573
+ throw new GrokTransportError("protocolError", "Grok Rewind marker is not available in Native history");
25574
+ }
25575
+ await delay3(25);
25576
+ }
24898
25577
  } catch (error53) {
24899
25578
  if (error53 instanceof GrokTransportError)
24900
25579
  throw error53;
@@ -24982,6 +25661,25 @@ var GrokAcpTransport = class {
24982
25661
  this.#initialize = initialize;
24983
25662
  return initialize;
24984
25663
  }
25664
+ observeBackground(observer) {
25665
+ this.#background = observer;
25666
+ }
25667
+ async goalControl(text) {
25668
+ if (!this.#connection || !this.#sessionId || this.#closed || this.#closing)
25669
+ throw new GrokTransportError("unavailable", "Grok goal Session is unavailable");
25670
+ if (this.#goalPrompts > 0 && ["/goal pause", "/goal clear"].includes(text)) {
25671
+ await this.#connection.cancel({ sessionId: this.#sessionId });
25672
+ }
25673
+ this.#goalPrompts++;
25674
+ try {
25675
+ return await this.#connection.prompt({
25676
+ sessionId: this.#sessionId,
25677
+ prompt: [{ type: "text", text }]
25678
+ });
25679
+ } finally {
25680
+ this.#goalPrompts--;
25681
+ }
25682
+ }
24985
25683
  async runTurn(text, onEvent, onPermission, onElicitation, onQuestion = async () => ({ outcome: "cancelled" })) {
24986
25684
  const connection = this.#connection;
24987
25685
  if (!connection || !this.#sessionId || this.#closed || this.#closing) {
@@ -24994,10 +25692,25 @@ var GrokAcpTransport = class {
24994
25692
  const active = { onEvent, onPermission, onElicitation, onQuestion };
24995
25693
  this.#activePrompt = active;
24996
25694
  try {
24997
- return await connection.prompt({
25695
+ const historyStart = (await this.getHistory()).length;
25696
+ const response = await connection.prompt({
24998
25697
  sessionId: this.#sessionId,
24999
25698
  prompt: [{ type: "text", text }]
25000
25699
  });
25700
+ const promptId = response._meta?.promptId;
25701
+ if (response.stopReason === "end_turn" && typeof promptId === "string" && promptId.length > 0) {
25702
+ const deadline = Date.now() + 3e3;
25703
+ for (; ; ) {
25704
+ const history = await this.getHistory();
25705
+ if (history.slice(historyStart).some((event) => event.type === "turn.completed" && event.nativeTurnKey === promptId))
25706
+ break;
25707
+ if (this.#closing || this.#closed || Date.now() >= deadline) {
25708
+ throw new GrokTransportError("protocolError", "Grok completed Prompt is not available in Native history");
25709
+ }
25710
+ await delay3(25);
25711
+ }
25712
+ }
25713
+ return response;
25001
25714
  } finally {
25002
25715
  await yieldToEventLoop();
25003
25716
  if (this.#activePrompt === active)
@@ -25038,6 +25751,49 @@ var GrokAcpTransport = class {
25038
25751
  this.#activeCompact = null;
25039
25752
  }
25040
25753
  }
25754
+ async interject(text, interjectionId) {
25755
+ const connection = this.#connection;
25756
+ const sessionId = this.#sessionId;
25757
+ if (!connection || !sessionId || this.#closed || this.#closing) {
25758
+ throw new GrokTransportError("unavailable", "Grok ACP Session is unavailable");
25759
+ }
25760
+ if (!this.#activePrompt) {
25761
+ const deadline = Date.now() + 2e3;
25762
+ while (!this.#activePrompt && Date.now() < deadline)
25763
+ await delay3(25);
25764
+ }
25765
+ if (!this.#activePrompt)
25766
+ throw new GrokSteerMissedTurnError();
25767
+ const params = {
25768
+ sessionId,
25769
+ text,
25770
+ ...interjectionId ? { interjectionId } : {}
25771
+ };
25772
+ let raw;
25773
+ try {
25774
+ raw = await connection.request(GROK_INTERJECT_METHOD, params);
25775
+ } catch (error53) {
25776
+ if (!isGrokMethodNotFound(error53)) {
25777
+ throw new GrokTransportError("unavailable", "Grok Native Interject failed", {
25778
+ cause: error53
25779
+ });
25780
+ }
25781
+ try {
25782
+ raw = await connection.request(GROK_INTERJECT_FALLBACK_METHOD, params);
25783
+ } catch (fallback) {
25784
+ if (isGrokMethodNotFound(fallback)) {
25785
+ throw new GrokTransportError("protocolError", `Grok ACP Method Not Found: ${GROK_INTERJECT_METHOD}`, { cause: fallback });
25786
+ }
25787
+ throw new GrokTransportError("unavailable", "Grok Native Interject failed", {
25788
+ cause: fallback
25789
+ });
25790
+ }
25791
+ }
25792
+ const parsed = parseGrokInterjectResult(raw);
25793
+ if (!parsed)
25794
+ throw new GrokSteerMissedTurnError();
25795
+ return parsed;
25796
+ }
25041
25797
  async setModel(modelId, reasoningEffort, contextWindowTokens) {
25042
25798
  const connection = this.#connection;
25043
25799
  if (!connection || !this.#sessionId)
@@ -25064,7 +25820,7 @@ var GrokAcpTransport = class {
25064
25820
  }
25065
25821
  cancel() {
25066
25822
  const connection = this.#connection;
25067
- if (!connection || !this.#sessionId || !this.#activePrompt && !this.#activeCompact) {
25823
+ if (!connection || !this.#sessionId || !this.#activePrompt && !this.#activeCompact && !this.#background && !this.#goalPrompts) {
25068
25824
  return Promise.reject(new Error("Grok ACP Session has no cancellable operation"));
25069
25825
  }
25070
25826
  if (this.#activeCompact)
@@ -25149,7 +25905,7 @@ var GrokAcpTransport = class {
25149
25905
  this.#availableCommands = parseGrokAvailableCommands(update.availableCommands);
25150
25906
  return;
25151
25907
  }
25152
- const metadata = isRecord15(notification._meta) ? notification._meta : void 0;
25908
+ const metadata = grokNotificationMetadata(notification._meta, notification.update._meta);
25153
25909
  const event = transportEvent(notification.update, metadata);
25154
25910
  if (!event)
25155
25911
  return;
@@ -25158,8 +25914,12 @@ var GrokAcpTransport = class {
25158
25914
  this.#replay.push(enriched);
25159
25915
  else if (this.#activePrompt)
25160
25916
  this.#activePrompt.onEvent(enriched);
25917
+ else if (this.#activeCompact)
25918
+ this.#activeCompact.onEvent(enriched);
25161
25919
  else
25162
- this.#activeCompact?.onEvent(enriched);
25920
+ this.#background?.onEvent(enriched);
25921
+ if (event.type === "goal.changed" && (this.#activePrompt || this.#activeCompact))
25922
+ this.#background?.onEvent(enriched);
25163
25923
  }
25164
25924
  #handleExtensionNotification(method, params) {
25165
25925
  if (!isGrokExtensionSessionUpdateMethod(method))
@@ -25169,13 +25929,17 @@ var GrokAcpTransport = class {
25169
25929
  this.#handleUpdate(params);
25170
25930
  }
25171
25931
  #handlePermission(params) {
25172
- if (params.sessionId !== this.#sessionId || !this.#activePrompt) {
25932
+ const observer = this.#activePrompt ?? this.#background;
25933
+ if (params.sessionId !== this.#sessionId || !observer) {
25173
25934
  return Promise.resolve({ outcome: { outcome: "cancelled" } });
25174
25935
  }
25175
- return this.#activePrompt.onPermission({ request: params, options: params.options });
25936
+ return observer.onPermission({
25937
+ request: params,
25938
+ options: params.options
25939
+ });
25176
25940
  }
25177
25941
  async #handleExtMethod(method, params) {
25178
- const activePrompt = !this.#closed && !this.#closing && this.#replay === null && this.#activeCompact === null ? this.#activePrompt : null;
25942
+ const activePrompt = !this.#closed && !this.#closing && this.#replay === null && this.#activeCompact === null ? this.#activePrompt ?? this.#background : null;
25179
25943
  if (method === GROK_ASK_USER_QUESTION_METHOD) {
25180
25944
  let request;
25181
25945
  try {
@@ -25212,8 +25976,8 @@ var GrokAcpTransport = class {
25212
25976
 
25213
25977
  // dist/session-import.js
25214
25978
  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";
25979
+ import { opendir as opendir2, readFile as readFile6, stat as stat2 } from "node:fs/promises";
25980
+ import path17 from "node:path";
25217
25981
  import { createInterface as createInterface2 } from "node:readline";
25218
25982
 
25219
25983
  // ../../harness-adapter/dist/session-import.js
@@ -25338,7 +26102,7 @@ function isRecord16(value) {
25338
26102
  return typeof value === "object" && value !== null && !Array.isArray(value);
25339
26103
  }
25340
26104
  async function readJson(file2, signal) {
25341
- return JSON.parse(await readFile5(file2, { encoding: "utf8", signal }));
26105
+ return JSON.parse(await readFile6(file2, { encoding: "utf8", signal }));
25342
26106
  }
25343
26107
  function processAlive(pid) {
25344
26108
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
@@ -25434,7 +26198,7 @@ var GrokSessionImport = class {
25434
26198
  const active = /* @__PURE__ */ new Set();
25435
26199
  let entries;
25436
26200
  try {
25437
- entries = await readJson(path16.join(this.#home(), "active_sessions.json"), signal);
26201
+ entries = await readJson(path17.join(this.#home(), "active_sessions.json"), signal);
25438
26202
  } catch (error53) {
25439
26203
  signal.throwIfAborted();
25440
26204
  if (isStorageAccessError(error53))
@@ -25451,7 +26215,7 @@ var GrokSessionImport = class {
25451
26215
  }
25452
26216
  /** Session ID to every directory claiming it. Enumerated links are not followed. */
25453
26217
  async #sessionDirectories(signal) {
25454
- const root = path16.join(this.#home(), "sessions");
26218
+ const root = path17.join(this.#home(), "sessions");
25455
26219
  const found = /* @__PURE__ */ new Map();
25456
26220
  const info = await optionalLstat(root);
25457
26221
  if (!info)
@@ -25462,7 +26226,7 @@ var GrokSessionImport = class {
25462
26226
  signal.throwIfAborted();
25463
26227
  if (!workspace.isDirectory())
25464
26228
  continue;
25465
- const workspaceDirectory = path16.join(root, workspace.name);
26229
+ const workspaceDirectory = path17.join(root, workspace.name);
25466
26230
  const sessions = await opendir2(workspaceDirectory).catch((error53) => {
25467
26231
  if (isMissingFileError(error53))
25468
26232
  return null;
@@ -25475,7 +26239,7 @@ var GrokSessionImport = class {
25475
26239
  if (!session.isDirectory())
25476
26240
  continue;
25477
26241
  const directories = found.get(session.name) ?? [];
25478
- directories.push(path16.join(workspaceDirectory, session.name));
26242
+ directories.push(path17.join(workspaceDirectory, session.name));
25479
26243
  found.set(session.name, directories);
25480
26244
  }
25481
26245
  }
@@ -25483,10 +26247,10 @@ var GrokSessionImport = class {
25483
26247
  }
25484
26248
  async #candidate(sessionDirectory, active, signal) {
25485
26249
  signal.throwIfAborted();
25486
- const nativeSessionId = path16.basename(sessionDirectory);
26250
+ const nativeSessionId = path17.basename(sessionDirectory);
25487
26251
  const files = [
25488
- path16.join(sessionDirectory, "summary.json"),
25489
- path16.join(sessionDirectory, "updates.jsonl")
26252
+ path17.join(sessionDirectory, "summary.json"),
26253
+ path17.join(sessionDirectory, "updates.jsonl")
25490
26254
  ];
25491
26255
  return readStableFiles(files, async ([summaryInfo, updates]) => {
25492
26256
  if (!summaryInfo?.isFile() || !updates?.isFile() || summaryInfo.size > MAX_METADATA_BYTES)
@@ -25498,12 +26262,12 @@ var GrokSessionImport = class {
25498
26262
  if (typeof summary.session_kind === "string" && SUBAGENT_SESSION_KINDS.has(summary.session_kind))
25499
26263
  return null;
25500
26264
  const nativeCwd = summary.info.cwd;
25501
- if (typeof nativeCwd !== "string" || !path16.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
26265
+ if (typeof nativeCwd !== "string" || !path17.isAbsolute(nativeCwd) || nativeCwd.includes("\0"))
25502
26266
  return null;
25503
- const cwd = path16.resolve(nativeCwd);
25504
- if (encodeURIComponent(cwd) !== path16.basename(path16.dirname(sessionDirectory)))
26267
+ const cwd = path17.resolve(nativeCwd);
26268
+ if (encodeURIComponent(cwd) !== path17.basename(path17.dirname(sessionDirectory)))
25505
26269
  return null;
25506
- if (!(await stat(cwd)).isDirectory())
26270
+ if (!(await stat2(cwd)).isDirectory())
25507
26271
  return null;
25508
26272
  const prompt = await firstUserText(files[1], signal);
25509
26273
  if (prompt === null)
@@ -25540,6 +26304,7 @@ var GrokSubagentLifecycle = class {
25540
26304
  #newItemId;
25541
26305
  #delegations = /* @__PURE__ */ new Map();
25542
26306
  #callIdByNativeId = /* @__PURE__ */ new Map();
26307
+ #completedNativeIds = /* @__PURE__ */ new Set();
25543
26308
  constructor(options) {
25544
26309
  this.#emit = options.emit;
25545
26310
  this.#newItemId = options.newItemId;
@@ -25595,12 +26360,23 @@ var GrokSubagentLifecycle = class {
25595
26360
  }
25596
26361
  for (const [callId, active] of this.#delegations) {
25597
26362
  const current = active.item.subagents[0];
25598
- if (!current || current.nativeSubagentId)
26363
+ if (input.parentPromptId || !current || current.nativeSubagentId)
25599
26364
  continue;
25600
26365
  if (input.description && current.description === input.description) {
25601
26366
  return this.update(turnId, callId, input);
25602
26367
  }
25603
26368
  }
26369
+ if (input.parentPromptId) {
26370
+ if (this.#completedNativeIds.has(input.nativeSubagentId))
26371
+ return void 0;
26372
+ return this.start(turnId, {
26373
+ ...input,
26374
+ callId: `grok-helper-${input.nativeSubagentId}`,
26375
+ operation: "spawn",
26376
+ description: input.description ?? "Grok Subagent",
26377
+ background: true
26378
+ });
26379
+ }
25604
26380
  return void 0;
25605
26381
  }
25606
26382
  update(turnId, callId, patch) {
@@ -25647,11 +26423,11 @@ var GrokSubagentLifecycle = class {
25647
26423
  if (callId && this.#delegations.has(callId)) {
25648
26424
  return this.complete(turnId, callId, { ...input, nativeSubagentId });
25649
26425
  }
25650
- const status = input.status ?? (input.cancellationRequested ? "interrupted" : input.failed ? "failed" : "completed");
26426
+ const status2 = input.status ?? (input.cancellationRequested ? "interrupted" : input.failed ? "failed" : "completed");
25651
26427
  this.#emit({
25652
26428
  type: "subagent.state.changed",
25653
26429
  nativeSubagentId,
25654
- status,
26430
+ status: status2,
25655
26431
  ...input.resultSummary ? { resultSummary: input.resultSummary } : {}
25656
26432
  });
25657
26433
  return void 0;
@@ -25664,13 +26440,15 @@ var GrokSubagentLifecycle = class {
25664
26440
  const current = active.item.subagents[0];
25665
26441
  if (!current)
25666
26442
  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");
26443
+ const status2 = input.status ?? (input.cancellationRequested ? "interrupted" : input.failed ? "failed" : input.keepRunning ? "running" : "completed");
25668
26444
  const nativeSubagentId = input.nativeSubagentId ?? current.nativeSubagentId;
25669
26445
  if (nativeSubagentId)
25670
26446
  this.#callIdByNativeId.set(nativeSubagentId, callId);
26447
+ if (nativeSubagentId)
26448
+ this.#completedNativeIds.add(nativeSubagentId);
25671
26449
  const subagent = {
25672
26450
  ...current,
25673
- status,
26451
+ status: status2,
25674
26452
  ...nativeSubagentId ? { nativeSubagentId, subagentId: nativeSubagentId } : {},
25675
26453
  ...input.resultSummary ? { resultSummary: input.resultSummary } : {}
25676
26454
  };
@@ -25688,14 +26466,14 @@ var GrokSubagentLifecycle = class {
25688
26466
  const current = active.item.subagents[0];
25689
26467
  if (!current)
25690
26468
  continue;
25691
- const status = outcome.status === "succeeded" ? current.status : outcome.status === "cancelled" ? "interrupted" : "failed";
25692
- const item = { ...active.item, subagents: [{ ...current, status }] };
26469
+ const status2 = outcome.status === "succeeded" ? current.status : outcome.status === "cancelled" ? "interrupted" : "failed";
26470
+ const item = { ...active.item, subagents: [{ ...current, status: status2 }] };
25693
26471
  if (!active.published) {
25694
26472
  active.item = item;
25695
26473
  this.#publish(turnId, active);
25696
26474
  }
25697
26475
  this.#emit({ type: "item.completed", turnId, snapshot: { item, outcome } });
25698
- this.#emitState({ ...current, status });
26476
+ this.#emitState({ ...current, status: status2 });
25699
26477
  }
25700
26478
  }
25701
26479
  #publish(turnId, active) {
@@ -25832,9 +26610,9 @@ function stateForGrokModel(modelState, nativeState, model2 = modelState.currentM
25832
26610
  }
25833
26611
 
25834
26612
  // dist/grok-credits.js
25835
- import { readFile as readFile6 } from "node:fs/promises";
26613
+ import { readFile as readFile7 } from "node:fs/promises";
25836
26614
  import os7 from "node:os";
25837
- import path17 from "node:path";
26615
+ import path18 from "node:path";
25838
26616
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
25839
26617
  var REQUEST_TIMEOUT_MS = 15e3;
25840
26618
  function isRecord18(value) {
@@ -25854,7 +26632,7 @@ function nonNegativeCentValue(value) {
25854
26632
  return amount;
25855
26633
  }
25856
26634
  function grokHome3(environment) {
25857
- return environment.GROK_HOME ?? path17.join(environment.HOME ?? environment.USERPROFILE ?? os7.homedir(), ".grok");
26635
+ return environment.GROK_HOME ?? path18.join(environment.HOME ?? environment.USERPROFILE ?? os7.homedir(), ".grok");
25858
26636
  }
25859
26637
  function periodTypeFrom(value) {
25860
26638
  if (typeof value !== "string")
@@ -25946,8 +26724,8 @@ async function fetchGrokAccount(input = {}) {
25946
26724
  if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((value) => value?.trim()))
25947
26725
  return null;
25948
26726
  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");
26727
+ const authPath = path18.join(grokHome3(environment), "auth.json");
26728
+ const raw = input.readAuthFile ? await input.readAuthFile(authPath) : await readFile7(authPath, "utf8");
25951
26729
  const token = selectAccessToken(JSON.parse(raw), now);
25952
26730
  if (!token)
25953
26731
  return null;
@@ -26176,14 +26954,16 @@ function sessionCostFromNative(value, initialCostUsd) {
26176
26954
  }
26177
26955
  function historyTurnKey(event, index) {
26178
26956
  const key = event.nativeTurnKey;
26179
- if (typeof key === "string" && key.startsWith("task-completed-"))
26180
- return null;
26181
26957
  return typeof key === "string" && key.length > 0 ? key : `anon-${index}`;
26182
26958
  }
26183
26959
  function sessionUsageFromHistory(events) {
26184
26960
  const latestByKey = /* @__PURE__ */ new Map();
26185
26961
  let index = 0;
26186
- for (const event of events) {
26962
+ const groups = classifyGrokHistory(events);
26963
+ for (const group of groups) {
26964
+ if (group.disposition !== "durable" && (group.user || !latestByKey.has(group.terminal.nativeTurnKey)))
26965
+ continue;
26966
+ const event = group.terminal;
26187
26967
  if (event?.type !== "turn.completed")
26188
26968
  continue;
26189
26969
  const key = historyTurnKey(event, index);
@@ -26270,18 +27050,6 @@ function usageFromUpdate(update, metadata, contextWindowTokens) {
26270
27050
 
26271
27051
  // dist/grok-adapter.js
26272
27052
  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
27053
  function capabilitiesForModels(modelState) {
26286
27054
  return {
26287
27055
  configuration: {
@@ -26290,7 +27058,12 @@ function capabilitiesForModels(modelState) {
26290
27058
  selectPermissionMode: true,
26291
27059
  permissionModeScope: "live"
26292
27060
  },
26293
- history: { fork: true, forkAcrossCwd: true, rollbackLastTurn: true },
27061
+ history: {
27062
+ fork: true,
27063
+ forkAcrossCwd: true,
27064
+ rollbackLastTurn: true,
27065
+ rollbackToCheckpoint: true
27066
+ },
26294
27067
  subagents: { observe: true, readTranscript: true }
26295
27068
  };
26296
27069
  }
@@ -26358,7 +27131,11 @@ function terminalOutcome2(response, cancelled) {
26358
27131
  var GrokHarnessSession = class {
26359
27132
  harnessId = grokHarnessId;
26360
27133
  capabilities;
27134
+ readCapabilities;
26361
27135
  commands;
27136
+ goals;
27137
+ #backgroundQueue = Promise.resolve();
27138
+ #goalCommand = null;
26362
27139
  initialState;
26363
27140
  initialUsage;
26364
27141
  outputs;
@@ -26382,8 +27159,11 @@ var GrokHarnessSession = class {
26382
27159
  #usage = null;
26383
27160
  #initialCostUsd;
26384
27161
  #costRequest = 0;
27162
+ #historyLength;
27163
+ #goalHelpers = [];
26385
27164
  constructor(cwd, transport, opened, modelState, onClosed, options) {
26386
27165
  this.#cwd = cwd;
27166
+ this.#historyLength = options.history.length;
26387
27167
  this.#sessionDirectory = options.sessionDirectory;
26388
27168
  this.#mediaRoots = grokMediaResolveRoots(cwd, options.sessionDirectory);
26389
27169
  this.#transport = transport;
@@ -26396,11 +27176,22 @@ var GrokHarnessSession = class {
26396
27176
  this.initialUsage = options.initialUsage ?? null;
26397
27177
  this.#usage = this.initialUsage;
26398
27178
  this.#initialCostUsd = this.initialUsage?.totalCostUsd ?? 0;
26399
- this.capabilities = capabilitiesForModels(modelState);
27179
+ this.capabilities = ((session) => ({
27180
+ ...capabilitiesForModels(modelState),
27181
+ ...transport.goalControl && transport.observeBackground ? { autonomousTurns: { observe: true } } : {},
27182
+ get steer() {
27183
+ return session.#canSteerActiveTurn();
27184
+ }
27185
+ }))(this);
26400
27186
  this.commands = {
26401
27187
  list: async () => ({ ok: true, value: this.#liveCommandCatalog() }),
26402
27188
  execute: (command) => this.#executeHarnessCommand(command)
26403
27189
  };
27190
+ this.readCapabilities = async () => ({
27191
+ ...this.capabilities,
27192
+ ...capabilitiesForModels(this.#modelState),
27193
+ steer: this.#canSteerActiveTurn()
27194
+ });
26404
27195
  this.#state = stateForGrokModel(modelState, { nativeRef: nativeRef(opened.sessionId) }, modelState.currentModel, modelState.currentThinkingOptionId, options.initialPermissionModeId);
26405
27196
  this.initialState = this.#state;
26406
27197
  this.#snapshot = {
@@ -26408,6 +27199,71 @@ var GrokHarnessSession = class {
26408
27199
  state: this.#state
26409
27200
  };
26410
27201
  this.outputs = this.#channel.outputs;
27202
+ const goalControl = transport.goalControl?.bind(transport);
27203
+ if (goalControl && transport.observeBackground) {
27204
+ const goals = new GrokGoals(options.sessionDirectory, async (prompt, signal) => {
27205
+ if (this.#phase !== "open" || this.#configuring)
27206
+ throw new Error("Grok Session cannot control goals during configuration");
27207
+ const active = this.#active;
27208
+ if (active) {
27209
+ if (!["/goal pause", "/goal clear"].includes(prompt))
27210
+ throw new Error("Pause the active Grok worker before changing its goal");
27211
+ const before = await readGrokGoal(this.#sessionDirectory);
27212
+ const current = await goals.read();
27213
+ if (!current.ok)
27214
+ throw new Error(current.error.message);
27215
+ signal.throwIfAborted();
27216
+ if (prompt !== "/goal clear" || current.value?.status !== "complete") {
27217
+ const cancelled = await this.#cancel({
27218
+ type: "turn.cancel",
27219
+ turnId: active.command.turnId
27220
+ });
27221
+ if (!cancelled.ok)
27222
+ throw new Error(cancelled.error.message);
27223
+ }
27224
+ await new Promise((resolve, reject) => {
27225
+ const aborted2 = () => reject(new Error("Grok goal control timed out waiting for its worker"));
27226
+ signal.addEventListener("abort", aborted2, { once: true });
27227
+ if (signal.aborted)
27228
+ aborted2();
27229
+ void active.completion.then(() => {
27230
+ signal.removeEventListener("abort", aborted2);
27231
+ resolve();
27232
+ });
27233
+ });
27234
+ const after = await readGrokGoal(this.#sessionDirectory);
27235
+ if (before?.state.goal_id !== after?.state.goal_id)
27236
+ throw new Error("Grok goal changed while waiting for its worker");
27237
+ }
27238
+ signal.throwIfAborted();
27239
+ if (this.#phase !== "open" || this.#active)
27240
+ throw new Error("Grok Session changed while controlling its goal");
27241
+ return goalControl(prompt);
27242
+ }, (goal) => this.#event({ type: "goal.changed", goal }), 3e4, () => transport.getHistory());
27243
+ this.goals = goals;
27244
+ transport.observeBackground({
27245
+ onEvent: (event) => {
27246
+ if (event.type === "goal.changed") {
27247
+ void goals.observe(event.update).catch((error53) => this.handleTransportFault(new GrokTransportError("protocolError", String(error53))));
27248
+ return;
27249
+ }
27250
+ this.#backgroundQueue = this.#backgroundQueue.then(() => this.#backgroundEvent(event)).catch((error53) => this.handleTransportFault(new GrokTransportError("protocolError", String(error53))));
27251
+ },
27252
+ onPermission: async (request) => {
27253
+ await this.#backgroundQueue;
27254
+ return this.#active ? this.#requestPermission(this.#active, request) : { outcome: { outcome: "cancelled" } };
27255
+ },
27256
+ onElicitation: async (request) => {
27257
+ await this.#backgroundQueue;
27258
+ return this.#active ? this.#requestElicitation(this.#active, request) : grokMcpElicitCancel();
27259
+ },
27260
+ onQuestion: async (request) => {
27261
+ await this.#backgroundQueue;
27262
+ return this.#active ? this.#active.questions.ask(request) : { outcome: "cancelled" };
27263
+ }
27264
+ });
27265
+ void this.goals.read();
27266
+ }
26411
27267
  }
26412
27268
  async questionActivity(interactionId) {
26413
27269
  const active = this.#active;
@@ -26434,7 +27290,7 @@ var GrokHarnessSession = class {
26434
27290
  if (this.#phase !== "open") {
26435
27291
  return { ok: false, error: invalidState("Grok Session is not open") };
26436
27292
  }
26437
- if (this.#active || this.#configuring) {
27293
+ if (this.#active || this.#configuring || this.#goalCommand || this.goals?.busy) {
26438
27294
  return {
26439
27295
  ok: false,
26440
27296
  error: {
@@ -26457,7 +27313,7 @@ var GrokHarnessSession = class {
26457
27313
  if ("commandId" in command)
26458
27314
  return this.#executeHarnessCommand(command);
26459
27315
  if (command.type === "turn.steer")
26460
- return unsupportedSteer("Grok");
27316
+ return this.#steer(command);
26461
27317
  if (command.type === "turn.cancel")
26462
27318
  return this.#cancel(command);
26463
27319
  if (command.type === "interaction.respond")
@@ -26468,7 +27324,10 @@ var GrokHarnessSession = class {
26468
27324
  return this.#selectThinking(command);
26469
27325
  if (command.type === "permissionMode.select")
26470
27326
  return this.#selectPermissionMode(command);
26471
- if (this.#active || this.#configuring) {
27327
+ return this.#startTurn(command);
27328
+ }
27329
+ async #startTurn(command, catalogCommand = false) {
27330
+ if (this.#active || this.#configuring || this.#goalCommand || this.goals?.busy) {
26472
27331
  return {
26473
27332
  ok: false,
26474
27333
  error: {
@@ -26478,6 +27337,15 @@ var GrokHarnessSession = class {
26478
27337
  }
26479
27338
  };
26480
27339
  }
27340
+ if (this.goals?.active)
27341
+ return {
27342
+ ok: false,
27343
+ error: {
27344
+ code: "sessionBusy",
27345
+ message: "Pause the native Grok goal before starting a user Turn",
27346
+ retryable: true
27347
+ }
27348
+ };
26481
27349
  const text = command.input.map(({ text: text2 }) => text2).join("\n");
26482
27350
  if (text.length === 0) {
26483
27351
  return {
@@ -26494,6 +27362,54 @@ var GrokHarnessSession = class {
26494
27362
  } catch (error53) {
26495
27363
  return { ok: false, error: normalizeError(error53, "nativeFailure") };
26496
27364
  }
27365
+ const active = this.#newActive(command, catalogCommand);
27366
+ this.#active = active;
27367
+ this.#event({ type: "turn.started", turnId: command.turnId });
27368
+ 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, {
27369
+ status: "failed",
27370
+ error: normalizeError(error53, "nativeFailure")
27371
+ }));
27372
+ return { ok: true, value: { turnId: command.turnId } };
27373
+ }
27374
+ #canSteerActiveTurn() {
27375
+ const active = this.#active;
27376
+ return this.#phase === "open" && active != null && !active.cancellationRequested && !active.catalogCommand && !active.command.turnId.startsWith("grok-autonomous-") && typeof this.#transport.interject === "function";
27377
+ }
27378
+ async #steer(command) {
27379
+ const active = this.#active;
27380
+ if (!this.#canSteerActiveTurn() || !active || active.command.turnId !== command.turnId) {
27381
+ if (typeof this.#transport.interject !== "function")
27382
+ return unsupportedSteer("Grok");
27383
+ return { ok: false, error: invalidState("Grok steer target is not the active Turn") };
27384
+ }
27385
+ const text = command.input.map((input) => input.text).join("\n");
27386
+ if (text.length === 0) {
27387
+ return {
27388
+ ok: false,
27389
+ error: {
27390
+ code: "invalidRequest",
27391
+ message: "Grok steer text must not be empty",
27392
+ retryable: false
27393
+ }
27394
+ };
27395
+ }
27396
+ const interject = this.#transport.interject;
27397
+ if (!interject)
27398
+ return unsupportedSteer("Grok");
27399
+ try {
27400
+ await interject.call(this.#transport, text, this.#randomUUID());
27401
+ } catch (error53) {
27402
+ if (error53 instanceof GrokSteerMissedTurnError) {
27403
+ return { ok: false, error: invalidState("Grok steer missed the active Turn") };
27404
+ }
27405
+ if (error53 instanceof GrokTransportError && error53.kind === "protocolError" && /method not found/iu.test(error53.message)) {
27406
+ return unsupportedSteer("Grok");
27407
+ }
27408
+ return { ok: false, error: normalizeError(error53, "nativeFailure") };
27409
+ }
27410
+ return { ok: true, value: { accepted: true } };
27411
+ }
27412
+ #newActive(command, catalogCommand = false) {
26497
27413
  let resolveCompletion = () => void 0;
26498
27414
  const completion = new Promise((resolve) => {
26499
27415
  resolveCompletion = resolve;
@@ -26519,16 +27435,71 @@ var GrokHarnessSession = class {
26519
27435
  questions: new GrokQuestions(command.turnId, this.#randomUUID, (output) => this.#channel.emit(output)),
26520
27436
  cancellationRequested: false,
26521
27437
  beforeNativeTurnKeys: new Set(this.#snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey)),
27438
+ historyStart: this.#historyLength,
27439
+ catalogCommand,
26522
27440
  completion,
26523
27441
  resolveCompletion
26524
27442
  };
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 } };
27443
+ return active;
27444
+ }
27445
+ hasBackgroundWork() {
27446
+ return this.goals?.active === true;
27447
+ }
27448
+ async #backgroundEvent(event) {
27449
+ await this.#goalCommand;
27450
+ if (this.#phase !== "open")
27451
+ return;
27452
+ if (this.#bufferGoalHelper(event))
27453
+ return;
27454
+ if (!this.#active && event.type === "subagent.finished") {
27455
+ this.#event({
27456
+ type: "subagent.state.changed",
27457
+ nativeSubagentId: event.nativeSubagentId,
27458
+ status: event.status,
27459
+ ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
27460
+ });
27461
+ return;
27462
+ }
27463
+ let user = event.type === "user.text" ? event : void 0;
27464
+ if (!this.#active && this.goals && !user && ["agent.text", "agent.thought", "tool.call", "tool.update", "turn.completed"].includes(event.type)) {
27465
+ const history = await this.#transport.getHistory();
27466
+ const candidate = history.findLast((entry) => entry.type === "user.text" && entry.metadata?.host_turn !== true && entry.metadata?.hostTurn !== true);
27467
+ const latestIndex = Math.max(-1, ...this.#snapshot.turns.map((turn) => Number(turn.checkpoint?.checkpointId ?? -1)));
27468
+ if (candidate?.type === "user.text" && typeof candidate.metadata?.promptIndex === "number" && candidate.metadata.promptIndex > latestIndex)
27469
+ user = candidate;
27470
+ }
27471
+ if (user && !this.#active && user.metadata?.host_turn !== true && user.metadata?.hostTurn !== true && (this.goals?.active === true || typeof user.metadata?.promptIndex === "number")) {
27472
+ const command = {
27473
+ type: "turn.start",
27474
+ turnId: hostTurnIdSchema.parse(`grok-autonomous-${this.#randomUUID()}`),
27475
+ input: [{ type: "text", text: user.text }]
27476
+ };
27477
+ const active2 = this.#newActive(command);
27478
+ const promptIndex = grokPromptIndex(user);
27479
+ if (promptIndex !== null)
27480
+ active2.backgroundPromptIndex = promptIndex;
27481
+ this.#active = active2;
27482
+ this.#event({
27483
+ type: "turn.autonomous.started",
27484
+ turnId: command.turnId,
27485
+ input: /^\s*<system-reminder>/u.test(user.text) ? [] : command.input
27486
+ });
27487
+ this.#event({ type: "turn.started", turnId: command.turnId });
27488
+ }
27489
+ const active = this.#active;
27490
+ if (!active)
27491
+ return;
27492
+ this.#handleEvent(active, event);
27493
+ if (event.type === "turn.completed") {
27494
+ const deadline = Date.now() + 3e3;
27495
+ while (Date.now() < deadline && this.#phase === "open") {
27496
+ const history = await this.#transport.getHistory();
27497
+ if (history.slice(active.historyStart).some((entry) => entry.type === "turn.completed" && entry.nativeTurnKey === event.nativeTurnKey))
27498
+ break;
27499
+ await new Promise((resolve) => setTimeout(resolve, 50));
27500
+ }
27501
+ await this.#settleFromHistory(active, terminalOutcome2({ stopReason: event.stopReason }, active.cancellationRequested), void 0, event.nativeTurnKey);
27502
+ }
26532
27503
  }
26533
27504
  /** Built-ins plus the commands, workflows and skills the open Session advertises. */
26534
27505
  #liveCommandCatalog() {
@@ -26536,13 +27507,90 @@ var GrokHarnessSession = class {
26536
27507
  return mergeLiveHarnessCommands(grokCommandCatalog, GROK_LIVE_COMMAND_ID_PREFIX, native ? grokLiveCommands(native) : null);
26537
27508
  }
26538
27509
  async #executeHarnessCommand(command) {
27510
+ if (this.#phase !== "open")
27511
+ return { ok: false, error: invalidState("Grok Session is not open") };
27512
+ if (command.commandId === "grok.goal" || command.commandId === "grok.desktop-goal") {
27513
+ const prompt = grokGoalPrompt(command.arguments);
27514
+ if (!prompt.ok)
27515
+ return prompt;
27516
+ const goals = this.goals;
27517
+ const goalControl = this.#transport.goalControl?.bind(this.#transport);
27518
+ if (goals && goalControl) {
27519
+ if (this.#active || this.#goalCommand || this.#configuring || this.goals?.busy)
27520
+ return {
27521
+ ok: false,
27522
+ error: {
27523
+ code: "sessionBusy",
27524
+ message: "Grok Session already has an active operation",
27525
+ retryable: true
27526
+ }
27527
+ };
27528
+ const argument = prompt.value.slice("/goal ".length).trim();
27529
+ this.#event({ type: "turn.started", turnId: command.turnId });
27530
+ this.#goalCommand = (async () => {
27531
+ const budget = /^(.*) --budget (\d+)$/su.exec(argument);
27532
+ const existing = await goals.read();
27533
+ const emptyControl = existing.ok && existing.value === null && ["pause", "resume"].includes(argument);
27534
+ const result = emptyControl ? await goalControl(prompt.value).then(() => ({ ok: true, value: null }), (error53) => ({
27535
+ ok: false,
27536
+ error: normalizeError(error53, "nativeFailure")
27537
+ })) : argument === "clear" ? await goals.clear() : argument === "status" || !argument ? await goals.read() : argument === "pause" || argument === "resume" ? await goals.set({
27538
+ status: argument === "pause" ? "paused" : "active",
27539
+ origin: "user"
27540
+ }) : await goals.set({
27541
+ objective: budget?.[1] ?? argument,
27542
+ ...budget ? { tokenBudget: Number(budget[2]) } : {},
27543
+ origin: "user"
27544
+ });
27545
+ if (result.ok && command.commandId !== "grok.desktop-goal") {
27546
+ const value = result.value;
27547
+ const text = value && typeof value === "object" && "objective" in value ? `Goal: ${value.objective}
27548
+ Status: ${value.status}
27549
+ Goal tokens used: ${value.tokensUsed}
27550
+ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleared." : "No goal is currently set.";
27551
+ const item = {
27552
+ type: "agentMessage",
27553
+ itemId: hostItemIdSchema.parse(this.#randomUUID()),
27554
+ text
27555
+ };
27556
+ this.#event({ type: "item.started", turnId: command.turnId, item });
27557
+ this.#event({
27558
+ type: "item.completed",
27559
+ turnId: command.turnId,
27560
+ snapshot: { item, outcome: { status: "succeeded" } }
27561
+ });
27562
+ }
27563
+ this.#event({
27564
+ type: "turn.completed",
27565
+ turnId: command.turnId,
27566
+ ephemeral: true,
27567
+ outcome: result.ok ? { status: "succeeded" } : { status: "failed", error: result.error }
27568
+ });
27569
+ })().catch((error53) => {
27570
+ this.#event({
27571
+ type: "turn.completed",
27572
+ turnId: command.turnId,
27573
+ ephemeral: true,
27574
+ outcome: { status: "failed", error: normalizeError(error53, "nativeFailure") }
27575
+ });
27576
+ }).finally(() => {
27577
+ this.#goalCommand = null;
27578
+ });
27579
+ return { ok: true, value: { turnId: command.turnId } };
27580
+ }
27581
+ return this.#startTurn({
27582
+ type: "turn.start",
27583
+ turnId: command.turnId,
27584
+ input: [{ type: "text", text: prompt.value }]
27585
+ }, true);
27586
+ }
26539
27587
  const livePrompt = liveHarnessCommandPrompt(this.#liveCommandCatalog(), GROK_LIVE_COMMAND_ID_PREFIX, command.commandId, command.arguments?.text);
26540
27588
  if (livePrompt !== null) {
26541
- const started = await this.execute({
27589
+ const started = await this.#startTurn({
26542
27590
  type: "turn.start",
26543
27591
  turnId: command.turnId,
26544
27592
  input: [{ type: "text", text: livePrompt }]
26545
- });
27593
+ }, true);
26546
27594
  return started.ok ? { ok: true, value: { turnId: command.turnId } } : started;
26547
27595
  }
26548
27596
  if (command.commandId !== "grok.compact") {
@@ -26555,7 +27603,7 @@ var GrokHarnessSession = class {
26555
27603
  }
26556
27604
  };
26557
27605
  }
26558
- if (this.#active || this.#configuring) {
27606
+ if (this.#active || this.#configuring || this.#goalCommand || this.goals?.busy || this.goals?.active) {
26559
27607
  return {
26560
27608
  ok: false,
26561
27609
  error: {
@@ -26611,6 +27659,8 @@ var GrokHarnessSession = class {
26611
27659
  questions: new GrokQuestions(command.turnId, this.#randomUUID, (output) => this.#channel.emit(output)),
26612
27660
  cancellationRequested: false,
26613
27661
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
27662
+ historyStart: this.#historyLength,
27663
+ catalogCommand: true,
26614
27664
  completion,
26615
27665
  resolveCompletion
26616
27666
  };
@@ -26668,6 +27718,7 @@ var GrokHarnessSession = class {
26668
27718
  const knownTurnRefs = this.#snapshot.turns.map((turn) => turn.nativeTurnRef);
26669
27719
  const refreshed = mapGrokReplay(history, this.harnessId, this.#transport.sessionId, this.#cwd, knownTurnRefs, this.#toolOutputLimit, this.#sessionDirectory);
26670
27720
  this.#snapshot.turns = refreshed.turns;
27721
+ this.#historyLength = history.length;
26671
27722
  return history;
26672
27723
  }
26673
27724
  async #selectModel(command) {
@@ -26697,7 +27748,7 @@ var GrokHarnessSession = class {
26697
27748
  return this.#configure(model2, parsed.data);
26698
27749
  }
26699
27750
  async #configure(model2, thinkingOptionId) {
26700
- if (this.#configuring) {
27751
+ if (this.#configuring || this.#goalCommand || this.goals?.busy || this.goals?.active) {
26701
27752
  return {
26702
27753
  ok: false,
26703
27754
  error: {
@@ -26743,7 +27794,7 @@ var GrokHarnessSession = class {
26743
27794
  }
26744
27795
  };
26745
27796
  }
26746
- if (this.#active || this.#configuring) {
27797
+ if (this.#active || this.#configuring || this.#goalCommand || this.goals?.busy || this.goals?.active) {
26747
27798
  return {
26748
27799
  ok: false,
26749
27800
  error: {
@@ -27185,7 +28236,7 @@ var GrokHarnessSession = class {
27185
28236
  this.#completeTool(active, event.callId, event.status, event.content, event.rawOutput);
27186
28237
  }
27187
28238
  }
27188
- #completeTool(active, callId, status, content, rawOutput) {
28239
+ #completeTool(active, callId, status2, content, rawOutput) {
27189
28240
  const tool = active.tools.get(callId);
27190
28241
  if (!tool)
27191
28242
  return;
@@ -27194,7 +28245,7 @@ var GrokHarnessSession = class {
27194
28245
  if (hasGrokToolProjection(projection)) {
27195
28246
  tool.item = applyGrokToolProjection(tool.item, projection);
27196
28247
  }
27197
- const outcome = status === "failed" ? {
28248
+ const outcome = status2 === "failed" ? {
27198
28249
  status: "failed",
27199
28250
  error: {
27200
28251
  code: "nativeFailure",
@@ -27203,7 +28254,7 @@ var GrokHarnessSession = class {
27203
28254
  }
27204
28255
  } : { status: "succeeded" };
27205
28256
  this.#completeItem(active, tool.item, outcome);
27206
- if (status !== "completed")
28257
+ if (status2 !== "completed")
27207
28258
  return;
27208
28259
  this.#completeWatchedSubagents(active, tool.item, content, rawOutput);
27209
28260
  const changes = projectGrokFileChanges(content, this.#cwd);
@@ -27223,11 +28274,11 @@ var GrokHarnessSession = class {
27223
28274
  this.#event({ type: "item.started", turnId: active.command.turnId, item: imageItem });
27224
28275
  this.#completeItem(active, imageItem, { status: "succeeded" });
27225
28276
  }
27226
- #completeSubagentTool(active, callId, status, event) {
28277
+ #completeSubagentTool(active, callId, status2, event) {
27227
28278
  const nativeSubagentId = grokNativeSubagentId(event.rawInput, event.rawOutput, event.content);
27228
28279
  const resultSummary = grokSubagentResultSummary(event.content, event.rawOutput);
27229
28280
  active.subagents.completeSpawn(active.command.turnId, callId, {
27230
- failed: status === "failed",
28281
+ failed: status2 === "failed",
27231
28282
  cancellationRequested: active.cancellationRequested,
27232
28283
  ...nativeSubagentId ? { nativeSubagentId } : {},
27233
28284
  ...resultSummary ? { resultSummary } : {}
@@ -27253,6 +28304,8 @@ var GrokHarnessSession = class {
27253
28304
  }
27254
28305
  }
27255
28306
  #bindSpawnedSubagent(active, event) {
28307
+ if (this.#bufferGoalHelper(event))
28308
+ return;
27256
28309
  active.subagents.bindNativeId(active.command.turnId, {
27257
28310
  nativeSubagentId: event.nativeSubagentId,
27258
28311
  ...event.description ? { description: event.description } : {},
@@ -27261,6 +28314,8 @@ var GrokHarnessSession = class {
27261
28314
  });
27262
28315
  }
27263
28316
  #finishNativeSubagent(active, event) {
28317
+ if (this.#bufferGoalHelper(event))
28318
+ return;
27264
28319
  active.subagents.completeByNativeId(active.command.turnId, event.nativeSubagentId, {
27265
28320
  failed: event.status === "failed",
27266
28321
  cancellationRequested: active.cancellationRequested || event.status === "interrupted",
@@ -27268,6 +28323,29 @@ var GrokHarnessSession = class {
27268
28323
  ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
27269
28324
  });
27270
28325
  }
28326
+ #bufferGoalHelper(event) {
28327
+ if (event.type === "subagent.spawned" && event.parentPromptId) {
28328
+ if (!this.#snapshot.turns.some((t) => t.nativeTurnRef.nativeTurnKey === event.parentPromptId))
28329
+ this.#goalHelpers.push(event);
28330
+ return true;
28331
+ }
28332
+ if (event.type === "subagent.finished" && this.#goalHelpers.some((e) => e.type === "subagent.spawned" && e.nativeSubagentId === event.nativeSubagentId)) {
28333
+ this.#goalHelpers.push(event);
28334
+ return true;
28335
+ }
28336
+ return false;
28337
+ }
28338
+ #publishGoalHelpers(active, key) {
28339
+ const ids = new Set(this.#goalHelpers.filter((e) => e.type === "subagent.spawned" && e.parentPromptId === key).map((e) => e.nativeSubagentId));
28340
+ const events = this.#goalHelpers.filter((e) => ids.has(e.nativeSubagentId));
28341
+ this.#goalHelpers = this.#goalHelpers.filter((e) => !ids.has(e.nativeSubagentId));
28342
+ for (const event of events) {
28343
+ if (event.type === "subagent.spawned")
28344
+ active.subagents.bindNativeId(active.command.turnId, event);
28345
+ else
28346
+ this.#finishNativeSubagent(active, event);
28347
+ }
28348
+ }
27271
28349
  #completeAgent(active, outcome) {
27272
28350
  const item = active.agent;
27273
28351
  if (item && active.rawAgentText.length > 0) {
@@ -27308,20 +28386,32 @@ var GrokHarnessSession = class {
27308
28386
  snapshot
27309
28387
  });
27310
28388
  }
27311
- async #settleFromHistory(active, outcome, response) {
28389
+ async #settleFromHistory(active, outcome, response, terminalKey) {
27312
28390
  let history = [];
27313
28391
  let nativeTurnRef;
27314
28392
  let checkpoint;
28393
+ let ephemeral = false;
28394
+ let persistedItems;
27315
28395
  try {
27316
28396
  history = await this.#refreshSnapshot();
28397
+ const expectedKey = terminalKey ?? (typeof response?._meta?.promptId === "string" ? response._meta.promptId : void 0);
28398
+ 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
28399
  const created = this.#snapshot.turns.filter((turn) => !active.beforeNativeTurnKeys.has(turn.nativeTurnRef.nativeTurnKey));
27318
- if (created.length !== 1) {
28400
+ const lastUser = history.findLast((event) => event.type === "user.text");
28401
+ 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);
28402
+ if (created.length !== 1 && !ephemeral) {
27319
28403
  throw new Error(`Grok Turn persisted ${created.length} new Native Turns; exactly one is required`);
27320
28404
  }
28405
+ if (!ephemeral && expectedKey && (created[0]?.nativeTurnRef.nativeTurnKey !== expectedKey || terminalKey && !group))
28406
+ throw new Error("Grok persisted terminal does not match the live Turn occurrence");
27321
28407
  nativeTurnRef = created[0]?.nativeTurnRef;
27322
28408
  checkpoint = created[0]?.checkpoint;
28409
+ if (nativeTurnRef)
28410
+ this.#publishGoalHelpers(active, nativeTurnRef.nativeTurnKey);
28411
+ if (active.backgroundPromptIndex !== void 0 && !ephemeral)
28412
+ persistedItems = created[0]?.items;
27323
28413
  } catch (error53) {
27324
- if (outcome.status === "succeeded") {
28414
+ if (outcome.status === "succeeded" || error53 instanceof GrokNativeIdentityReuseError) {
27325
28415
  outcome = { status: "failed", error: normalizeError(error53, "protocolError") };
27326
28416
  }
27327
28417
  }
@@ -27336,12 +28426,29 @@ var GrokHarnessSession = class {
27336
28426
  }
27337
28427
  const usage = sessionUsageFromHistory(history);
27338
28428
  await this.#refreshCredits().catch(() => void 0);
27339
- this.#finish(active, checkpoint ? { ...outcome, checkpoint } : outcome, usage, nativeTurnRef);
28429
+ this.#finish(active, checkpoint ? { ...outcome, checkpoint } : outcome, usage, nativeTurnRef, ephemeral, outcome.status === "succeeded" ? persistedItems : void 0);
27340
28430
  }
27341
- #finish(active, outcome, usage = null, nativeTurnRef) {
28431
+ #finish(active, outcome, usage = null, nativeTurnRef, ephemeral = false, persistedItems) {
27342
28432
  if (this.#active !== active)
27343
28433
  return;
27344
28434
  const itemOutcome = outcome;
28435
+ const persistedMessages = persistedItems ? settledGrokAgentMessages(persistedItems, active.completedItems) : [];
28436
+ const pendingId = active.agent?.itemId;
28437
+ const pendingMessage = persistedMessages.find((item) => item.itemId === pendingId);
28438
+ if (pendingMessage && active.agent) {
28439
+ const text = pendingMessage.text.startsWith(active.agent.text) ? pendingMessage.text : active.agent.text;
28440
+ const delta = text.slice(active.agent.text.length);
28441
+ if (delta)
28442
+ this.#event({
28443
+ type: "item.updated",
28444
+ turnId: active.command.turnId,
28445
+ itemId: pendingMessage.itemId,
28446
+ update: { type: "text.append", text: delta }
28447
+ });
28448
+ active.agent = { ...pendingMessage, text };
28449
+ active.rawAgentText = text;
28450
+ active.projectedAgentText = text;
28451
+ }
27345
28452
  this.#completeReasoning(active, itemOutcome);
27346
28453
  this.#completeAgent(active, itemOutcome);
27347
28454
  active.subagents.finalize(active.command.turnId, itemOutcome);
@@ -27352,6 +28459,12 @@ var GrokHarnessSession = class {
27352
28459
  for (const tool of active.tools.values())
27353
28460
  this.#completeItem(active, tool.item, itemOutcome);
27354
28461
  active.tools.clear();
28462
+ for (const item of persistedMessages) {
28463
+ if (item.itemId === pendingId)
28464
+ continue;
28465
+ this.#event({ type: "item.started", turnId: active.command.turnId, item });
28466
+ this.#completeItem(active, item, itemOutcome);
28467
+ }
27355
28468
  for (const [interactionId, pending] of active.approvals) {
27356
28469
  active.approvals.delete(interactionId);
27357
28470
  pending.resolve({ outcome: { outcome: "cancelled" } });
@@ -27371,6 +28484,7 @@ var GrokHarnessSession = class {
27371
28484
  type: "turn.completed",
27372
28485
  turnId: active.command.turnId,
27373
28486
  ...nativeTurnRef ? { nativeTurnRef } : {},
28487
+ ...ephemeral ? { ephemeral: true } : {},
27374
28488
  outcome
27375
28489
  });
27376
28490
  active.resolveCompletion();
@@ -27396,6 +28510,7 @@ var GrokHarnessSession = class {
27396
28510
  if (this.#phase === "closed")
27397
28511
  return;
27398
28512
  this.#phase = "closing";
28513
+ this.goals?.close();
27399
28514
  const active = this.#active;
27400
28515
  if (active) {
27401
28516
  active.cancellationRequested = true;
@@ -27422,6 +28537,7 @@ var GrokHarnessSession = class {
27422
28537
  if (this.#phase !== "open")
27423
28538
  return;
27424
28539
  const normalized = normalizeError(error53, "processExited");
28540
+ this.goals?.close();
27425
28541
  if (this.#active)
27426
28542
  this.#finish(this.#active, { status: "failed", error: normalized });
27427
28543
  this.#phase = "faulted";
@@ -27540,7 +28656,7 @@ var GrokAdapter = class {
27540
28656
  async inspect(input = {}) {
27541
28657
  if (this.#closePromise)
27542
28658
  return { status: "unavailable", error: invalidState("Grok Adapter is closed") };
27543
- const cwd = path18.resolve(input.cwd ?? process.cwd());
28659
+ const cwd = path19.resolve(input.cwd ?? process.cwd());
27544
28660
  if (!input.refresh) {
27545
28661
  const cached2 = this.#inspectionCache.get(cwd);
27546
28662
  if (cached2)
@@ -27615,7 +28731,7 @@ var GrokAdapter = class {
27615
28731
  }
27616
28732
  };
27617
28733
  }
27618
- const cwd = path18.resolve(input.cwd);
28734
+ const cwd = path19.resolve(input.cwd);
27619
28735
  const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : null;
27620
28736
  if (parsedRef && (!parsedRef.success || parsedRef.data.harnessId !== this.harnessId)) {
27621
28737
  return {
@@ -27633,7 +28749,7 @@ var GrokAdapter = class {
27633
28749
  let initialPermissionModeId = requestedPermissionModeId;
27634
28750
  try {
27635
28751
  let opened;
27636
- if (input.kind === "rollbackLastTurn") {
28752
+ if (input.kind === "rollbackLastTurn" || input.kind === "rollbackToCheckpoint") {
27637
28753
  const sourceRef = nativeSessionRefSchema.safeParse(input.sourceRef);
27638
28754
  if (!sourceRef.success || sourceRef.data.harnessId !== this.harnessId) {
27639
28755
  await transport.close().catch(() => void 0);
@@ -27648,10 +28764,11 @@ var GrokAdapter = class {
27648
28764
  }
27649
28765
  const sourceSession = [...this.#sessions].find((entry) => entry.initialState.nativeRef?.nativeSessionId === sourceRef.data.nativeSessionId);
27650
28766
  sourceConfiguration = sourceSession?.currentConfiguration();
27651
- const rewound = await rewindGrokLastTurn({
28767
+ const rewound = await rewindGrokSession({
27652
28768
  cwd,
27653
28769
  harnessId: this.harnessId,
27654
28770
  sourceRef: sourceRef.data,
28771
+ ...input.kind === "rollbackToCheckpoint" ? { checkpoint: input.checkpoint } : {},
27655
28772
  locateSource: (sessionId) => transport.locateSession(sessionId),
27656
28773
  readHistory: (historyCwd, sessionId) => transport.readHistory(sessionId, historyCwd),
27657
28774
  rewindAndLoad: async (params) => {
@@ -27711,7 +28828,7 @@ var GrokAdapter = class {
27711
28828
  ok: false,
27712
28829
  error: {
27713
28830
  code: "nativeFailure",
27714
- message: input.kind === "rollbackLastTurn" ? "Grok Native Rewind did not open a Session" : "Grok Native Fork did not open a Session",
28831
+ message: input.kind === "rollbackLastTurn" || input.kind === "rollbackToCheckpoint" ? "Grok Native Rewind did not open a Session" : "Grok Native Fork did not open a Session",
27715
28832
  retryable: true
27716
28833
  }
27717
28834
  };
@@ -27722,8 +28839,8 @@ var GrokAdapter = class {
27722
28839
  const nativeModelId = modelState.currentModel.id;
27723
28840
  const nativeThinkingOptionId = modelState.currentThinkingOptionId;
27724
28841
  const retainedConfiguration = sourceConfiguration;
27725
- if ((input.kind === "rollbackLastTurn" || input.kind === "fork") && retainedConfiguration) {
27726
- const operation = input.kind === "rollbackLastTurn" ? "Rewind" : "Fork";
28842
+ if ((input.kind === "rollbackLastTurn" || input.kind === "rollbackToCheckpoint" || input.kind === "fork") && retainedConfiguration) {
28843
+ const operation = input.kind === "fork" ? "Fork" : "Rewind";
27727
28844
  initialPermissionModeId = retainedConfiguration.permissionModeId ?? GROK_DEFAULT_PERMISSION_MODE_ID;
27728
28845
  const catalogModel = modelState.catalog.models.find(({ ref }) => ref.id === retainedConfiguration.model.id);
27729
28846
  if (!catalogModel) {
@@ -27770,7 +28887,7 @@ var GrokAdapter = class {
27770
28887
  }
27771
28888
  await transport.setPermissionMode(initialPermissionModeId);
27772
28889
  const history = await transport.getHistory();
27773
- let initialUsage = input.kind === "resume" || input.kind === "fork" || input.kind === "rollbackLastTurn" ? combineUsage(sessionUsageFromHistory(history), usageFromSignals(opened.signals)) : null;
28890
+ let initialUsage = input.kind === "resume" || input.kind === "fork" || input.kind === "rollbackLastTurn" || input.kind === "rollbackToCheckpoint" ? combineUsage(sessionUsageFromHistory(history), usageFromSignals(opened.signals)) : null;
27774
28891
  if (contextWindow !== void 0 && initialUsage?.contextUsedTokens !== void 0) {
27775
28892
  initialUsage = combineUsage(initialUsage, { contextWindowTokens: contextWindow });
27776
28893
  }