@karlorz/codexhost-cli-win32-x64 0.18.0-1 → 0.19.0-1

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.
Files changed (57) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +59 -2
  4. package/app/console-web.js +98 -8
  5. package/app/cpa-live-voice-hook.js +59 -2
  6. package/app/desktop-controller.mjs +290 -12
  7. package/app/host-runtime.mjs +12896 -2966
  8. package/app/plugins/antigravity/plugin.mjs +654 -216
  9. package/app/plugins/claude-code/plugin.mjs +138 -11
  10. package/app/plugins/codebuddy/plugin.mjs +152 -20
  11. package/app/plugins/codex-usage/plugin.mjs +59 -2
  12. package/app/plugins/copilot/plugin.mjs +59 -2
  13. package/app/plugins/cursor-cli/plugin.mjs +134 -12
  14. package/app/plugins/deepseek-harness/manifest.json +2 -2
  15. package/app/plugins/deepseek-harness/plugin.mjs +86 -7
  16. package/app/plugins/devin/plugin.mjs +59 -2
  17. package/app/plugins/grok/plugin.mjs +1093 -970
  18. package/app/plugins/hermes/plugin.mjs +138 -14
  19. package/app/plugins/kimi-code/plugin.mjs +59 -2
  20. package/app/plugins/kiro-cli/plugin.mjs +287 -18
  21. package/app/plugins/omp/plugin.mjs +789 -628
  22. package/app/plugins/opencode/plugin.mjs +59 -2
  23. package/app/plugins/pi/plugin.mjs +786 -660
  24. package/app/plugins/qoder/plugin.mjs +61 -6
  25. package/app/plugins/qoder-cn/plugin.mjs +61 -6
  26. package/app/plugins/qwen-code/plugin.mjs +168 -94
  27. package/app/plugins/workbuddy/plugin.mjs +152 -20
  28. package/app/plugins/zcode/plugin.mjs +132 -5
  29. package/app/renderer-extension.js +434 -39
  30. package/app/web/assets/{index-py6Ho-Dy.js → index-BCyiiDDL.js} +62 -62
  31. package/app/web/assets/index-BNQIOOHE.css +1 -0
  32. package/app/web/codexhost-settings.js +84 -4
  33. package/app/web/index.html +2 -2
  34. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  35. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +8 -8
  36. package/app/web/plugins/deepseek-ai__dsh-client-file-upload/client.js +1 -1
  37. package/app/web/plugins/deepseek-ai__dsh-client-locale/client.js +3 -3
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-attachment/client.js +1 -1
  39. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +129 -8
  40. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +8 -6
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +95 -93
  42. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  43. package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +2 -2
  44. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +1 -1
  45. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
  46. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.excel.js +1 -1
  47. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-files/client.js +1 -1
  48. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +16 -16
  49. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +1 -1
  50. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +11 -11
  51. package/app/web-modules/server.mjs +2345 -1518
  52. package/bin/codexhost.exe +0 -0
  53. package/libexec/codexhost-node-repl.exe +0 -0
  54. package/libexec/codexhost-shim.exe +0 -0
  55. package/libexec/codexhost-updater.exe +0 -0
  56. package/package.json +1 -1
  57. package/app/web/assets/index-C3lniEH1.css +0 -1
@@ -15903,6 +15903,10 @@ var CLIENT_CHANNEL_VERSION = 1;
15903
15903
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
15904
15904
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
15905
15905
  var clientThreadPinParamsSchema = external_exports.object({ threadId: external_exports.string().min(1).max(1024), pinned: external_exports.boolean() }).strict();
15906
+ var clientThreadTreeReadParamsSchema = external_exports.object({}).strict();
15907
+ var clientThreadTreeSchema = external_exports.object({
15908
+ parents: external_exports.record(external_exports.string().min(1), external_exports.string().min(1))
15909
+ }).strict();
15906
15910
  var clientProjectlessWorkspaceSchema = external_exports.object({
15907
15911
  prompt: external_exports.string().max(16384).optional()
15908
15912
  }).strict();
@@ -15919,6 +15923,11 @@ var clientChannelCursorSchema = external_exports.object({
15919
15923
  sequence: external_exports.number().int().nonnegative()
15920
15924
  });
15921
15925
  var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
15926
+ external_exports.object({
15927
+ type: external_exports.literal("skills-changed"),
15928
+ cursor: clientChannelCursorSchema,
15929
+ cwd: external_exports.string().optional()
15930
+ }),
15922
15931
  external_exports.object({ type: external_exports.literal("display-settings-changed"), cursor: clientChannelCursorSchema }),
