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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +317 -59
  4. package/app/console-web.js +1889 -141
  5. package/app/cpa-live-voice-hook.js +1938 -428
  6. package/app/desktop-controller.mjs +2081 -212
  7. package/app/host-runtime.mjs +14818 -3381
  8. package/app/overlay-voice-bootstrap.js +1616 -0
  9. package/app/plugins/antigravity/plugin.mjs +963 -324
  10. package/app/plugins/claude-code/plugin.mjs +395 -67
  11. package/app/plugins/codebuddy/plugin.mjs +409 -76
  12. package/app/plugins/codex-usage/plugin.mjs +316 -58
  13. package/app/plugins/copilot/plugin.mjs +316 -58
  14. package/app/plugins/cursor-cli/plugin.mjs +391 -68
  15. package/app/plugins/deepseek-harness/manifest.json +2 -2
  16. package/app/plugins/deepseek-harness/plugin.mjs +343 -63
  17. package/app/plugins/devin/plugin.mjs +316 -58
  18. package/app/plugins/grok/plugin.mjs +1350 -1026
  19. package/app/plugins/hermes/plugin.mjs +395 -70
  20. package/app/plugins/kimi-code/plugin.mjs +316 -58
  21. package/app/plugins/kiro-cli/plugin.mjs +544 -74
  22. package/app/plugins/omp/plugin.mjs +1264 -902
  23. package/app/plugins/opencode/plugin.mjs +316 -58
  24. package/app/plugins/pi/plugin.mjs +1189 -862
  25. package/app/plugins/qoder/plugin.mjs +318 -62
  26. package/app/plugins/qoder-cn/plugin.mjs +318 -62
  27. package/app/plugins/qwen-code/plugin.mjs +425 -150
  28. package/app/plugins/workbuddy/plugin.mjs +409 -76
  29. package/app/plugins/zcode/plugin.mjs +389 -61
  30. package/app/renderer-extension.js +11830 -8531
  31. package/app/voice-profile-pins.json +25 -0
  32. package/app/voice-qualification.json +4 -0
  33. package/app/web/assets/index-BCyiiDDL.js +199 -0
  34. package/app/web/assets/index-BNQIOOHE.css +1 -0
  35. package/app/web/codexhost-settings.js +1895 -190
  36. package/app/web/index.html +2 -2
  37. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  38. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +69 -69
  39. package/app/web/plugins/deepseek-ai__dsh-client-file-upload/client.js +1 -1
  40. package/app/web/plugins/deepseek-ai__dsh-client-locale/client.js +3 -3
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-attachment/client.js +1 -1
  42. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +129 -8
  43. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +65 -63
  44. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +95 -93
  45. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  46. package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +2 -2
  47. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +1 -1
  48. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
  49. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.excel.js +1 -1
  50. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-files/client.js +1 -1
  51. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +79 -79
  52. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +1 -1
  53. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +11 -11
  54. package/app/web-modules/server.mjs +3279 -1676
  55. package/bin/codexhost.exe +0 -0
  56. package/libexec/codexhost-node-repl.exe +0 -0
  57. package/libexec/codexhost-shim.exe +0 -0
  58. package/libexec/codexhost-updater.exe +0 -0
  59. package/package.json +1 -1
  60. package/app/web/assets/index-Bs17Kuah.js +0 -199
  61. package/app/web/assets/index-C3lniEH1.css +0 -1
@@ -14933,7 +14933,7 @@ var harnessGoalSetSchema = external_exports.object({
14933
14933
  origin: goalOriginSchema
14934
14934
  });
14935
14935
 
