@codexhost/cli-darwin-x64 0.6.0 → 0.6.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.
@@ -14549,6 +14549,8 @@ var threadUsageSnapshotSchema = external_exports.object({
14549
14549
  reasoningOutputTokens: nonNegativeSafeIntegerSchema.optional(),
14550
14550
  totalTokens: nonNegativeSafeIntegerSchema.optional(),
14551
14551
  totalCostUsd: finiteNonNegativeNumberSchema.optional(),
14552
+ totalCredits: finiteNonNegativeNumberSchema.optional(),
14553
+ contextUsagePercent: finiteNonNegativeNumberSchema.optional(),
14552
14554
  cacheHitRatePercent: cacheHitRatePercentSchema.optional(),
14553
14555
  contextWindowTokens: nonNegativeSafeIntegerSchema.optional(),
14554
14556
  contextUsedTokens: nonNegativeSafeIntegerSchema.optional(),
@@ -15444,7 +15446,9 @@ var usageFields = /* @__PURE__ */ new Set([
15444
15446
  ...tokenFields,
15445
15447
  ...safeIntegerFields,
15446
15448
  ...percentFields,
15447
- "totalCostUsd"
15449
+ "totalCostUsd",
15450
+ "totalCredits",
15451
+ "contextUsagePercent"
15448
15452
  ]);
15449
15453
  function isRecord(value) {
15450
15454
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -15460,6 +15464,12 @@ function parseHostUsage(value) {
15460
15464
  throw new Error(`Harness Usage contains unknown field '${key}'`);
15461
15465
  }
15462
15466
  }
15467
+ for (const field of ["totalCredits", "contextUsagePercent"]) {
15468
+ const candidate = value[field];
15469
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
15470
+ throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
15471
+ }
15472
+ }
15463
15473
  for (const field of tokenFields) {
15464
15474
  const candidate = value[field];
15465
15475
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
@@ -19928,8 +19938,13 @@ function resolveGrokExecutable(input = {}) {
19928
19938
  throw new GrokExecutableError("Grok CLI is not installed");
19929
19939
  return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path3.resolve(resolution.executable);
19930
19940
  }
19931
- function grokInvocation(command, platform = process.platform) {
19932
- return commandInvocation(command, ["agent", "--no-leader", "stdio"], process.env, platform);
19941
+ function grokInvocation(command, platform = process.platform, modelId) {
19942
+ const arguments_ = ["agent", "--no-leader"];
19943
+ const trimmed = modelId?.trim();
19944
+ if (trimmed)
19945
+ arguments_.push("--model", trimmed);
19946
+ arguments_.push("stdio");
19947
+ return commandInvocation(command, arguments_, process.env, platform);
19933
19948
  }
19934
19949
 
19935
19950
  // dist/grok-fork.js
@@ -20920,6 +20935,309 @@ function hasGrokToolProjection(projection) {
20920
20935
  return projection.output !== void 0 || projection.exitCode !== void 0;
20921
20936
  }
20922
20937
 
20938
+ // dist/grok-subagent.js
20939
+ var SPAWN_TOOL_NAMES = /* @__PURE__ */ new Set(["spawn_subagent", "spawn_agent", "task"]);
20940
+ var SEND_TOOL_NAMES = /* @__PURE__ */ new Set(["send_subagent_message"]);
20941
+ var WAIT_TOOL_NAMES = /* @__PURE__ */ new Set([
20942
+ "get_command_or_subagent_output",
20943
+ "get_task_output",
20944
+ "wait_tasks"
20945
+ ]);
20946
+ var KILL_TOOL_NAMES = /* @__PURE__ */ new Set(["kill_command_or_subagent", "kill_task"]);
20947
+ var DESCRIPTION_LIMIT = 500;
20948
+ var SUMMARY_LIMIT = 2e3;
20949
+ function isRecord5(value) {
20950
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20951
+ }
20952
+ function idField(value, key) {
20953
+ if (!isRecord5(value))
20954
+ return void 0;
20955
+ const field = value[key];
20956
+ if (typeof field === "string") {
20957
+ const trimmed = field.trim();
20958
+ return trimmed.length > 0 ? trimmed : void 0;
20959
+ }
20960
+ if (typeof field === "number" && Number.isFinite(field))
20961
+ return String(field);
20962
+ return void 0;
20963
+ }
20964
+ function stringField2(value, key) {
20965
+ if (!isRecord5(value) || typeof value[key] !== "string")
20966
+ return void 0;
20967
+ const trimmed = value[key].trim();
20968
+ return trimmed.length > 0 ? trimmed : void 0;
20969
+ }
20970
+ function bounded(value, limit) {
20971
+ if (!value)
20972
+ return void 0;
20973
+ return value.slice(0, limit);
20974
+ }
20975
+ function toolId(name, title) {
20976
+ return grokToolName(name, title).toLowerCase();
20977
+ }
20978
+ function collectIds(value) {
20979
+ const ids = [];
20980
+ const push = (entry) => {
20981
+ if (typeof entry === "string" && entry.trim().length > 0)
20982
+ ids.push(entry.trim());
20983
+ else if (typeof entry === "number" && Number.isFinite(entry))
20984
+ ids.push(String(entry));
20985
+ };
20986
+ push(idField(value, "task_id"));
20987
+ push(idField(value, "subagent_id"));
20988
+ if (isRecord5(value)) {
20989
+ const list = value.task_ids ?? value.subagent_ids;
20990
+ if (Array.isArray(list)) {
20991
+ for (const entry of list)
20992
+ push(entry);
20993
+ } else {
20994
+ push(list);
20995
+ }
20996
+ }
20997
+ return [...new Set(ids)];
20998
+ }
20999
+ function grokSubagentOperation(name, title, rawInput) {
21000
+ const id = toolId(name, title);
21001
+ if (WAIT_TOOL_NAMES.has(id) || KILL_TOOL_NAMES.has(id))
21002
+ return null;
21003
+ if (SEND_TOOL_NAMES.has(id))
21004
+ return "send";
21005
+ if (SPAWN_TOOL_NAMES.has(id))
21006
+ return "spawn";
21007
+ if (isRecord5(rawInput) && rawInput.variant === "Task")
21008
+ return "spawn";
21009
+ return null;
21010
+ }
21011
+ function grokSubagentWaitIds(name, title, rawInput) {
21012
+ if (!WAIT_TOOL_NAMES.has(toolId(name, title)) && !KILL_TOOL_NAMES.has(toolId(name, title))) {
21013
+ return [];
21014
+ }
21015
+ return collectIds(rawInput);
21016
+ }
21017
+ function grokSubagentKill(name, title) {
21018
+ return KILL_TOOL_NAMES.has(toolId(name, title));
21019
+ }
21020
+ function grokSubagentDescription(rawInput, title, fallback = "Grok Subagent") {
21021
+ return bounded(stringField2(rawInput, "description"), DESCRIPTION_LIMIT) ?? bounded(stringField2(rawInput, "name"), DESCRIPTION_LIMIT) ?? (title && !SPAWN_TOOL_NAMES.has(title.toLowerCase()) && !SEND_TOOL_NAMES.has(title.toLowerCase()) ? bounded(title, DESCRIPTION_LIMIT) : void 0) ?? fallback;
21022
+ }
21023
+ function grokSubagentPrompt(rawInput) {
21024
+ return bounded(stringField2(rawInput, "prompt") ?? stringField2(rawInput, "message"), SUMMARY_LIMIT);
21025
+ }
21026
+ function grokSubagentRole(rawInput) {
21027
+ return bounded(stringField2(rawInput, "subagent_type") ?? stringField2(rawInput, "agent_type") ?? stringField2(rawInput, "type"), DESCRIPTION_LIMIT);
21028
+ }
21029
+ function grokSubagentBackground(rawInput) {
21030
+ if (!isRecord5(rawInput))
21031
+ return true;
21032
+ if (rawInput.background === false || rawInput.run_in_background === false)
21033
+ return false;
21034
+ return true;
21035
+ }
21036
+ function grokSubagentModel(rawInput) {
21037
+ return bounded(stringField2(rawInput, "model"), DESCRIPTION_LIMIT);
21038
+ }
21039
+ function grokNativeSubagentId(...candidates) {
21040
+ const fromKey = (key) => {
21041
+ for (const candidate of candidates) {
21042
+ const value = idField(candidate, key);
21043
+ if (value)
21044
+ return value;
21045
+ }
21046
+ return void 0;
21047
+ };
21048
+ const fromText = (pattern) => {
21049
+ for (const candidate of candidates) {
21050
+ const text = extractText(candidate);
21051
+ const match = text?.match(pattern);
21052
+ if (match?.[1])
21053
+ return match[1].trim();
21054
+ }
21055
+ return void 0;
21056
+ };
21057
+ return fromKey("subagent_id") ?? fromText(/subagent_id:\s*([^\s]+)/i) ?? fromKey("task_id") ?? fromKey("id") ?? fromText(/task_id:\s*([^\s]+)/i) ?? fromText(/task_ids=\["([^"]+)"\]/);
21058
+ }
21059
+ function grokSubagentResultSummary(...candidates) {
21060
+ for (const candidate of candidates) {
21061
+ const text = extractText(candidate);
21062
+ if (text)
21063
+ return bounded(text, SUMMARY_LIMIT);
21064
+ }
21065
+ return void 0;
21066
+ }
21067
+ function grokSubagentEventFromUpdate(update) {
21068
+ if (!isRecord5(update) || typeof update.sessionUpdate !== "string")
21069
+ return null;
21070
+ const nativeSubagentId = idField(update, "subagent_id") ?? idField(update, "child_session_id");
21071
+ if (!nativeSubagentId)
21072
+ return null;
21073
+ if (update.sessionUpdate === "subagent_spawned") {
21074
+ const description = bounded(stringField2(update, "description"), DESCRIPTION_LIMIT);
21075
+ const role = bounded(stringField2(update, "subagent_type") ?? stringField2(update, "role"), DESCRIPTION_LIMIT);
21076
+ const model = bounded(stringField2(update, "model"), DESCRIPTION_LIMIT);
21077
+ return {
21078
+ type: "subagent.spawned",
21079
+ nativeSubagentId,
21080
+ ...description ? { description } : {},
21081
+ ...role ? { role } : {},
21082
+ ...model ? { model } : {}
21083
+ };
21084
+ }
21085
+ if (update.sessionUpdate === "subagent_finished") {
21086
+ const mapped = mapTaskStatus(typeof update.status === "string" ? update.status : void 0);
21087
+ if (!mapped || mapped === "running" || mapped === "pending")
21088
+ return null;
21089
+ const status = mapped === "failed" ? "failed" : mapped === "interrupted" ? "interrupted" : "completed";
21090
+ const resultSummary = bounded(typeof update.output === "string" ? update.output.trim() : void 0, SUMMARY_LIMIT);
21091
+ return {
21092
+ type: "subagent.finished",
21093
+ nativeSubagentId,
21094
+ status,
21095
+ ...resultSummary ? { resultSummary } : {}
21096
+ };
21097
+ }
21098
+ return null;
21099
+ }
21100
+ function grokSubagentWaitSettlements(input) {
21101
+ const ids = grokSubagentWaitIds(input.name, input.title, input.rawInput);
21102
+ if (grokSubagentKill(input.name, input.title)) {
21103
+ return ids.map((id) => ({ id, status: "interrupted" }));
21104
+ }
21105
+ if (ids.length === 0)
21106
+ return [];
21107
+ const resultEntries = taskOutputResults(input.rawOutput);
21108
+ if (resultEntries.length > 0) {
21109
+ const settled = [];
21110
+ for (const result of resultEntries) {
21111
+ const id = idField(result, "task_id") ?? idField(result, "subagent_id");
21112
+ const status = mapTaskStatus(typeof result.status === "string" ? result.status : void 0);
21113
+ if (!id || !status || status === "running" || status === "pending")
21114
+ continue;
21115
+ const resultSummary = bounded(typeof result.output === "string" ? result.output.trim() : void 0, SUMMARY_LIMIT);
21116
+ settled.push({ id, status, ...resultSummary ? { resultSummary } : {} });
21117
+ }
21118
+ return settled;
21119
+ }
21120
+ const fromText = taskOutputTextSettlements(input.rawOutput, input.content, ids);
21121
+ if (fromText.length > 0)
21122
+ return fromText;
21123
+ const overall = mapTaskStatus(taskOutputStatus(input.rawOutput, input.content));
21124
+ if (!overall || overall === "running" || overall === "pending")
21125
+ return [];
21126
+ return ids.map((id) => ({ id, status: overall }));
21127
+ }
21128
+ function taskOutputResults(rawOutput) {
21129
+ if (!isRecord5(rawOutput))
21130
+ return [];
21131
+ if (Array.isArray(rawOutput.results)) {
21132
+ return rawOutput.results.filter(isRecord5);
21133
+ }
21134
+ const nested = firstRecord(rawOutput.MultiResult, rawOutput.multiResult, rawOutput.multi_result);
21135
+ if (nested && Array.isArray(nested.results)) {
21136
+ return nested.results.filter(isRecord5);
21137
+ }
21138
+ const single = firstRecord(rawOutput.Result, rawOutput.result);
21139
+ if (single)
21140
+ return [single];
21141
+ if (typeof rawOutput.status === "string")
21142
+ return [rawOutput];
21143
+ return [];
21144
+ }
21145
+ function firstRecord(...values) {
21146
+ for (const value of values) {
21147
+ if (isRecord5(value))
21148
+ return value;
21149
+ }
21150
+ return void 0;
21151
+ }
21152
+ function taskOutputTextSettlements(rawOutput, content, ids) {
21153
+ const text = extractText(content) ?? extractText(rawOutput);
21154
+ if (!text)
21155
+ return [];
21156
+ const settled = [];
21157
+ const pattern = /---\s*Task\s+(\S+)\s+\[(completed|failed|interrupted|cancelled|canceled)\]\s*---/gi;
21158
+ for (const match of text.matchAll(pattern)) {
21159
+ const id = match[1]?.trim();
21160
+ const status = mapTaskStatus(match[2]);
21161
+ if (!id || !status || status === "running" || status === "pending")
21162
+ continue;
21163
+ if (!ids.includes(id))
21164
+ continue;
21165
+ settled.push({ id, status });
21166
+ }
21167
+ return settled;
21168
+ }
21169
+ function taskOutputStatus(rawOutput, content) {
21170
+ if (isRecord5(rawOutput) && typeof rawOutput.status === "string")
21171
+ return rawOutput.status;
21172
+ const text = extractText(content) ?? extractText(rawOutput);
21173
+ if (!text)
21174
+ return void 0;
21175
+ if (/<subagent_meta>|<subagent_result>/i.test(text))
21176
+ return "completed";
21177
+ if (/\bstatus["']?\s*[:=]\s*["']?completed/i.test(text))
21178
+ return "completed";
21179
+ if (/\bstatus["']?\s*[:=]\s*["']?failed/i.test(text))
21180
+ return "failed";
21181
+ if (/\bstatus["']?\s*[:=]\s*["']?(cancelled|canceled|interrupted)/i.test(text)) {
21182
+ return "interrupted";
21183
+ }
21184
+ if (/\bstill running\b|\bstatus["']?\s*[:=]\s*["']?(running|pending|in_progress)/i.test(text)) {
21185
+ return "running";
21186
+ }
21187
+ return void 0;
21188
+ }
21189
+ function mapTaskStatus(status) {
21190
+ if (!status)
21191
+ return void 0;
21192
+ switch (status.toLowerCase()) {
21193
+ case "completed":
21194
+ case "succeeded":
21195
+ case "success":
21196
+ return "completed";
21197
+ case "failed":
21198
+ case "error":
21199
+ case "errored":
21200
+ return "failed";
21201
+ case "cancelled":
21202
+ case "canceled":
21203
+ case "interrupted":
21204
+ return "interrupted";
21205
+ case "running":
21206
+ case "pending":
21207
+ case "in_progress":
21208
+ case "inprogress":
21209
+ return "running";
21210
+ default:
21211
+ return void 0;
21212
+ }
21213
+ }
21214
+ function extractText(value, depth = 0) {
21215
+ if (depth > 6)
21216
+ return void 0;
21217
+ if (typeof value === "string") {
21218
+ const trimmed = value.trim();
21219
+ return trimmed.length > 0 ? trimmed : void 0;
21220
+ }
21221
+ if (Array.isArray(value)) {
21222
+ const parts = value.flatMap((entry) => {
21223
+ const text = extractText(entry, depth + 1);
21224
+ return text ? [text] : [];
21225
+ });
21226
+ const joined = parts.join("\n").trim();
21227
+ return joined.length > 0 ? joined : void 0;
21228
+ }
21229
+ if (!isRecord5(value))
21230
+ return void 0;
21231
+ if (typeof value.text === "string" && value.text.trim().length > 0)
21232
+ return value.text.trim();
21233
+ if (typeof value.output === "string" && value.output.trim().length > 0) {
21234
+ return value.output.trim();
21235
+ }
21236
+ if (value.content !== void 0)
21237
+ return extractText(value.content, depth + 1);
21238
+ return void 0;
21239
+ }
21240
+
20923
21241
  // dist/grok-history.js
20924
21242
  function stableId(kind, turn, index) {
20925
21243
  return hostItemIdSchema.parse(`grok-history-${kind}-${turn}-${index}`);
@@ -20982,6 +21300,90 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
20982
21300
  let reasoning = null;
20983
21301
  const tools = /* @__PURE__ */ new Map();
20984
21302
  const mediaRoots = grokMediaResolveRoots(cwd, sessionDirectory);
21303
+ const subagents = /* @__PURE__ */ new Map();
21304
+ const subagentAliases = /* @__PURE__ */ new Map();
21305
+ const rememberSubagentAlias = (callId, nativeId) => {
21306
+ subagentAliases.set(callId, callId);
21307
+ if (nativeId)
21308
+ subagentAliases.set(nativeId, callId);
21309
+ };
21310
+ const completeHistorySubagent = (callId, status, content, rawOutput, rawInput) => {
21311
+ const current = subagents.get(callId);
21312
+ const currentAgent = current?.subagents[0];
21313
+ if (!current || !currentAgent)
21314
+ return;
21315
+ const nativeSubagentId = grokNativeSubagentId(rawInput, rawOutput, content) ?? currentAgent.nativeSubagentId;
21316
+ rememberSubagentAlias(callId, nativeSubagentId);
21317
+ const summary = grokSubagentResultSummary(content, rawOutput);
21318
+ const failed = status === "failed";
21319
+ const keepRunning = !failed && (currentAgent.background === true || current.operation === "send");
21320
+ const item = {
21321
+ ...current,
21322
+ subagents: [
21323
+ {
21324
+ ...currentAgent,
21325
+ status: failed ? "failed" : keepRunning ? "running" : "completed",
21326
+ ...nativeSubagentId ? { nativeSubagentId, subagentId: nativeSubagentId } : {},
21327
+ ...summary ? { resultSummary: summary } : {}
21328
+ }
21329
+ ]
21330
+ };
21331
+ if (keepRunning) {
21332
+ subagents.set(callId, item);
21333
+ return;
21334
+ }
21335
+ subagents.delete(callId);
21336
+ items.push({
21337
+ item,
21338
+ outcome: failed ? {
21339
+ status: "failed",
21340
+ error: {
21341
+ code: "nativeFailure",
21342
+ message: "Grok Subagent delegation failed",
21343
+ retryable: false
21344
+ }
21345
+ } : { status: "succeeded" }
21346
+ });
21347
+ };
21348
+ const settleWatchedSubagents = (name, rawInput, content, rawOutput) => {
21349
+ const summary = grokSubagentResultSummary(content, rawOutput);
21350
+ for (const settlement of grokSubagentWaitSettlements({
21351
+ ...name ? { name, title: name } : {},
21352
+ rawInput,
21353
+ content,
21354
+ rawOutput
21355
+ })) {
21356
+ const spawnId = subagentAliases.get(settlement.id);
21357
+ const item = spawnId ? subagents.get(spawnId) : void 0;
21358
+ if (!item?.subagents[0])
21359
+ continue;
21360
+ if (spawnId)
21361
+ subagents.delete(spawnId);
21362
+ const resultSummary = settlement.resultSummary ?? summary;
21363
+ items.push({
21364
+ item: {
21365
+ ...item,
21366
+ subagents: [
21367
+ {
21368
+ ...item.subagents[0],
21369
+ status: settlement.status,
21370
+ nativeSubagentId: item.subagents[0].nativeSubagentId ?? settlement.id,
21371
+ subagentId: item.subagents[0].nativeSubagentId ?? settlement.id,
21372
+ ...resultSummary ? { resultSummary } : {}
21373
+ }
21374
+ ]
21375
+ },
21376
+ outcome: settlement.status === "failed" ? {
21377
+ status: "failed",
21378
+ error: {
21379
+ code: "nativeFailure",
21380
+ message: "Grok Subagent delegation failed",
21381
+ retryable: false
21382
+ }
21383
+ } : settlement.status === "interrupted" ? { status: "cancelled", reason: "Cancelled by user" } : { status: "succeeded" }
21384
+ });
21385
+ }
21386
+ };
20985
21387
  const completeAgent = () => {
20986
21388
  if (!agent || agent.text.length === 0)
20987
21389
  return;
@@ -21002,6 +21404,10 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
21002
21404
  items.push({ item: tool, outcome: { status: "succeeded" } });
21003
21405
  }
21004
21406
  tools.clear();
21407
+ for (const item of subagents.values()) {
21408
+ items.push({ item, outcome: { status: "succeeded" } });
21409
+ }
21410
+ subagents.clear();
21005
21411
  };
21006
21412
  const applyToolProjection = (callId, content, rawOutput) => {
21007
21413
  const tool = tools.get(callId);
@@ -21026,6 +21432,9 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
21026
21432
  retryable: false
21027
21433
  }
21028
21434
  } : { status: "succeeded" };
21435
+ if (status === "completed") {
21436
+ settleWatchedSubagents(tool.type === "toolExecution" ? tool.toolName : tool.command, tool.type === "toolExecution" ? tool.arguments : void 0, content, rawOutput);
21437
+ }
21029
21438
  items.push({ item: tool, outcome });
21030
21439
  if (status !== "completed")
21031
21440
  return;
@@ -21093,6 +21502,8 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
21093
21502
  agent = null;
21094
21503
  reasoning = null;
21095
21504
  tools.clear();
21505
+ subagents.clear();
21506
+ subagentAliases.clear();
21096
21507
  continue;
21097
21508
  }
21098
21509
  if (event.type === "user.text") {
@@ -21167,23 +21578,99 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
21167
21578
  } else if (event.type === "tool.call") {
21168
21579
  completeReasoning();
21169
21580
  completeAgent();
21170
- tools.set(event.callId, startGrokToolItem({
21171
- itemId: stableId("tool", turnIndex, ++messageIndex),
21172
- name: event.name,
21173
- title: event.title,
21174
- kind: event.kind,
21175
- rawInput: event.rawInput,
21176
- cwd
21177
- }));
21178
- applyToolProjection(event.callId, event.content, event.rawOutput);
21179
- if (event.status === "completed" || event.status === "failed") {
21180
- completeTool(event.callId, event.status, event.content, event.rawOutput);
21581
+ const operation = grokSubagentOperation(event.name, event.title, event.rawInput);
21582
+ if (operation) {
21583
+ const nativeSubagentId = grokNativeSubagentId(event.rawInput, event.rawOutput, event.content);
21584
+ rememberSubagentAlias(event.callId, nativeSubagentId);
21585
+ const prompt = grokSubagentPrompt(event.rawInput);
21586
+ const role = grokSubagentRole(event.rawInput);
21587
+ const model = grokSubagentModel(event.rawInput);
21588
+ subagents.set(event.callId, {
21589
+ type: "subagentDelegation",
21590
+ itemId: stableId("subagent", turnIndex, ++messageIndex),
21591
+ operation,
21592
+ ...prompt ? { prompt } : {},
21593
+ subagents: [
21594
+ {
21595
+ subagentId: nativeSubagentId ?? event.callId,
21596
+ ...nativeSubagentId ? { nativeSubagentId } : {},
21597
+ description: grokSubagentDescription(event.rawInput, event.title),
21598
+ ...role ? { role } : {},
21599
+ ...model ? { model } : {},
21600
+ background: grokSubagentBackground(event.rawInput),
21601
+ status: "running"
21602
+ }
21603
+ ]
21604
+ });
21605
+ if (event.status === "completed" || event.status === "failed") {
21606
+ completeHistorySubagent(event.callId, event.status, event.content, event.rawOutput, event.rawInput);
21607
+ }
21608
+ } else {
21609
+ tools.set(event.callId, startGrokToolItem({
21610
+ itemId: stableId("tool", turnIndex, ++messageIndex),
21611
+ name: event.name,
21612
+ title: event.title,
21613
+ kind: event.kind,
21614
+ rawInput: event.rawInput,
21615
+ cwd
21616
+ }));
21617
+ applyToolProjection(event.callId, event.content, event.rawOutput);
21618
+ if (event.status === "completed" || event.status === "failed") {
21619
+ completeTool(event.callId, event.status, event.content, event.rawOutput);
21620
+ }
21181
21621
  }
21182
21622
  } else if (event.type === "tool.update") {
21183
- applyToolProjection(event.callId, event.content, event.rawOutput);
21184
- if (event.status === "completed" || event.status === "failed") {
21185
- completeTool(event.callId, event.status, event.content, event.rawOutput);
21623
+ if (subagents.has(event.callId)) {
21624
+ const current = subagents.get(event.callId);
21625
+ if (current?.subagents[0]) {
21626
+ const nativeSubagentId = grokNativeSubagentId(event.rawInput, event.rawOutput, event.content) ?? current.subagents[0].nativeSubagentId;
21627
+ rememberSubagentAlias(event.callId, nativeSubagentId);
21628
+ subagents.set(event.callId, {
21629
+ ...current,
21630
+ subagents: [
21631
+ {
21632
+ ...current.subagents[0],
21633
+ description: grokSubagentDescription(event.rawInput, event.title, current.subagents[0].description),
21634
+ ...nativeSubagentId ? { nativeSubagentId, subagentId: nativeSubagentId } : {}
21635
+ }
21636
+ ]
21637
+ });
21638
+ }
21639
+ if (event.status === "completed" || event.status === "failed") {
21640
+ completeHistorySubagent(event.callId, event.status, event.content, event.rawOutput, event.rawInput);
21641
+ }
21642
+ } else {
21643
+ applyToolProjection(event.callId, event.content, event.rawOutput);
21644
+ if (event.status === "completed" || event.status === "failed") {
21645
+ completeTool(event.callId, event.status, event.content, event.rawOutput);
21646
+ }
21647
+ }
21648
+ } else if (event.type === "subagent.spawned") {
21649
+ for (const [callId, current] of subagents) {
21650
+ const agent2 = current.subagents[0];
21651
+ if (!agent2)
21652
+ continue;
21653
+ const matchesId = agent2.nativeSubagentId === event.nativeSubagentId;
21654
+ const matchesDescription = !agent2.nativeSubagentId && event.description !== void 0 && agent2.description === event.description;
21655
+ if (!matchesId && !matchesDescription)
21656
+ continue;
21657
+ rememberSubagentAlias(callId, event.nativeSubagentId);
21658
+ subagents.set(callId, {
21659
+ ...current,
21660
+ subagents: [
21661
+ {
21662
+ ...agent2,
21663
+ nativeSubagentId: event.nativeSubagentId,
21664
+ subagentId: event.nativeSubagentId,
21665
+ ...event.role ? { role: event.role } : {},
21666
+ ...event.model ? { model: event.model } : {}
21667
+ }
21668
+ ]
21669
+ });
21670
+ break;
21186
21671
  }
21672
+ } else if (event.type === "subagent.finished") {
21673
+ 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 });
21187
21674
  }
21188
21675
  }
21189
21676
  completeTurn({ status: "unknown", reason: "Grok Native history has no terminal signal" });
@@ -21208,11 +21695,11 @@ var GROK_SESSION_DELETE_METHOD = "_x.ai/session/delete";
21208
21695
  function error51(code, message, retryable = false) {
21209
21696
  return { code, message, retryable };
21210
21697
  }
21211
- function isRecord5(value) {
21698
+ function isRecord6(value) {
21212
21699
  return typeof value === "object" && value !== null && !Array.isArray(value);
21213
21700
  }
21214
21701
  function isGrokMethodNotFound(error53) {
21215
- if (isRecord5(error53) && error53.code === -32601)
21702
+ if (isRecord6(error53) && error53.code === -32601)
21216
21703
  return true;
21217
21704
  const message = error53 instanceof Error ? error53.message : String(error53);
21218
21705
  return /method not found/iu.test(message);
@@ -21230,10 +21717,10 @@ function buildGrokForkParams(input) {
21230
21717
  };
21231
21718
  }
21232
21719
  function parseGrokForkResponse(value) {
21233
- if (!isRecord5(value) || value.error !== void 0)
21720
+ if (!isRecord6(value) || value.error !== void 0)
21234
21721
  return null;
21235
- const payload = typeof value.newSessionId !== "string" && isRecord5(value.result) ? value.result : value;
21236
- if (!isRecord5(payload) || payload.error !== void 0)
21722
+ const payload = typeof value.newSessionId !== "string" && isRecord6(value.result) ? value.result : value;
21723
+ if (!isRecord6(payload) || payload.error !== void 0)
21237
21724
  return null;
21238
21725
  if (typeof payload.newSessionId !== "string" || payload.newSessionId.length === 0)
21239
21726
  return null;
@@ -21396,7 +21883,7 @@ var GROK_SESSION_UPDATE_EXTENSION_METHODS = [
21396
21883
  "_x.ai/session/update",
21397
21884
  "x.ai/session_notification"
21398
21885
  ];
21399
- function isRecord6(value) {
21886
+ function isRecord7(value) {
21400
21887
  return typeof value === "object" && value !== null && !Array.isArray(value);
21401
21888
  }
21402
21889
  function optionalNonNegativeInt(value) {
@@ -21417,7 +21904,7 @@ function isGrokExtensionSessionUpdateMethod(method) {
21417
21904
  return GROK_SESSION_UPDATE_EXTENSION_METHODS.includes(method);
21418
21905
  }
21419
21906
  function grokCompactionEventFromUpdate(update) {
21420
- if (!isRecord6(update) || typeof update.sessionUpdate !== "string")
21907
+ if (!isRecord7(update) || typeof update.sessionUpdate !== "string")
21421
21908
  return null;
21422
21909
  const tokensUsed = optionalNonNegativeInt(firstPresent(update, ["tokensUsed", "tokens_used"]));
21423
21910
  const contextWindowTokens = optionalNonNegativeInt(firstPresent(update, ["contextWindowTokens", "contextWindow", "context_window"]));
@@ -21456,7 +21943,7 @@ function grokCompactionEventFromUpdate(update) {
21456
21943
  // dist/grok-manual-compaction.js
21457
21944
  var GROK_COMPACT_CONVERSATION_METHOD = "x.ai/compact_conversation";
21458
21945
  var GROK_COMPACT_CONVERSATION_FALLBACK_METHOD = "_x.ai/compact_conversation";
21459
- function isRecord7(value) {
21946
+ function isRecord8(value) {
21460
21947
  return typeof value === "object" && value !== null && !Array.isArray(value);
21461
21948
  }
21462
21949
  function optionalNonNegativeInt2(value) {
@@ -21468,7 +21955,7 @@ function optionalErrorMessage2(value) {
21468
21955
  function parseGrokCompactResult(value, cancelled = false) {
21469
21956
  if (cancelled)
21470
21957
  return { outcome: "cancelled" };
21471
- if (!isRecord7(value))
21958
+ if (!isRecord8(value))
21472
21959
  return { outcome: "succeeded" };
21473
21960
  const tokensBefore = optionalNonNegativeInt2(value.tokensBefore ?? value.tokens_before);
21474
21961
  const tokensAfter = optionalNonNegativeInt2(value.tokensAfter ?? value.tokens_after);
@@ -21506,7 +21993,7 @@ var GROK_REWIND_EXECUTE_METHOD = "_x.ai/rewind/execute";
21506
21993
  function error52(code, message, retryable = false) {
21507
21994
  return { code, message, retryable };
21508
21995
  }
21509
- function isRecord8(value) {
21996
+ function isRecord9(value) {
21510
21997
  return typeof value === "object" && value !== null && !Array.isArray(value);
21511
21998
  }
21512
21999
  function buildGrokRewindParams(input) {
@@ -21518,10 +22005,10 @@ function buildGrokRewindParams(input) {
21518
22005
  };
21519
22006
  }
21520
22007
  function parseGrokRewindResponse(value) {
21521
- if (!isRecord8(value))
22008
+ if (!isRecord9(value))
21522
22009
  return null;
21523
- const payload = typeof value.success !== "boolean" && isRecord8(value.result) ? value.result : value;
21524
- if (!isRecord8(payload) || typeof payload.success !== "boolean")
22010
+ const payload = typeof value.success !== "boolean" && isRecord9(value.result) ? value.result : value;
22011
+ if (!isRecord9(payload) || typeof payload.success !== "boolean")
21525
22012
  return null;
21526
22013
  return rewindPayload(payload);
21527
22014
  }
@@ -21678,9 +22165,18 @@ var GrokTransportError = class extends Error {
21678
22165
  this.name = "GrokTransportError";
21679
22166
  }
21680
22167
  };
21681
- function isRecord9(value) {
22168
+ function isRecord10(value) {
21682
22169
  return typeof value === "object" && value !== null && !Array.isArray(value);
21683
22170
  }
22171
+ function acpToolName(update, metadata) {
22172
+ if (!isRecord10(update))
22173
+ return void 0;
22174
+ if (typeof update.name === "string" && update.name.length > 0)
22175
+ return update.name;
22176
+ const meta3 = isRecord10(update._meta) ? update._meta : metadata;
22177
+ const tool = meta3 && isRecord10(meta3["x.ai/tool"]) ? meta3["x.ai/tool"] : void 0;
22178
+ return tool && typeof tool.name === "string" && tool.name.length > 0 ? tool.name : void 0;
22179
+ }
21684
22180
  function errorText(error53) {
21685
22181
  return error53 instanceof Error ? error53.message : String(error53);
21686
22182
  }
@@ -21734,7 +22230,7 @@ function signalProcessTree(child, signal) {
21734
22230
  try {
21735
22231
  process.kill(-child.pid, signal);
21736
22232
  } catch (error53) {
21737
- if (!isRecord9(error53) || error53.code !== "ESRCH")
22233
+ if (!isRecord10(error53) || error53.code !== "ESRCH")
21738
22234
  throw error53;
21739
22235
  }
21740
22236
  }
@@ -21759,6 +22255,9 @@ function transportEvent(update, metadata) {
21759
22255
  const compaction = grokCompactionEventFromUpdate(extension);
21760
22256
  if (compaction)
21761
22257
  return compaction;
22258
+ const subagent = grokSubagentEventFromUpdate(extension);
22259
+ if (subagent)
22260
+ return subagent;
21762
22261
  switch (update.sessionUpdate) {
21763
22262
  case "user_message_chunk":
21764
22263
  case "agent_message_chunk":
@@ -21770,30 +22269,34 @@ function transportEvent(update, metadata) {
21770
22269
  text: update.content.text,
21771
22270
  ...update.messageId ? { messageId: update.messageId } : {}
21772
22271
  };
21773
- case "tool_call":
22272
+ case "tool_call": {
22273
+ const name = acpToolName(update, metadata);
21774
22274
  return {
21775
22275
  type: "tool.call",
21776
22276
  callId: update.toolCallId,
21777
22277
  title: update.title,
21778
- ...update.name ? { name: update.name } : {},
22278
+ ...name ? { name } : {},
21779
22279
  ...update.kind ? { kind: update.kind } : {},
21780
22280
  ...update.status ? { status: update.status } : {},
21781
22281
  ...update.rawInput !== void 0 ? { rawInput: update.rawInput } : {},
21782
22282
  ...update.rawOutput !== void 0 ? { rawOutput: update.rawOutput } : {},
21783
22283
  ...update.content ? { content: update.content } : {}
21784
22284
  };
21785
- case "tool_call_update":
22285
+ }
22286
+ case "tool_call_update": {
22287
+ const name = acpToolName(update, metadata);
21786
22288
  return {
21787
22289
  type: "tool.update",
21788
22290
  callId: update.toolCallId,
21789
22291
  ...update.title !== void 0 ? { title: update.title } : {},
21790
- ...update.name !== void 0 ? { name: update.name } : {},
22292
+ ...name ? { name } : {},
21791
22293
  ...update.kind !== void 0 ? { kind: update.kind } : {},
21792
22294
  ...update.status !== void 0 ? { status: update.status } : {},
21793
22295
  ...update.rawInput !== void 0 ? { rawInput: update.rawInput } : {},
21794
22296
  ...update.rawOutput !== void 0 ? { rawOutput: update.rawOutput } : {},
21795
22297
  ...update.content !== void 0 ? { content: update.content } : {}
21796
22298
  };
22299
+ }
21797
22300
  case "usage_update":
21798
22301
  return { type: "usage", update, ...metadata ? { metadata } : {} };
21799
22302
  default:
@@ -21822,7 +22325,7 @@ async function readNativeSignals(options, sessionId) {
21822
22325
  }
21823
22326
  }
21824
22327
  function isMissingFile(error53) {
21825
- return isRecord9(error53) && error53.code === "ENOENT";
22328
+ return isRecord10(error53) && error53.code === "ENOENT";
21826
22329
  }
21827
22330
  async function locateGrokNativeSession(options, sessionId) {
21828
22331
  if (sessionId.length === 0)
@@ -21845,7 +22348,7 @@ async function locateGrokNativeSession(options, sessionId) {
21845
22348
  try {
21846
22349
  summaryRaw = await readFile(path8.join(grokHomeDir(options), "sessions", entry.name, sessionId, "summary.json"), "utf8");
21847
22350
  } catch (error53) {
21848
- if (isMissingFile(error53) || isRecord9(error53) && error53.code === "ENOTDIR")
22351
+ if (isMissingFile(error53) || isRecord10(error53) && error53.code === "ENOTDIR")
21849
22352
  continue;
21850
22353
  throw new GrokTransportError("unavailable", "Grok Native Session metadata could not be read", {
21851
22354
  cause: error53
@@ -21857,10 +22360,10 @@ async function locateGrokNativeSession(options, sessionId) {
21857
22360
  } catch {
21858
22361
  continue;
21859
22362
  }
21860
- if (!isRecord9(parsed))
22363
+ if (!isRecord10(parsed))
21861
22364
  continue;
21862
22365
  const info = parsed.info;
21863
- const cwd = isRecord9(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path8.resolve(info.cwd) : path8.resolve(decodeURIComponent(entry.name));
22366
+ const cwd = isRecord10(info) && typeof info.cwd === "string" && info.cwd.length > 0 ? path8.resolve(info.cwd) : path8.resolve(decodeURIComponent(entry.name));
21864
22367
  const sourceWorkspaceDir = typeof parsed.source_workspace_dir === "string" && parsed.source_workspace_dir.length > 0 ? path8.resolve(parsed.source_workspace_dir) : void 0;
21865
22368
  matches.push({
21866
22369
  cwd,
@@ -21893,12 +22396,12 @@ function parseNativeHistory(contents, sessionId) {
21893
22396
  } catch {
21894
22397
  throw new GrokTransportError("protocolError", "Grok Native history contains invalid JSON");
21895
22398
  }
21896
- if (!isRecord9(record2) || !isRecord9(record2.params))
22399
+ if (!isRecord10(record2) || !isRecord10(record2.params))
21897
22400
  continue;
21898
22401
  const params = record2.params;
21899
- if (params.sessionId !== sessionId || !isRecord9(params.update))
22402
+ if (params.sessionId !== sessionId || !isRecord10(params.update))
21900
22403
  continue;
21901
- const metadata = isRecord9(params._meta) ? params._meta : void 0;
22404
+ const metadata = isRecord10(params._meta) ? params._meta : void 0;
21902
22405
  const event = transportEvent(params.update, metadata);
21903
22406
  if (event)
21904
22407
  events.push(metadata ? { ...event, metadata } : event);
@@ -21916,6 +22419,7 @@ var GrokAcpTransport = class {
21916
22419
  #initialize = null;
21917
22420
  #replay = null;
21918
22421
  #sessionId = null;
22422
+ #startupModelId;
21919
22423
  #stderrTail = "";
21920
22424
  constructor(options) {
21921
22425
  this.#options = {
@@ -21972,6 +22476,8 @@ var GrokAcpTransport = class {
21972
22476
  if (this.#sessionId || this.#closed)
21973
22477
  throw new Error("Grok ACP Transport cannot be opened twice");
21974
22478
  try {
22479
+ if (input.kind === "create")
22480
+ this.#startupModelId = input.modelId;
21975
22481
  const initialize = await this.#ensureInitialized();
21976
22482
  const connection = this.#connection;
21977
22483
  if (!connection)
@@ -22097,7 +22603,7 @@ var GrokAcpTransport = class {
22097
22603
  ...this.#options.command ? { command: this.#options.command } : {},
22098
22604
  environment: this.#options.environment ?? process.env
22099
22605
  });
22100
- const invocation = grokInvocation(executable);
22606
+ const invocation = grokInvocation(executable, process.platform, this.#startupModelId);
22101
22607
  const child = spawn(invocation.command, invocation.arguments, {
22102
22608
  cwd: this.#options.cwd,
22103
22609
  env: { ...process.env, ...this.#options.environment },
@@ -22200,7 +22706,7 @@ var GrokAcpTransport = class {
22200
22706
  modelId,
22201
22707
  ...reasoningEffort ? { reasoningEffort } : {}
22202
22708
  });
22203
- if (!isRecord9(response) || !isRecord9(response._meta) || !isRecord9(response._meta.model)) {
22709
+ if (!isRecord10(response) || !isRecord10(response._meta) || !isRecord10(response._meta.model)) {
22204
22710
  throw new GrokTransportError("protocolError", "Grok rejected Model configuration");
22205
22711
  }
22206
22712
  const selected = response._meta.model.Ok;
@@ -22243,7 +22749,7 @@ var GrokAcpTransport = class {
22243
22749
  #handleUpdate(notification) {
22244
22750
  if (this.#sessionId && notification.sessionId !== this.#sessionId)
22245
22751
  return;
22246
- const metadata = isRecord9(notification._meta) ? notification._meta : void 0;
22752
+ const metadata = isRecord10(notification._meta) ? notification._meta : void 0;
22247
22753
  const event = transportEvent(notification.update, metadata);
22248
22754
  if (!event)
22249
22755
  return;
@@ -22258,7 +22764,7 @@ var GrokAcpTransport = class {
22258
22764
  #handleExtensionNotification(method, params) {
22259
22765
  if (!isGrokExtensionSessionUpdateMethod(method))
22260
22766
  return;
22261
- if (typeof params.sessionId !== "string" || !isRecord9(params.update))
22767
+ if (typeof params.sessionId !== "string" || !isRecord10(params.update))
22262
22768
  return;
22263
22769
  this.#handleUpdate(params);
22264
22770
  }
@@ -22275,8 +22781,200 @@ var GrokAcpTransport = class {
22275
22781
  }
22276
22782
  };
22277
22783
 
22784
+ // dist/grok-subagent-lifecycle.js
22785
+ function subagentFailure() {
22786
+ return {
22787
+ code: "nativeFailure",
22788
+ message: "Grok Subagent delegation failed",
22789
+ retryable: false
22790
+ };
22791
+ }
22792
+ var GrokSubagentLifecycle = class {
22793
+ #emit;
22794
+ #newItemId;
22795
+ #delegations = /* @__PURE__ */ new Map();
22796
+ #callIdByNativeId = /* @__PURE__ */ new Map();
22797
+ constructor(options) {
22798
+ this.#emit = options.emit;
22799
+ this.#newItemId = options.newItemId;
22800
+ }
22801
+ get size() {
22802
+ return this.#delegations.size;
22803
+ }
22804
+ has(callId) {
22805
+ return this.#delegations.has(callId);
22806
+ }
22807
+ nativeSubagentId(callId) {
22808
+ return this.#delegations.get(callId)?.item.subagents[0]?.nativeSubagentId;
22809
+ }
22810
+ start(turnId, input) {
22811
+ if (this.#delegations.has(input.callId)) {
22812
+ throw new Error("Grok Subagent delegation started more than once");
22813
+ }
22814
+ this.#callIdByNativeId.set(input.callId, input.callId);
22815
+ if (input.nativeSubagentId)
22816
+ this.#callIdByNativeId.set(input.nativeSubagentId, input.callId);
22817
+ const subagent = {
22818
+ subagentId: input.nativeSubagentId ?? input.callId,
22819
+ ...input.nativeSubagentId ? { nativeSubagentId: input.nativeSubagentId } : {},
22820
+ description: input.description,
22821
+ ...input.role ? { role: input.role } : {},
22822
+ ...input.model ? { model: input.model } : {},
22823
+ ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {},
22824
+ background: input.background,
22825
+ status: "running"
22826
+ };
22827
+ const item = {
22828
+ type: "subagentDelegation",
22829
+ itemId: this.#newItemId(),
22830
+ operation: input.operation,
22831
+ ...input.prompt ? { prompt: input.prompt } : {},
22832
+ subagents: [subagent]
22833
+ };
22834
+ this.#delegations.set(input.callId, { callId: input.callId, item });
22835
+ this.#emit({ type: "item.started", turnId, item });
22836
+ this.#emitState(subagent);
22837
+ return subagent;
22838
+ }
22839
+ bindNativeId(turnId, input) {
22840
+ for (const [callId, active] of this.#delegations) {
22841
+ const current = active.item.subagents[0];
22842
+ if (!current)
22843
+ continue;
22844
+ if (current.nativeSubagentId === input.nativeSubagentId) {
22845
+ return this.update(turnId, callId, input);
22846
+ }
22847
+ }
22848
+ for (const [callId, active] of this.#delegations) {
22849
+ const current = active.item.subagents[0];
22850
+ if (!current || current.nativeSubagentId)
22851
+ continue;
22852
+ if (input.description && current.description === input.description) {
22853
+ return this.update(turnId, callId, input);
22854
+ }
22855
+ }
22856
+ return void 0;
22857
+ }
22858
+ update(turnId, callId, patch) {
22859
+ const active = this.#delegations.get(callId);
22860
+ if (!active)
22861
+ return void 0;
22862
+ const current = active.item.subagents[0];
22863
+ if (!current)
22864
+ throw new Error("Grok Subagent delegation has no Agent state");
22865
+ if (patch.nativeSubagentId)
22866
+ this.#callIdByNativeId.set(patch.nativeSubagentId, callId);
22867
+ const nativeSubagentId = patch.nativeSubagentId ?? current.nativeSubagentId;
22868
+ const subagent = {
22869
+ ...current,
22870
+ ...nativeSubagentId ? { nativeSubagentId, subagentId: nativeSubagentId } : {},
22871
+ ...patch.description ? { description: patch.description } : {},
22872
+ ...patch.role ? { role: patch.role } : {},
22873
+ ...patch.model ? { model: patch.model } : {},
22874
+ ...patch.reasoningEffort ? { reasoningEffort: patch.reasoningEffort } : {},
22875
+ ...patch.resultSummary ? { resultSummary: patch.resultSummary } : {},
22876
+ ...patch.status ? { status: patch.status } : {}
22877
+ };
22878
+ active.item = { ...active.item, subagents: [subagent] };
22879
+ this.#emit({
22880
+ type: "item.updated",
22881
+ turnId,
22882
+ itemId: active.item.itemId,
22883
+ update: { type: "subagents.replace", subagents: active.item.subagents }
22884
+ });
22885
+ this.#emitState(subagent);
22886
+ return subagent;
22887
+ }
22888
+ completeSpawn(turnId, callId, input) {
22889
+ const active = this.#delegations.get(callId);
22890
+ const background = input.background ?? active?.item.subagents[0]?.background ?? true;
22891
+ const keepRunning = !input.failed && !input.cancellationRequested && (background || active?.item.operation === "send");
22892
+ if (keepRunning) {
22893
+ return this.update(turnId, callId, {
22894
+ status: "running",
22895
+ ...input.nativeSubagentId ? { nativeSubagentId: input.nativeSubagentId } : {},
22896
+ ...input.resultSummary ? { resultSummary: input.resultSummary } : {}
22897
+ });
22898
+ }
22899
+ return this.complete(turnId, callId, { ...input, keepRunning: false });
22900
+ }
22901
+ completeByNativeId(turnId, nativeSubagentId, input) {
22902
+ const callId = this.#callIdByNativeId.get(nativeSubagentId) ?? this.#callIdForNative(nativeSubagentId);
22903
+ if (callId && this.#delegations.has(callId)) {
22904
+ return this.complete(turnId, callId, { ...input, nativeSubagentId });
22905
+ }
22906
+ const status = input.status ?? (input.cancellationRequested ? "interrupted" : input.failed ? "failed" : "completed");
22907
+ this.#emit({
22908
+ type: "subagent.state.changed",
22909
+ nativeSubagentId,
22910
+ status,
22911
+ ...input.resultSummary ? { resultSummary: input.resultSummary } : {}
22912
+ });
22913
+ return void 0;
22914
+ }
22915
+ complete(turnId, callId, input) {
22916
+ const active = this.#delegations.get(callId);
22917
+ if (!active)
22918
+ return void 0;
22919
+ this.#delegations.delete(callId);
22920
+ const current = active.item.subagents[0];
22921
+ if (!current)
22922
+ throw new Error("Grok Subagent delegation has no Agent state");
22923
+ const status = input.status ?? (input.cancellationRequested ? "interrupted" : input.failed ? "failed" : input.keepRunning ? "running" : "completed");
22924
+ const nativeSubagentId = input.nativeSubagentId ?? current.nativeSubagentId;
22925
+ if (nativeSubagentId)
22926
+ this.#callIdByNativeId.set(nativeSubagentId, callId);
22927
+ const subagent = {
22928
+ ...current,
22929
+ status,
22930
+ ...nativeSubagentId ? { nativeSubagentId, subagentId: nativeSubagentId } : {},
22931
+ ...input.resultSummary ? { resultSummary: input.resultSummary } : {}
22932
+ };
22933
+ const item = { ...active.item, subagents: [subagent] };
22934
+ this.#emit({
22935
+ type: "item.updated",
22936
+ turnId,
22937
+ itemId: item.itemId,
22938
+ update: { type: "subagents.replace", subagents: item.subagents }
22939
+ });
22940
+ const outcome = input.cancellationRequested ? { status: "cancelled", reason: "Cancelled by user" } : input.failed ? { status: "failed", error: subagentFailure() } : { status: "succeeded" };
22941
+ this.#emit({ type: "item.completed", turnId, snapshot: { item, outcome } });
22942
+ this.#emitState(subagent);
22943
+ return subagent;
22944
+ }
22945
+ finalize(turnId, outcome) {
22946
+ for (const [callId, active] of this.#delegations) {
22947
+ this.#delegations.delete(callId);
22948
+ const current = active.item.subagents[0];
22949
+ if (!current)
22950
+ continue;
22951
+ const status = outcome.status === "succeeded" ? current.status : outcome.status === "cancelled" ? "interrupted" : "failed";
22952
+ const item = { ...active.item, subagents: [{ ...current, status }] };
22953
+ this.#emit({ type: "item.completed", turnId, snapshot: { item, outcome } });
22954
+ this.#emitState({ ...current, status });
22955
+ }
22956
+ }
22957
+ #callIdForNative(nativeSubagentId) {
22958
+ for (const [callId, active] of this.#delegations) {
22959
+ if (active.item.subagents[0]?.nativeSubagentId === nativeSubagentId)
22960
+ return callId;
22961
+ }
22962
+ return void 0;
22963
+ }
22964
+ #emitState(subagent) {
22965
+ if (!subagent.nativeSubagentId)
22966
+ return;
22967
+ this.#emit({
22968
+ type: "subagent.state.changed",
22969
+ nativeSubagentId: subagent.nativeSubagentId,
22970
+ status: subagent.status,
22971
+ ...subagent.resultSummary ? { resultSummary: subagent.resultSummary } : {}
22972
+ });
22973
+ }
22974
+ };
22975
+
22278
22976
  // dist/grok-models.js
22279
- function isRecord10(value) {
22977
+ function isRecord11(value) {
22280
22978
  return typeof value === "object" && value !== null && !Array.isArray(value);
22281
22979
  }
22282
22980
  function nonBlank(value) {
@@ -22288,7 +22986,7 @@ function thinkingOptions(value) {
22288
22986
  const seen = /* @__PURE__ */ new Set();
22289
22987
  const options = [];
22290
22988
  for (const candidate of value) {
22291
- if (!isRecord10(candidate) || !nonBlank(candidate.label))
22989
+ if (!isRecord11(candidate) || !nonBlank(candidate.label))
22292
22990
  continue;
22293
22991
  const id = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
22294
22992
  if (!id.success || seen.has(id.data))
@@ -22299,7 +22997,7 @@ function thinkingOptions(value) {
22299
22997
  return options;
22300
22998
  }
22301
22999
  function parseGrokModelState(value) {
22302
- if (!isRecord10(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
23000
+ if (!isRecord11(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
22303
23001
  return null;
22304
23002
  }
22305
23003
  const currentModel = harnessModelRefSchema.safeParse({ id: value.currentModelId });
@@ -22310,12 +23008,12 @@ function parseGrokModelState(value) {
22310
23008
  const models = [];
22311
23009
  let currentThinkingOptionId;
22312
23010
  for (const candidate of value.availableModels) {
22313
- if (!isRecord10(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
23011
+ if (!isRecord11(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
22314
23012
  continue;
22315
23013
  const ref = harnessModelRefSchema.safeParse({ id: candidate.modelId });
22316
23014
  if (!ref.success)
22317
23015
  continue;
22318
- const metadata = isRecord10(candidate._meta) ? candidate._meta : {};
23016
+ const metadata = isRecord11(candidate._meta) ? candidate._meta : {};
22319
23017
  const options2 = thinkingOptions(metadata.reasoningEfforts);
22320
23018
  if (typeof metadata.totalContextTokens === "number" && Number.isSafeInteger(metadata.totalContextTokens) && metadata.totalContextTokens > 0) {
22321
23019
  contextWindowTokensByModel.set(ref.data.id, metadata.totalContextTokens);
@@ -22350,10 +23048,10 @@ function parseGrokModelState(value) {
22350
23048
  };
22351
23049
  }
22352
23050
  function modelStateFromInitialize(response) {
22353
- return parseGrokModelState(isRecord10(response._meta) ? response._meta.modelState : void 0);
23051
+ return parseGrokModelState(isRecord11(response._meta) ? response._meta.modelState : void 0);
22354
23052
  }
22355
23053
  function modelStateFromSessionResponse(response) {
22356
- return parseGrokModelState(isRecord10(response) ? response.models : void 0);
23054
+ return parseGrokModelState(isRecord11(response) ? response.models : void 0);
22357
23055
  }
22358
23056
  function stateForGrokModel(modelState, nativeState, model = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
22359
23057
  const selectedModel = model;
@@ -22377,7 +23075,7 @@ import os4 from "node:os";
22377
23075
  import path9 from "node:path";
22378
23076
  var GROK_CREDITS_ENDPOINT = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
22379
23077
  var REQUEST_TIMEOUT_MS = 15e3;
22380
- function isRecord11(value) {
23078
+ function isRecord12(value) {
22381
23079
  return typeof value === "object" && value !== null && !Array.isArray(value);
22382
23080
  }
22383
23081
  function finitePercent(value) {
@@ -22385,10 +23083,13 @@ function finitePercent(value) {
22385
23083
  return void 0;
22386
23084
  return Math.min(100, Math.max(0, value));
22387
23085
  }
22388
- function nonNegativeNumber(value) {
22389
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
23086
+ function nonNegativeCentValue(value) {
23087
+ if (!isRecord12(value))
22390
23088
  return void 0;
22391
- return value;
23089
+ const amount = value.val === void 0 ? 0 : value.val;
23090
+ if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
23091
+ return void 0;
23092
+ return amount;
22392
23093
  }
22393
23094
  function grokHome(environment) {
22394
23095
  return environment.GROK_HOME ?? path9.join(environment.HOME ?? environment.USERPROFILE ?? os4.homedir(), ".grok");
@@ -22407,7 +23108,7 @@ function productUsageFrom(value) {
22407
23108
  if (!Array.isArray(value))
22408
23109
  return void 0;
22409
23110
  const products = value.flatMap((entry) => {
22410
- if (!isRecord11(entry) || typeof entry.product !== "string")
23111
+ if (!isRecord12(entry) || typeof entry.product !== "string")
22411
23112
  return [];
22412
23113
  const usagePercent = finitePercent(entry.usagePercent);
22413
23114
  return usagePercent === void 0 ? [] : [{ product: entry.product, usagePercent }];
@@ -22415,31 +23116,41 @@ function productUsageFrom(value) {
22415
23116
  return products.length > 0 ? products : void 0;
22416
23117
  }
22417
23118
  function parseGrokCreditsResponse(value, fetchedAt = (/* @__PURE__ */ new Date()).toISOString()) {
22418
- if (!isRecord11(value) || !isRecord11(value.config))
23119
+ if (!isRecord12(value) || !isRecord12(value.config))
22419
23120
  return null;
22420
23121
  const config2 = value.config;
22421
- const period = isRecord11(config2.currentPeriod) ? config2.currentPeriod : void 0;
23122
+ const period = isRecord12(config2.currentPeriod) ? config2.currentPeriod : void 0;
23123
+ const periodType = periodTypeFrom(period?.type);
22422
23124
  const resetsAt = (typeof period?.end === "string" && period.end.length > 0 ? period.end : void 0) ?? (typeof config2.billingPeriodEnd === "string" && config2.billingPeriodEnd.length > 0 ? config2.billingPeriodEnd : void 0);
22423
- const onDemandCap = isRecord11(config2.onDemandCap) ? nonNegativeNumber(config2.onDemandCap.val) : void 0;
22424
- const onDemandUsed = isRecord11(config2.onDemandUsed) ? nonNegativeNumber(config2.onDemandUsed.val) : void 0;
22425
- const usedPercent = finitePercent(config2.creditUsagePercent) ?? (onDemandCap !== void 0 && onDemandCap > 0 && onDemandUsed !== void 0 ? Math.min(100, Math.max(0, onDemandUsed / onDemandCap * 100)) : void 0);
23125
+ let usedPercent = finitePercent(config2.creditUsagePercent);
23126
+ if (config2.creditUsagePercent === void 0) {
23127
+ const monthlyLimit = nonNegativeCentValue(config2.monthlyLimit);
23128
+ const used = nonNegativeCentValue(config2.used);
23129
+ if (config2.monthlyLimit !== void 0 && monthlyLimit === void 0 || config2.used !== void 0 && used === void 0)
23130
+ return null;
23131
+ if (monthlyLimit !== void 0 && monthlyLimit > 0) {
23132
+ usedPercent = Math.min(100, (used ?? 0) / monthlyLimit * 100);
23133
+ } else if (periodType !== "unknown" && resetsAt !== void 0 && Number.isFinite(Date.parse(resetsAt))) {
23134
+ usedPercent = 0;
23135
+ }
23136
+ }
22426
23137
  if (usedPercent === void 0)
22427
23138
  return null;
22428
23139
  const productUsage = productUsageFrom(config2.productUsage);
22429
23140
  return {
22430
23141
  usedPercent,
22431
- periodType: periodTypeFrom(period?.type),
23142
+ periodType,
22432
23143
  fetchedAt,
22433
23144
  ...resetsAt ? { resetsAt } : {},
22434
23145
  ...productUsage ? { productUsage } : {}
22435
23146
  };
22436
23147
  }
22437
23148
  function selectAccessToken(auth, now) {
22438
- if (!isRecord11(auth))
23149
+ if (!isRecord12(auth))
22439
23150
  return null;
22440
- const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord11(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
23151
+ const entries = Object.entries(auth).filter(([issuer, value]) => (issuer === "https://auth.x.ai" || issuer.startsWith("https://auth.x.ai::")) && isRecord12(value) && typeof value.key === "string" && value.key.length > 0).sort(([left], [right]) => Number(right.startsWith("https://auth.x.ai")) - Number(left.startsWith("https://auth.x.ai")));
22441
23152
  for (const [, value] of entries) {
22442
- if (!isRecord11(value) || typeof value.key !== "string")
23153
+ if (!isRecord12(value) || typeof value.key !== "string")
22443
23154
  continue;
22444
23155
  if (typeof value.expires_at === "string") {
22445
23156
  const expiresAt = Date.parse(value.expires_at);
@@ -22510,7 +23221,7 @@ async function fetchGrokCredits(input = {}) {
22510
23221
 
22511
23222
  // dist/grok-usage.js
22512
23223
  var USD_TICKS_PER_DOLLAR = 1e10;
22513
- function isRecord12(value) {
23224
+ function isRecord13(value) {
22514
23225
  return typeof value === "object" && value !== null && !Array.isArray(value);
22515
23226
  }
22516
23227
  function optionalToken(value) {
@@ -22527,7 +23238,7 @@ function combineUsage(base, next) {
22527
23238
  return base === null ? next : parseHostUsage({ ...base, ...next });
22528
23239
  }
22529
23240
  function usageFromNative(value) {
22530
- if (!isRecord12(value))
23241
+ if (!isRecord13(value))
22531
23242
  return null;
22532
23243
  const inputTokens = optionalToken(value.inputTokens);
22533
23244
  const cachedRead = optionalToken(value.cachedReadTokens);
@@ -22554,7 +23265,7 @@ function usageFromPrompt(response) {
22554
23265
  return response.usage ? usageFromNative(response.usage) : null;
22555
23266
  }
22556
23267
  function usageFromSignals(value) {
22557
- if (!isRecord12(value))
23268
+ if (!isRecord13(value))
22558
23269
  return null;
22559
23270
  try {
22560
23271
  return parseHostUsage({
@@ -22574,7 +23285,7 @@ var summedUsageFields = [
22574
23285
  "totalTokens"
22575
23286
  ];
22576
23287
  function nativeCostTicks(value) {
22577
- if (!isRecord12(value))
23288
+ if (!isRecord13(value))
22578
23289
  return void 0;
22579
23290
  const ticks = value.costUsdTicks;
22580
23291
  if (typeof ticks !== "number" || !Number.isSafeInteger(ticks) || ticks < 0)
@@ -22651,7 +23362,7 @@ function usageFromCompact(tokensAfter, contextWindowTokens) {
22651
23362
  function usageFromUpdate(update, metadata, contextWindowTokens) {
22652
23363
  try {
22653
23364
  if (update?.sessionUpdate === "usage_update") {
22654
- const cost = isRecord12(update.cost) ? update.cost : null;
23365
+ const cost = isRecord13(update.cost) ? update.cost : null;
22655
23366
  return parseHostUsage({
22656
23367
  contextUsedTokens: update.used,
22657
23368
  contextWindowTokens: update.size,
@@ -22692,7 +23403,8 @@ function capabilitiesForModels(modelState) {
22692
23403
  selectPermissionMode: true,
22693
23404
  permissionModeScope: "atCreate"
22694
23405
  },
22695
- history: { fork: true, forkAcrossCwd: true, rollbackLastTurn: true }
23406
+ history: { fork: true, forkAcrossCwd: true, rollbackLastTurn: true },
23407
+ subagents: { observe: true, readTranscript: true }
22696
23408
  };
22697
23409
  }
22698
23410
  var DEFAULT_CLOSE_TIMEOUT_MS = 2e3;
@@ -22892,6 +23604,7 @@ var GrokHarnessSession = class {
22892
23604
  compactionContextWindow: void 0,
22893
23605
  compactionTerminal: null,
22894
23606
  tools: /* @__PURE__ */ new Map(),
23607
+ subagents: this.#createSubagents(),
22895
23608
  completedItems: [],
22896
23609
  approvals: /* @__PURE__ */ new Map(),
22897
23610
  cancellationRequested: false,
@@ -22966,6 +23679,7 @@ var GrokHarnessSession = class {
22966
23679
  compactionContextWindow: void 0,
22967
23680
  compactionTerminal: null,
22968
23681
  tools: /* @__PURE__ */ new Map(),
23682
+ subagents: this.#createSubagents(),
22969
23683
  completedItems: [],
22970
23684
  approvals: /* @__PURE__ */ new Map(),
22971
23685
  cancellationRequested: false,
@@ -23194,6 +23908,10 @@ var GrokHarnessSession = class {
23194
23908
  this.#startTool(active, event);
23195
23909
  else if (event.type === "tool.update")
23196
23910
  this.#updateTool(active, event);
23911
+ else if (event.type === "subagent.spawned")
23912
+ this.#bindSpawnedSubagent(active, event);
23913
+ else if (event.type === "subagent.finished")
23914
+ this.#finishNativeSubagent(active, event);
23197
23915
  else if (event.type === "compaction.started")
23198
23916
  this.#startCompaction(active, event);
23199
23917
  else if (event.type === "compaction.completed") {
@@ -23300,9 +24018,36 @@ var GrokHarnessSession = class {
23300
24018
  update: { type: "text.append", text }
23301
24019
  });
23302
24020
  }
24021
+ #createSubagents() {
24022
+ return new GrokSubagentLifecycle({
24023
+ newItemId: () => hostItemIdSchema.parse(this.#randomUUID()),
24024
+ emit: (event) => this.#event(event)
24025
+ });
24026
+ }
23303
24027
  #startTool(active, event) {
23304
24028
  this.#completeReasoning(active, { status: "succeeded" });
23305
24029
  this.#completeAgent(active, { status: "succeeded" });
24030
+ const operation = grokSubagentOperation(event.name, event.title, event.rawInput);
24031
+ if (operation) {
24032
+ const prompt = grokSubagentPrompt(event.rawInput);
24033
+ const role = grokSubagentRole(event.rawInput);
24034
+ const nativeSubagentId = grokNativeSubagentId(event.rawInput);
24035
+ const model = grokSubagentModel(event.rawInput);
24036
+ active.subagents.start(active.command.turnId, {
24037
+ callId: event.callId,
24038
+ operation,
24039
+ description: grokSubagentDescription(event.rawInput, event.title),
24040
+ ...prompt ? { prompt } : {},
24041
+ ...role ? { role } : {},
24042
+ ...model ? { model } : {},
24043
+ background: grokSubagentBackground(event.rawInput),
24044
+ ...nativeSubagentId ? { nativeSubagentId } : {}
24045
+ });
24046
+ if (event.status === "completed" || event.status === "failed") {
24047
+ this.#completeSubagentTool(active, event.callId, event.status, event);
24048
+ }
24049
+ return;
24050
+ }
23306
24051
  let item = startGrokToolItem({
23307
24052
  itemId: hostItemIdSchema.parse(this.#randomUUID()),
23308
24053
  name: event.name,
@@ -23321,6 +24066,34 @@ var GrokHarnessSession = class {
23321
24066
  }
23322
24067
  }
23323
24068
  #updateTool(active, event) {
24069
+ if (!active.subagents.has(event.callId) && !active.tools.has(event.callId) && grokSubagentOperation(event.name, event.title, event.rawInput)) {
24070
+ this.#startTool(active, {
24071
+ type: "tool.call",
24072
+ callId: event.callId,
24073
+ title: event.title ?? "Grok Subagent",
24074
+ ...event.name ? { name: event.name } : {},
24075
+ ...event.kind ? { kind: event.kind } : {},
24076
+ ...event.status ? { status: event.status } : {},
24077
+ ...event.rawInput !== void 0 ? { rawInput: event.rawInput } : {},
24078
+ ...event.rawOutput !== void 0 ? { rawOutput: event.rawOutput } : {},
24079
+ ...event.content ? { content: event.content } : {}
24080
+ });
24081
+ return;
24082
+ }
24083
+ if (active.subagents.has(event.callId)) {
24084
+ if (event.status === "completed" || event.status === "failed") {
24085
+ this.#completeSubagentTool(active, event.callId, event.status, event);
24086
+ return;
24087
+ }
24088
+ const role = grokSubagentRole(event.rawInput);
24089
+ const nativeSubagentId = grokNativeSubagentId(event.rawInput, event.rawOutput, event.content);
24090
+ active.subagents.update(active.command.turnId, event.callId, {
24091
+ ...event.title ? { description: grokSubagentDescription(event.rawInput, event.title) } : {},
24092
+ ...role ? { role } : {},
24093
+ ...nativeSubagentId ? { nativeSubagentId } : {}
24094
+ });
24095
+ return;
24096
+ }
23324
24097
  const tool = active.tools.get(event.callId);
23325
24098
  if (!tool)
23326
24099
  return;
@@ -23376,6 +24149,7 @@ var GrokHarnessSession = class {
23376
24149
  this.#completeItem(active, tool.item, outcome);
23377
24150
  if (status !== "completed")
23378
24151
  return;
24152
+ this.#completeWatchedSubagents(active, tool.item, content, rawOutput);
23379
24153
  const changes = projectGrokFileChanges(content, this.#cwd);
23380
24154
  if (!changes)
23381
24155
  return;
@@ -23387,6 +24161,51 @@ var GrokHarnessSession = class {
23387
24161
  this.#event({ type: "item.started", turnId: active.command.turnId, item: fileItem });
23388
24162
  this.#completeItem(active, fileItem, { status: "succeeded" });
23389
24163
  }
24164
+ #completeSubagentTool(active, callId, status, event) {
24165
+ const nativeSubagentId = grokNativeSubagentId(event.rawInput, event.rawOutput, event.content);
24166
+ const resultSummary = grokSubagentResultSummary(event.content, event.rawOutput);
24167
+ active.subagents.completeSpawn(active.command.turnId, callId, {
24168
+ failed: status === "failed",
24169
+ cancellationRequested: active.cancellationRequested,
24170
+ ...nativeSubagentId ? { nativeSubagentId } : {},
24171
+ ...resultSummary ? { resultSummary } : {}
24172
+ });
24173
+ }
24174
+ #completeWatchedSubagents(active, item, content, rawOutput) {
24175
+ const name = item.type === "toolExecution" ? item.toolName : item.command;
24176
+ const rawInput = item.type === "toolExecution" ? item.arguments : void 0;
24177
+ const resultSummary = grokSubagentResultSummary(content, rawOutput);
24178
+ for (const settlement of grokSubagentWaitSettlements({
24179
+ name,
24180
+ title: name,
24181
+ rawInput,
24182
+ content,
24183
+ rawOutput
24184
+ })) {
24185
+ active.subagents.completeByNativeId(active.command.turnId, settlement.id, {
24186
+ failed: settlement.status === "failed",
24187
+ cancellationRequested: active.cancellationRequested || settlement.status === "interrupted",
24188
+ status: settlement.status,
24189
+ ...settlement.resultSummary ? { resultSummary: settlement.resultSummary } : resultSummary ? { resultSummary } : {}
24190
+ });
24191
+ }
24192
+ }
24193
+ #bindSpawnedSubagent(active, event) {
24194
+ active.subagents.bindNativeId(active.command.turnId, {
24195
+ nativeSubagentId: event.nativeSubagentId,
24196
+ ...event.description ? { description: event.description } : {},
24197
+ ...event.role ? { role: event.role } : {},
24198
+ ...event.model ? { model: event.model } : {}
24199
+ });
24200
+ }
24201
+ #finishNativeSubagent(active, event) {
24202
+ active.subagents.completeByNativeId(active.command.turnId, event.nativeSubagentId, {
24203
+ failed: event.status === "failed",
24204
+ cancellationRequested: active.cancellationRequested || event.status === "interrupted",
24205
+ status: event.status,
24206
+ ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
24207
+ });
24208
+ }
23390
24209
  #completeAgent(active, outcome) {
23391
24210
  const item = active.agent;
23392
24211
  if (item && active.rawAgentText.length > 0) {
@@ -23453,6 +24272,7 @@ var GrokHarnessSession = class {
23453
24272
  const itemOutcome = outcome;
23454
24273
  this.#completeReasoning(active, itemOutcome);
23455
24274
  this.#completeAgent(active, itemOutcome);
24275
+ active.subagents.finalize(active.command.turnId, itemOutcome);
23456
24276
  if (active.compactionItem) {
23457
24277
  this.#completeItem(active, active.compactionItem, itemOutcome);
23458
24278
  active.compactionItem = null;
@@ -23535,6 +24355,39 @@ var GrokHarnessSession = class {
23535
24355
  var GrokAdapter = class {
23536
24356
  commandCatalog = grokCommandCatalog;
23537
24357
  harnessId = grokHarnessId;
24358
+ subagents = {
24359
+ readSnapshot: async (input) => {
24360
+ if (input.parent.harnessId !== this.harnessId || input.nativeSubagentId.trim().length === 0) {
24361
+ return {
24362
+ ok: false,
24363
+ error: {
24364
+ code: "invalidRequest",
24365
+ message: "Grok Subagent reference is invalid",
24366
+ retryable: false
24367
+ }
24368
+ };
24369
+ }
24370
+ try {
24371
+ const location = await locateGrokNativeSession(this.#environment ? { environment: this.#environment } : {}, input.nativeSubagentId);
24372
+ const cwd = location?.cwd ?? input.cwd;
24373
+ const history = await readGrokNativeHistory(this.#environment ? { cwd, environment: this.#environment } : { cwd }, input.nativeSubagentId);
24374
+ return {
24375
+ ok: true,
24376
+ value: mapGrokReplay(
24377
+ history,
24378
+ this.harnessId,
24379
+ // Host Subagent records keep the parent Native Session identity.
24380
+ input.parent.nativeSessionId,
24381
+ cwd,
24382
+ [],
24383
+ this.#toolOutputLimit
24384
+ )
24385
+ };
24386
+ } catch (error53) {
24387
+ return { ok: false, error: normalizeError(error53, "protocolError") };
24388
+ }
24389
+ }
24390
+ };
23538
24391
  #closeTimeoutMs;
23539
24392
  #dependencies;
23540
24393
  #environment;
@@ -23738,7 +24591,11 @@ var GrokAdapter = class {
23738
24591
  kind: "resume",
23739
24592
  sessionId: parsedRef.data.nativeSessionId,
23740
24593
  permissionModeId: requestedPermissionModeId
23741
- } : { kind: "create", permissionModeId: requestedPermissionModeId });
24594
+ } : {
24595
+ kind: "create",
24596
+ permissionModeId: requestedPermissionModeId,
24597
+ ...input.kind === "create" && input.model ? { modelId: input.model.id } : {}
24598
+ });
23742
24599
  }
23743
24600
  if (!opened) {
23744
24601
  await transport.close().catch(() => void 0);