15923
15932
  external_exports.object({
15924
15933
  type: external_exports.literal("preferences-changed"),
@@ -16116,6 +16125,28 @@ var voiceTranscribeResultSchema = external_exports.discriminatedUnion("ok", [
16116
16125
  external_exports.object({ ok: external_exports.literal(false), error: external_exports.object({ code: voiceErrorCodeSchema }).strict() }).strict()
16117
16126
  ]);
16118
16127
 
16128
+ // ../../shared-contracts/dist/skills.js
16129
+ var skillsListParamsSchema = external_exports.object({
16130
+ threadId: hostThreadIdSchema.optional(),
16131
+ cwd: external_exports.string().min(1).optional()
16132
+ }).strict().refine((params) => !(params.threadId && params.cwd), {
16133
+ message: "Specify threadId or cwd, not both"
16134
+ });
16135
+ var librarySkillSchema = external_exports.object({
16136
+ name: external_exports.string().min(1).regex(/^[^\s[\]]+$/u),
16137
+ description: external_exports.string().optional(),
16138
+ path: external_exports.string().min(1),
16139
+ scope: external_exports.enum(["project", "global"]),
16140
+ source: external_exports.string().min(1)
16141
+ }).strict();
16142
+ var skillsListResultSchema = external_exports.object({
16143
+ revision: external_exports.number().int().nonnegative(),
16144
+ complete: external_exports.boolean(),
16145
+ skills: external_exports.array(librarySkillSchema),
16146
+ warnings: external_exports.array(external_exports.string()).optional()
16147
+ }).strict();
16148
+ var skillsChangedParamsSchema = external_exports.object({ cwd: external_exports.string().min(1).optional() }).strict();
16149
+
16119
16150
  // ../../shared-contracts/dist/web-access-tokens.js
16120
16151
  var webNetworkAccessUrlSchema = external_exports.object({
16121
16152
  /**
@@ -16221,8 +16252,8 @@ var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
16221
16252
  var delegationReadParamsSchema = external_exports.strictObject({
16222
16253
  threadId: external_exports.string().min(1).max(1024),
16223
16254
  view: external_exports.enum(["result", "messages"]),
16224
- cursor: external_exports.string().min(1).max(8192).optional(),
16225
- limit: external_exports.number().int().min(1).max(100).optional()
16255
+ from: external_exports.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
16256
+ to: external_exports.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional()
16226
16257
  });
16227
16258
 
16228
16259
  // ../../shared-contracts/dist/credential-imports.js
@@ -17224,6 +17255,17 @@ var updateStatusResultSchema = external_exports.strictObject({
17224
17255
  status: updateStatusSchema.nullable()
17225
17256
  });
17226
17257
 
17258
+ // ../../shared-contracts/dist/thread-watch-notice.js
17259
+ var THREAD_WATCH_NOTICE_OUTCOMES = [
17260
+ "completed",
17261
+ "failed",
17262
+ "interrupted",
17263
+ "timedOut",
17264
+ "unreadable",
17265
+ "notFound"
17266
+ ];
17267
+ var ENTRY_PATTERN = new RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): ` + `(${THREAD_WATCH_NOTICE_OUTCOMES.join("|")})(?:. (.+))?$`, "u");
17268
+
17227
17269
  // ../../shared-contracts/dist/remote-runtime.js
17228
17270
  var remoteUpdatePhaseSchema = external_exports.enum([
17229
17271
  "idle",
@@ -17271,6 +17313,14 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
17271
17313
  archived: external_exports.boolean()
17272
17314
  }),
17273
17315
  external_exports.strictObject({ kind: external_exports.literal("read"), ...thread }),
17316
+ external_exports.strictObject({
17317
+ kind: external_exports.literal("configure"),
17318
+ ...thread,
17319
+ epoch: identity,
17320
+ modelId: identity.optional(),
17321
+ thinkingOptionId: identity.optional(),
17322
+ permissionModeId: identity.optional()
17323
+ }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting"),
17274
17324
  external_exports.strictObject({
17275
17325
  kind: external_exports.literal("prompt"),
17276
17326
  ...thread,
@@ -17343,6 +17393,13 @@ var remoteConnectionsReplySchema = external_exports.union([
17343
17393
  external_exports.strictObject({ error: external_exports.strictObject({ code: external_exports.number().int(), message: external_exports.string() }) })
17344
17394
  ]);
17345
17395
 
17396
+ // ../../shared-contracts/dist/thread-title.js
17397
+ var threadTitleInputSchema = external_exports.strictObject({
17398
+ prompt: external_exports.string().trim().min(1).max(2e3),
17399
+ cwd: external_exports.string().max(4096).nullable()
17400
+ });
17401
+ var threadTitleResultSchema = external_exports.string().trim().min(1).max(60).nullable();
17402
+
17346
17403
  // ../../shared-contracts/dist/web-ui-extensions.js
17347
17404
  var webUiExtensionIdSchema = external_exports.string().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u);
17348
17405
  var localizedTextSchema2 = external_exports.union([
@@ -17715,1061 +17772,1112 @@ var GrokGoals = class {
17715
17772
  }
17716
17773
  };
17717
17774
 
17718
- // dist/usage-statistics.js
17719
- import os2 from "node:os";
17720
- import path6 from "node:path";
17721
- import { readFile as readFile2 } from "node:fs/promises";
17722
-
17723
- // ../../harness-adapter/dist/usage-statistics.js
17724
- import { createReadStream } from "node:fs";
17725
- import { lstat, opendir } from "node:fs/promises";
17726
- import path5 from "node:path";
17727
- import { createInterface } from "node:readline";
17728
- var MAX_SESSION_ID_LENGTH = 512;
17729
- var MAX_CWD_LENGTH = 4096;
17730
- var MAX_SESSION_TITLE_LENGTH = 200;
17731
- function usageSessionTitle(value) {
17732
- if (typeof value !== "string")
17733
- return void 0;
17734
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
17735
- if (!normalized)
17736
- return void 0;
17737
- if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
17738
- return normalized;
17739
- let title = "";
17740
- for (const character of normalized) {
17741
- if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
17742
- break;
17743
- title += character;
17744
- }
17745
- return `${title.trimEnd()}…`;
17746
- }
17747
- function sessionIdOk(value) {
17748
- return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
17775
+ // ../../harness-adapter/dist/approval.js
17776
+ function invalidRequest(message) {
17777
+ return { code: "invalidRequest", message, retryable: false };
17749
17778
  }
17750
- function cwdOk(value) {
17751
- 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("\\\\"));
17779
+ function validateHostApprovalResponse(interaction, response) {
17780
+ return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17752
17781
  }
17753
- function withUsageSession(entry, session) {
17754
- const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
17755
- const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
17756
- const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
17757
- if (sessionId === void 0 && cwd === void 0)
17758
- return entry;
17759
- return {
17760
- ...entry,
17761
- ...sessionId !== void 0 ? { sessionId } : {},
17762
- ...cwd !== void 0 ? { cwd } : {},
17763
- ...sessionTitle !== void 0 ? { sessionTitle } : {}
17764
- };
17782
+
17783
+ // ../../harness-adapter/dist/question.js
17784
+ function invalidRequest2(message) {
17785
+ return { code: "invalidRequest", message, retryable: false };
17765
17786
  }
17766
- async function jsonlUsageSources(root, maxDepth, signal) {
17767
- const sources = [];
17768
- const visit = async (directory, depth) => {
17769
- signal.throwIfAborted();
17770
- const entries = await opendir(directory).catch((error53) => {
17771
- if (error53.code === "ENOENT")
17772
- return null;
17773
- throw error53;
17774
- });
17775
- if (!entries)
17776
- return;
17777
- for await (const entry of entries) {
17778
- signal.throwIfAborted();
17779
- const file2 = path5.join(directory, entry.name);
17780
- if (entry.isDirectory()) {
17781
- if (depth < maxDepth)
17782
- await visit(file2, depth + 1);
17783
- } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
17784
- const info = await lstat(file2).catch(() => null);
17785
- if (info?.isFile() && info.size > 0) {
17786
- sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
17787
- }
17788
- }
17787
+ function validateHostQuestionResponse(interaction, response) {
17788
+ const questionIds = new Set(interaction.questions.map(({ id }) => id));
17789
+ if (response.cancelled) {
17790
+ return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
17791
+ }
17792
+ for (const answerId of Object.keys(response.answers)) {
17793
+ if (!questionIds.has(answerId)) {
17794
+ return invalidRequest2("Question Response contains an unknown Question ID");
17789
17795
  }
17790
- };
17791
- await visit(root, 0);
17792
- return sources;
17793
- }
17794
- async function* jsonlRecords(file2, marker, signal) {
17795
- const lines = createInterface({
17796
- input: createReadStream(file2, { encoding: "utf8", signal }),
17797
- crlfDelay: Infinity
17798
- });
17799
- for await (const line of lines) {
17800
- if (!line.includes(marker))
17801
- continue;
17802
- let value;
17803
- try {
17804
- value = JSON.parse(line);
17805
- } catch {
17796
+ }
17797
+ for (const question of interaction.questions) {
17798
+ const answers = response.answers[question.id] ?? [];
17799
+ if (new Set(answers).size !== answers.length) {
17800
+ return invalidRequest2("Question Response contains duplicate answers");
17801
+ }
17802
+ if (!question.optional && answers.length === 0) {
17803
+ return invalidRequest2("Question Response omits a required answer");
17804
+ }
17805
+ if (question.type === "text") {
17806
+ if (answers.length > 1) {
17807
+ return invalidRequest2("Text Question accepts at most one answer");
17808
+ }
17806
17809
  continue;
17807
17810
  }
17808
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
17809
- yield value;
17811
+ if (!question.multiple && answers.length > 1) {
17812
+ return invalidRequest2("Single-choice Question accepts at most one answer");
17813
+ }
17814
+ const declared = new Set(question.options.map(({ value }) => value));
17815
+ if (!question.allowOther && answers.some((answer) => !declared.has(answer))) {
17816
+ return invalidRequest2("Question Response contains an undeclared choice");
17810
17817
  }
17811
17818
  }
17812
- }
17813
- function nativeTimeMs(value) {
17814
- const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
17815
- return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
17819
+ return null;
17816
17820
  }
17817
17821
 
17818
- // dist/usage-statistics.js
17819
- function isRecord(value) {
17820
- return typeof value === "object" && value !== null && !Array.isArray(value);
17821
- }
17822
- var USD_TICKS = 1e10;
17823
- function count3(value) {
17824
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
17825
- }
17826
- function grokHome(environment) {
17827
- return environment.GROK_HOME || path6.join(environment.HOME || os2.homedir(), ".grok");
17828
- }
17829
- async function grokSummary(directory) {
17830
- try {
17831
- const summary = JSON.parse(await readFile2(path6.join(directory, "summary.json"), "utf8"));
17832
- if (!isRecord(summary))
17833
- return { forkedAt: null };
17834
- const title = usageSessionTitle(summary.generated_title) ?? usageSessionTitle(summary.session_summary);
17835
- return {
17836
- forkedAt: typeof summary.parent_session_id === "string" ? nativeTimeMs(summary.created_at) : null,
17837
- ...title ? { title } : {}
17822
+ // ../../harness-adapter/dist/output-channel.js
17823
+ var HarnessOutputChannel = class {
17824
+ outputs;
17825
+ #consumerCreated = false;
17826
+ #ended = false;
17827
+ #pending = [];
17828
+ #values = [];
17829
+ constructor() {
17830
+ this.outputs = {
17831
+ [Symbol.asyncIterator]: () => {
17832
+ if (this.#consumerCreated) {
17833
+ throw new Error("Harness outputs allow only one consumer");
17834
+ }
17835
+ this.#consumerCreated = true;
17836
+ return {
17837
+ next: () => this.#next()
17838
+ };
17839
+ }
17838
17840
  };
17839
- } catch {
17840
- return { forkedAt: null };
17841
17841
  }
17842
- }
17843
- function grokSession(file2) {
17844
- const directory = path6.dirname(file2);
17845
- let cwd;
17846
- try {
17847
- cwd = decodeURIComponent(path6.basename(path6.dirname(directory)));
17848
- } catch {
17849
- cwd = void 0;
17842
+ emit(value) {
17843
+ if (this.#ended)
17844
+ return false;
17845
+ const resolve = this.#pending.shift();
17846
+ if (resolve)
17847
+ resolve({ done: false, value });
17848
+ else
17849
+ this.#values.push(value);
17850
+ return true;
17850
17851
  }
17851
- return { sessionId: path6.basename(directory), cwd };
17852
+ end() {
17853
+ if (this.#ended)
17854
+ return;
17855
+ this.#ended = true;
17856
+ if (this.#values.length !== 0)
17857
+ return;
17858
+ for (const resolve of this.#pending.splice(0))
17859
+ resolve({ done: true, value: void 0 });
17860
+ }
17861
+ #next() {
17862
+ const value = this.#values.shift();
17863
+ if (value !== void 0)
17864
+ return Promise.resolve({ done: false, value });
17865
+ if (this.#ended)
17866
+ return Promise.resolve({ done: true, value: void 0 });
17867
+ return new Promise((resolve) => this.#pending.push(resolve));
17868
+ }
17869
+ };
17870
+
17871
+ // ../../harness-adapter/dist/diagnostics.js
17872
+ var DIAGNOSTIC_TAIL_MAX_LENGTH = 8e3;
17873
+ var SENSITIVE_VALUE_PATTERN = /(api[_-]?key|access[_-]?token|auth(?:orization)?|password|secret)(\s*[:=]\s*)([^\s,;]+)/giu;
17874
+ var BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]+/giu;
17875
+ function sanitizeDiagnosticTail(value) {
17876
+ const redacted = value.replace(BEARER_PATTERN, "Bearer [redacted]").replace(SENSITIVE_VALUE_PATTERN, "$1$2[redacted]");
17877
+ return redacted.length <= DIAGNOSTIC_TAIL_MAX_LENGTH ? redacted : redacted.slice(-DIAGNOSTIC_TAIL_MAX_LENGTH);
17852
17878
  }
17853
- async function readGrokUsage(file2, signal) {
17854
- const summary = await grokSummary(path6.dirname(file2));
17855
- const forkedAt = summary.forkedAt;
17856
- let title = summary.title;
17857
- const session = grokSession(file2);
17858
- const entries = [];
17859
- for await (const line of jsonlRecords(file2, '"sessionUpdate"', signal)) {
17860
- const params = isRecord(line.params) ? line.params : {};
17861
- const update = isRecord(params.update) ? params.update : {};
17862
- if (!title && update.sessionUpdate === "user_message_chunk") {
17863
- title = usageSessionTitle(isRecord(update.content) ? update.content.text : void 0);
17864
- continue;
17879
+
17880
+ // ../../harness-adapter/dist/steer.js
17881
+ function unsupportedSteer(harnessLabel) {
17882
+ return {
17883
+ ok: false,
17884
+ error: {
17885
+ code: "unsupported",
17886
+ message: `${harnessLabel} cannot steer an active Turn natively`,
17887
+ retryable: false
17865
17888
  }
17866
- const usage = isRecord(update.usage) ? update.usage : {};
17867
- if (update.sessionUpdate !== "turn_completed" || typeof update.prompt_id !== "string")
17868
- continue;
17869
- const meta3 = isRecord(params._meta) ? params._meta : {};
17870
- const at = nativeTimeMs(meta3.agentTimestampMs) ?? (typeof line.timestamp === "number" ? nativeTimeMs(line.timestamp * 1e3) : null);
17871
- if (at === null || forkedAt !== null && at <= forkedAt)
17872
- continue;
17873
- for (const [model2, value] of Object.entries(isRecord(usage.modelUsage) ? usage.modelUsage : {})) {
17874
- if (!isRecord(value))
17875
- continue;
17876
- const input = count3(value.inputTokens);
17877
- const output = count3(value.outputTokens);
17878
- const cached2 = count3(value.cachedReadTokens);
17879
- const written = count3(value.cacheCreationTokens ?? 0);
17880
- const reasoning = count3(value.reasoningTokens);
17881
- const ticks = count3(value.costUsdTicks);
17882
- if (input === null || output === null || value.totalTokens !== input + output)
17883
- continue;
17884
- const cacheKnown = cached2 !== null && cached2 <= input && written === 0;
17885
- entries.push(withUsageSession({
17886
- id: `${update.prompt_id}:${model2}`,
17887
- occurredAtMs: at,
17888
- model: model2,
17889
- inputTokens: input,
17890
- ...cacheKnown ? { cachedInputTokens: cached2, cacheWriteInputTokens: 0 } : {},
17891
- outputTokens: output,
17892
- ...reasoning !== null && reasoning <= output ? { reasoningOutputTokens: reasoning } : {},
17893
- // A turn Grok marks incomplete has no cost of its own; it counts as free rather
17894
- // than as a model without a price.
17895
- ...ticks !== null ? { costUsd: ticks / USD_TICKS } : usage.usageIsIncomplete === true ? { costUsd: 0 } : {}
17896
- }, { ...session, ...title ? { title } : {} }));
17897
- }
17898
- }
17899
- return entries;
17900
- }
17901
- function createGrokUsageStatistics(environment) {
17902
- return Object.freeze({
17903
- // sessions/<url-encoded cwd>/<session>/updates.jsonl; subagents are sessions of their own.
17904
- listSources: async (signal) => (await jsonlUsageSources(path6.join(grokHome(environment), "sessions"), 2, signal)).filter((source) => path6.basename(source.id) === "updates.jsonl"),
17905
- readSource: (id, signal) => readGrokUsage(id, signal)
17906
- });
17889
+ };
17907
17890
  }
17908
17891
 
17909
- // dist/grok-commands.js
17910
- var grokCommandCatalog = harnessCommandCatalogSchema.parse({
17911
- commands: [
17912
- {
17913
- id: "grok.compact",
17914
- invocation: "/compact",
17915
- localizations: { "zh-CN": { label: "压缩上下文", description: "压缩当前对话上下文" } },
17916
- label: "Compact context",
17917
- description: "Compact the current conversation context",
17918
- argumentMode: "text"
17919
- },
17920
- {
17921
- id: "grok.desktop-goal",
17922
- invocation: "/goal",
17923
- label: "Goal",
17924
- description: "Start a native goal through Desktop Goal mode",
17925
- argumentMode: "text"
17926
- },
17927
- {
17928
- id: "grok.goal",
17929
- invocation: "/grok-goal",
17930
- label: "Grok goal",
17931
- description: "Set an objective [--budget tokens], or status / pause / resume / clear",
17932
- localizations: {
17933
- "zh-CN": {
17934
- label: "Grok 目标",
17935
- description: "设置原生目标与可选 token 预算,或 status / pause / resume / clear"
17936
- }
17937
- },
17938
- argumentMode: "text"
17939
- },
17940
- {
17941
- id: "grok.loop",
17942
- invocation: "/loop",
17943
- label: "Loop",
17944
- description: "Create a native timed Loop; include the interval and task",
17945
- argumentMode: "text"
17946
- }
17947
- ]
17948
- });
17949
- var GROK_GOAL_CONTROL_PATTERN = /^\/goal(?:\s+(?:status|pause|clear|resume))?\s*$/u;
17950
- function isGrokGoalControlPrompt(value) {
17951
- return GROK_GOAL_CONTROL_PATTERN.test(value.trim());
17892
+ // ../../harness-adapter/dist/usage.js
17893
+ var tokenFields = [
17894
+ "inputTokens",
17895
+ "cachedInputTokens",
17896
+ "cacheWriteInputTokens",
17897
+ "outputTokens",
17898
+ "reasoningOutputTokens",
17899
+ "totalTokens",
17900
+ "contextWindowTokens",
17901
+ "contextUsedTokens"
17902
+ ];
17903
+ var safeIntegerFields = [
17904
+ "planFiveHourResetsAtUnix",
17905
+ "planSevenDayResetsAtUnix",
17906
+ "timeToFirstOutputMs"
17907
+ ];
17908
+ var percentFields = [
17909
+ "cacheHitRatePercent",
17910
+ "sessionCacheHitRatePercent",
17911
+ "planFiveHourUsedPercent",
17912
+ "planSevenDayUsedPercent"
17913
+ ];
17914
+ var usageFields = /* @__PURE__ */ new Set([
17915
+ ...tokenFields,
17916
+ ...safeIntegerFields,
17917
+ ...percentFields,
17918
+ "sessionCacheUsage",
17919
+ "composerIndicators",
17920
+ "totalCostUsd",
17921
+ "totalCredits",
17922
+ "contextUsagePercent",
17923
+ "outputTokensPerSecond",
17924
+ "apiOutputTokensPerSecond",
17925
+ "costSource",
17926
+ "unpricedModels"
17927
+ ]);
17928
+ function isRecord(value) {
17929
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17952
17930
  }
17953
- function grokGoalPrompt(arguments_) {
17954
- if (arguments_ && (Object.keys(arguments_).some((key) => key !== "text") || arguments_.text !== void 0 && typeof arguments_.text !== "string")) {
17955
- return {
17956
- ok: false,
17957
- error: {
17958
- code: "invalidRequest",
17959
- message: "Grok goal accepts only a text argument",
17960
- retryable: false
17961
- }
17962
- };
17931
+ function parseHostUsage(value) {
17932
+ if (!isRecord(value))
17933
+ throw new Error("Harness Usage must be an object");
17934
+ const keys = Object.keys(value);
17935
+ if (keys.length === 0)
17936
+ throw new Error("Harness Usage must contain a reliable field");
17937
+ for (const key of keys) {
17938
+ if (!usageFields.has(key)) {
17939
+ throw new Error(`Harness Usage contains unknown field '${key}'`);
17940
+ }
17963
17941
  }
17964
- const text = typeof arguments_?.text === "string" ? arguments_.text.trim() : "";
17965
- return { ok: true, value: text ? `/goal ${text}` : "/goal" };
17966
- }
17967
-
17968
- // dist/grok-adapter.js
17969
- import { randomUUID as randomUUID2 } from "node:crypto";
17970
-
17971
- // dist/grok-text-item-id.js
17972
- import { createHash } from "node:crypto";
17973
- function grokTextItemId(sessionId, turnIndex, kind, ordinal) {
17974
- const identity2 = JSON.stringify([sessionId, turnIndex, kind, ordinal]);
17975
- return hostItemIdSchema.parse(`grok-text-${createHash("sha256").update(identity2).digest("hex")}`);
17976
- }
17977
-
17978
- // dist/grok-stop-diagnostic.js
17979
- function isRecord2(value) {
17980
- return typeof value === "object" && value !== null && Array.isArray(value) === false;
17981
- }
17982
- function collectText(value, into, depth = 0) {
17983
- if (depth > 4)
17984
- return;
17985
- if (typeof value === "string") {
17986
- const text = value.trim();
17987
- if (text.length > 0 && !into.includes(text))
17988
- into.push(text);
17989
- return;
17942
+ const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
17943
+ for (const field2 of [
17944
+ "totalCredits",
17945
+ "contextUsagePercent",
17946
+ "apiOutputTokensPerSecond"
17947
+ ]) {
17948
+ const candidate = value[field2];
17949
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
17950
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
17951
+ }
17990
17952
  }
17991
- if (Array.isArray(value)) {
17992
- for (const entry of value)
17993
- collectText(entry, into, depth + 1);
17994
- return;
17953
+ for (const field2 of tokenFields) {
17954
+ const candidate = value[field2];
17955
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17956
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
17957
+ }
17995
17958
  }
17996
- if (!isRecord2(value))
17997
- return;
17998
- for (const key of [
17999
- "message",
18000
- "error",
18001
- "reason",
18002
- "detail",
18003
- "details",
18004
- "diagnostic",
18005
- "cause",
18006
- "err"
18007
- ]) {
18008
- if (Object.hasOwn(value, key))
18009
- collectText(value[key], into, depth + 1);
17959
+ for (const field2 of safeIntegerFields) {
17960
+ const candidate = value[field2];
17961
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17962
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
17963
+ }
18010
17964
  }
17965
+ if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
17966
+ throw new Error("Harness Usage 'outputTokensPerSecond' must be a finite non-negative number");
17967
+ }
17968
+ if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
17969
+ throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
17970
+ }
17971
+ for (const field2 of percentFields) {
17972
+ const candidate = value[field2];
17973
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
17974
+ throw new Error(`Harness Usage '${field2}' must be between 0 and 100`);
17975
+ }
17976
+ }
17977
+ if (value.sessionCacheUsage !== void 0) {
17978
+ const totals2 = value.sessionCacheUsage;
17979
+ if (!isRecord(totals2) || Object.keys(totals2).some((key) => key !== "inputTokens" && key !== "cachedInputTokens") || typeof totals2.inputTokens !== "number" || !Number.isSafeInteger(totals2.inputTokens) || totals2.inputTokens < 0 || typeof totals2.cachedInputTokens !== "number" || !Number.isSafeInteger(totals2.cachedInputTokens) || totals2.cachedInputTokens < 0 || totals2.cachedInputTokens > totals2.inputTokens) {
17980
+ throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
17981
+ }
17982
+ }
17983
+ const hasContextUsed = value.contextUsedTokens !== void 0;
17984
+ const hasContextWindow = value.contextWindowTokens !== void 0;
17985
+ if (hasContextUsed !== hasContextWindow) {
17986
+ throw new Error("Harness Usage context fields must be provided together");
17987
+ }
17988
+ if (hasContextWindow && value.contextWindowTokens === 0) {
17989
+ throw new Error("Harness Usage 'contextWindowTokens' must be greater than zero");
17990
+ }
17991
+ if (value.planFiveHourResetsAtUnix !== void 0 && value.planFiveHourUsedPercent === void 0) {
17992
+ throw new Error("Harness Usage 'planFiveHourResetsAtUnix' must be provided with 'planFiveHourUsedPercent'");
17993
+ }
17994
+ if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
17995
+ throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
17996
+ }
17997
+ if (value.costSource !== void 0) {
17998
+ if (value.costSource !== "publicPrice" && value.costSource !== "native") {
17999
+ throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
18000
+ }
18001
+ if (value.totalCostUsd === void 0) {
18002
+ throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
18003
+ }
18004
+ }
18005
+ if (value.unpricedModels !== void 0) {
18006
+ const models = value.unpricedModels;
18007
+ if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
18008
+ throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
18009
+ }
18010
+ if (value.costSource !== "publicPrice") {
18011
+ throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
18012
+ }
18013
+ return { ...value, ...indicators, unpricedModels: [...models] };
18014
+ }
18015
+ return { ...value, ...indicators };
18011
18016
  }
18012
- function grokStopDetail(source, stopReason) {
18013
- const parts = [];
18014
- collectText(source, parts);
18015
- const useful = parts.filter((part) => part !== stopReason && part.toLowerCase() !== "error" && part.length > 1);
18016
- return useful.length > 0 ? useful.join(": ") : void 0;
18017
- }
18018
- function grokTurnStopError(stopReason, source) {
18019
- const detail = grokStopDetail(source, stopReason);
18020
- const diagnostic = source !== void 0 && source !== null ? JSON.stringify(source) : void 0;
18021
- return {
18022
- code: "nativeFailure",
18023
- message: detail ? `Grok stopped the Turn: ${stopReason}: ${detail}` : `Grok stopped the Turn: ${stopReason}`,
18024
- retryable: stopReason === "max_tokens" || stopReason === "max_turn_requests",
18025
- ...diagnostic && diagnostic !== "{}" && diagnostic !== "null" ? { diagnostic } : {}
18026
- };
18027
- }
18028
- function grokPromptStopError(response) {
18029
- return grokTurnStopError(response.stopReason, response._meta ?? void 0);
18030
- }
18017
+ var requestTokenFields = [
18018
+ "inputTokens",
18019
+ "cachedInputTokens",
18020
+ "cacheWriteInputTokens",
18021
+ "cacheWrite1hInputTokens",
18022
+ "outputTokens",
18023
+ "reasoningOutputTokens",
18024
+ "startedAtMs",
18025
+ "completedAtMs"
18026
+ ];
18027
+ var requestFields = /* @__PURE__ */ new Set([
18028
+ ...requestTokenFields,
18029
+ "requestId",
18030
+ "historical",
18031
+ "model",
18032
+ "provider"
18033
+ ]);
18031
18034
 
18032
- // dist/grok-agent-messages.js
18033
- function settledGrokAgentMessages(persisted, completedItems) {
18034
- const messages = persisted.flatMap(({ item }) => item.type === "agentMessage" ? [item] : []);
18035
- const completed = new Set(completedItems.map(({ item }) => item.itemId));
18036
- return messages.flatMap((item, index) => {
18037
- const phase = index === messages.length - 1 ? "final_answer" : "commentary";
18038
- if (completed.has(item.itemId))
18039
- return [];
18040
- return [{ ...item, phase }];
18041
- });
18035
+ // ../../harness-adapter/dist/live-command-catalog.js
18036
+ var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
18037
+ // Session lifecycle
18038
+ "branch",
18039
+ "clear",
18040
+ "exit",
18041
+ "fork",
18042
+ "fresh",
18043
+ "new",
18044
+ "quit",
18045
+ "rename",
18046
+ "rename-chat",
18047
+ "reset",
18048
+ "resume",
18049
+ "rewind",
18050
+ "session",
18051
+ "sessions",
18052
+ // Desktop-owned configuration
18053
+ "autocompact",
18054
+ "color",
18055
+ "config",
18056
+ "effort",
18057
+ "fast",
18058
+ "keybindings",
18059
+ "model",
18060
+ "models",
18061
+ "output-style",
18062
+ "permissions",
18063
+ "settings",
18064
+ "statusline",
18065
+ "terminal-setup",
18066
+ "theme",
18067
+ "vim",
18068
+ // Trust and approval policy
18069
+ "always-approve",
18070
+ "auto-mode-setup",
18071
+ // Native login
18072
+ "login",
18073
+ "logout",
18074
+ // Work outliving the Turn
18075
+ "autopilot",
18076
+ "background",
18077
+ "bg",
18078
+ "goal",
18079
+ "jobs",
18080
+ "loop",
18081
+ "multitask",
18082
+ "queue",
18083
+ "remote-control",
18084
+ "schedule",
18085
+ "steer",
18086
+ // Native terminal UI
18087
+ "copy",
18088
+ "debug",
18089
+ "feedback",
18090
+ "heapdump",
18091
+ "share",
18092
+ "shell",
18093
+ // Plugin and MCP management
18094
+ "marketplace",
18095
+ "mcp",
18096
+ "plugins",
18097
+ "reload-plugins"
18098
+ ]);
18099
+ var COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES = ["__", "hooks-"];
18100
+ function isExcludedLiveCommand(name, extra = {}) {
18101
+ const normalized = name.trim().replace(/^\//u, "");
18102
+ if (new Set(extra.names ?? []).has(normalized))
18103
+ return true;
18104
+ if (extra.prefixes?.some((prefix) => normalized.startsWith(prefix)))
18105
+ return true;
18106
+ return COMMON_EXCLUDED_LIVE_COMMANDS.has(normalized) || COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES.some((prefix) => normalized.startsWith(prefix));
18042
18107
  }
18043
-
18044
- // dist/grok-credential-export.js
18045
- import { createHash as createHash2 } from "node:crypto";
18046
- import { readFile as readFile3 } from "node:fs/promises";
18047
- import os3 from "node:os";
18048
- import path7 from "node:path";
18049
- async function readGrokCredentials(environment) {
18050
- if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((v) => v?.trim()))
18051
- return [];
18052
- try {
18053
- const home = environment.GROK_HOME ?? path7.join(environment.HOME ?? os3.homedir(), ".grok");
18054
- const auth = JSON.parse(await readFile3(path7.join(home, "auth.json"), "utf8"));
18055
- const client2 = "b1a00492-073a-47ea-816f-4c329264a828";
18056
- const entry = auth[`https://auth.x.ai::${client2}`] ?? auth["https://auth.x.ai"];
18057
- if (!entry || entry.oidc_issuer !== "https://auth.x.ai" || entry.oidc_client_id !== client2)
18058
- return [];
18059
- if (![entry.key, entry.refresh_token, entry.user_id].every((v) => typeof v === "string" && v.length))
18060
- return [];
18061
- const expires = Date.parse(entry.expires_at);
18062
- if (!Number.isFinite(expires))
18063
- return [];
18064
- return [
18065
- {
18066
- source: {
18067
- id: `grok:${createHash2("sha256").update(entry.user_id).digest("hex")}`,
18068
- harnessId: "grok",
18069
- provider: "xai",
18070
- label: typeof entry.email === "string" && entry.email ? entry.email : "Grok"
18071
- },
18072
- oauth: { access: entry.key, refresh: entry.refresh_token, expires: expires - 3e5 }
18073
- }
18074
- ];
18075
- } catch {
18076
- return [];
18108
+ function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
18109
+ if (!commandId.startsWith(idPrefix))
18110
+ return null;
18111
+ const descriptor = catalog.commands.find(({ id }) => id === commandId);
18112
+ if (!descriptor)
18113
+ return null;
18114
+ const text = typeof argumentText === "string" ? argumentText.trim() : "";
18115
+ return text ? `${descriptor.invocation} ${text}` : descriptor.invocation;
18116
+ }
18117
+ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
18118
+ if (!live)
18119
+ return builtIns;
18120
+ const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
18121
+ const ids = new Set(builtIns.commands.map(({ id }) => id));
18122
+ const dynamic = [];
18123
+ for (const command of live) {
18124
+ const name = command.name.trim().replace(/^\//u, "");
18125
+ if (!name || /\s/u.test(name))
18126
+ continue;
18127
+ if (isExcludedLiveCommand(name, exclusions))
18128
+ continue;
18129
+ const invocation = `/${name}`;
18130
+ const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
18131
+ if (invocations.has(invocation) || ids.has(id))
18132
+ continue;
18133
+ const description = command.description?.trim().slice(0, 512);
18134
+ const parsed = harnessCommandDescriptorSchema.safeParse({
18135
+ id,
18136
+ invocation,
18137
+ label: name.slice(0, 128),
18138
+ ...description ? { description } : {},
18139
+ argumentMode: "text"
18140
+ });
18141
+ if (!parsed.success)
18142
+ continue;
18143
+ invocations.add(invocation);
18144
+ ids.add(id);
18145
+ dynamic.push(parsed.data);
18077
18146
  }
18147
+ return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
18078
18148
  }
18079
18149
 
18080
- // dist/grok-adapter.js
18081
- import path22 from "node:path";
18082
-
18083
- // ../../harness-plugin-files/dist/grok-computer-use.js
18084
- import { randomUUID } from "node:crypto";
18085
- import { access, mkdir as mkdir2, readFile as readFile4, rename, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
18086
- import os4 from "node:os";
18087
- import path9 from "node:path";
18088
-
18089
- // ../../harness-plugin-files/dist/grok-computer-use-lock.js
18090
- import { mkdir, rm as rm2 } from "node:fs/promises";
18091
- import path8 from "node:path";
18092
- import { setTimeout as delay2 } from "node:timers/promises";
18093
- async function withGrokComputerUseLock(dataDirectory2, grokHome4, operation) {
18094
- const locks = [
18095
- .../* @__PURE__ */ new Set([
18096
- path8.join(dataDirectory2, ".grok-computer-use.lock"),
18097
- path8.join(grokHome4, ".codexhost-cua.lock")
18098
- ])
18099
- ].sort();
18100
- const acquired = [];
18101
- const deadline = Date.now() + 5e3;
18102
- try {
18103
- for (const lock of locks) {
18104
- await mkdir(path8.dirname(lock), { recursive: true, mode: 448 });
18105
- for (; ; ) {
18106
- try {
18107
- await mkdir(lock, { mode: 448 });
18108
- acquired.push(lock);
18109
- break;
18110
- } catch (error53) {
18111
- if (error53.code !== "EEXIST")
18112
- throw error53;
18113
- if (Date.now() >= deadline)
18114
- throw new Error("Grok Computer Use settings are locked");
18115
- await delay2(25);
18150
+ // ../../harness-adapter/dist/subagent-configuration.js
18151
+ function subagentConfiguration(value) {
18152
+ if (typeof value !== "object" || value === null || Array.isArray(value))
18153
+ return {};
18154
+ const row = value;
18155
+ const text = (value2) => typeof value2 === "string" && value2.trim() ? value2 : void 0;
18156
+ const model2 = row.model === "inherit" ? void 0 : text(row.model);
18157
+ const reasoningEffort = text(row.reasoningEffort) ?? text(row.reasoning_effort) ?? text(row.thinking);
18158
+ return { ...model2 ? { model: model2 } : {}, ...reasoningEffort ? { reasoningEffort } : {} };
18159
+ }
18160
+ function inheritSubagentConfiguration(child, parent) {
18161
+ const native = subagentConfiguration(child);
18162
+ const model2 = native.model ?? parent.model;
18163
+ const reasoningEffort = native.reasoningEffort ?? parent.reasoningEffort;
18164
+ const next = { ...child };
18165
+ delete next.model;
18166
+ delete next.reasoningEffort;
18167
+ return { ...next, ...model2 ? { model: model2 } : {}, ...reasoningEffort ? { reasoningEffort } : {} };
18168
+ }
18169
+ function configureSubagentEvent(event, parent) {
18170
+ const children = (states) => states.map((child) => inheritSubagentConfiguration(child, parent));
18171
+ if (event.type === "item.started" && event.item.type === "subagentDelegation")
18172
+ return { ...event, item: { ...event.item, subagents: children(event.item.subagents) } };
18173
+ if (event.type === "item.updated" && event.update.type === "subagents.replace")
18174
+ return { ...event, update: { ...event.update, subagents: children(event.update.subagents) } };
18175
+ if (event.type === "item.completed" && event.snapshot.item.type === "subagentDelegation")
18176
+ return {
18177
+ ...event,
18178
+ snapshot: {
18179
+ ...event.snapshot,
18180
+ item: {
18181
+ ...event.snapshot.item,
18182
+ subagents: children(event.snapshot.item.subagents)
18116
18183
  }
18117
18184
  }
18118
- }
18119
- return await operation();
18120
- } finally {
18121
- for (const lock of acquired.reverse())
18122
- await rm2(lock, { recursive: true });
18123
- }
18124
- }
18125
-
18126
- // ../../harness-plugin-files/dist/grok-computer-use.js
18127
- var GROK_BROWSER_BINDING_SUPPORTED = false;
18128
- var PREFERENCE_FILE = "grok-computer-use.json";
18129
- var TABLE = "[mcp_servers.cua_repl]";
18130
- var ENV_TABLE = "[mcp_servers.cua_repl.env]";
18131
- var APPLY_FAILED = "Could not apply Grok Computer Use settings to Grok config.";
18132
- var GrokComputerUseError = class extends Error {
18133
- constructor(message) {
18134
- super(message);
18135
- this.name = "GrokComputerUseError";
18136
- }
18137
- };
18138
- function dataDirectory(environment) {
18139
- return environment.CODEXHOST_DATA_DIR ? path9.resolve(environment.CODEXHOST_DATA_DIR) : path9.join(os4.homedir(), ".codexhost");
18140
- }
18141
- function grokHome2(environment) {
18142
- return environment.GROK_HOME ? path9.resolve(environment.GROK_HOME) : path9.join(environment.HOME ?? os4.homedir(), ".grok");
18185
+ };
18186
+ return event;
18143
18187
  }
18144
- function chatgptApp(environment, platform) {
18145
- if (environment.CODEXHOST_CHATGPT_APP)
18146
- return path9.resolve(environment.CODEXHOST_CHATGPT_APP);
18147
- if (platform === "darwin")
18148
- return "/Applications/ChatGPT.app";
18149
- return void 0;
18188
+ function configureSubagentSnapshot(snapshot, parent) {
18189
+ return {
18190
+ ...snapshot,
18191
+ turns: snapshot.turns.map((turn) => ({
18192
+ ...turn,
18193
+ items: turn.items.map((entry) => entry.item.type === "subagentDelegation" ? {
18194
+ ...entry,
18195
+ item: {
18196
+ ...entry.item,
18197
+ subagents: entry.item.subagents.map((child) => inheritSubagentConfiguration(child, parent))
18198
+ }
18199
+ } : entry)
18200
+ }))
18201
+ };
18150
18202
  }
18151
- async function isFile(target2) {
18152
- try {
18153
- await access(target2);
18154
- return true;
18155
- } catch {
18156
- return false;
18203
+
18204
+ // dist/usage-statistics.js
18205
+ import os2 from "node:os";
18206
+ import path6 from "node:path";
18207
+ import { readFile as readFile2 } from "node:fs/promises";
18208
+
18209
+ // ../../harness-adapter/dist/usage-statistics.js
18210
+ import { createReadStream } from "node:fs";
18211
+ import { lstat, opendir } from "node:fs/promises";
18212
+ import path5 from "node:path";
18213
+ import { createInterface } from "node:readline";
18214
+ var MAX_SESSION_ID_LENGTH = 512;
18215
+ var MAX_CWD_LENGTH = 4096;
18216
+ var MAX_SESSION_TITLE_LENGTH = 200;
18217
+ function usageSessionTitle(value) {
18218
+ if (typeof value !== "string")
18219
+ return void 0;
18220
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
18221
+ if (!normalized)
18222
+ return void 0;
18223
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
18224
+ return normalized;
18225
+ let title = "";
18226
+ for (const character of normalized) {
18227
+ if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
18228
+ break;
18229
+ title += character;
18157
18230
  }
18231
+ return `${title.trimEnd()}…`;
18158
18232
  }
18159
- function isNotFound(error53) {
18160
- return Boolean(error53 && typeof error53 === "object" && "code" in error53 && error53.code === "ENOENT");
18233
+ function sessionIdOk(value) {
18234
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
18161
18235
  }
18162
- async function writeAtomically(file2, content) {
18163
- await mkdir2(path9.dirname(file2), { recursive: true, mode: 448 });
18164
- const temporary = `${file2}.${randomUUID()}.tmp`;
18165
- try {
18166
- await writeFile2(temporary, content, { mode: 384, flag: "wx" });
18167
- await rename(temporary, file2);
18168
- } finally {
18169
- await rm3(temporary, { force: true });
18170
- }
18236
+ function cwdOk(value) {
18237
+ 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("\\\\"));
18171
18238
  }
18172
- function launchPaths(environment, platform) {
18173
- const app = chatgptApp(environment, platform);
18174
- if (!app)
18175
- return void 0;
18176
- const resources = path9.join(app, "Contents", "Resources");
18177
- const cuaNode = path9.join(resources, "cua_node");
18239
+ function withUsageSession(entry, session) {
18240
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
18241
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
18242
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
18243
+ if (sessionId === void 0 && cwd === void 0)
18244
+ return entry;
18178
18245
  return {
18179
- node: path9.join(cuaNode, "bin", "node"),
18180
- cuaRepl: path9.join(cuaNode, "lib", "node_modules", "@oai", "cua-repl", "bin", "cua-repl.mjs"),
18181
- nodeRepl: path9.join(cuaNode, "bin", "node_repl"),
18182
- nodeModules: path9.join(cuaNode, "lib", "node_modules"),
18183
- codexCli: path9.join(resources, "codex-cli", "bin", "codex"),
18184
- skyApp: path9.join(environment.HOME ?? os4.homedir(), ".codex", "computer-use", "Codex Computer Use.app"),
18185
- codexHome: path9.join(environment.HOME ?? os4.homedir(), ".codex"),
18186
- browserDesktop: path9.join(cuaNode, "lib", "node_modules", "@oai", "browser-desktop")
18246
+ ...entry,
18247
+ ...sessionId !== void 0 ? { sessionId } : {},
18248
+ ...cwd !== void 0 ? { cwd } : {},
18249
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
18187
18250
  };
18188
18251
  }
18189
- async function sharedRuntimePresent(launch) {
18190
- const present = await Promise.all([launch.node, launch.cuaRepl, launch.nodeRepl].map(isFile));
18191
- return present.every(Boolean);
18192
- }
18193
- async function computerFilesPresent(launch) {
18194
- const present = await Promise.all([isFile(launch.skyApp), isFile(launch.codexCli)]);
18195
- return present.every(Boolean);
18196
- }
18197
- async function browserFilesPresent(launch) {
18198
- return isFile(path9.join(launch.browserDesktop, "package.json"));
18199
- }
18200
- async function discoverGrokComputerUseLaunch(environment = process.env, platform = process.platform) {
18201
- const launch = launchPaths(environment, platform);
18202
- if (!launch || !await sharedRuntimePresent(launch))
18203
- return void 0;
18204
- return launch;
18205
- }
18206
- function tableRange(text, header) {
18207
- const lines = text.split(/\n/);
18208
- let start = -1;
18209
- for (let index = 0; index < lines.length; index += 1) {
18210
- if (lines[index] === header) {
18211
- start = index;
18212
- break;
18252
+ async function jsonlUsageSources(root, maxDepth, signal) {
18253
+ const sources = [];
18254
+ const visit = async (directory, depth) => {
18255
+ signal.throwIfAborted();
18256
+ const entries = await opendir(directory).catch((error53) => {
18257
+ if (error53.code === "ENOENT")
18258
+ return null;
18259
+ throw error53;
18260
+ });
18261
+ if (!entries)
18262
+ return;
18263
+ for await (const entry of entries) {
18264
+ signal.throwIfAborted();
18265
+ const file2 = path5.join(directory, entry.name);
18266
+ if (entry.isDirectory()) {
18267
+ if (depth < maxDepth)
18268
+ await visit(file2, depth + 1);
18269
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
18270
+ const info = await lstat(file2).catch(() => null);
18271
+ if (info?.isFile() && info.size > 0) {
18272
+ sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
18273
+ }
18274
+ }
18213
18275
  }
18214
- }
18215
- if (start < 0)
18216
- return void 0;
18217
- let end = lines.length;
18218
- for (let index = start + 1; index < lines.length; index += 1) {
18219
- const line = lines[index] ?? "";
18220
- if (line.startsWith("[") && line.endsWith("]")) {
18221
- end = index;
18222
- break;
18276
+ };
18277
+ await visit(root, 0);
18278
+ return sources;
18279
+ }
18280
+ async function* jsonlRecords(file2, marker, signal) {
18281
+ const lines = createInterface({
18282
+ input: createReadStream(file2, { encoding: "utf8", signal }),
18283
+ crlfDelay: Infinity
18284
+ });
18285
+ for await (const line of lines) {
18286
+ if (!line.includes(marker))
18287
+ continue;
18288
+ let value;
18289
+ try {
18290
+ value = JSON.parse(line);
18291
+ } catch {
18292
+ continue;
18293
+ }
18294
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
18295
+ yield value;
18223
18296
  }
18224
18297
  }
18225
- return { start, end };
18226
18298
  }
18227
- function removeTables(text, headers) {
18228
- let current = text;
18229
- for (const header of headers) {
18230
- const range = tableRange(current, header);
18231
- if (!range)
18232
- continue;
18233
- const lines = current.split(/\n/);
18234
- lines.splice(range.start, range.end - range.start);
18235
- current = lines.join("\n");
18299
+ function nativeTimeMs(value) {
18300
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
18301
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
18302
+ }
18303
+
18304
+ // dist/usage-statistics.js
18305
+ function isRecord2(value) {
18306
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18307
+ }
18308
+ var USD_TICKS = 1e10;
18309
+ function count3(value) {
18310
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
18311
+ }
18312
+ function grokHome(environment) {
18313
+ return environment.GROK_HOME || path6.join(environment.HOME || os2.homedir(), ".grok");
18314
+ }
18315
+ async function grokSummary(directory) {
18316
+ try {
18317
+ const summary = JSON.parse(await readFile2(path6.join(directory, "summary.json"), "utf8"));
18318
+ if (!isRecord2(summary))
18319
+ return { forkedAt: null };
18320
+ const title = usageSessionTitle(summary.generated_title) ?? usageSessionTitle(summary.session_summary);
18321
+ return {
18322
+ forkedAt: typeof summary.parent_session_id === "string" ? nativeTimeMs(summary.created_at) : null,
18323
+ ...title ? { title } : {}
18324
+ };
18325
+ } catch {
18326
+ return { forkedAt: null };
18236
18327
  }
18237
- return current.replace(/\n{3,}/g, "\n\n");
18238
18328
  }
18239
- function cuaReplEnabledInToml(text) {
18240
- const range = tableRange(text, TABLE);
18241
- if (!range)
18242
- return false;
18243
- const body = text.split(/\n/).slice(range.start, range.end);
18244
- for (const line of body) {
18245
- if (/^enabled\s*=\s*false\b/u.test(line))
18246
- return false;
18247
- if (/^enabled\s*=\s*true\b/u.test(line))
18248
- return true;
18329
+ function grokSession(file2) {
18330
+ const directory = path6.dirname(file2);
18331
+ let cwd;
18332
+ try {
18333
+ cwd = decodeURIComponent(path6.basename(path6.dirname(directory)));
18334
+ } catch {
18335
+ cwd = void 0;
18249
18336
  }
18250
- return true;
18337
+ return { sessionId: path6.basename(directory), cwd };
18251
18338
  }
18252
- function inferredSurfaces(text) {
18253
- if (!cuaReplEnabledInToml(text))
18254
- return { enabled: false, browser: false };
18255
- const range = tableRange(text, ENV_TABLE);
18256
- const body = range ? text.split(/\n/).slice(range.start, range.end).join("\n") : "";
18257
- const literal2 = /^CUA_REPL_ENABLED_SURFACES\s*=\s*(["'])([^"']*)\1\s*(?:#.*)?$/mu.exec(body);
18258
- if (!literal2)
18259
- return { enabled: true, browser: false };
18260
- const surfaces = new Set(literal2[2]?.split(",").map((surface) => surface.trim()));
18261
- return { enabled: surfaces.has("computer"), browser: surfaces.has("browser") };
18339
+ async function readGrokUsage(file2, signal) {
18340
+ const summary = await grokSummary(path6.dirname(file2));
18341
+ const forkedAt = summary.forkedAt;
18342
+ let title = summary.title;
18343
+ const session = grokSession(file2);
18344
+ const entries = [];
18345
+ for await (const line of jsonlRecords(file2, '"sessionUpdate"', signal)) {
18346
+ const params = isRecord2(line.params) ? line.params : {};
18347
+ const update = isRecord2(params.update) ? params.update : {};
18348
+ if (!title && update.sessionUpdate === "user_message_chunk") {
18349
+ title = usageSessionTitle(isRecord2(update.content) ? update.content.text : void 0);
18350
+ continue;
18351
+ }
18352
+ const usage = isRecord2(update.usage) ? update.usage : {};
18353
+ if (update.sessionUpdate !== "turn_completed" || typeof update.prompt_id !== "string")
18354
+ continue;
18355
+ const meta3 = isRecord2(params._meta) ? params._meta : {};
18356
+ const at = nativeTimeMs(meta3.agentTimestampMs) ?? (typeof line.timestamp === "number" ? nativeTimeMs(line.timestamp * 1e3) : null);
18357
+ if (at === null || forkedAt !== null && at <= forkedAt)
18358
+ continue;
18359
+ for (const [model2, value] of Object.entries(isRecord2(usage.modelUsage) ? usage.modelUsage : {})) {
18360
+ if (!isRecord2(value))
18361
+ continue;
18362
+ const input = count3(value.inputTokens);
18363
+ const output = count3(value.outputTokens);
18364
+ const cached2 = count3(value.cachedReadTokens);
18365
+ const written = count3(value.cacheCreationTokens ?? 0);
18366
+ const reasoning = count3(value.reasoningTokens);
18367
+ const ticks = count3(value.costUsdTicks);
18368
+ if (input === null || output === null || value.totalTokens !== input + output)
18369
+ continue;
18370
+ const cacheKnown = cached2 !== null && cached2 <= input && written === 0;
18371
+ entries.push(withUsageSession({
18372
+ id: `${update.prompt_id}:${model2}`,
18373
+ occurredAtMs: at,
18374
+ model: model2,
18375
+ inputTokens: input,
18376
+ ...cacheKnown ? { cachedInputTokens: cached2, cacheWriteInputTokens: 0 } : {},
18377
+ outputTokens: output,
18378
+ ...reasoning !== null && reasoning <= output ? { reasoningOutputTokens: reasoning } : {},
18379
+ // A turn Grok marks incomplete has no cost of its own; it counts as free rather
18380
+ // than as a model without a price.
18381
+ ...ticks !== null ? { costUsd: ticks / USD_TICKS } : usage.usageIsIncomplete === true ? { costUsd: 0 } : {}
18382
+ }, { ...session, ...title ? { title } : {} }));
18383
+ }
18384
+ }
18385
+ return entries;
18386
+ }
18387
+ function createGrokUsageStatistics(environment) {
18388
+ return Object.freeze({
18389
+ // sessions/<url-encoded cwd>/<session>/updates.jsonl; subagents are sessions of their own.
18390
+ listSources: async (signal) => (await jsonlUsageSources(path6.join(grokHome(environment), "sessions"), 2, signal)).filter((source) => path6.basename(source.id) === "updates.jsonl"),
18391
+ readSource: (id, signal) => readGrokUsage(id, signal)
18392
+ });
18262
18393
  }
18263
- function stanza(launch, state) {
18264
- const trusted = `${launch.codexHome}:${launch.nodeModules}`;
18265
- const services = {};
18266
- if (state.browser)
18267
- services.browser = "@oai/browser-desktop/service";
18268
- if (state.enabled)
18269
- services.sky = "@oai/sky/service";
18270
- const surfaces = [state.browser ? "browser" : "", state.enabled ? "computer" : ""].filter(Boolean).join(",");
18271
- const backends = state.browser ? 'BROWSER_USE_AVAILABLE_BACKENDS = "iab"\n' : "";
18272
- const active = state.enabled || state.browser;
18273
- return `${TABLE}
18274
- command = ${JSON.stringify(launch.node)}
18275
- args = [${JSON.stringify(launch.cuaRepl)}]
18276
- enabled = ${active ? "true" : "false"}
18277
- startup_timeout_sec = 120
18278
18394
 
18279
- ${ENV_TABLE}
18280
- NODE_REPL_TRUSTED_SERVICES = ${JSON.stringify(JSON.stringify(services))}
18281
- NODE_REPL_TRUSTED_CODE_PATHS = ${JSON.stringify(trusted)}
18282
- NODE_REPL_NODE_PATH = ${JSON.stringify(launch.node)}
18283
- CODEX_HOME = ${JSON.stringify(launch.codexHome)}
18284
- CUA_REPL_NODE_REPL_PATH = ${JSON.stringify(launch.nodeRepl)}
18285
- NODE_REPL_NODE_MODULE_DIRS = ${JSON.stringify(launch.nodeModules)}
18286
- NODE_REPL_NATIVE_PIPE_CONNECT_TIMEOUT_MS = "1000"
18287
- SKY_CUA_SERVICE_PATH = ${JSON.stringify(launch.skyApp)}
18288
- CODEX_CLI_PATH = ${JSON.stringify(launch.codexCli)}
18289
- ${backends}CUA_REPL_ENABLED_SURFACES = ${JSON.stringify(surfaces)}
18290
- `;
18395
+ // dist/grok-commands.js
18396
+ var grokCommandCatalog = harnessCommandCatalogSchema.parse({
18397
+ commands: [
18398
+ {
18399
+ id: "grok.compact",
18400
+ invocation: "/compact",
18401
+ localizations: { "zh-CN": { label: "压缩上下文", description: "压缩当前对话上下文" } },
18402
+ label: "Compact context",
18403
+ description: "Compact the current conversation context",
18404
+ argumentMode: "text"
18405
+ },
18406
+ {
18407
+ id: "grok.desktop-goal",
18408
+ invocation: "/goal",
18409
+ label: "Goal",
18410
+ description: "Start a native goal through Desktop Goal mode",
18411
+ argumentMode: "text"
18412
+ },
18413
+ {
18414
+ id: "grok.goal",
18415
+ invocation: "/grok-goal",
18416
+ label: "Grok goal",
18417
+ description: "Set an objective [--budget tokens], or status / pause / resume / clear",
18418
+ localizations: {
18419
+ "zh-CN": {
18420
+ label: "Grok 目标",
18421
+ description: "设置原生目标与可选 token 预算,或 status / pause / resume / clear"
18422
+ }
18423
+ },
18424
+ argumentMode: "text"
18425
+ },
18426
+ {
18427
+ id: "grok.loop",
18428
+ invocation: "/loop",
18429
+ label: "Loop",
18430
+ description: "Create a native timed Loop; include the interval and task",
18431
+ argumentMode: "text"
18432
+ }
18433
+ ]
18434
+ });
18435
+ var GROK_GOAL_CONTROL_PATTERN = /^\/goal(?:\s+(?:status|pause|clear|resume))?\s*$/u;
18436
+ function isGrokGoalControlPrompt(value) {
18437
+ return GROK_GOAL_CONTROL_PATTERN.test(value.trim());
18291
18438
  }
18292
- async function readPreference(environment) {
18293
- try {
18294
- const document = JSON.parse(await readFile4(path9.join(dataDirectory(environment), PREFERENCE_FILE), "utf8"));
18439
+ function grokGoalPrompt(arguments_) {
18440
+ if (arguments_ && (Object.keys(arguments_).some((key) => key !== "text") || arguments_.text !== void 0 && typeof arguments_.text !== "string")) {
18295
18441
  return {
18296
- ...typeof document.enabled === "boolean" ? { enabled: document.enabled } : {},
18297
- ...typeof document.browser === "boolean" ? { browser: document.browser } : {},
18298
- ...typeof document.applyError === "string" && document.applyError ? { applyError: document.applyError } : {}
18442
+ ok: false,
18443
+ error: {
18444
+ code: "invalidRequest",
18445
+ message: "Grok goal accepts only a text argument",
18446
+ retryable: false
18447
+ }
18299
18448
  };
18300
- } catch (error53) {
18301
- if (isNotFound(error53))
18302
- return void 0;
18303
- throw new GrokComputerUseError("Could not read Grok Computer Use settings");
18304
18449
  }
18450
+ const text = typeof arguments_?.text === "string" ? arguments_.text.trim() : "";
18451
+ return { ok: true, value: text ? `/goal ${text}` : "/goal" };
18305
18452
  }
18306
- async function writePreference(environment, state) {
18307
- const document = {
18308
- ...typeof state.enabled === "boolean" ? { enabled: state.enabled } : {},
18309
- ...typeof state.browser === "boolean" ? { browser: state.browser } : {},
18310
- ...state.applyError ? { applyError: state.applyError } : {}
18311
- };
18312
- await writeAtomically(path9.join(dataDirectory(environment), PREFERENCE_FILE), `${JSON.stringify(document)}
18313
- `);
18453
+
18454
+ // dist/grok-adapter.js
18455
+ import { randomUUID as randomUUID2 } from "node:crypto";
18456
+
18457
+ // dist/grok-text-item-id.js
18458
+ import { createHash } from "node:crypto";
18459
+ function grokTextItemId(sessionId, turnIndex, kind, ordinal) {
18460
+ const identity2 = JSON.stringify([sessionId, turnIndex, kind, ordinal]);
18461
+ return hostItemIdSchema.parse(`grok-text-${createHash("sha256").update(identity2).digest("hex")}`);
18314
18462
  }
18315
- async function readGrokConfig(environment) {
18316
- try {
18317
- return await readFile4(path9.join(grokHome2(environment), "config.toml"), "utf8");
18318
- } catch (error53) {
18319
- if (isNotFound(error53))
18320
- return "";
18321
- throw new GrokComputerUseError("Could not read Grok config");
18463
+
18464
+ // dist/grok-stop-diagnostic.js
18465
+ function isRecord3(value) {
18466
+ return typeof value === "object" && value !== null && Array.isArray(value) === false;
18467
+ }
18468
+ function collectText(value, into, depth = 0) {
18469
+ if (depth > 4)
18470
+ return;
18471
+ if (typeof value === "string") {
18472
+ const text = value.trim();
18473
+ if (text.length > 0 && !into.includes(text))
18474
+ into.push(text);
18475
+ return;
18476
+ }
18477
+ if (Array.isArray(value)) {
18478
+ for (const entry of value)
18479
+ collectText(entry, into, depth + 1);
18480
+ return;
18481
+ }
18482
+ if (!isRecord3(value))
18483
+ return;
18484
+ for (const key of [
18485
+ "message",
18486
+ "error",
18487
+ "reason",
18488
+ "detail",
18489
+ "details",
18490
+ "diagnostic",
18491
+ "cause",
18492
+ "err"
18493
+ ]) {
18494
+ if (Object.hasOwn(value, key))
18495
+ collectText(value[key], into, depth + 1);
18322
18496
  }
18323
18497
  }
18324
- async function writeGrokConfig(environment, text) {
18325
- await writeAtomically(path9.join(grokHome2(environment), "config.toml"), text.endsWith("\n") ? text : `${text}
18326
- `);
18498
+ function grokStopDetail(source, stopReason) {
18499
+ const parts = [];
18500
+ collectText(source, parts);
18501
+ const useful = parts.filter((part) => part !== stopReason && part.toLowerCase() !== "error" && part.length > 1);
18502
+ return useful.length > 0 ? useful.join(": ") : void 0;
18327
18503
  }
18328
- async function currentState(environment, preference) {
18329
- const resolved = preference ?? await readPreference(environment);
18330
- const inferred = resolved?.enabled === void 0 ? inferredSurfaces(await readGrokConfig(environment)) : void 0;
18504
+ function grokTurnStopError(stopReason, source) {
18505
+ const detail = grokStopDetail(source, stopReason);
18506
+ const diagnostic = source !== void 0 && source !== null ? JSON.stringify(source) : void 0;
18331
18507
  return {
18332
- enabled: resolved?.enabled ?? inferred?.enabled ?? false,
18333
- browser: resolved ? resolved.browser ?? false : inferred?.browser ?? false,
18334
- ...resolved?.applyError ? { applyError: resolved.applyError } : {}
18508
+ code: "nativeFailure",
18509
+ message: detail ? `Grok stopped the Turn: ${stopReason}: ${detail}` : `Grok stopped the Turn: ${stopReason}`,
18510
+ retryable: stopReason === "max_tokens" || stopReason === "max_turn_requests",
18511
+ ...diagnostic && diagnostic !== "{}" && diagnostic !== "null" ? { diagnostic } : {}
18335
18512
  };
18336
18513
  }
18337
- async function surfaceFiles(launch) {
18338
- if (!launch)
18339
- return { computer: false, browser: false };
18340
- const [computer, browser] = await Promise.all([
18341
- computerFilesPresent(launch),
18342
- browserFilesPresent(launch)
18343
- ]);
18344
- return { computer, browser };
18514
+ function grokPromptStopError(response) {
18515
+ return grokTurnStopError(response.stopReason, response._meta ?? void 0);
18345
18516
  }
18346
- async function writeConfigForState(state, launch, files, environment) {
18347
- const current = await readGrokConfig(environment);
18348
- const range = tableRange(current, TABLE);
18349
- const effective = {
18350
- enabled: state.enabled && files.computer,
18351
- browser: state.browser && files.browser && GROK_BROWSER_BINDING_SUPPORTED
18352
- };
18353
- if (!effective.enabled && !effective.browser && !range)
18354
- return;
18355
- if (!launch) {
18356
- if (!range)
18357
- return;
18358
- const lines = current.split(/\n/);
18359
- const body = lines.slice(range.start, range.end);
18360
- const replaced = body.map((line) => /^enabled\s*=/u.test(line) ? "enabled = false" : line);
18361
- if (!replaced.some((line) => /^enabled\s*=/u.test(line))) {
18362
- replaced.splice(1, 0, "enabled = false");
18363
- }
18364
- lines.splice(range.start, range.end - range.start, ...replaced);
18365
- await writeGrokConfig(environment, lines.join("\n"));
18366
- return;
18367
- }
18368
- const stripped = removeTables(current, [ENV_TABLE, TABLE]).replace(/\s+$/u, "\n");
18369
- await writeGrokConfig(environment, `${stripped.trimEnd()}
18370
18517
 
18371
- ${stanza(launch, effective)}`);
18372
- }
18373
- async function applyGrokComputerUsePreference(environment = process.env, platform = process.platform) {
18374
- await withGrokComputerUseLock(dataDirectory(environment), grokHome2(environment), async () => {
18375
- const preference = await readPreference(environment);
18376
- if (preference === void 0)
18377
- return;
18378
- const launch = await discoverGrokComputerUseLaunch(environment, platform);
18379
- const files = await surfaceFiles(launch);
18380
- const state = await currentState(environment, preference);
18381
- try {
18382
- await writeConfigForState(state, launch, files, environment);
18383
- if (state.applyError)
18384
- await writePreference(environment, { enabled: state.enabled, browser: state.browser });
18385
- } catch (error53) {
18386
- const applyError = error53 instanceof GrokComputerUseError ? error53.message : APPLY_FAILED;
18387
- await writePreference(environment, {
18388
- enabled: state.enabled,
18389
- browser: state.browser,
18390
- applyError
18391
- }).catch(() => void 0);
18392
- throw error53 instanceof GrokComputerUseError ? error53 : new GrokComputerUseError(APPLY_FAILED);
18393
- }
18518
+ // dist/grok-agent-messages.js
18519
+ function settledGrokAgentMessages(persisted, completedItems) {
18520
+ const messages = persisted.flatMap(({ item }) => item.type === "agentMessage" ? [item] : []);
18521
+ const completed = new Set(completedItems.map(({ item }) => item.itemId));
18522
+ return messages.flatMap((item, index) => {
18523
+ const phase = index === messages.length - 1 ? "final_answer" : "commentary";
18524
+ if (completed.has(item.itemId))
18525
+ return [];
18526
+ return [{ ...item, phase }];
18394
18527
  });
18395
18528
  }
18396
18529
 
18397
- // ../../harness-adapter/dist/approval.js
18398
- function invalidRequest(message) {
18399
- return { code: "invalidRequest", message, retryable: false };
18400
- }
18401
- function validateHostApprovalResponse(interaction, response) {
18402
- return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
18530
+ // dist/grok-credential-export.js
18531
+ import { createHash as createHash2 } from "node:crypto";
18532
+ import { readFile as readFile3 } from "node:fs/promises";
18533
+ import os3 from "node:os";
18534
+ import path7 from "node:path";
18535
+ async function readGrokCredentials(environment) {
18536
+ if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((v) => v?.trim()))
18537
+ return [];
18538
+ try {
18539
+ const home = environment.GROK_HOME ?? path7.join(environment.HOME ?? os3.homedir(), ".grok");
18540
+ const auth = JSON.parse(await readFile3(path7.join(home, "auth.json"), "utf8"));
18541
+ const client2 = "b1a00492-073a-47ea-816f-4c329264a828";
18542
+ const entry = auth[`https://auth.x.ai::${client2}`] ?? auth["https://auth.x.ai"];
18543
+ if (!entry || entry.oidc_issuer !== "https://auth.x.ai" || entry.oidc_client_id !== client2)
18544
+ return [];
18545
+ if (![entry.key, entry.refresh_token, entry.user_id].every((v) => typeof v === "string" && v.length))
18546
+ return [];
18547
+ const expires = Date.parse(entry.expires_at);
18548
+ if (!Number.isFinite(expires))
18549
+ return [];
18550
+ return [
18551
+ {
18552
+ source: {
18553
+ id: `grok:${createHash2("sha256").update(entry.user_id).digest("hex")}`,
18554
+ harnessId: "grok",
18555
+ provider: "xai",
18556
+ label: typeof entry.email === "string" && entry.email ? entry.email : "Grok"
18557
+ },
18558
+ oauth: { access: entry.key, refresh: entry.refresh_token, expires: expires - 3e5 }
18559
+ }
18560
+ ];
18561
+ } catch {
18562
+ return [];
18563
+ }
18403
18564
  }
18404
18565
 
18405
- // ../../harness-adapter/dist/question.js
18406
- function invalidRequest2(message) {
18407
- return { code: "invalidRequest", message, retryable: false };
18408
- }
18409
- function validateHostQuestionResponse(interaction, response) {
18410
- const questionIds = new Set(interaction.questions.map(({ id }) => id));
18411
- if (response.cancelled) {
18412
- return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
18413
- }
18414
- for (const answerId of Object.keys(response.answers)) {
18415
- if (!questionIds.has(answerId)) {
18416
- return invalidRequest2("Question Response contains an unknown Question ID");
18417
- }
18418
- }
18419
- for (const question of interaction.questions) {
18420
- const answers = response.answers[question.id] ?? [];
18421
- if (new Set(answers).size !== answers.length) {
18422
- return invalidRequest2("Question Response contains duplicate answers");
18423
- }
18424
- if (!question.optional && answers.length === 0) {
18425
- return invalidRequest2("Question Response omits a required answer");
18426
- }
18427
- if (question.type === "text") {
18428
- if (answers.length > 1) {
18429
- return invalidRequest2("Text Question accepts at most one answer");
18566
+ // dist/grok-adapter.js
18567
+ import path22 from "node:path";
18568
+
18569
+ // ../../harness-plugin-files/dist/grok-computer-use.js
18570
+ import { randomUUID } from "node:crypto";
18571
+ import { access, mkdir as mkdir2, readFile as readFile4, rename, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
18572
+ import os4 from "node:os";
18573
+ import path9 from "node:path";
18574
+
18575
+ // ../../harness-plugin-files/dist/grok-computer-use-lock.js
18576
+ import { mkdir, rm as rm2 } from "node:fs/promises";
18577
+ import path8 from "node:path";
18578
+ import { setTimeout as delay2 } from "node:timers/promises";
18579
+ async function withGrokComputerUseLock(dataDirectory2, grokHome4, operation) {
18580
+ const locks = [
18581
+ .../* @__PURE__ */ new Set([
18582
+ path8.join(dataDirectory2, ".grok-computer-use.lock"),
18583
+ path8.join(grokHome4, ".codexhost-cua.lock")
18584
+ ])
18585
+ ].sort();
18586
+ const acquired = [];
18587
+ const deadline = Date.now() + 5e3;
18588
+ try {
18589
+ for (const lock of locks) {
18590
+ await mkdir(path8.dirname(lock), { recursive: true, mode: 448 });
18591
+ for (; ; ) {
18592
+ try {
18593
+ await mkdir(lock, { mode: 448 });
18594
+ acquired.push(lock);
18595
+ break;
18596
+ } catch (error53) {
18597
+ if (error53.code !== "EEXIST")
18598
+ throw error53;
18599
+ if (Date.now() >= deadline)
18600
+ throw new Error("Grok Computer Use settings are locked");
18601
+ await delay2(25);
18602
+ }
18430
18603
  }
18431
- continue;
18432
- }
18433
- if (!question.multiple && answers.length > 1) {
18434
- return invalidRequest2("Single-choice Question accepts at most one answer");
18435
- }
18436
- const declared = new Set(question.options.map(({ value }) => value));
18437
- if (!question.allowOther && answers.some((answer) => !declared.has(answer))) {
18438
- return invalidRequest2("Question Response contains an undeclared choice");
18439
18604
  }
18605
+ return await operation();
18606
+ } finally {
18607
+ for (const lock of acquired.reverse())
18608
+ await rm2(lock, { recursive: true });
18440
18609
  }
18441
- return null;
18442
18610
  }
18443
18611
 
18444
- // ../../harness-adapter/dist/output-channel.js
18445
- var HarnessOutputChannel = class {
18446
- outputs;
18447
- #consumerCreated = false;
18448
- #ended = false;
18449
- #pending = [];
18450
- #values = [];
18451
- constructor() {
18452
- this.outputs = {
18453
- [Symbol.asyncIterator]: () => {
18454
- if (this.#consumerCreated) {
18455
- throw new Error("Harness outputs allow only one consumer");
18456
- }
18457
- this.#consumerCreated = true;
18458
- return {
18459
- next: () => this.#next()
18460
- };
18461
- }
18462
- };
18612
+ // ../../harness-plugin-files/dist/grok-computer-use.js
18613
+ var GROK_BROWSER_BINDING_SUPPORTED = false;
18614
+ var PREFERENCE_FILE = "grok-computer-use.json";
18615
+ var TABLE = "[mcp_servers.cua_repl]";
18616
+ var ENV_TABLE = "[mcp_servers.cua_repl.env]";
18617
+ var APPLY_FAILED = "Could not apply Grok Computer Use settings to Grok config.";
18618
+ var GrokComputerUseError = class extends Error {
18619
+ constructor(message) {
18620
+ super(message);
18621
+ this.name = "GrokComputerUseError";
18463
18622
  }
18464
- emit(value) {
18465
- if (this.#ended)
18466
- return false;
18467
- const resolve = this.#pending.shift();
18468
- if (resolve)
18469
- resolve({ done: false, value });
18470
- else
18471
- this.#values.push(value);
18623
+ };
18624
+ function dataDirectory(environment) {
18625
+ return environment.CODEXHOST_DATA_DIR ? path9.resolve(environment.CODEXHOST_DATA_DIR) : path9.join(os4.homedir(), ".codexhost");
18626
+ }
18627
+ function grokHome2(environment) {
18628
+ return environment.GROK_HOME ? path9.resolve(environment.GROK_HOME) : path9.join(environment.HOME ?? os4.homedir(), ".grok");
18629
+ }
18630
+ function chatgptApp(environment, platform) {
18631
+ if (environment.CODEXHOST_CHATGPT_APP)
18632
+ return path9.resolve(environment.CODEXHOST_CHATGPT_APP);
18633
+ if (platform === "darwin")
18634
+ return "/Applications/ChatGPT.app";
18635
+ return void 0;
18636
+ }
18637
+ async function isFile(target2) {
18638
+ try {
18639
+ await access(target2);
18472
18640
  return true;
18641
+ } catch {
18642
+ return false;
18473
18643
  }
18474
- end() {
18475
- if (this.#ended)
18476
- return;
18477
- this.#ended = true;
18478
- if (this.#values.length !== 0)
18479
- return;
18480
- for (const resolve of this.#pending.splice(0))
18481
- resolve({ done: true, value: void 0 });
18482
- }
18483
- #next() {
18484
- const value = this.#values.shift();
18485
- if (value !== void 0)
18486
- return Promise.resolve({ done: false, value });
18487
- if (this.#ended)
18488
- return Promise.resolve({ done: true, value: void 0 });
18489
- return new Promise((resolve) => this.#pending.push(resolve));
18644
+ }
18645
+ function isNotFound(error53) {
18646
+ return Boolean(error53 && typeof error53 === "object" && "code" in error53 && error53.code === "ENOENT");
18647
+ }
18648
+ async function writeAtomically(file2, content) {
18649
+ await mkdir2(path9.dirname(file2), { recursive: true, mode: 448 });
18650
+ const temporary = `${file2}.${randomUUID()}.tmp`;
18651
+ try {
18652
+ await writeFile2(temporary, content, { mode: 384, flag: "wx" });
18653
+ await rename(temporary, file2);
18654
+ } finally {
18655
+ await rm3(temporary, { force: true });
18490
18656
  }
18491
- };
18492
-
18493
- // ../../harness-adapter/dist/diagnostics.js
18494
- var DIAGNOSTIC_TAIL_MAX_LENGTH = 8e3;
18495
- var SENSITIVE_VALUE_PATTERN = /(api[_-]?key|access[_-]?token|auth(?:orization)?|password|secret)(\s*[:=]\s*)([^\s,;]+)/giu;
18496
- var BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]+/giu;
18497
- function sanitizeDiagnosticTail(value) {
18498
- const redacted = value.replace(BEARER_PATTERN, "Bearer [redacted]").replace(SENSITIVE_VALUE_PATTERN, "$1$2[redacted]");
18499
- return redacted.length <= DIAGNOSTIC_TAIL_MAX_LENGTH ? redacted : redacted.slice(-DIAGNOSTIC_TAIL_MAX_LENGTH);
18500
18657
  }
18501
-
18502
- // ../../harness-adapter/dist/steer.js
18503
- function unsupportedSteer(harnessLabel) {
18658
+ function launchPaths(environment, platform) {
18659
+ const app = chatgptApp(environment, platform);
18660
+ if (!app)
18661
+ return void 0;
18662
+ const resources = path9.join(app, "Contents", "Resources");
18663
+ const cuaNode = path9.join(resources, "cua_node");
18504
18664
  return {
18505
- ok: false,
18506
- error: {
18507
- code: "unsupported",
18508
- message: `${harnessLabel} cannot steer an active Turn natively`,
18509
- retryable: false
18510
- }
18665
+ node: path9.join(cuaNode, "bin", "node"),
18666
+ cuaRepl: path9.join(cuaNode, "lib", "node_modules", "@oai", "cua-repl", "bin", "cua-repl.mjs"),
18667
+ nodeRepl: path9.join(cuaNode, "bin", "node_repl"),
18668
+ nodeModules: path9.join(cuaNode, "lib", "node_modules"),
18669
+ codexCli: path9.join(resources, "codex-cli", "bin", "codex"),
18670
+ skyApp: path9.join(environment.HOME ?? os4.homedir(), ".codex", "computer-use", "Codex Computer Use.app"),
18671
+ codexHome: path9.join(environment.HOME ?? os4.homedir(), ".codex"),
18672
+ browserDesktop: path9.join(cuaNode, "lib", "node_modules", "@oai", "browser-desktop")
18511
18673
  };
18512
18674
  }
18513
-
18514
- // ../../harness-adapter/dist/usage.js
18515
- var tokenFields = [
18516
- "inputTokens",
18517
- "cachedInputTokens",
18518
- "cacheWriteInputTokens",
18519
- "outputTokens",
18520
- "reasoningOutputTokens",
18521
- "totalTokens",
18522
- "contextWindowTokens",
18523
- "contextUsedTokens"
18524
- ];
18525
- var safeIntegerFields = [
18526
- "planFiveHourResetsAtUnix",
18527
- "planSevenDayResetsAtUnix",
18528
- "timeToFirstOutputMs"
18529
- ];
18530
- var percentFields = [
18531
- "cacheHitRatePercent",
18532
- "sessionCacheHitRatePercent",
18533
- "planFiveHourUsedPercent",
18534
- "planSevenDayUsedPercent"
18535
- ];
18536
- var usageFields = /* @__PURE__ */ new Set([
18537
- ...tokenFields,
18538
- ...safeIntegerFields,
18539
- ...percentFields,
18540
- "sessionCacheUsage",
18541
- "composerIndicators",
18542
- "totalCostUsd",
18543
- "totalCredits",
18544
- "contextUsagePercent",
18545
- "outputTokensPerSecond",
18546
- "apiOutputTokensPerSecond",
18547
- "costSource",
18548
- "unpricedModels"
18549
- ]);
18550
- function isRecord3(value) {
18551
- return typeof value === "object" && value !== null && !Array.isArray(value);
18675
+ async function sharedRuntimePresent(launch) {
18676
+ const present = await Promise.all([launch.node, launch.cuaRepl, launch.nodeRepl].map(isFile));
18677
+ return present.every(Boolean);
18552
18678
  }
18553
- function parseHostUsage(value) {
18554
- if (!isRecord3(value))
18555
- throw new Error("Harness Usage must be an object");
18556
- const keys = Object.keys(value);
18557
- if (keys.length === 0)
18558
- throw new Error("Harness Usage must contain a reliable field");
18559
- for (const key of keys) {
18560
- if (!usageFields.has(key)) {
18561
- throw new Error(`Harness Usage contains unknown field '${key}'`);
18562
- }
18563
- }
18564
- const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
18565
- for (const field2 of [
18566
- "totalCredits",
18567
- "contextUsagePercent",
18568
- "apiOutputTokensPerSecond"
18569
- ]) {
18570
- const candidate = value[field2];
18571
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
18572
- throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
18573
- }
18574
- }
18575
- for (const field2 of tokenFields) {
18576
- const candidate = value[field2];
18577
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
18578
- throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
18579
- }
18580
- }
18581
- for (const field2 of safeIntegerFields) {
18582
- const candidate = value[field2];
18583
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
18584
- throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
18585
- }
18586
- }
18587
- if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
18588
- throw new Error("Harness Usage 'outputTokensPerSecond' must be a finite non-negative number");
18589
- }
18590
- if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
18591
- throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
18592
- }
18593
- for (const field2 of percentFields) {
18594
- const candidate = value[field2];
18595
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
18596
- throw new Error(`Harness Usage '${field2}' must be between 0 and 100`);
18679
+ async function computerFilesPresent(launch) {
18680
+ const present = await Promise.all([isFile(launch.skyApp), isFile(launch.codexCli)]);
18681
+ return present.every(Boolean);
18682
+ }
18683
+ async function browserFilesPresent(launch) {
18684
+ return isFile(path9.join(launch.browserDesktop, "package.json"));
18685
+ }
18686
+ async function discoverGrokComputerUseLaunch(environment = process.env, platform = process.platform) {
18687
+ const launch = launchPaths(environment, platform);
18688
+ if (!launch || !await sharedRuntimePresent(launch))
18689
+ return void 0;
18690
+ return launch;
18691
+ }
18692
+ function tableRange(text, header) {
18693
+ const lines = text.split(/\n/);
18694
+ let start = -1;
18695
+ for (let index = 0; index < lines.length; index += 1) {
18696
+ if (lines[index] === header) {
18697
+ start = index;
18698
+ break;
18597
18699
  }
18598
18700
  }
18599
- if (value.sessionCacheUsage !== void 0) {
18600
- const totals2 = value.sessionCacheUsage;
18601
- if (!isRecord3(totals2) || Object.keys(totals2).some((key) => key !== "inputTokens" && key !== "cachedInputTokens") || typeof totals2.inputTokens !== "number" || !Number.isSafeInteger(totals2.inputTokens) || totals2.inputTokens < 0 || typeof totals2.cachedInputTokens !== "number" || !Number.isSafeInteger(totals2.cachedInputTokens) || totals2.cachedInputTokens < 0 || totals2.cachedInputTokens > totals2.inputTokens) {
18602
- throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
18701
+ if (start < 0)
18702
+ return void 0;
18703
+ let end = lines.length;
18704
+ for (let index = start + 1; index < lines.length; index += 1) {
18705
+ const line = lines[index] ?? "";
18706
+ if (line.startsWith("[") && line.endsWith("]")) {
18707
+ end = index;
18708
+ break;
18603
18709
  }
18604
18710
  }
18605
- const hasContextUsed = value.contextUsedTokens !== void 0;
18606
- const hasContextWindow = value.contextWindowTokens !== void 0;
18607
- if (hasContextUsed !== hasContextWindow) {
18608
- throw new Error("Harness Usage context fields must be provided together");
18609
- }
18610
- if (hasContextWindow && value.contextWindowTokens === 0) {
18611
- throw new Error("Harness Usage 'contextWindowTokens' must be greater than zero");
18612
- }
18613
- if (value.planFiveHourResetsAtUnix !== void 0 && value.planFiveHourUsedPercent === void 0) {
18614
- throw new Error("Harness Usage 'planFiveHourResetsAtUnix' must be provided with 'planFiveHourUsedPercent'");
18711
+ return { start, end };
18712
+ }
18713
+ function removeTables(text, headers) {
18714
+ let current = text;
18715
+ for (const header of headers) {
18716
+ const range = tableRange(current, header);
18717
+ if (!range)
18718
+ continue;
18719
+ const lines = current.split(/\n/);
18720
+ lines.splice(range.start, range.end - range.start);
18721
+ current = lines.join("\n");
18615
18722
  }
18616
- if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
18617
- throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
18723
+ return current.replace(/\n{3,}/g, "\n\n");
18724
+ }
18725
+ function cuaReplEnabledInToml(text) {
18726
+ const range = tableRange(text, TABLE);
18727
+ if (!range)
18728
+ return false;
18729
+ const body = text.split(/\n/).slice(range.start, range.end);
18730
+ for (const line of body) {
18731
+ if (/^enabled\s*=\s*false\b/u.test(line))
18732
+ return false;
18733
+ if (/^enabled\s*=\s*true\b/u.test(line))
18734
+ return true;
18618
18735
  }
18619
- if (value.costSource !== void 0) {
18620
- if (value.costSource !== "publicPrice" && value.costSource !== "native") {
18621
- throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
18622
- }
18623
- if (value.totalCostUsd === void 0) {
18624
- throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
18625
- }
18736
+ return true;
18737
+ }
18738
+ function inferredSurfaces(text) {
18739
+ if (!cuaReplEnabledInToml(text))
18740
+ return { enabled: false, browser: false };
18741
+ const range = tableRange(text, ENV_TABLE);
18742
+ const body = range ? text.split(/\n/).slice(range.start, range.end).join("\n") : "";
18743
+ const literal2 = /^CUA_REPL_ENABLED_SURFACES\s*=\s*(["'])([^"']*)\1\s*(?:#.*)?$/mu.exec(body);
18744
+ if (!literal2)
18745
+ return { enabled: true, browser: false };
18746
+ const surfaces = new Set(literal2[2]?.split(",").map((surface) => surface.trim()));
18747
+ return { enabled: surfaces.has("computer"), browser: surfaces.has("browser") };
18748
+ }
18749
+ function stanza(launch, state) {
18750
+ const trusted = `${launch.codexHome}:${launch.nodeModules}`;
18751
+ const services = {};
18752
+ if (state.browser)
18753
+ services.browser = "@oai/browser-desktop/service";
18754
+ if (state.enabled)
18755
+ services.sky = "@oai/sky/service";
18756
+ const surfaces = [state.browser ? "browser" : "", state.enabled ? "computer" : ""].filter(Boolean).join(",");
18757
+ const backends = state.browser ? 'BROWSER_USE_AVAILABLE_BACKENDS = "iab"\n' : "";
18758
+ const active = state.enabled || state.browser;
18759
+ return `${TABLE}
18760
+ command = ${JSON.stringify(launch.node)}
18761
+ args = [${JSON.stringify(launch.cuaRepl)}]
18762
+ enabled = ${active ? "true" : "false"}
18763
+ startup_timeout_sec = 120
18764
+
18765
+ ${ENV_TABLE}
18766
+ NODE_REPL_TRUSTED_SERVICES = ${JSON.stringify(JSON.stringify(services))}
18767
+ NODE_REPL_TRUSTED_CODE_PATHS = ${JSON.stringify(trusted)}
18768
+ NODE_REPL_NODE_PATH = ${JSON.stringify(launch.node)}
18769
+ CODEX_HOME = ${JSON.stringify(launch.codexHome)}
18770
+ CUA_REPL_NODE_REPL_PATH = ${JSON.stringify(launch.nodeRepl)}
18771
+ NODE_REPL_NODE_MODULE_DIRS = ${JSON.stringify(launch.nodeModules)}
18772
+ NODE_REPL_NATIVE_PIPE_CONNECT_TIMEOUT_MS = "1000"
18773
+ SKY_CUA_SERVICE_PATH = ${JSON.stringify(launch.skyApp)}
18774
+ CODEX_CLI_PATH = ${JSON.stringify(launch.codexCli)}
18775
+ ${backends}CUA_REPL_ENABLED_SURFACES = ${JSON.stringify(surfaces)}
18776
+ `;
18777
+ }
18778
+ async function readPreference(environment) {
18779
+ try {
18780
+ const document = JSON.parse(await readFile4(path9.join(dataDirectory(environment), PREFERENCE_FILE), "utf8"));
18781
+ return {
18782
+ ...typeof document.enabled === "boolean" ? { enabled: document.enabled } : {},
18783
+ ...typeof document.browser === "boolean" ? { browser: document.browser } : {},
18784
+ ...typeof document.applyError === "string" && document.applyError ? { applyError: document.applyError } : {}
18785
+ };
18786
+ } catch (error53) {
18787
+ if (isNotFound(error53))
18788
+ return void 0;
18789
+ throw new GrokComputerUseError("Could not read Grok Computer Use settings");
18626
18790
  }
18627
- if (value.unpricedModels !== void 0) {
18628
- const models = value.unpricedModels;
18629
- if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
18630
- throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
18631
- }
18632
- if (value.costSource !== "publicPrice") {
18633
- throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
18634
- }
18635
- return { ...value, ...indicators, unpricedModels: [...models] };
18791
+ }
18792
+ async function writePreference(environment, state) {
18793
+ const document = {
18794
+ ...typeof state.enabled === "boolean" ? { enabled: state.enabled } : {},
18795
+ ...typeof state.browser === "boolean" ? { browser: state.browser } : {},
18796
+ ...state.applyError ? { applyError: state.applyError } : {}
18797
+ };
18798
+ await writeAtomically(path9.join(dataDirectory(environment), PREFERENCE_FILE), `${JSON.stringify(document)}
18799
+ `);
18800
+ }
18801
+ async function readGrokConfig(environment) {
18802
+ try {
18803
+ return await readFile4(path9.join(grokHome2(environment), "config.toml"), "utf8");
18804
+ } catch (error53) {
18805
+ if (isNotFound(error53))
18806
+ return "";
18807
+ throw new GrokComputerUseError("Could not read Grok config");
18636
18808
  }
18637
- return { ...value, ...indicators };
18638
18809
  }
18639
- var requestTokenFields = [
18640
- "inputTokens",
18641
- "cachedInputTokens",
18642
- "cacheWriteInputTokens",
18643
- "cacheWrite1hInputTokens",
18644
- "outputTokens",
18645
- "reasoningOutputTokens",
18646
- "startedAtMs",
18647
- "completedAtMs"
18648
- ];
18649
- var requestFields = /* @__PURE__ */ new Set([
18650
- ...requestTokenFields,
18651
- "requestId",
18652
- "historical",
18653
- "model",
18654
- "provider"
18655
- ]);
18656
-
18657
- // ../../harness-adapter/dist/live-command-catalog.js
18658
- var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
18659
- // Session lifecycle
18660
- "branch",
18661
- "clear",
18662
- "exit",
18663
- "fork",
18664
- "fresh",
18665
- "new",
18666
- "quit",
18667
- "rename",
18668
- "rename-chat",
18669
- "reset",
18670
- "resume",
18671
- "rewind",
18672
- "session",
18673
- "sessions",
18674
- // Desktop-owned configuration
18675
- "autocompact",
18676
- "color",
18677
- "config",
18678
- "effort",
18679
- "fast",
18680
- "keybindings",
18681
- "model",
18682
- "models",
18683
- "output-style",
18684
- "permissions",
18685
- "settings",
18686
- "statusline",
18687
- "terminal-setup",
18688
- "theme",
18689
- "vim",
18690
- // Trust and approval policy
18691
- "always-approve",
18692
- "auto-mode-setup",
18693
- // Native login
18694
- "login",
18695
- "logout",
18696
- // Work outliving the Turn
18697
- "autopilot",
18698
- "background",
18699
- "bg",
18700
- "goal",
18701
- "jobs",
18702
- "loop",
18703
- "multitask",
18704
- "queue",
18705
- "remote-control",
18706
- "schedule",
18707
- "steer",
18708
- // Native terminal UI
18709
- "copy",
18710
- "debug",
18711
- "feedback",
18712
- "heapdump",
18713
- "share",
18714
- "shell",
18715
- // Plugin and MCP management
18716
- "marketplace",
18717
- "mcp",
18718
- "plugins",
18719
- "reload-plugins"
18720
- ]);
18721
- var COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES = ["__", "hooks-"];
18722
- function isExcludedLiveCommand(name, kind, extra = {}) {
18723
- const normalized = name.trim().replace(/^\//u, "");
18724
- if (new Set(extra.names ?? []).has(normalized))
18725
- return true;
18726
- if (extra.prefixes?.some((prefix) => normalized.startsWith(prefix)))
18727
- return true;
18728
- if (kind === "skill")
18729
- return false;
18730
- return COMMON_EXCLUDED_LIVE_COMMANDS.has(normalized) || COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES.some((prefix) => normalized.startsWith(prefix));
18810
+ async function writeGrokConfig(environment, text) {
18811
+ await writeAtomically(path9.join(grokHome2(environment), "config.toml"), text.endsWith("\n") ? text : `${text}
18812
+ `);
18731
18813
  }
18732
- function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
18733
- if (!commandId.startsWith(idPrefix))
18734
- return null;
18735
- const descriptor = catalog.commands.find(({ id }) => id === commandId);
18736
- if (!descriptor)
18737
- return null;
18738
- const text = typeof argumentText === "string" ? argumentText.trim() : "";
18739
- return text ? `${descriptor.invocation} ${text}` : descriptor.invocation;
18814
+ async function currentState(environment, preference) {
18815
+ const resolved = preference ?? await readPreference(environment);
18816
+ const inferred = resolved?.enabled === void 0 ? inferredSurfaces(await readGrokConfig(environment)) : void 0;
18817
+ return {
18818
+ enabled: resolved?.enabled ?? inferred?.enabled ?? false,
18819
+ browser: resolved ? resolved.browser ?? false : inferred?.browser ?? false,
18820
+ ...resolved?.applyError ? { applyError: resolved.applyError } : {}
18821
+ };
18740
18822
  }
18741
- function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
18742
- if (!live)
18743
- return builtIns;
18744
- const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
18745
- const ids = new Set(builtIns.commands.map(({ id }) => id));
18746
- const dynamic = [];
18747
- for (const command of live) {
18748
- const name = command.name.trim().replace(/^\//u, "");
18749
- if (!name || /\s/u.test(name))
18750
- continue;
18751
- if (isExcludedLiveCommand(name, command.kind, exclusions))
18752
- continue;
18753
- const invocation = `/${name}`;
18754
- const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
18755
- if (invocations.has(invocation) || ids.has(id))
18756
- continue;
18757
- const description = command.description?.trim().slice(0, 512);
18758
- const parsed = harnessCommandDescriptorSchema.safeParse({
18759
- id,
18760
- invocation,
18761
- label: name.slice(0, 128),
18762
- ...description ? { description } : {},
18763
- argumentMode: "text",
18764
- kind: command.kind
18765
- });
18766
- if (!parsed.success)
18767
- continue;
18768
- invocations.add(invocation);
18769
- ids.add(id);
18770
- dynamic.push(parsed.data);
18823
+ async function surfaceFiles(launch) {
18824
+ if (!launch)
18825
+ return { computer: false, browser: false };
18826
+ const [computer, browser] = await Promise.all([
18827
+ computerFilesPresent(launch),
18828
+ browserFilesPresent(launch)
18829
+ ]);
18830
+ return { computer, browser };
18831
+ }
18832
+ async function writeConfigForState(state, launch, files, environment) {
18833
+ const current = await readGrokConfig(environment);
18834
+ const range = tableRange(current, TABLE);
18835
+ const effective = {
18836
+ enabled: state.enabled && files.computer,
18837
+ browser: state.browser && files.browser && GROK_BROWSER_BINDING_SUPPORTED
18838
+ };
18839
+ if (!effective.enabled && !effective.browser && !range)
18840
+ return;
18841
+ if (!launch) {
18842
+ if (!range)
18843
+ return;
18844
+ const lines = current.split(/\n/);
18845
+ const body = lines.slice(range.start, range.end);
18846
+ const replaced = body.map((line) => /^enabled\s*=/u.test(line) ? "enabled = false" : line);
18847
+ if (!replaced.some((line) => /^enabled\s*=/u.test(line))) {
18848
+ replaced.splice(1, 0, "enabled = false");
18849
+ }
18850
+ lines.splice(range.start, range.end - range.start, ...replaced);
18851
+ await writeGrokConfig(environment, lines.join("\n"));
18852
+ return;
18771
18853
  }
18772
- return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
18854
+ const stripped = removeTables(current, [ENV_TABLE, TABLE]).replace(/\s+$/u, "\n");
18855
+ await writeGrokConfig(environment, `${stripped.trimEnd()}
18856
+
18857
+ ${stanza(launch, effective)}`);
18858
+ }
18859
+ async function applyGrokComputerUsePreference(environment = process.env, platform = process.platform) {
18860
+ await withGrokComputerUseLock(dataDirectory(environment), grokHome2(environment), async () => {
18861
+ const preference = await readPreference(environment);
18862
+ if (preference === void 0)
18863
+ return;
18864
+ const launch = await discoverGrokComputerUseLaunch(environment, platform);
18865
+ const files = await surfaceFiles(launch);
18866
+ const state = await currentState(environment, preference);
18867
+ try {
18868
+ await writeConfigForState(state, launch, files, environment);
18869
+ if (state.applyError)
18870
+ await writePreference(environment, { enabled: state.enabled, browser: state.browser });
18871
+ } catch (error53) {
18872
+ const applyError = error53 instanceof GrokComputerUseError ? error53.message : APPLY_FAILED;
18873
+ await writePreference(environment, {
18874
+ enabled: state.enabled,
18875
+ browser: state.browser,
18876
+ applyError
18877
+ }).catch(() => void 0);
18878
+ throw error53 instanceof GrokComputerUseError ? error53 : new GrokComputerUseError(APPLY_FAILED);
18879
+ }
18880
+ });
18773
18881
  }
18774
18882
 
18775
18883
  // ../../harness-adapter/dist/local-media-markdown.js
@@ -23324,15 +23432,13 @@ function parseGrokAvailableCommands(value) {
23324
23432
  ];
23325
23433
  });
23326
23434
  }
23327
- function isGrokSkill(command) {
23328
- const path23 = command.meta?.path;
23329
- return typeof path23 === "string" && /(^|[\\/])SKILL\.md$/u.test(path23) || typeof command.meta?.qualifiedName === "string";
23330
- }
23331
23435
  function grokLiveCommands(native) {
23332
- return native.map((command) => ({
23436
+ return native.filter(({ meta: meta3 }) => {
23437
+ const path23 = meta3?.path;
23438
+ return !(typeof path23 === "string" && /(^|[\\/])SKILL\.md$/u.test(path23) || typeof meta3?.qualifiedName === "string");
23439
+ }).map((command) => ({
23333
23440
  name: command.name,
23334
- description: command.description,
23335
- kind: isGrokSkill(command) ? "skill" : "command"
23441
+ description: command.description
23336
23442
  }));
23337
23443
  }
23338
23444
 
@@ -25374,6 +25480,7 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
25374
25480
  description: grokSubagentDescription(event.rawInput, event.title),
25375
25481
  ...role ? { role } : {},
25376
25482
  ...model2 ? { model: model2 } : {},
25483
+ ...subagentConfiguration(event.rawInput),
25377
25484
  background: grokSubagentBackground(event.rawInput),
25378
25485
  status: "running"
25379
25486
  }
@@ -29617,7 +29724,19 @@ var GrokHarnessSession = class {
29617
29724
  ...this.#state.effectivePermissionModeId ? { permissionModeId: this.#state.effectivePermissionModeId } : {}
29618
29725
  };
29619
29726
  }
29727
+ #subagentConfiguration() {
29728
+ const state = this.#state;
29729
+ const model2 = state.effectiveModel ? state.effectiveModel.id : void 0;
29730
+ return {
29731
+ ...model2 ? { model: model2 } : {},
29732
+ ...state.effectiveThinkingOptionId ? { reasoningEffort: state.effectiveThinkingOptionId } : {}
29733
+ };
29734
+ }
29620
29735
  async readSnapshot() {
29736
+ const result = await this.#readSnapshot();
29737
+ return result.ok ? { ok: true, value: configureSubagentSnapshot(result.value, this.#subagentConfiguration()) } : result;
29738
+ }
29739
+ async #readSnapshot() {
29621
29740
  if (this.#phase !== "open") {
29622
29741
  return { ok: false, error: invalidState("Grok Session is not open") };
29623
29742
  }
@@ -30707,6 +30826,7 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
30707
30826
  ...prompt ? { prompt } : {},
30708
30827
  ...role ? { role } : {},
30709
30828
  ...model2 ? { model: model2 } : {},
30829
+ ...subagentConfiguration(event.rawInput),
30710
30830
  background: grokSubagentBackground(event.rawInput),
30711
30831
  ...nativeSubagentId ? { nativeSubagentId } : {}
30712
30832
  });
@@ -30767,6 +30887,8 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
30767
30887
  const role = grokSubagentRole(event.rawInput);
30768
30888
  const nativeSubagentId = grokNativeSubagentId(event.rawInput, event.rawOutput, event.content);
30769
30889
  active.subagents.update(active.command.turnId, event.callId, {
30890
+ ...subagentConfiguration(event.rawInput),
30891
+ ...subagentConfiguration(event.rawOutput),
30770
30892
  ...event.title ? { description: grokSubagentDescription(event.rawInput, event.title) } : {},
30771
30893
  ...role ? { role } : {},
30772
30894
  ...nativeSubagentId ? { nativeSubagentId } : {}
@@ -31131,6 +31253,7 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
31131
31253
  this.#onClosed();
31132
31254
  }
31133
31255
  #event(event) {
31256
+ event = configureSubagentEvent(event, this.#subagentConfiguration());
31134
31257
  this.#channel.emit({ kind: "event", event });
31135
31258
  }
31136
31259
  };