14936
- // ../../shared-contracts/dist/realtime-call.js
14936
+ // ../../shared-contracts/dist/realtime-call-core.js
14937
14937
  var REALTIME_CALL_FORWARDED_HEADERS = [
14938
14938
  "openai-alpha",
14939
14939
  "thread-id",
@@ -14942,7 +14942,9 @@ var REALTIME_CALL_FORWARDED_HEADERS = [
14942
14942
  "x-codex-turn-metadata"
14943
14943
  ];
14944
14944
  var FORWARDED_HEADERS = new Set(REALTIME_CALL_FORWARDED_HEADERS);
14945
- var REALTIME_CALL_ID_PATTERN = /^rtc_[A-Za-z0-9_-]{1,128}$/u;
14945
+ var REALTIME_CALL_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/u;
14946
+
14947
+ // ../../shared-contracts/dist/realtime-call.js
14946
14948
  var requestId = external_exports.string().min(1).max(128);
14947
14949
  var realtimeCallParamsSchema = external_exports.discriminatedUnion("operation", [
14948
14950
  external_exports.object({
@@ -14997,12 +14999,6 @@ var RELAY_PUBLIC_ORIGIN = "https://codexhost.karldigi.dev";
14997
14999
  var RELAY_PUBLIC_RESOURCE = `${RELAY_PUBLIC_ORIGIN}/mcp`;
14998
15000
  var RELAY_WAIT_TIMEOUT_MAX_MS = 25e3;
14999
15001
  var RELAY_MAX_BODY_BYTES = 2 * 1024 * 1024;
15000
- var RELAY_ALLOWED_ROUTES = [
15001
- "/v1/enroll/status",
15002
- "/v1/thread/read",
15003
- "/v1/thread/wait",
15004
- "/v1/thread/send"
15005
- ];
15006
15002
  var relayLinkHelloSchema = external_exports.strictObject({
15007
15003
  v: external_exports.literal(RELAY_LINK_PROTOCOL_VERSION),
15008
15004
  secret: external_exports.string().min(1).max(4096)
@@ -15014,8 +15010,11 @@ var relayLinkHelloAckSchema = external_exports.strictObject({
15014
15010
  var relayLinkRequestSchema = external_exports.strictObject({
15015
15011
  requestId: external_exports.string().min(1).max(128),
15016
15012
  deadlineMs: external_exports.number().int().positive(),
15017
- route: external_exports.enum(RELAY_ALLOWED_ROUTES),
15018
- body: external_exports.record(external_exports.string(), external_exports.unknown())
15013
+ route: external_exports.string().min(1).max(128),
15014
+ body: external_exports.record(external_exports.string(), external_exports.unknown()),
15015
+ operationalClient: external_exports.string().min(1).max(64).optional(),
15016
+ oauthClientId: external_exports.string().min(1).max(128).optional(),
15017
+ dispatchGrant: external_exports.enum(["legacy-four", "full-dispatch"]).optional()
15019
15018
  });
15020
15019
  var relayLinkErrorSchema = external_exports.strictObject({
15021
15020
  code: external_exports.string().min(1).max(64),
@@ -15059,6 +15058,204 @@ var relayEnrollStatusResultSchema = external_exports.strictObject({
15059
15058
  runtime: external_exports.enum(["reachable", "unreachable"])
15060
15059
  });
15061
15060
 
15061
+ // ../../shared-contracts/dist/external-clients.js
15062
+ var EXTERNAL_CLIENT_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u;
15063
+ var externalClientNameSchema = external_exports.string().trim().min(1).max(64).regex(EXTERNAL_CLIENT_NAME_PATTERN);
15064
+ var externalClientAccessSchema = external_exports.enum(["all-threads", "selected-workspaces"]);
15065
+ var externalClientConnectionModeSchema = external_exports.enum(["public-relay", "local", "direct"]);
15066
+ var externalClientDispatchGrantSchema = external_exports.enum(["legacy-four", "full-dispatch"]);
15067
+ var workspacePathSchema = external_exports.string().trim().min(1).max(4096);
15068
+ var directUrlSchema = external_exports.string().trim().max(2048);
15069
+ var externalClientPublicViewSchema = external_exports.strictObject({
15070
+ name: externalClientNameSchema,
15071
+ createdAt: external_exports.string().min(1).max(64),
15072
+ access: externalClientAccessSchema,
15073
+ workspaces: external_exports.array(workspacePathSchema).max(64),
15074
+ connectionMode: externalClientConnectionModeSchema,
15075
+ dispatchGrant: externalClientDispatchGrantSchema,
15076
+ oauthClientId: external_exports.string().trim().min(1).max(128).optional(),
15077
+ directUrl: directUrlSchema.optional(),
15078
+ mcpUrl: external_exports.string().min(1).max(2048).optional(),
15079
+ mcpUrlNote: external_exports.string().min(1).max(512).optional()
15080
+ });
15081
+ var externalClientListParamsSchema = external_exports.strictObject({});
15082
+ var externalClientListResultSchema = external_exports.strictObject({
15083
+ clients: external_exports.array(externalClientPublicViewSchema).max(256)
15084
+ });
15085
+ var externalClientWriteFieldsSchema = external_exports.strictObject({
15086
+ access: externalClientAccessSchema.optional(),
15087
+ workspaces: external_exports.array(workspacePathSchema).max(64).optional(),
15088
+ connectionMode: externalClientConnectionModeSchema.optional(),
15089
+ dispatchGrant: externalClientDispatchGrantSchema.optional(),
15090
+ oauthClientId: external_exports.string().trim().min(1).max(128).optional(),
15091
+ directUrl: directUrlSchema.optional()
15092
+ });
15093
+ var externalClientCreateParamsSchema = externalClientWriteFieldsSchema.extend({
15094
+ name: externalClientNameSchema
15095
+ });
15096
+ var externalClientCreateResultSchema = externalClientPublicViewSchema.extend({
15097
+ token: external_exports.string().min(1).max(256).optional()
15098
+ });
15099
+ var externalClientUpdateParamsSchema = externalClientWriteFieldsSchema.extend({
15100
+ name: externalClientNameSchema,
15101
+ clearOauthClientId: external_exports.literal(true).optional()
15102
+ });
15103
+ var externalClientRevokeParamsSchema = external_exports.strictObject({
15104
+ name: externalClientNameSchema
15105
+ });
15106
+ var externalClientRevokeResultSchema = external_exports.strictObject({
15107
+ name: externalClientNameSchema,
15108
+ revoked: external_exports.literal(true)
15109
+ });
15110
+ var stringProp = (description) => ({ type: "string", description });
15111
+ var integerProp = (description) => ({
15112
+ type: "integer",
15113
+ minimum: 0,
15114
+ description
15115
+ });
15116
+ var threadProp = stringProp("Thread id or codex://threads/<id> link");
15117
+ var EXTERNAL_MCP_TOOL_DESCRIPTORS = [
15118
+ {
15119
+ name: "harness_list",
15120
+ description: "List the Harnesses this codexhost can delegate to.",
15121
+ inputSchema: { type: "object", properties: {} }
15122
+ },
15123
+ {
15124
+ name: "harness_inspect",
15125
+ description: "Read a Harness's Models, Thinking options and defaults; use the returned ids when delegating.",
15126
+ inputSchema: {
15127
+ type: "object",
15128
+ properties: {
15129
+ harnessId: stringProp("Harness id from harness_list"),
15130
+ cwd: stringProp("Absolute workspace path"),
15131
+ refresh: { type: "boolean" }
15132
+ },
15133
+ required: ["harnessId"]
15134
+ }
15135
+ },
15136
+ {
15137
+ name: "delegate_start",
15138
+ description: "Start a task in a new Thread and return at once. Without parentThread the work belongs to this client and cwd is required. watch=true records an event for this client when the Thread stops (read it with events_poll or the SSE stream).",
15139
+ inputSchema: {
15140
+ type: "object",
15141
+ properties: {
15142
+ harnessId: stringProp("Harness id from harness_list"),
15143
+ task: stringProp("The full task text"),
15144
+ taskName: stringProp("Short display name"),
15145
+ cwd: stringProp("Absolute workspace path"),
15146
+ model: stringProp("Model id from harness_inspect"),
15147
+ thinking: stringProp("Thinking option id from harness_inspect"),
15148
+ parentThread: stringProp("Optional parent Thread"),
15149
+ requestId: stringProp("Reuse to retry idempotently"),
15150
+ refs: {
15151
+ type: "array",
15152
+ items: { type: "string" },
15153
+ description: "Absolute URIs of where the work came from"
15154
+ },
15155
+ watch: { type: "boolean", description: "Record an event when the Thread stops" },
15156
+ watchTimeoutMs: integerProp("How long to watch; default 29 minutes")
15157
+ },
15158
+ required: ["harnessId", "task"]
15159
+ }
15160
+ },
15161
+ {
15162
+ name: "thread_read",
15163
+ description: "Read a Thread's status and latest result, or page its visible messages (view=messages). Never changes the Thread.",
15164
+ inputSchema: {
15165
+ type: "object",
15166
+ properties: {
15167
+ thread: threadProp,
15168
+ view: { type: "string", enum: ["result", "messages"] },
15169
+ cursor: stringProp("Message cursor"),
15170
+ limit: integerProp("Messages per page, at most 100")
15171
+ },
15172
+ required: ["thread"]
15173
+ }
15174
+ },
15175
+ {
15176
+ name: "thread_wait",
15177
+ description: "Wait up to timeoutMs (at most 60000) for a Thread to stop, then return the same snapshot as thread_read plus timedOut.",
15178
+ inputSchema: {
15179
+ type: "object",
15180
+ properties: {
15181
+ thread: threadProp,
15182
+ timeoutMs: integerProp("At most 60000; default 30000"),
15183
+ view: { type: "string", enum: ["result", "messages"] }
15184
+ },
15185
+ required: ["thread"]
15186
+ }
15187
+ },
15188
+ {
15189
+ name: "thread_list",
15190
+ description: "List Threads: by workspace (cwd), by parent Thread, by the client that started them, or by reference.",
15191
+ inputSchema: {
15192
+ type: "object",
15193
+ properties: {
15194
+ cwd: stringProp("Absolute workspace path"),
15195
+ parent: stringProp("Parent Thread"),
15196
+ client: stringProp("Client name"),
15197
+ ref: stringProp("Reference URI"),
15198
+ limit: integerProp("At most 100; default 25"),
15199
+ cursor: stringProp("Cursor from a previous page"),
15200
+ sort: {
15201
+ type: "string",
15202
+ enum: [
15203
+ "created-asc",
15204
+ "created-desc",
15205
+ "updated-asc",
15206
+ "updated-desc",
15207
+ "recency-asc",
15208
+ "recency-desc"
15209
+ ]
15210
+ }
15211
+ }
15212
+ }
15213
+ },
15214
+ {
15215
+ name: "thread_send",
15216
+ description: "Start a new Turn in an idle Thread. THREAD_BUSY means its current Turn is still running; messages are not queued.",
15217
+ inputSchema: {
15218
+ type: "object",
15219
+ properties: { thread: threadProp, message: stringProp("Message text") },
15220
+ required: ["thread", "message"]
15221
+ }
15222
+ },
15223
+ {
15224
+ name: "thread_cancel",
15225
+ description: "Cancel a Thread's active Turn, keeping the Thread and its history.",
15226
+ inputSchema: { type: "object", properties: { thread: threadProp }, required: ["thread"] }
15227
+ },
15228
+ {
15229
+ name: "thread_watch",
15230
+ description: "Record one event for this client when the Thread stops or the watch expires.",
15231
+ inputSchema: {
15232
+ type: "object",
15233
+ properties: { thread: threadProp, timeoutMs: integerProp("Default 29 minutes") },
15234
+ required: ["thread"]
15235
+ }
15236
+ },
15237
+ {
15238
+ name: "thread_watches",
15239
+ description: "List watches that have not been delivered yet.",
15240
+ inputSchema: { type: "object", properties: {} }
15241
+ },
15242
+ {
15243
+ name: "events_poll",
15244
+ description: "Read this client's events after a cursor (0 for all retained). Waits up to timeoutMs (at most 60000) for the first one. Pass the returned cursor back next time. CURSOR_EXPIRED: reconcile with thread_list client=<this client>.",
15245
+ inputSchema: {
15246
+ type: "object",
15247
+ properties: {
15248
+ after: integerProp("Cursor; 0 for all retained"),
15249
+ timeoutMs: integerProp("At most 60000; default 0"),
15250
+ limit: integerProp("At most 100")
15251
+ }
15252
+ }
15253
+ }
15254
+ ];
15255
+
15256
+ // ../../shared-contracts/dist/external-mcp-map.js
15257
+ var DEFAULT_WATCH_MS = 29 * 6e4;
15258
+
15062
15259
  // ../../shared-contracts/dist/grok-computer-use.js
15063
15260
  var grokComputerUseGetSchema = external_exports.object({}).strict();
15064
15261
  var grokComputerUseSetSchema = external_exports.object({
@@ -15655,11 +15852,61 @@ var threadSteeringInspectResultSchema = external_exports.object({
15655
15852
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15656
15853
  }).strict();
15657
15854
 
15855
+ // ../../shared-contracts/dist/voice-settings.js
15856
+ var voiceRoutesSchema = external_exports.strictObject({
15857
+ chatExperience: external_exports.enum(["chatgpt", "codex"]),
15858
+ chatConnection: external_exports.enum(["desktop", "gateway"]),
15859
+ workConnection: external_exports.enum(["desktop", "gateway"])
15860
+ });
15861
+ var DEFAULT_VOICE_ROUTES = Object.freeze({
15862
+ chatExperience: "chatgpt",
15863
+ chatConnection: "desktop",
15864
+ workConnection: "gateway"
15865
+ });
15866
+ var voiceSettingsSchema = voiceRoutesSchema.extend({ inject: external_exports.boolean() });
15867
+ var voiceSettingsRequestSchema = external_exports.discriminatedUnion("operation", [
15868
+ external_exports.strictObject({
15869
+ operation: external_exports.literal("get"),
15870
+ runtime: external_exports.strictObject({
15871
+ id: external_exports.string().uuid(),
15872
+ revision: external_exports.string().max(64),
15873
+ activeCall: external_exports.boolean()
15874
+ }).optional()
15875
+ }),
15876
+ external_exports.strictObject({ operation: external_exports.literal("migrate"), routes: voiceRoutesSchema }),
15877
+ external_exports.strictObject({
15878
+ operation: external_exports.literal("set"),
15879
+ settings: voiceSettingsSchema,
15880
+ revision: external_exports.string().max(64)
15881
+ }),
15882
+ external_exports.strictObject({ operation: external_exports.literal("restart"), confirm: external_exports.literal(true) })
15883
+ ]);
15884
+ var voiceSettingsStateSchema = external_exports.strictObject({
15885
+ settings: voiceSettingsSchema,
15886
+ initialized: external_exports.boolean(),
15887
+ revision: external_exports.string(),
15888
+ activeInject: external_exports.boolean().nullable(),
15889
+ envOverride: external_exports.enum(["0", "1"]).nullable(),
15890
+ activeEnvOverride: external_exports.enum(["0", "1"]).nullable(),
15891
+ routesActive: external_exports.boolean().nullable(),
15892
+ activeCall: external_exports.boolean().nullable(),
15893
+ gatewayReady: external_exports.boolean().nullable(),
15894
+ restartAvailable: external_exports.boolean(),
15895
+ restart: external_exports.strictObject({
15896
+ phase: external_exports.enum(["idle", "restarting", "succeeded", "failed"]),
15897
+ error: external_exports.string().nullable()
15898
+ })
15899
+ });
15900
+
15658
15901
  // ../../shared-contracts/dist/client-channel.js
15659
15902
  var CLIENT_CHANNEL_VERSION = 1;
15660
15903
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
15661
15904
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
15662
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();
15663
15910
  var clientProjectlessWorkspaceSchema = external_exports.object({
15664
15911
  prompt: external_exports.string().max(16384).optional()
15665
15912
  }).strict();
@@ -15676,6 +15923,11 @@ var clientChannelCursorSchema = external_exports.object({
15676
15923
  sequence: external_exports.number().int().nonnegative()
15677
15924
  });
15678
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
+ }),
15679
15931
  external_exports.object({ type: external_exports.literal("display-settings-changed"), cursor: clientChannelCursorSchema }),
15680
15932
  external_exports.object({
15681
15933
  type: external_exports.literal("preferences-changed"),
@@ -15873,6 +16125,28 @@ var voiceTranscribeResultSchema = external_exports.discriminatedUnion("ok", [
15873
16125
  external_exports.object({ ok: external_exports.literal(false), error: external_exports.object({ code: voiceErrorCodeSchema }).strict() }).strict()
15874
16126
  ]);
15875
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
+
15876
16150
  // ../../shared-contracts/dist/web-access-tokens.js
15877
16151
  var webNetworkAccessUrlSchema = external_exports.object({
15878
16152
  /**
@@ -15978,8 +16252,8 @@ var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
15978
16252
  var delegationReadParamsSchema = external_exports.strictObject({
15979
16253
  threadId: external_exports.string().min(1).max(1024),
15980
16254
  view: external_exports.enum(["result", "messages"]),
15981
- cursor: external_exports.string().min(1).max(8192).optional(),
15982
- 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()
15983
16257
  });
15984
16258
 
15985
16259
  // ../../shared-contracts/dist/credential-imports.js
@@ -16431,6 +16705,10 @@ var CONSOLE_HOST_METHODS = Object.freeze([
16431
16705
  "codexhost/voice/gateway-status",
16432
16706
  "codexhost/enrollment/list",
16433
16707
  "codexhost/enrollment/revoke",
16708
+ "codexhost/external-clients/list",
16709
+ "codexhost/external-clients/create",
16710
+ "codexhost/external-clients/update",
16711
+ "codexhost/external-clients/revoke",
16434
16712
  "codexhost/console/remote-connections",
16435
16713
  "codexhost/runtime/status",
16436
16714
  "codexhost/remote/ssh-setup",
@@ -16977,6 +17255,17 @@ var updateStatusResultSchema = external_exports.strictObject({
16977
17255
  status: updateStatusSchema.nullable()
16978
17256
  });
16979
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
+
16980
17269
  // ../../shared-contracts/dist/remote-runtime.js
16981
17270
  var remoteUpdatePhaseSchema = external_exports.enum([
16982
17271
  "idle",
@@ -17024,6 +17313,14 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
17024
17313
  archived: external_exports.boolean()
17025
17314
  }),
17026
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"),
17027
17324
  external_exports.strictObject({
17028
17325
  kind: external_exports.literal("prompt"),
17029
17326
  ...thread,
@@ -17096,6 +17393,13 @@ var remoteConnectionsReplySchema = external_exports.union([
17096
17393
  external_exports.strictObject({ error: external_exports.strictObject({ code: external_exports.number().int(), message: external_exports.string() }) })
17097
17394
  ]);
17098
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
+
17099
17403
  // ../../shared-contracts/dist/web-ui-extensions.js
17100
17404
  var webUiExtensionIdSchema = external_exports.string().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u);
17101
17405
  var localizedTextSchema2 = external_exports.union([
@@ -17136,52 +17440,6 @@ var webUiExtensionInstallSchema = external_exports.object({
17136
17440
  var webUiExtensionEnabledSchema = external_exports.object({ id: webUiExtensionIdSchema, enabled: external_exports.boolean() }).strict();
17137
17441
  var webUiExtensionRemoveSchema = external_exports.object({ id: webUiExtensionIdSchema }).strict();
17138
17442
 
17139
- // ../../shared-contracts/dist/voice-settings.js
17140
- var voiceRoutesSchema = external_exports.strictObject({
17141
- chatExperience: external_exports.enum(["chatgpt", "codex"]),
17142
- chatConnection: external_exports.enum(["desktop", "gateway"]),
17143
- workConnection: external_exports.enum(["desktop", "gateway"])
17144
- });
17145
- var DEFAULT_VOICE_ROUTES = Object.freeze({
17146
- chatExperience: "chatgpt",
17147
- chatConnection: "desktop",
17148
- workConnection: "gateway"
17149
- });
17150
- var voiceSettingsSchema = voiceRoutesSchema.extend({ inject: external_exports.boolean() });
17151
- var voiceSettingsRequestSchema = external_exports.discriminatedUnion("operation", [
17152
- external_exports.strictObject({
17153
- operation: external_exports.literal("get"),
17154
- runtime: external_exports.strictObject({
17155
- id: external_exports.string().uuid(),
17156
- revision: external_exports.string().max(64),
17157
- activeCall: external_exports.boolean()
17158
- }).optional()
17159
- }),
17160
- external_exports.strictObject({ operation: external_exports.literal("migrate"), routes: voiceRoutesSchema }),
17161
- external_exports.strictObject({
17162
- operation: external_exports.literal("set"),
17163
- settings: voiceSettingsSchema,
17164
- revision: external_exports.string().max(64)
17165
- }),
17166
- external_exports.strictObject({ operation: external_exports.literal("restart"), confirm: external_exports.literal(true) })
17167
- ]);
17168
- var voiceSettingsStateSchema = external_exports.strictObject({
17169
- settings: voiceSettingsSchema,
17170
- initialized: external_exports.boolean(),
17171
- revision: external_exports.string(),
17172
- activeInject: external_exports.boolean().nullable(),
17173
- envOverride: external_exports.enum(["0", "1"]).nullable(),
17174
- activeEnvOverride: external_exports.enum(["0", "1"]).nullable(),
17175
- routesActive: external_exports.boolean().nullable(),
17176
- activeCall: external_exports.boolean().nullable(),
17177
- gatewayReady: external_exports.boolean().nullable(),
17178
- restartAvailable: external_exports.boolean(),
17179
- restart: external_exports.strictObject({
17180
- phase: external_exports.enum(["idle", "restarting", "succeeded", "failed"]),
17181
- error: external_exports.string().nullable()
17182
- })
17183
- });
17184
-
17185
17443
  // ../../shared-contracts/dist/background-activity.js
17186
17444
  var backgroundActivitySchema = external_exports.strictObject({
17187
17445
  id: external_exports.string().min(1),
@@ -17514,1061 +17772,1112 @@ var GrokGoals = class {
17514
17772
  }
17515
17773
  };
17516
17774
 
17517
- // dist/usage-statistics.js
17518
- import os2 from "node:os";
17519
- import path6 from "node:path";
17520
- import { readFile as readFile2 } from "node:fs/promises";
17521
-
17522
- // ../../harness-adapter/dist/usage-statistics.js
17523
- import { createReadStream } from "node:fs";
17524
- import { lstat, opendir } from "node:fs/promises";
17525
- import path5 from "node:path";
17526
- import { createInterface } from "node:readline";
17527
- var MAX_SESSION_ID_LENGTH = 512;
17528
- var MAX_CWD_LENGTH = 4096;
17529
- var MAX_SESSION_TITLE_LENGTH = 200;
17530
- function usageSessionTitle(value) {
17531
- if (typeof value !== "string")
17532
- return void 0;
17533
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
17534
- if (!normalized)
17535
- return void 0;
17536
- if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
17537
- return normalized;
17538
- let title = "";
17539
- for (const character of normalized) {
17540
- if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
17541
- break;
17542
- title += character;
17543
- }
17544
- return `${title.trimEnd()}…`;
17545
- }
17546
- function sessionIdOk(value) {
17547
- return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
17548
- }
17549
- function cwdOk(value) {
17550
- 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("\\\\"));
17775
+ // ../../harness-adapter/dist/approval.js
17776
+ function invalidRequest(message) {
17777
+ return { code: "invalidRequest", message, retryable: false };
17551
17778
  }
17552
- function withUsageSession(entry, session) {
17553
- const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
17554
- const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
17555
- const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
17556
- if (sessionId === void 0 && cwd === void 0)
17557
- return entry;
17558
- return {
17559
- ...entry,
17560
- ...sessionId !== void 0 ? { sessionId } : {},
17561
- ...cwd !== void 0 ? { cwd } : {},
17562
- ...sessionTitle !== void 0 ? { sessionTitle } : {}
17563
- };
17779
+ function validateHostApprovalResponse(interaction, response) {
17780
+ return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17564
17781
  }
17565
- async function jsonlUsageSources(root, maxDepth, signal) {
17566
- const sources = [];
17567
- const visit = async (directory, depth) => {
17568
- signal.throwIfAborted();
17569
- const entries = await opendir(directory).catch((error53) => {
17570
- if (error53.code === "ENOENT")
17571
- return null;
17572
- throw error53;
17573
- });
17574
- if (!entries)
17575
- return;
17576
- for await (const entry of entries) {
17577
- signal.throwIfAborted();
17578
- const file2 = path5.join(directory, entry.name);
17579
- if (entry.isDirectory()) {
17580
- if (depth < maxDepth)
17581
- await visit(file2, depth + 1);
17582
- } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
17583
- const info = await lstat(file2).catch(() => null);
17584
- if (info?.isFile() && info.size > 0) {
17585
- sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
17586
- }
17587
- }
17588
- }
17589
- };
17590
- await visit(root, 0);
17591
- return sources;
17782
+
17783
+ // ../../harness-adapter/dist/question.js
17784
+ function invalidRequest2(message) {
17785
+ return { code: "invalidRequest", message, retryable: false };
17592
17786
  }
17593
- async function* jsonlRecords(file2, marker, signal) {
17594
- const lines = createInterface({
17595
- input: createReadStream(file2, { encoding: "utf8", signal }),
17596
- crlfDelay: Infinity
17597
- });
17598
- for await (const line of lines) {
17599
- if (!line.includes(marker))
17600
- continue;
17601
- let value;
17602
- try {
17603
- value = JSON.parse(line);
17604
- } catch {
17605
- continue;
17606
- }
17607
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
17608
- yield value;
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");
17609
17795
  }
17610
17796
  }
17611
- }
17612
- function nativeTimeMs(value) {
17613
- const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
17614
- return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
17615
- }
17616
-
17617
- // dist/usage-statistics.js
17618
- function isRecord(value) {
17619
- return typeof value === "object" && value !== null && !Array.isArray(value);
17620
- }
17621
- var USD_TICKS = 1e10;
17622
- function count3(value) {
17623
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
17624
- }
17625
- function grokHome(environment) {
17626
- return environment.GROK_HOME || path6.join(environment.HOME || os2.homedir(), ".grok");
17627
- }
17628
- async function grokSummary(directory) {
17629
- try {
17630
- const summary = JSON.parse(await readFile2(path6.join(directory, "summary.json"), "utf8"));
17631
- if (!isRecord(summary))
17632
- return { forkedAt: null };
17633
- const title = usageSessionTitle(summary.generated_title) ?? usageSessionTitle(summary.session_summary);
17634
- return {
17635
- forkedAt: typeof summary.parent_session_id === "string" ? nativeTimeMs(summary.created_at) : null,
17636
- ...title ? { title } : {}
17637
- };
17638
- } catch {
17639
- return { forkedAt: null };
17640
- }
17641
- }
17642
- function grokSession(file2) {
17643
- const directory = path6.dirname(file2);
17644
- let cwd;
17645
- try {
17646
- cwd = decodeURIComponent(path6.basename(path6.dirname(directory)));
17647
- } catch {
17648
- cwd = void 0;
17649
- }
17650
- return { sessionId: path6.basename(directory), cwd };
17651
- }
17652
- async function readGrokUsage(file2, signal) {
17653
- const summary = await grokSummary(path6.dirname(file2));
17654
- const forkedAt = summary.forkedAt;
17655
- let title = summary.title;
17656
- const session = grokSession(file2);
17657
- const entries = [];
17658
- for await (const line of jsonlRecords(file2, '"sessionUpdate"', signal)) {
17659
- const params = isRecord(line.params) ? line.params : {};
17660
- const update = isRecord(params.update) ? params.update : {};
17661
- if (!title && update.sessionUpdate === "user_message_chunk") {
17662
- title = usageSessionTitle(isRecord(update.content) ? update.content.text : void 0);
17663
- continue;
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");
17664
17801
  }
17665
- const usage = isRecord(update.usage) ? update.usage : {};
17666
- if (update.sessionUpdate !== "turn_completed" || typeof update.prompt_id !== "string")
17667
- continue;
17668
- const meta3 = isRecord(params._meta) ? params._meta : {};
17669
- const at = nativeTimeMs(meta3.agentTimestampMs) ?? (typeof line.timestamp === "number" ? nativeTimeMs(line.timestamp * 1e3) : null);
17670
- if (at === null || forkedAt !== null && at <= forkedAt)
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
+ }
17671
17809
  continue;
17672
- for (const [model2, value] of Object.entries(isRecord(usage.modelUsage) ? usage.modelUsage : {})) {
17673
- if (!isRecord(value))
17674
- continue;
17675
- const input = count3(value.inputTokens);
17676
- const output = count3(value.outputTokens);
17677
- const cached2 = count3(value.cachedReadTokens);
17678
- const written = count3(value.cacheCreationTokens ?? 0);
17679
- const reasoning = count3(value.reasoningTokens);
17680
- const ticks = count3(value.costUsdTicks);
17681
- if (input === null || output === null || value.totalTokens !== input + output)
17682
- continue;
17683
- const cacheKnown = cached2 !== null && cached2 <= input && written === 0;
17684
- entries.push(withUsageSession({
17685
- id: `${update.prompt_id}:${model2}`,
17686
- occurredAtMs: at,
17687
- model: model2,
17688
- inputTokens: input,
17689
- ...cacheKnown ? { cachedInputTokens: cached2, cacheWriteInputTokens: 0 } : {},
17690
- outputTokens: output,
17691
- ...reasoning !== null && reasoning <= output ? { reasoningOutputTokens: reasoning } : {},
17692
- // A turn Grok marks incomplete has no cost of its own; it counts as free rather
17693
- // than as a model without a price.
17694
- ...ticks !== null ? { costUsd: ticks / USD_TICKS } : usage.usageIsIncomplete === true ? { costUsd: 0 } : {}
17695
- }, { ...session, ...title ? { title } : {} }));
17810
+ }
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");
17696
17817
  }
17697
17818
  }
17698
- return entries;
17699
- }
17700
- function createGrokUsageStatistics(environment) {
17701
- return Object.freeze({
17702
- // sessions/<url-encoded cwd>/<session>/updates.jsonl; subagents are sessions of their own.
17703
- listSources: async (signal) => (await jsonlUsageSources(path6.join(grokHome(environment), "sessions"), 2, signal)).filter((source) => path6.basename(source.id) === "updates.jsonl"),
17704
- readSource: (id, signal) => readGrokUsage(id, signal)
17705
- });
17819
+ return null;
17706
17820
  }
17707
17821
 
17708
- // dist/grok-commands.js
17709
- var grokCommandCatalog = harnessCommandCatalogSchema.parse({
17710
- commands: [
17711
- {
17712
- id: "grok.compact",
17713
- invocation: "/compact",
17714
- localizations: { "zh-CN": { label: "压缩上下文", description: "压缩当前对话上下文" } },
17715
- label: "Compact context",
17716
- description: "Compact the current conversation context",
17717
- argumentMode: "text"
17718
- },
17719
- {
17720
- id: "grok.desktop-goal",
17721
- invocation: "/goal",
17722
- label: "Goal",
17723
- description: "Start a native goal through Desktop Goal mode",
17724
- argumentMode: "text"
17725
- },
17726
- {
17727
- id: "grok.goal",
17728
- invocation: "/grok-goal",
17729
- label: "Grok goal",
17730
- description: "Set an objective [--budget tokens], or status / pause / resume / clear",
17731
- localizations: {
17732
- "zh-CN": {
17733
- label: "Grok 目标",
17734
- description: "设置原生目标与可选 token 预算,或 status / pause / resume / clear"
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");
17735
17834
  }
17736
- },
17737
- argumentMode: "text"
17738
- },
17739
- {
17740
- id: "grok.loop",
17741
- invocation: "/loop",
17742
- label: "Loop",
17743
- description: "Create a native timed Loop; include the interval and task",
17744
- argumentMode: "text"
17745
- }
17746
- ]
17747
- });
17748
- var GROK_GOAL_CONTROL_PATTERN = /^\/goal(?:\s+(?:status|pause|clear|resume))?\s*$/u;
17749
- function isGrokGoalControlPrompt(value) {
17750
- return GROK_GOAL_CONTROL_PATTERN.test(value.trim());
17751
- }
17752
- function grokGoalPrompt(arguments_) {
17753
- if (arguments_ && (Object.keys(arguments_).some((key) => key !== "text") || arguments_.text !== void 0 && typeof arguments_.text !== "string")) {
17754
- return {
17755
- ok: false,
17756
- error: {
17757
- code: "invalidRequest",
17758
- message: "Grok goal accepts only a text argument",
17759
- retryable: false
17835
+ this.#consumerCreated = true;
17836
+ return {
17837
+ next: () => this.#next()
17838
+ };
17760
17839
  }
17761
17840
  };
17762
17841
  }
17763
- const text = typeof arguments_?.text === "string" ? arguments_.text.trim() : "";
17764
- return { ok: true, value: text ? `/goal ${text}` : "/goal" };
17765
- }
17766
-
17767
- // dist/grok-adapter.js
17768
- import { randomUUID as randomUUID2 } from "node:crypto";
17769
-
17770
- // dist/grok-text-item-id.js
17771
- import { createHash } from "node:crypto";
17772
- function grokTextItemId(sessionId, turnIndex, kind, ordinal) {
17773
- const identity2 = JSON.stringify([sessionId, turnIndex, kind, ordinal]);
17774
- return hostItemIdSchema.parse(`grok-text-${createHash("sha256").update(identity2).digest("hex")}`);
17775
- }
17776
-
17777
- // dist/grok-stop-diagnostic.js
17778
- function isRecord2(value) {
17779
- return typeof value === "object" && value !== null && Array.isArray(value) === false;
17780
- }
17781
- function collectText(value, into, depth = 0) {
17782
- if (depth > 4)
17783
- return;
17784
- if (typeof value === "string") {
17785
- const text = value.trim();
17786
- if (text.length > 0 && !into.includes(text))
17787
- into.push(text);
17788
- return;
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;
17789
17851
  }
17790
- if (Array.isArray(value)) {
17791
- for (const entry of value)
17792
- collectText(entry, into, depth + 1);
17793
- return;
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 });
17794
17860
  }
17795
- if (!isRecord2(value))
17796
- return;
17797
- for (const key of [
17798
- "message",
17799
- "error",
17800
- "reason",
17801
- "detail",
17802
- "details",
17803
- "diagnostic",
17804
- "cause",
17805
- "err"
17806
- ]) {
17807
- if (Object.hasOwn(value, key))
17808
- collectText(value[key], into, depth + 1);
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));
17809
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);
17810
17878
  }
17811
- function grokStopDetail(source, stopReason) {
17812
- const parts = [];
17813
- collectText(source, parts);
17814
- const useful = parts.filter((part) => part !== stopReason && part.toLowerCase() !== "error" && part.length > 1);
17815
- return useful.length > 0 ? useful.join(": ") : void 0;
17816
- }
17817
- function grokTurnStopError(stopReason, source) {
17818
- const detail = grokStopDetail(source, stopReason);
17819
- const diagnostic = source !== void 0 && source !== null ? JSON.stringify(source) : void 0;
17879
+
17880
+ // ../../harness-adapter/dist/steer.js
17881
+ function unsupportedSteer(harnessLabel) {
17820
17882
  return {
17821
- code: "nativeFailure",
17822
- message: detail ? `Grok stopped the Turn: ${stopReason}: ${detail}` : `Grok stopped the Turn: ${stopReason}`,
17823
- retryable: stopReason === "max_tokens" || stopReason === "max_turn_requests",
17824
- ...diagnostic && diagnostic !== "{}" && diagnostic !== "null" ? { diagnostic } : {}
17883
+ ok: false,
17884
+ error: {
17885
+ code: "unsupported",
17886
+ message: `${harnessLabel} cannot steer an active Turn natively`,
17887
+ retryable: false
17888
+ }
17825
17889
  };
17826
17890
  }
17827
- function grokPromptStopError(response) {
17828
- return grokTurnStopError(response.stopReason, response._meta ?? void 0);
17829
- }
17830
17891
 
17831
- // dist/grok-agent-messages.js
17832
- function settledGrokAgentMessages(persisted, completedItems) {
17833
- const messages = persisted.flatMap(({ item }) => item.type === "agentMessage" ? [item] : []);
17834
- const completed = new Set(completedItems.map(({ item }) => item.itemId));
17835
- return messages.flatMap((item, index) => {
17836
- const phase = index === messages.length - 1 ? "final_answer" : "commentary";
17837
- if (completed.has(item.itemId))
17838
- return [];
17839
- return [{ ...item, phase }];
17840
- });
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);
17930
+ }
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
+ }
17941
+ }
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
+ }
17952
+ }
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
+ }
17958
+ }
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
+ }
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 };
17841
18016
  }
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
+ ]);
17842
18034
 
17843
- // dist/grok-credential-export.js
17844
- import { createHash as createHash2 } from "node:crypto";
17845
- import { readFile as readFile3 } from "node:fs/promises";
17846
- import os3 from "node:os";
17847
- import path7 from "node:path";
17848
- async function readGrokCredentials(environment) {
17849
- if ([environment.XAI_API_KEY, environment.GROK_API_KEY, environment.GROK_TOKEN].some((v) => v?.trim()))
17850
- return [];
17851
- try {
17852
- const home = environment.GROK_HOME ?? path7.join(environment.HOME ?? os3.homedir(), ".grok");
17853
- const auth = JSON.parse(await readFile3(path7.join(home, "auth.json"), "utf8"));
17854
- const client2 = "b1a00492-073a-47ea-816f-4c329264a828";
17855
- const entry = auth[`https://auth.x.ai::${client2}`] ?? auth["https://auth.x.ai"];
17856
- if (!entry || entry.oidc_issuer !== "https://auth.x.ai" || entry.oidc_client_id !== client2)
17857
- return [];
17858
- if (![entry.key, entry.refresh_token, entry.user_id].every((v) => typeof v === "string" && v.length))
17859
- return [];
17860
- const expires = Date.parse(entry.expires_at);
17861
- if (!Number.isFinite(expires))
17862
- return [];
17863
- return [
17864
- {
17865
- source: {
17866
- id: `grok:${createHash2("sha256").update(entry.user_id).digest("hex")}`,
17867
- harnessId: "grok",
17868
- provider: "xai",
17869
- label: typeof entry.email === "string" && entry.email ? entry.email : "Grok"
17870
- },
17871
- oauth: { access: entry.key, refresh: entry.refresh_token, expires: expires - 3e5 }
17872
- }
17873
- ];
17874
- } catch {
17875
- return [];
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));
18107
+ }
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);
17876
18146
  }
18147
+ return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
17877
18148
  }
17878
18149
 
17879
- // dist/grok-adapter.js
17880
- import path22 from "node:path";
17881
-
17882
- // ../../harness-plugin-files/dist/grok-computer-use.js
17883
- import { randomUUID } from "node:crypto";
17884
- import { access, mkdir as mkdir2, readFile as readFile4, rename, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
17885
- import os4 from "node:os";
17886
- import path9 from "node:path";
17887
-
17888
- // ../../harness-plugin-files/dist/grok-computer-use-lock.js
17889
- import { mkdir, rm as rm2 } from "node:fs/promises";
17890
- import path8 from "node:path";
17891
- import { setTimeout as delay2 } from "node:timers/promises";
17892
- async function withGrokComputerUseLock(dataDirectory2, grokHome4, operation) {
17893
- const locks = [
17894
- .../* @__PURE__ */ new Set([
17895
- path8.join(dataDirectory2, ".grok-computer-use.lock"),
17896
- path8.join(grokHome4, ".codexhost-cua.lock")
17897
- ])
17898
- ].sort();
17899
- const acquired = [];
17900
- const deadline = Date.now() + 5e3;
17901
- try {
17902
- for (const lock of locks) {
17903
- await mkdir(path8.dirname(lock), { recursive: true, mode: 448 });
17904
- for (; ; ) {
17905
- try {
17906
- await mkdir(lock, { mode: 448 });
17907
- acquired.push(lock);
17908
- break;
17909
- } catch (error53) {
17910
- if (error53.code !== "EEXIST")
17911
- throw error53;
17912
- if (Date.now() >= deadline)
17913
- throw new Error("Grok Computer Use settings are locked");
17914
- 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)
17915
18183
  }
17916
18184
  }
17917
- }
17918
- return await operation();
17919
- } finally {
17920
- for (const lock of acquired.reverse())
17921
- await rm2(lock, { recursive: true });
17922
- }
17923
- }
17924
-
17925
- // ../../harness-plugin-files/dist/grok-computer-use.js
17926
- var GROK_BROWSER_BINDING_SUPPORTED = false;
17927
- var PREFERENCE_FILE = "grok-computer-use.json";
17928
- var TABLE = "[mcp_servers.cua_repl]";
17929
- var ENV_TABLE = "[mcp_servers.cua_repl.env]";
17930
- var APPLY_FAILED = "Could not apply Grok Computer Use settings to Grok config.";
17931
- var GrokComputerUseError = class extends Error {
17932
- constructor(message) {
17933
- super(message);
17934
- this.name = "GrokComputerUseError";
17935
- }
17936
- };
17937
- function dataDirectory(environment) {
17938
- return environment.CODEXHOST_DATA_DIR ? path9.resolve(environment.CODEXHOST_DATA_DIR) : path9.join(os4.homedir(), ".codexhost");
17939
- }
17940
- function grokHome2(environment) {
17941
- return environment.GROK_HOME ? path9.resolve(environment.GROK_HOME) : path9.join(environment.HOME ?? os4.homedir(), ".grok");
18185
+ };
18186
+ return event;
17942
18187
  }
17943
- function chatgptApp(environment, platform) {
17944
- if (environment.CODEXHOST_CHATGPT_APP)
17945
- return path9.resolve(environment.CODEXHOST_CHATGPT_APP);
17946
- if (platform === "darwin")
17947
- return "/Applications/ChatGPT.app";
17948
- 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
+ };
17949
18202
  }
17950
- async function isFile(target2) {
17951
- try {
17952
- await access(target2);
17953
- return true;
17954
- } catch {
17955
- 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;
17956
18230
  }
18231
+ return `${title.trimEnd()}…`;
17957
18232
  }
17958
- function isNotFound(error53) {
17959
- 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;
17960
18235
  }
17961
- async function writeAtomically(file2, content) {
17962
- await mkdir2(path9.dirname(file2), { recursive: true, mode: 448 });
17963
- const temporary = `${file2}.${randomUUID()}.tmp`;
17964
- try {
17965
- await writeFile2(temporary, content, { mode: 384, flag: "wx" });
17966
- await rename(temporary, file2);
17967
- } finally {
17968
- await rm3(temporary, { force: true });
17969
- }
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("\\\\"));
17970
18238
  }
17971
- function launchPaths(environment, platform) {
17972
- const app = chatgptApp(environment, platform);
17973
- if (!app)
17974
- return void 0;
17975
- const resources = path9.join(app, "Contents", "Resources");
17976
- 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;
17977
18245
  return {
17978
- node: path9.join(cuaNode, "bin", "node"),
17979
- cuaRepl: path9.join(cuaNode, "lib", "node_modules", "@oai", "cua-repl", "bin", "cua-repl.mjs"),
17980
- nodeRepl: path9.join(cuaNode, "bin", "node_repl"),
17981
- nodeModules: path9.join(cuaNode, "lib", "node_modules"),
17982
- codexCli: path9.join(resources, "codex-cli", "bin", "codex"),
17983
- skyApp: path9.join(environment.HOME ?? os4.homedir(), ".codex", "computer-use", "Codex Computer Use.app"),
17984
- codexHome: path9.join(environment.HOME ?? os4.homedir(), ".codex"),
17985
- 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 } : {}
17986
18250
  };
17987
18251
  }
17988
- async function sharedRuntimePresent(launch) {
17989
- const present = await Promise.all([launch.node, launch.cuaRepl, launch.nodeRepl].map(isFile));
17990
- return present.every(Boolean);
17991
- }
17992
- async function computerFilesPresent(launch) {
17993
- const present = await Promise.all([isFile(launch.skyApp), isFile(launch.codexCli)]);
17994
- return present.every(Boolean);
17995
- }
17996
- async function browserFilesPresent(launch) {
17997
- return isFile(path9.join(launch.browserDesktop, "package.json"));
17998
- }
17999
- async function discoverGrokComputerUseLaunch(environment = process.env, platform = process.platform) {
18000
- const launch = launchPaths(environment, platform);
18001
- if (!launch || !await sharedRuntimePresent(launch))
18002
- return void 0;
18003
- return launch;
18004
- }
18005
- function tableRange(text, header) {
18006
- const lines = text.split(/\n/);
18007
- let start = -1;
18008
- for (let index = 0; index < lines.length; index += 1) {
18009
- if (lines[index] === header) {
18010
- start = index;
18011
- 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
+ }
18012
18275
  }
18013
- }
18014
- if (start < 0)
18015
- return void 0;
18016
- let end = lines.length;
18017
- for (let index = start + 1; index < lines.length; index += 1) {
18018
- const line = lines[index] ?? "";
18019
- if (line.startsWith("[") && line.endsWith("]")) {
18020
- end = index;
18021
- 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;
18022
18296
  }
18023
18297
  }
18024
- return { start, end };
18025
18298
  }
18026
- function removeTables(text, headers) {
18027
- let current = text;
18028
- for (const header of headers) {
18029
- const range = tableRange(current, header);
18030
- if (!range)
18031
- continue;
18032
- const lines = current.split(/\n/);
18033
- lines.splice(range.start, range.end - range.start);
18034
- 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 };
18035
18327
  }
18036
- return current.replace(/\n{3,}/g, "\n\n");
18037
18328
  }
18038
- function cuaReplEnabledInToml(text) {
18039
- const range = tableRange(text, TABLE);
18040
- if (!range)
18041
- return false;
18042
- const body = text.split(/\n/).slice(range.start, range.end);
18043
- for (const line of body) {
18044
- if (/^enabled\s*=\s*false\b/u.test(line))
18045
- return false;
18046
- if (/^enabled\s*=\s*true\b/u.test(line))
18047
- 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;
18048
18336
  }
18049
- return true;
18337
+ return { sessionId: path6.basename(directory), cwd };
18050
18338
  }
18051
- function inferredSurfaces(text) {
18052
- if (!cuaReplEnabledInToml(text))
18053
- return { enabled: false, browser: false };
18054
- const range = tableRange(text, ENV_TABLE);
18055
- const body = range ? text.split(/\n/).slice(range.start, range.end).join("\n") : "";
18056
- const literal2 = /^CUA_REPL_ENABLED_SURFACES\s*=\s*(["'])([^"']*)\1\s*(?:#.*)?$/mu.exec(body);
18057
- if (!literal2)
18058
- return { enabled: true, browser: false };
18059
- const surfaces = new Set(literal2[2]?.split(",").map((surface) => surface.trim()));
18060
- 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
+ });
18061
18393
  }
18062
- function stanza(launch, state) {
18063
- const trusted = `${launch.codexHome}:${launch.nodeModules}`;
18064
- const services = {};
18065
- if (state.browser)
18066
- services.browser = "@oai/browser-desktop/service";
18067
- if (state.enabled)
18068
- services.sky = "@oai/sky/service";
18069
- const surfaces = [state.browser ? "browser" : "", state.enabled ? "computer" : ""].filter(Boolean).join(",");
18070
- const backends = state.browser ? 'BROWSER_USE_AVAILABLE_BACKENDS = "iab"\n' : "";
18071
- const active = state.enabled || state.browser;
18072
- return `${TABLE}
18073
- command = ${JSON.stringify(launch.node)}
18074
- args = [${JSON.stringify(launch.cuaRepl)}]
18075
- enabled = ${active ? "true" : "false"}
18076
- startup_timeout_sec = 120
18077
18394
 
18078
- ${ENV_TABLE}
18079
- NODE_REPL_TRUSTED_SERVICES = ${JSON.stringify(JSON.stringify(services))}
18080
- NODE_REPL_TRUSTED_CODE_PATHS = ${JSON.stringify(trusted)}
18081
- NODE_REPL_NODE_PATH = ${JSON.stringify(launch.node)}
18082
- CODEX_HOME = ${JSON.stringify(launch.codexHome)}
18083
- CUA_REPL_NODE_REPL_PATH = ${JSON.stringify(launch.nodeRepl)}
18084
- NODE_REPL_NODE_MODULE_DIRS = ${JSON.stringify(launch.nodeModules)}
18085
- NODE_REPL_NATIVE_PIPE_CONNECT_TIMEOUT_MS = "1000"
18086
- SKY_CUA_SERVICE_PATH = ${JSON.stringify(launch.skyApp)}
18087
- CODEX_CLI_PATH = ${JSON.stringify(launch.codexCli)}
18088
- ${backends}CUA_REPL_ENABLED_SURFACES = ${JSON.stringify(surfaces)}
18089
- `;
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());
18090
18438
  }
18091
- async function readPreference(environment) {
18092
- try {
18093
- 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")) {
18094
18441
  return {
18095
- ...typeof document.enabled === "boolean" ? { enabled: document.enabled } : {},
18096
- ...typeof document.browser === "boolean" ? { browser: document.browser } : {},
18097
- ...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
+ }
18098
18448
  };
18099
- } catch (error53) {
18100
- if (isNotFound(error53))
18101
- return void 0;
18102
- throw new GrokComputerUseError("Could not read Grok Computer Use settings");
18103
18449
  }
18450
+ const text = typeof arguments_?.text === "string" ? arguments_.text.trim() : "";
18451
+ return { ok: true, value: text ? `/goal ${text}` : "/goal" };
18104
18452
  }
18105
- async function writePreference(environment, state) {
18106
- const document = {
18107
- ...typeof state.enabled === "boolean" ? { enabled: state.enabled } : {},
18108
- ...typeof state.browser === "boolean" ? { browser: state.browser } : {},
18109
- ...state.applyError ? { applyError: state.applyError } : {}
18110
- };
18111
- await writeAtomically(path9.join(dataDirectory(environment), PREFERENCE_FILE), `${JSON.stringify(document)}
18112
- `);
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")}`);
18113
18462
  }
18114
- async function readGrokConfig(environment) {
18115
- try {
18116
- return await readFile4(path9.join(grokHome2(environment), "config.toml"), "utf8");
18117
- } catch (error53) {
18118
- if (isNotFound(error53))
18119
- return "";
18120
- 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);
18121
18496
  }
18122
18497
  }
18123
- async function writeGrokConfig(environment, text) {
18124
- await writeAtomically(path9.join(grokHome2(environment), "config.toml"), text.endsWith("\n") ? text : `${text}
18125
- `);
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;
18126
18503
  }
18127
- async function currentState(environment, preference) {
18128
- const resolved = preference ?? await readPreference(environment);
18129
- 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;
18130
18507
  return {
18131
- enabled: resolved?.enabled ?? inferred?.enabled ?? false,
18132
- browser: resolved ? resolved.browser ?? false : inferred?.browser ?? false,
18133
- ...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 } : {}
18134
18512
  };
18135
18513
  }
18136
- async function surfaceFiles(launch) {
18137
- if (!launch)
18138
- return { computer: false, browser: false };
18139
- const [computer, browser] = await Promise.all([
18140
- computerFilesPresent(launch),
18141
- browserFilesPresent(launch)
18142
- ]);
18143
- return { computer, browser };
18514
+ function grokPromptStopError(response) {
18515
+ return grokTurnStopError(response.stopReason, response._meta ?? void 0);
18144
18516
  }
18145
- async function writeConfigForState(state, launch, files, environment) {
18146
- const current = await readGrokConfig(environment);
18147
- const range = tableRange(current, TABLE);
18148
- const effective = {
18149
- enabled: state.enabled && files.computer,
18150
- browser: state.browser && files.browser && GROK_BROWSER_BINDING_SUPPORTED
18151
- };
18152
- if (!effective.enabled && !effective.browser && !range)
18153
- return;
18154
- if (!launch) {
18155
- if (!range)
18156
- return;
18157
- const lines = current.split(/\n/);
18158
- const body = lines.slice(range.start, range.end);
18159
- const replaced = body.map((line) => /^enabled\s*=/u.test(line) ? "enabled = false" : line);
18160
- if (!replaced.some((line) => /^enabled\s*=/u.test(line))) {
18161
- replaced.splice(1, 0, "enabled = false");
18162
- }
18163
- lines.splice(range.start, range.end - range.start, ...replaced);
18164
- await writeGrokConfig(environment, lines.join("\n"));
18165
- return;
18166
- }
18167
- const stripped = removeTables(current, [ENV_TABLE, TABLE]).replace(/\s+$/u, "\n");
18168
- await writeGrokConfig(environment, `${stripped.trimEnd()}
18169
18517
 
18170
- ${stanza(launch, effective)}`);
18171
- }
18172
- async function applyGrokComputerUsePreference(environment = process.env, platform = process.platform) {
18173
- await withGrokComputerUseLock(dataDirectory(environment), grokHome2(environment), async () => {
18174
- const preference = await readPreference(environment);
18175
- if (preference === void 0)
18176
- return;
18177
- const launch = await discoverGrokComputerUseLaunch(environment, platform);
18178
- const files = await surfaceFiles(launch);
18179
- const state = await currentState(environment, preference);
18180
- try {
18181
- await writeConfigForState(state, launch, files, environment);
18182
- if (state.applyError)
18183
- await writePreference(environment, { enabled: state.enabled, browser: state.browser });
18184
- } catch (error53) {
18185
- const applyError = error53 instanceof GrokComputerUseError ? error53.message : APPLY_FAILED;
18186
- await writePreference(environment, {
18187
- enabled: state.enabled,
18188
- browser: state.browser,
18189
- applyError
18190
- }).catch(() => void 0);
18191
- throw error53 instanceof GrokComputerUseError ? error53 : new GrokComputerUseError(APPLY_FAILED);
18192
- }
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 }];
18193
18527
  });
18194
18528
  }
18195
18529
 
18196
- // ../../harness-adapter/dist/approval.js
18197
- function invalidRequest(message) {
18198
- return { code: "invalidRequest", message, retryable: false };
18199
- }
18200
- function validateHostApprovalResponse(interaction, response) {
18201
- 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
+ }
18202
18564
  }
18203
18565
 
18204
- // ../../harness-adapter/dist/question.js
18205
- function invalidRequest2(message) {
18206
- return { code: "invalidRequest", message, retryable: false };
18207
- }
18208
- function validateHostQuestionResponse(interaction, response) {
18209
- const questionIds = new Set(interaction.questions.map(({ id }) => id));
18210
- if (response.cancelled) {
18211
- return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
18212
- }
18213
- for (const answerId of Object.keys(response.answers)) {
18214
- if (!questionIds.has(answerId)) {
18215
- return invalidRequest2("Question Response contains an unknown Question ID");
18216
- }
18217
- }
18218
- for (const question of interaction.questions) {
18219
- const answers = response.answers[question.id] ?? [];
18220
- if (new Set(answers).size !== answers.length) {
18221
- return invalidRequest2("Question Response contains duplicate answers");
18222
- }
18223
- if (!question.optional && answers.length === 0) {
18224
- return invalidRequest2("Question Response omits a required answer");
18225
- }
18226
- if (question.type === "text") {
18227
- if (answers.length > 1) {
18228
- 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
+ }
18229
18603
  }
18230
- continue;
18231
- }
18232
- if (!question.multiple && answers.length > 1) {
18233
- return invalidRequest2("Single-choice Question accepts at most one answer");
18234
- }
18235
- const declared = new Set(question.options.map(({ value }) => value));
18236
- if (!question.allowOther && answers.some((answer) => !declared.has(answer))) {
18237
- return invalidRequest2("Question Response contains an undeclared choice");
18238
18604
  }
18605
+ return await operation();
18606
+ } finally {
18607
+ for (const lock of acquired.reverse())
18608
+ await rm2(lock, { recursive: true });
18239
18609
  }
18240
- return null;
18241
18610
  }
18242
18611
 
18243
- // ../../harness-adapter/dist/output-channel.js
18244
- var HarnessOutputChannel = class {
18245
- outputs;
18246
- #consumerCreated = false;
18247
- #ended = false;
18248
- #pending = [];
18249
- #values = [];
18250
- constructor() {
18251
- this.outputs = {
18252
- [Symbol.asyncIterator]: () => {
18253
- if (this.#consumerCreated) {
18254
- throw new Error("Harness outputs allow only one consumer");
18255
- }
18256
- this.#consumerCreated = true;
18257
- return {
18258
- next: () => this.#next()
18259
- };
18260
- }
18261
- };
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";
18262
18622
  }
18263
- emit(value) {
18264
- if (this.#ended)
18265
- return false;
18266
- const resolve = this.#pending.shift();
18267
- if (resolve)
18268
- resolve({ done: false, value });
18269
- else
18270
- 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);
18271
18640
  return true;
18641
+ } catch {
18642
+ return false;
18272
18643
  }
18273
- end() {
18274
- if (this.#ended)
18275
- return;
18276
- this.#ended = true;
18277
- if (this.#values.length !== 0)
18278
- return;
18279
- for (const resolve of this.#pending.splice(0))
18280
- resolve({ done: true, value: void 0 });
18281
- }
18282
- #next() {
18283
- const value = this.#values.shift();
18284
- if (value !== void 0)
18285
- return Promise.resolve({ done: false, value });
18286
- if (this.#ended)
18287
- return Promise.resolve({ done: true, value: void 0 });
18288
- 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 });
18289
18656
  }
18290
- };
18291
-
18292
- // ../../harness-adapter/dist/diagnostics.js
18293
- var DIAGNOSTIC_TAIL_MAX_LENGTH = 8e3;
18294
- var SENSITIVE_VALUE_PATTERN = /(api[_-]?key|access[_-]?token|auth(?:orization)?|password|secret)(\s*[:=]\s*)([^\s,;]+)/giu;
18295
- var BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]+/giu;
18296
- function sanitizeDiagnosticTail(value) {
18297
- const redacted = value.replace(BEARER_PATTERN, "Bearer [redacted]").replace(SENSITIVE_VALUE_PATTERN, "$1$2[redacted]");
18298
- return redacted.length <= DIAGNOSTIC_TAIL_MAX_LENGTH ? redacted : redacted.slice(-DIAGNOSTIC_TAIL_MAX_LENGTH);
18299
18657
  }
18300
-
18301
- // ../../harness-adapter/dist/steer.js
18302
- 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");
18303
18664
  return {
18304
- ok: false,
18305
- error: {
18306
- code: "unsupported",
18307
- message: `${harnessLabel} cannot steer an active Turn natively`,
18308
- retryable: false
18309
- }
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")
18310
18673
  };
18311
18674
  }
18312
-
18313
- // ../../harness-adapter/dist/usage.js
18314
- var tokenFields = [
18315
- "inputTokens",
18316
- "cachedInputTokens",
18317
- "cacheWriteInputTokens",
18318
- "outputTokens",
18319
- "reasoningOutputTokens",
18320
- "totalTokens",
18321
- "contextWindowTokens",
18322
- "contextUsedTokens"
18323
- ];
18324
- var safeIntegerFields = [
18325
- "planFiveHourResetsAtUnix",
18326
- "planSevenDayResetsAtUnix",
18327
- "timeToFirstOutputMs"
18328
- ];
18329
- var percentFields = [
18330
- "cacheHitRatePercent",
18331
- "sessionCacheHitRatePercent",
18332
- "planFiveHourUsedPercent",
18333
- "planSevenDayUsedPercent"
18334
- ];
18335
- var usageFields = /* @__PURE__ */ new Set([
18336
- ...tokenFields,
18337
- ...safeIntegerFields,
18338
- ...percentFields,
18339
- "sessionCacheUsage",
18340
- "composerIndicators",
18341
- "totalCostUsd",
18342
- "totalCredits",
18343
- "contextUsagePercent",
18344
- "outputTokensPerSecond",
18345
- "apiOutputTokensPerSecond",
18346
- "costSource",
18347
- "unpricedModels"
18348
- ]);
18349
- function isRecord3(value) {
18350
- 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);
18351
18678
  }
18352
- function parseHostUsage(value) {
18353
- if (!isRecord3(value))
18354
- throw new Error("Harness Usage must be an object");
18355
- const keys = Object.keys(value);
18356
- if (keys.length === 0)
18357
- throw new Error("Harness Usage must contain a reliable field");
18358
- for (const key of keys) {
18359
- if (!usageFields.has(key)) {
18360
- throw new Error(`Harness Usage contains unknown field '${key}'`);
18361
- }
18362
- }
18363
- const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
18364
- for (const field2 of [
18365
- "totalCredits",
18366
- "contextUsagePercent",
18367
- "apiOutputTokensPerSecond"
18368
- ]) {
18369
- const candidate = value[field2];
18370
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
18371
- throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
18372
- }
18373
- }
18374
- for (const field2 of tokenFields) {
18375
- const candidate = value[field2];
18376
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
18377
- throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
18378
- }
18379
- }
18380
- for (const field2 of safeIntegerFields) {
18381
- const candidate = value[field2];
18382
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
18383
- throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
18384
- }
18385
- }
18386
- if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
18387
- throw new Error("Harness Usage 'outputTokensPerSecond' must be a finite non-negative number");
18388
- }
18389
- if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
18390
- throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
18391
- }
18392
- for (const field2 of percentFields) {
18393
- const candidate = value[field2];
18394
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
18395
- 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;
18396
18699
  }
18397
18700
  }
18398
- if (value.sessionCacheUsage !== void 0) {
18399
- const totals2 = value.sessionCacheUsage;
18400
- 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) {
18401
- 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;
18402
18709
  }
18403
18710
  }
18404
- const hasContextUsed = value.contextUsedTokens !== void 0;
18405
- const hasContextWindow = value.contextWindowTokens !== void 0;
18406
- if (hasContextUsed !== hasContextWindow) {
18407
- throw new Error("Harness Usage context fields must be provided together");
18408
- }
18409
- if (hasContextWindow && value.contextWindowTokens === 0) {
18410
- throw new Error("Harness Usage 'contextWindowTokens' must be greater than zero");
18411
- }
18412
- if (value.planFiveHourResetsAtUnix !== void 0 && value.planFiveHourUsedPercent === void 0) {
18413
- 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");
18414
18722
  }
18415
- if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
18416
- 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;
18417
18735
  }
18418
- if (value.costSource !== void 0) {
18419
- if (value.costSource !== "publicPrice" && value.costSource !== "native") {
18420
- throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
18421
- }
18422
- if (value.totalCostUsd === void 0) {
18423
- throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
18424
- }
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");
18425
18790
  }
18426
- if (value.unpricedModels !== void 0) {
18427
- const models = value.unpricedModels;
18428
- if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
18429
- throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
18430
- }
18431
- if (value.costSource !== "publicPrice") {
18432
- throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
18433
- }
18434
- 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");
18435
18808
  }
18436
- return { ...value, ...indicators };
18437
18809
  }
18438
- var requestTokenFields = [
18439
- "inputTokens",
18440
- "cachedInputTokens",
18441
- "cacheWriteInputTokens",
18442
- "cacheWrite1hInputTokens",
18443
- "outputTokens",
18444
- "reasoningOutputTokens",
18445
- "startedAtMs",
18446
- "completedAtMs"
18447
- ];
18448
- var requestFields = /* @__PURE__ */ new Set([
18449
- ...requestTokenFields,
18450
- "requestId",
18451
- "historical",
18452
- "model",
18453
- "provider"
18454
- ]);
18455
-
18456
- // ../../harness-adapter/dist/live-command-catalog.js
18457
- var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
18458
- // Session lifecycle
18459
- "branch",
18460
- "clear",
18461
- "exit",
18462
- "fork",
18463
- "fresh",
18464
- "new",
18465
- "quit",
18466
- "rename",
18467
- "rename-chat",
18468
- "reset",
18469
- "resume",
18470
- "rewind",
18471
- "session",
18472
- "sessions",
18473
- // Desktop-owned configuration
18474
- "autocompact",
18475
- "color",
18476
- "config",
18477
- "effort",
18478
- "fast",
18479
- "keybindings",
18480
- "model",
18481
- "models",
18482
- "output-style",
18483
- "permissions",
18484
- "settings",
18485
- "statusline",
18486
- "terminal-setup",
18487
- "theme",
18488
- "vim",
18489
- // Trust and approval policy
18490
- "always-approve",
18491
- "auto-mode-setup",
18492
- // Native login
18493
- "login",
18494
- "logout",
18495
- // Work outliving the Turn
18496
- "autopilot",
18497
- "background",
18498
- "bg",
18499
- "goal",
18500
- "jobs",
18501
- "loop",
18502
- "multitask",
18503
- "queue",
18504
- "remote-control",
18505
- "schedule",
18506
- "steer",
18507
- // Native terminal UI
18508
- "copy",
18509
- "debug",
18510
- "feedback",
18511
- "heapdump",
18512
- "share",
18513
- "shell",
18514
- // Plugin and MCP management
18515
- "marketplace",
18516
- "mcp",
18517
- "plugins",
18518
- "reload-plugins"
18519
- ]);
18520
- var COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES = ["__", "hooks-"];
18521
- function isExcludedLiveCommand(name, kind, extra = {}) {
18522
- const normalized = name.trim().replace(/^\//u, "");
18523
- if (new Set(extra.names ?? []).has(normalized))
18524
- return true;
18525
- if (extra.prefixes?.some((prefix) => normalized.startsWith(prefix)))
18526
- return true;
18527
- if (kind === "skill")
18528
- return false;
18529
- 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
+ `);
18530
18813
  }
18531
- function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
18532
- if (!commandId.startsWith(idPrefix))
18533
- return null;
18534
- const descriptor = catalog.commands.find(({ id }) => id === commandId);
18535
- if (!descriptor)
18536
- return null;
18537
- const text = typeof argumentText === "string" ? argumentText.trim() : "";
18538
- 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
+ };
18539
18822
  }
18540
- function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
18541
- if (!live)
18542
- return builtIns;
18543
- const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
18544
- const ids = new Set(builtIns.commands.map(({ id }) => id));
18545
- const dynamic = [];
18546
- for (const command of live) {
18547
- const name = command.name.trim().replace(/^\//u, "");
18548
- if (!name || /\s/u.test(name))
18549
- continue;
18550
- if (isExcludedLiveCommand(name, command.kind, exclusions))
18551
- continue;
18552
- const invocation = `/${name}`;
18553
- const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
18554
- if (invocations.has(invocation) || ids.has(id))
18555
- continue;
18556
- const description = command.description?.trim().slice(0, 512);
18557
- const parsed = harnessCommandDescriptorSchema.safeParse({
18558
- id,
18559
- invocation,
18560
- label: name.slice(0, 128),
18561
- ...description ? { description } : {},
18562
- argumentMode: "text",
18563
- kind: command.kind
18564
- });
18565
- if (!parsed.success)
18566
- continue;
18567
- invocations.add(invocation);
18568
- ids.add(id);
18569
- 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;
18570
18853
  }
18571
- 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
+ });
18572
18881
  }
18573
18882
 
18574
18883
  // ../../harness-adapter/dist/local-media-markdown.js
@@ -23123,15 +23432,13 @@ function parseGrokAvailableCommands(value) {
23123
23432
  ];
23124
23433
  });
23125
23434
  }
23126
- function isGrokSkill(command) {
23127
- const path23 = command.meta?.path;
23128
- return typeof path23 === "string" && /(^|[\\/])SKILL\.md$/u.test(path23) || typeof command.meta?.qualifiedName === "string";
23129
- }
23130
23435
  function grokLiveCommands(native) {
23131
- 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) => ({
23132
23440
  name: command.name,
23133
- description: command.description,
23134
- kind: isGrokSkill(command) ? "skill" : "command"
23441
+ description: command.description
23135
23442
  }));
23136
23443
  }
23137
23444
 
@@ -25173,6 +25480,7 @@ function mapGrokReplay(replay, harnessId, sessionId, cwd, knownTurnRefs = [], to
25173
25480
  description: grokSubagentDescription(event.rawInput, event.title),
25174
25481
  ...role ? { role } : {},
25175
25482
  ...model2 ? { model: model2 } : {},
25483
+ ...subagentConfiguration(event.rawInput),
25176
25484
  background: grokSubagentBackground(event.rawInput),
25177
25485
  status: "running"
25178
25486
  }
@@ -29416,7 +29724,19 @@ var GrokHarnessSession = class {
29416
29724
  ...this.#state.effectivePermissionModeId ? { permissionModeId: this.#state.effectivePermissionModeId } : {}
29417
29725
  };
29418
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
+ }
29419
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() {
29420
29740
  if (this.#phase !== "open") {
29421
29741
  return { ok: false, error: invalidState("Grok Session is not open") };
29422
29742
  }
@@ -30506,6 +30826,7 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
30506
30826
  ...prompt ? { prompt } : {},
30507
30827
  ...role ? { role } : {},
30508
30828
  ...model2 ? { model: model2 } : {},
30829
+ ...subagentConfiguration(event.rawInput),
30509
30830
  background: grokSubagentBackground(event.rawInput),
30510
30831
  ...nativeSubagentId ? { nativeSubagentId } : {}
30511
30832
  });
@@ -30566,6 +30887,8 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
30566
30887
  const role = grokSubagentRole(event.rawInput);
30567
30888
  const nativeSubagentId = grokNativeSubagentId(event.rawInput, event.rawOutput, event.content);
30568
30889
  active.subagents.update(active.command.turnId, event.callId, {
30890
+ ...subagentConfiguration(event.rawInput),
30891
+ ...subagentConfiguration(event.rawOutput),
30569
30892
  ...event.title ? { description: grokSubagentDescription(event.rawInput, event.title) } : {},
30570
30893
  ...role ? { role } : {},
30571
30894
  ...nativeSubagentId ? { nativeSubagentId } : {}
@@ -30930,6 +31253,7 @@ Elapsed seconds: ${value.timeUsedSeconds}` : argument === "clear" ? "Goal cleare
30930
31253
  this.#onClosed();
30931
31254
  }
30932
31255
  #event(event) {
31256
+ event = configureSubagentEvent(event, this.#subagentConfiguration());
30933
31257
  this.#channel.emit({ kind: "event", event });
30934
31258
  }
30935
31259
  };