@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
@@ -408,152 +408,6 @@ function createHarnessInstaller(environment, source) {
408
408
  };
409
409
  }
410
410
 
411
- // ../../harness-adapter/dist/usage-statistics.js
412
- import { createReadStream } from "node:fs";
413
- import { lstat, opendir } from "node:fs/promises";
414
- import path4 from "node:path";
415
- import { createInterface } from "node:readline";
416
- var MAX_SESSION_ID_LENGTH = 512;
417
- var MAX_CWD_LENGTH = 4096;
418
- var MAX_SESSION_TITLE_LENGTH = 200;
419
- function usageSessionTitle(value) {
420
- if (typeof value !== "string")
421
- return void 0;
422
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
423
- if (!normalized)
424
- return void 0;
425
- if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
426
- return normalized;
427
- let title = "";
428
- for (const character of normalized) {
429
- if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
430
- break;
431
- title += character;
432
- }
433
- return `${title.trimEnd()}…`;
434
- }
435
- function sessionIdOk(value) {
436
- return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
437
- }
438
- function cwdOk(value) {
439
- 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("\\\\"));
440
- }
441
- function withUsageSession(entry, session) {
442
- const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
443
- const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
444
- const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
445
- if (sessionId === void 0 && cwd === void 0)
446
- return entry;
447
- return {
448
- ...entry,
449
- ...sessionId !== void 0 ? { sessionId } : {},
450
- ...cwd !== void 0 ? { cwd } : {},
451
- ...sessionTitle !== void 0 ? { sessionTitle } : {}
452
- };
453
- }
454
- function usageEntryFromRequest(request, occurredAtMs) {
455
- if (!Number.isSafeInteger(occurredAtMs) || occurredAtMs <= 0)
456
- return null;
457
- return {
458
- id: request.requestId,
459
- occurredAtMs,
460
- ...request.model !== void 0 ? { model: request.model } : {},
461
- inputTokens: request.inputTokens,
462
- ...request.cachedInputTokens !== void 0 ? { cachedInputTokens: request.cachedInputTokens } : {},
463
- ...request.cacheWriteInputTokens !== void 0 ? { cacheWriteInputTokens: request.cacheWriteInputTokens } : {},
464
- ...request.cacheWrite1hInputTokens !== void 0 ? { cacheWrite1hInputTokens: request.cacheWrite1hInputTokens } : {},
465
- outputTokens: request.outputTokens,
466
- ...request.reasoningOutputTokens !== void 0 ? { reasoningOutputTokens: request.reasoningOutputTokens } : {}
467
- };
468
- }
469
- async function jsonlUsageSources(root, maxDepth, signal) {
470
- const sources = [];
471
- const visit = async (directory, depth) => {
472
- signal.throwIfAborted();
473
- const entries = await opendir(directory).catch((error51) => {
474
- if (error51.code === "ENOENT")
475
- return null;
476
- throw error51;
477
- });
478
- if (!entries)
479
- return;
480
- for await (const entry of entries) {
481
- signal.throwIfAborted();
482
- const file2 = path4.join(directory, entry.name);
483
- if (entry.isDirectory()) {
484
- if (depth < maxDepth)
485
- await visit(file2, depth + 1);
486
- } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
487
- const info = await lstat(file2).catch(() => null);
488
- if (info?.isFile() && info.size > 0) {
489
- sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
490
- }
491
- }
492
- }
493
- };
494
- await visit(root, 0);
495
- return sources;
496
- }
497
- async function* jsonlRecords(file2, marker, signal) {
498
- const lines = createInterface({
499
- input: createReadStream(file2, { encoding: "utf8", signal }),
500
- crlfDelay: Infinity
501
- });
502
- for await (const line of lines) {
503
- if (!line.includes(marker))
504
- continue;
505
- let value;
506
- try {
507
- value = JSON.parse(line);
508
- } catch {
509
- continue;
510
- }
511
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
512
- yield value;
513
- }
514
- }
515
- }
516
- async function jsonlHeader(file2, match, signal, maxLines = 4) {
517
- const stream = createReadStream(file2, { encoding: "utf8", signal });
518
- const lines = createInterface({ input: stream, crlfDelay: Infinity });
519
- let seen = 0;
520
- try {
521
- for await (const line of lines) {
522
- if (++seen > maxLines)
523
- break;
524
- let value;
525
- try {
526
- value = JSON.parse(line);
527
- } catch {
528
- continue;
529
- }
530
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
531
- const record3 = value;
532
- if (match(record3))
533
- return record3;
534
- }
535
- }
536
- return null;
537
- } finally {
538
- lines.close();
539
- stream.destroy();
540
- }
541
- }
542
- function nativeTimeMs(value) {
543
- const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
544
- return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
545
- }
546
-
547
- // dist/session-import.js
548
- import { createReadStream as createReadStream2 } from "node:fs";
549
- import { opendir as opendir2, realpath, stat } from "node:fs/promises";
550
- import os2 from "node:os";
551
- import path5 from "node:path";
552
- import { createInterface as createInterface2 } from "node:readline";
553
-
554
- // ../../harness-adapter/dist/session-import.js
555
- import { lstat as lstat2 } from "node:fs/promises";
556
-
557
411
  // ../../../node_modules/zod/v4/classic/external.js
558
412
  var external_exports = {};
559
413
  __export(external_exports, {
@@ -15095,7 +14949,7 @@ var harnessGoalSetSchema = external_exports.object({
15095
14949
  origin: goalOriginSchema
15096
14950
  });
15097
14951
 
15098
- // ../../shared-contracts/dist/realtime-call.js
14952
+ // ../../shared-contracts/dist/realtime-call-core.js
15099
14953
  var REALTIME_CALL_FORWARDED_HEADERS = [
15100
14954
  "openai-alpha",
15101
14955
  "thread-id",
@@ -15104,7 +14958,9 @@ var REALTIME_CALL_FORWARDED_HEADERS = [
15104
14958
  "x-codex-turn-metadata"
15105
14959
  ];
15106
14960
  var FORWARDED_HEADERS = new Set(REALTIME_CALL_FORWARDED_HEADERS);
15107
- var REALTIME_CALL_ID_PATTERN = /^rtc_[A-Za-z0-9_-]{1,128}$/u;
14961
+ var REALTIME_CALL_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/u;
14962
+
14963
+ // ../../shared-contracts/dist/realtime-call.js
15108
14964
  var requestId = external_exports.string().min(1).max(128);
15109
14965
  var realtimeCallParamsSchema = external_exports.discriminatedUnion("operation", [
15110
14966
  external_exports.object({
@@ -15159,12 +15015,6 @@ var RELAY_PUBLIC_ORIGIN = "https://codexhost.karldigi.dev";
15159
15015
  var RELAY_PUBLIC_RESOURCE = `${RELAY_PUBLIC_ORIGIN}/mcp`;
15160
15016
  var RELAY_WAIT_TIMEOUT_MAX_MS = 25e3;
15161
15017
  var RELAY_MAX_BODY_BYTES = 2 * 1024 * 1024;
15162
- var RELAY_ALLOWED_ROUTES = [
15163
- "/v1/enroll/status",
15164
- "/v1/thread/read",
15165
- "/v1/thread/wait",
15166
- "/v1/thread/send"
15167
- ];
15168
15018
  var relayLinkHelloSchema = external_exports.strictObject({
15169
15019
  v: external_exports.literal(RELAY_LINK_PROTOCOL_VERSION),
15170
15020
  secret: external_exports.string().min(1).max(4096)
@@ -15176,8 +15026,11 @@ var relayLinkHelloAckSchema = external_exports.strictObject({
15176
15026
  var relayLinkRequestSchema = external_exports.strictObject({
15177
15027
  requestId: external_exports.string().min(1).max(128),
15178
15028
  deadlineMs: external_exports.number().int().positive(),
15179
- route: external_exports.enum(RELAY_ALLOWED_ROUTES),
15180
- body: external_exports.record(external_exports.string(), external_exports.unknown())
15029
+ route: external_exports.string().min(1).max(128),
15030
+ body: external_exports.record(external_exports.string(), external_exports.unknown()),
15031
+ operationalClient: external_exports.string().min(1).max(64).optional(),
15032
+ oauthClientId: external_exports.string().min(1).max(128).optional(),
15033
+ dispatchGrant: external_exports.enum(["legacy-four", "full-dispatch"]).optional()
15181
15034
  });
15182
15035
  var relayLinkErrorSchema = external_exports.strictObject({
15183
15036
  code: external_exports.string().min(1).max(64),
@@ -15221,6 +15074,204 @@ var relayEnrollStatusResultSchema = external_exports.strictObject({
15221
15074
  runtime: external_exports.enum(["reachable", "unreachable"])
15222
15075
  });
15223
15076
 
15077
+ // ../../shared-contracts/dist/external-clients.js
15078
+ var EXTERNAL_CLIENT_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u;
15079
+ var externalClientNameSchema = external_exports.string().trim().min(1).max(64).regex(EXTERNAL_CLIENT_NAME_PATTERN);
15080
+ var externalClientAccessSchema = external_exports.enum(["all-threads", "selected-workspaces"]);
15081
+ var externalClientConnectionModeSchema = external_exports.enum(["public-relay", "local", "direct"]);
15082
+ var externalClientDispatchGrantSchema = external_exports.enum(["legacy-four", "full-dispatch"]);
15083
+ var workspacePathSchema = external_exports.string().trim().min(1).max(4096);
15084
+ var directUrlSchema = external_exports.string().trim().max(2048);
15085
+ var externalClientPublicViewSchema = external_exports.strictObject({
15086
+ name: externalClientNameSchema,
15087
+ createdAt: external_exports.string().min(1).max(64),
15088
+ access: externalClientAccessSchema,
15089
+ workspaces: external_exports.array(workspacePathSchema).max(64),
15090
+ connectionMode: externalClientConnectionModeSchema,
15091
+ dispatchGrant: externalClientDispatchGrantSchema,
15092
+ oauthClientId: external_exports.string().trim().min(1).max(128).optional(),
15093
+ directUrl: directUrlSchema.optional(),
15094
+ mcpUrl: external_exports.string().min(1).max(2048).optional(),
15095
+ mcpUrlNote: external_exports.string().min(1).max(512).optional()
15096
+ });
15097
+ var externalClientListParamsSchema = external_exports.strictObject({});
15098
+ var externalClientListResultSchema = external_exports.strictObject({
15099
+ clients: external_exports.array(externalClientPublicViewSchema).max(256)
15100
+ });
15101
+ var externalClientWriteFieldsSchema = external_exports.strictObject({
15102
+ access: externalClientAccessSchema.optional(),
15103
+ workspaces: external_exports.array(workspacePathSchema).max(64).optional(),
15104
+ connectionMode: externalClientConnectionModeSchema.optional(),
15105
+ dispatchGrant: externalClientDispatchGrantSchema.optional(),
15106
+ oauthClientId: external_exports.string().trim().min(1).max(128).optional(),
15107
+ directUrl: directUrlSchema.optional()
15108
+ });
15109
+ var externalClientCreateParamsSchema = externalClientWriteFieldsSchema.extend({
15110
+ name: externalClientNameSchema
15111
+ });
15112
+ var externalClientCreateResultSchema = externalClientPublicViewSchema.extend({
15113
+ token: external_exports.string().min(1).max(256).optional()
15114
+ });
15115
+ var externalClientUpdateParamsSchema = externalClientWriteFieldsSchema.extend({
15116
+ name: externalClientNameSchema,
15117
+ clearOauthClientId: external_exports.literal(true).optional()
15118
+ });
15119
+ var externalClientRevokeParamsSchema = external_exports.strictObject({
15120
+ name: externalClientNameSchema
15121
+ });
15122
+ var externalClientRevokeResultSchema = external_exports.strictObject({
15123
+ name: externalClientNameSchema,
15124
+ revoked: external_exports.literal(true)
15125
+ });
15126
+ var stringProp = (description) => ({ type: "string", description });
15127
+ var integerProp = (description) => ({
15128
+ type: "integer",
15129
+ minimum: 0,
15130
+ description
15131
+ });
15132
+ var threadProp = stringProp("Thread id or codex://threads/<id> link");
15133
+ var EXTERNAL_MCP_TOOL_DESCRIPTORS = [
15134
+ {
15135
+ name: "harness_list",
15136
+ description: "List the Harnesses this codexhost can delegate to.",
15137
+ inputSchema: { type: "object", properties: {} }
15138
+ },
15139
+ {
15140
+ name: "harness_inspect",
15141
+ description: "Read a Harness's Models, Thinking options and defaults; use the returned ids when delegating.",
15142
+ inputSchema: {
15143
+ type: "object",
15144
+ properties: {
15145
+ harnessId: stringProp("Harness id from harness_list"),
15146
+ cwd: stringProp("Absolute workspace path"),
15147
+ refresh: { type: "boolean" }
15148
+ },
15149
+ required: ["harnessId"]
15150
+ }
15151
+ },
15152
+ {
15153
+ name: "delegate_start",
15154
+ 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).",
15155
+ inputSchema: {
15156
+ type: "object",
15157
+ properties: {
15158
+ harnessId: stringProp("Harness id from harness_list"),
15159
+ task: stringProp("The full task text"),
15160
+ taskName: stringProp("Short display name"),
15161
+ cwd: stringProp("Absolute workspace path"),
15162
+ model: stringProp("Model id from harness_inspect"),
15163
+ thinking: stringProp("Thinking option id from harness_inspect"),
15164
+ parentThread: stringProp("Optional parent Thread"),
15165
+ requestId: stringProp("Reuse to retry idempotently"),
15166
+ refs: {
15167
+ type: "array",
15168
+ items: { type: "string" },
15169
+ description: "Absolute URIs of where the work came from"
15170
+ },
15171
+ watch: { type: "boolean", description: "Record an event when the Thread stops" },
15172
+ watchTimeoutMs: integerProp("How long to watch; default 29 minutes")
15173
+ },
15174
+ required: ["harnessId", "task"]
15175
+ }
15176
+ },
15177
+ {
15178
+ name: "thread_read",
15179
+ description: "Read a Thread's status and latest result, or page its visible messages (view=messages). Never changes the Thread.",
15180
+ inputSchema: {
15181
+ type: "object",
15182
+ properties: {
15183
+ thread: threadProp,
15184
+ view: { type: "string", enum: ["result", "messages"] },
15185
+ cursor: stringProp("Message cursor"),
15186
+ limit: integerProp("Messages per page, at most 100")
15187
+ },
15188
+ required: ["thread"]
15189
+ }
15190
+ },
15191
+ {
15192
+ name: "thread_wait",
15193
+ description: "Wait up to timeoutMs (at most 60000) for a Thread to stop, then return the same snapshot as thread_read plus timedOut.",
15194
+ inputSchema: {
15195
+ type: "object",
15196
+ properties: {
15197
+ thread: threadProp,
15198
+ timeoutMs: integerProp("At most 60000; default 30000"),
15199
+ view: { type: "string", enum: ["result", "messages"] }
15200
+ },
15201
+ required: ["thread"]
15202
+ }
15203
+ },
15204
+ {
15205
+ name: "thread_list",
15206
+ description: "List Threads: by workspace (cwd), by parent Thread, by the client that started them, or by reference.",
15207
+ inputSchema: {
15208
+ type: "object",
15209
+ properties: {
15210
+ cwd: stringProp("Absolute workspace path"),
15211
+ parent: stringProp("Parent Thread"),
15212
+ client: stringProp("Client name"),
15213
+ ref: stringProp("Reference URI"),
15214
+ limit: integerProp("At most 100; default 25"),
15215
+ cursor: stringProp("Cursor from a previous page"),
15216
+ sort: {
15217
+ type: "string",
15218
+ enum: [
15219
+ "created-asc",
15220
+ "created-desc",
15221
+ "updated-asc",
15222
+ "updated-desc",
15223
+ "recency-asc",
15224
+ "recency-desc"
15225
+ ]
15226
+ }
15227
+ }
15228
+ }
15229
+ },
15230
+ {
15231
+ name: "thread_send",
15232
+ description: "Start a new Turn in an idle Thread. THREAD_BUSY means its current Turn is still running; messages are not queued.",
15233
+ inputSchema: {
15234
+ type: "object",
15235
+ properties: { thread: threadProp, message: stringProp("Message text") },
15236
+ required: ["thread", "message"]
15237
+ }
15238
+ },
15239
+ {
15240
+ name: "thread_cancel",
15241
+ description: "Cancel a Thread's active Turn, keeping the Thread and its history.",
15242
+ inputSchema: { type: "object", properties: { thread: threadProp }, required: ["thread"] }
15243
+ },
15244
+ {
15245
+ name: "thread_watch",
15246
+ description: "Record one event for this client when the Thread stops or the watch expires.",
15247
+ inputSchema: {
15248
+ type: "object",
15249
+ properties: { thread: threadProp, timeoutMs: integerProp("Default 29 minutes") },
15250
+ required: ["thread"]
15251
+ }
15252
+ },
15253
+ {
15254
+ name: "thread_watches",
15255
+ description: "List watches that have not been delivered yet.",
15256
+ inputSchema: { type: "object", properties: {} }
15257
+ },
15258
+ {
15259
+ name: "events_poll",
15260
+ 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>.",
15261
+ inputSchema: {
15262
+ type: "object",
15263
+ properties: {
15264
+ after: integerProp("Cursor; 0 for all retained"),
15265
+ timeoutMs: integerProp("At most 60000; default 0"),
15266
+ limit: integerProp("At most 100")
15267
+ }
15268
+ }
15269
+ }
15270
+ ];
15271
+
15272
+ // ../../shared-contracts/dist/external-mcp-map.js
15273
+ var DEFAULT_WATCH_MS = 29 * 6e4;
15274
+
15224
15275
  // ../../shared-contracts/dist/grok-computer-use.js
15225
15276
  var grokComputerUseGetSchema = external_exports.object({}).strict();
15226
15277
  var grokComputerUseSetSchema = external_exports.object({
@@ -15817,11 +15868,61 @@ var threadSteeringInspectResultSchema = external_exports.object({
15817
15868
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15818
15869
  }).strict();
15819
15870
 
15871
+ // ../../shared-contracts/dist/voice-settings.js
15872
+ var voiceRoutesSchema = external_exports.strictObject({
15873
+ chatExperience: external_exports.enum(["chatgpt", "codex"]),
15874
+ chatConnection: external_exports.enum(["desktop", "gateway"]),
15875
+ workConnection: external_exports.enum(["desktop", "gateway"])
15876
+ });
15877
+ var DEFAULT_VOICE_ROUTES = Object.freeze({
15878
+ chatExperience: "chatgpt",
15879
+ chatConnection: "desktop",
15880
+ workConnection: "gateway"
15881
+ });
15882
+ var voiceSettingsSchema = voiceRoutesSchema.extend({ inject: external_exports.boolean() });
15883
+ var voiceSettingsRequestSchema = external_exports.discriminatedUnion("operation", [
15884
+ external_exports.strictObject({
15885
+ operation: external_exports.literal("get"),
15886
+ runtime: external_exports.strictObject({
15887
+ id: external_exports.string().uuid(),
15888
+ revision: external_exports.string().max(64),
15889
+ activeCall: external_exports.boolean()
15890
+ }).optional()
15891
+ }),
15892
+ external_exports.strictObject({ operation: external_exports.literal("migrate"), routes: voiceRoutesSchema }),
15893
+ external_exports.strictObject({
15894
+ operation: external_exports.literal("set"),
15895
+ settings: voiceSettingsSchema,
15896
+ revision: external_exports.string().max(64)
15897
+ }),
15898
+ external_exports.strictObject({ operation: external_exports.literal("restart"), confirm: external_exports.literal(true) })
15899
+ ]);
15900
+ var voiceSettingsStateSchema = external_exports.strictObject({
15901
+ settings: voiceSettingsSchema,
15902
+ initialized: external_exports.boolean(),
15903
+ revision: external_exports.string(),
15904
+ activeInject: external_exports.boolean().nullable(),
15905
+ envOverride: external_exports.enum(["0", "1"]).nullable(),
15906
+ activeEnvOverride: external_exports.enum(["0", "1"]).nullable(),
15907
+ routesActive: external_exports.boolean().nullable(),
15908
+ activeCall: external_exports.boolean().nullable(),
15909
+ gatewayReady: external_exports.boolean().nullable(),
15910
+ restartAvailable: external_exports.boolean(),
15911
+ restart: external_exports.strictObject({
15912
+ phase: external_exports.enum(["idle", "restarting", "succeeded", "failed"]),
15913
+ error: external_exports.string().nullable()
15914
+ })
15915
+ });
15916
+
15820
15917
  // ../../shared-contracts/dist/client-channel.js
15821
15918
  var CLIENT_CHANNEL_VERSION = 1;
15822
15919
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
15823
15920
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
15824
15921
  var clientThreadPinParamsSchema = external_exports.object({ threadId: external_exports.string().min(1).max(1024), pinned: external_exports.boolean() }).strict();
15922
+ var clientThreadTreeReadParamsSchema = external_exports.object({}).strict();
15923
+ var clientThreadTreeSchema = external_exports.object({
15924
+ parents: external_exports.record(external_exports.string().min(1), external_exports.string().min(1))
15925
+ }).strict();
15825
15926
  var clientProjectlessWorkspaceSchema = external_exports.object({
15826
15927
  prompt: external_exports.string().max(16384).optional()
15827
15928
  }).strict();
@@ -15838,6 +15939,11 @@ var clientChannelCursorSchema = external_exports.object({
15838
15939
  sequence: external_exports.number().int().nonnegative()
15839
15940
  });
15840
15941
  var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
15942
+ external_exports.object({
15943
+ type: external_exports.literal("skills-changed"),
15944
+ cursor: clientChannelCursorSchema,
15945
+ cwd: external_exports.string().optional()
15946
+ }),
15841
15947
  external_exports.object({ type: external_exports.literal("display-settings-changed"), cursor: clientChannelCursorSchema }),
15842
15948
  external_exports.object({
15843
15949
  type: external_exports.literal("preferences-changed"),
@@ -16035,6 +16141,28 @@ var voiceTranscribeResultSchema = external_exports.discriminatedUnion("ok", [
16035
16141
  external_exports.object({ ok: external_exports.literal(false), error: external_exports.object({ code: voiceErrorCodeSchema }).strict() }).strict()
16036
16142
  ]);
16037
16143
 
16144
+ // ../../shared-contracts/dist/skills.js
16145
+ var skillsListParamsSchema = external_exports.object({
16146
+ threadId: hostThreadIdSchema.optional(),
16147
+ cwd: external_exports.string().min(1).optional()
16148
+ }).strict().refine((params) => !(params.threadId && params.cwd), {
16149
+ message: "Specify threadId or cwd, not both"
16150
+ });
16151
+ var librarySkillSchema = external_exports.object({
16152
+ name: external_exports.string().min(1).regex(/^[^\s[\]]+$/u),
16153
+ description: external_exports.string().optional(),
16154
+ path: external_exports.string().min(1),
16155
+ scope: external_exports.enum(["project", "global"]),
16156
+ source: external_exports.string().min(1)
16157
+ }).strict();
16158
+ var skillsListResultSchema = external_exports.object({
16159
+ revision: external_exports.number().int().nonnegative(),
16160
+ complete: external_exports.boolean(),
16161
+ skills: external_exports.array(librarySkillSchema),
16162
+ warnings: external_exports.array(external_exports.string()).optional()
16163
+ }).strict();
16164
+ var skillsChangedParamsSchema = external_exports.object({ cwd: external_exports.string().min(1).optional() }).strict();
16165
+
16038
16166
  // ../../shared-contracts/dist/web-access-tokens.js
16039
16167
  var webNetworkAccessUrlSchema = external_exports.object({
16040
16168
  /**
@@ -16140,8 +16268,8 @@ var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
16140
16268
  var delegationReadParamsSchema = external_exports.strictObject({
16141
16269
  threadId: external_exports.string().min(1).max(1024),
16142
16270
  view: external_exports.enum(["result", "messages"]),
16143
- cursor: external_exports.string().min(1).max(8192).optional(),
16144
- limit: external_exports.number().int().min(1).max(100).optional()
16271
+ from: external_exports.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
16272
+ to: external_exports.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional()
16145
16273
  });
16146
16274
 
16147
16275
  // ../../shared-contracts/dist/credential-imports.js
@@ -16593,6 +16721,10 @@ var CONSOLE_HOST_METHODS = Object.freeze([
16593
16721
  "codexhost/voice/gateway-status",
16594
16722
  "codexhost/enrollment/list",
16595
16723
  "codexhost/enrollment/revoke",
16724
+ "codexhost/external-clients/list",
16725
+ "codexhost/external-clients/create",
16726
+ "codexhost/external-clients/update",
16727
+ "codexhost/external-clients/revoke",
16596
16728
  "codexhost/console/remote-connections",
16597
16729
  "codexhost/runtime/status",
16598
16730
  "codexhost/remote/ssh-setup",
@@ -17139,6 +17271,17 @@ var updateStatusResultSchema = external_exports.strictObject({
17139
17271
  status: updateStatusSchema.nullable()
17140
17272
  });
17141
17273
 
17274
+ // ../../shared-contracts/dist/thread-watch-notice.js
17275
+ var THREAD_WATCH_NOTICE_OUTCOMES = [
17276
+ "completed",
17277
+ "failed",
17278
+ "interrupted",
17279
+ "timedOut",
17280
+ "unreadable",
17281
+ "notFound"
17282
+ ];
17283
+ var ENTRY_PATTERN = new RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): ` + `(${THREAD_WATCH_NOTICE_OUTCOMES.join("|")})(?:. (.+))?$`, "u");
17284
+
17142
17285
  // ../../shared-contracts/dist/remote-runtime.js
17143
17286
  var remoteUpdatePhaseSchema = external_exports.enum([
17144
17287
  "idle",
@@ -17186,6 +17329,14 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
17186
17329
  archived: external_exports.boolean()
17187
17330
  }),
17188
17331
  external_exports.strictObject({ kind: external_exports.literal("read"), ...thread }),
17332
+ external_exports.strictObject({
17333
+ kind: external_exports.literal("configure"),
17334
+ ...thread,
17335
+ epoch: identity,
17336
+ modelId: identity.optional(),
17337
+ thinkingOptionId: identity.optional(),
17338
+ permissionModeId: identity.optional()
17339
+ }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting"),
17189
17340
  external_exports.strictObject({
17190
17341
  kind: external_exports.literal("prompt"),
17191
17342
  ...thread,
@@ -17258,6 +17409,13 @@ var remoteConnectionsReplySchema = external_exports.union([
17258
17409
  external_exports.strictObject({ error: external_exports.strictObject({ code: external_exports.number().int(), message: external_exports.string() }) })
17259
17410
  ]);
17260
17411
 
17412
+ // ../../shared-contracts/dist/thread-title.js
17413
+ var threadTitleInputSchema = external_exports.strictObject({
17414
+ prompt: external_exports.string().trim().min(1).max(2e3),
17415
+ cwd: external_exports.string().max(4096).nullable()
17416
+ });
17417
+ var threadTitleResultSchema = external_exports.string().trim().min(1).max(60).nullable();
17418
+
17261
17419
  // ../../shared-contracts/dist/web-ui-extensions.js
17262
17420
  var webUiExtensionIdSchema = external_exports.string().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u);
17263
17421
  var localizedTextSchema2 = external_exports.union([
@@ -17298,65 +17456,19 @@ var webUiExtensionInstallSchema = external_exports.object({
17298
17456
  var webUiExtensionEnabledSchema = external_exports.object({ id: webUiExtensionIdSchema, enabled: external_exports.boolean() }).strict();
17299
17457
  var webUiExtensionRemoveSchema = external_exports.object({ id: webUiExtensionIdSchema }).strict();
17300
17458
 
17301
- // ../../shared-contracts/dist/voice-settings.js
17302
- var voiceRoutesSchema = external_exports.strictObject({
17303
- chatExperience: external_exports.enum(["chatgpt", "codex"]),
17304
- chatConnection: external_exports.enum(["desktop", "gateway"]),
17305
- workConnection: external_exports.enum(["desktop", "gateway"])
17306
- });
17307
- var DEFAULT_VOICE_ROUTES = Object.freeze({
17308
- chatExperience: "chatgpt",
17309
- chatConnection: "desktop",
17310
- workConnection: "gateway"
17311
- });
17312
- var voiceSettingsSchema = voiceRoutesSchema.extend({ inject: external_exports.boolean() });
17313
- var voiceSettingsRequestSchema = external_exports.discriminatedUnion("operation", [
17314
- external_exports.strictObject({
17315
- operation: external_exports.literal("get"),
17316
- runtime: external_exports.strictObject({
17317
- id: external_exports.string().uuid(),
17318
- revision: external_exports.string().max(64),
17319
- activeCall: external_exports.boolean()
17320
- }).optional()
17321
- }),
17322
- external_exports.strictObject({ operation: external_exports.literal("migrate"), routes: voiceRoutesSchema }),
17323
- external_exports.strictObject({
17324
- operation: external_exports.literal("set"),
17325
- settings: voiceSettingsSchema,
17326
- revision: external_exports.string().max(64)
17327
- }),
17328
- external_exports.strictObject({ operation: external_exports.literal("restart"), confirm: external_exports.literal(true) })
17329
- ]);
17330
- var voiceSettingsStateSchema = external_exports.strictObject({
17331
- settings: voiceSettingsSchema,
17332
- initialized: external_exports.boolean(),
17333
- revision: external_exports.string(),
17334
- activeInject: external_exports.boolean().nullable(),
17335
- envOverride: external_exports.enum(["0", "1"]).nullable(),
17336
- activeEnvOverride: external_exports.enum(["0", "1"]).nullable(),
17337
- routesActive: external_exports.boolean().nullable(),
17338
- activeCall: external_exports.boolean().nullable(),
17339
- gatewayReady: external_exports.boolean().nullable(),
17340
- restartAvailable: external_exports.boolean(),
17341
- restart: external_exports.strictObject({
17342
- phase: external_exports.enum(["idle", "restarting", "succeeded", "failed"]),
17343
- error: external_exports.string().nullable()
17344
- })
17345
- });
17346
-
17347
- // ../../shared-contracts/dist/background-activity.js
17348
- var backgroundActivitySchema = external_exports.strictObject({
17349
- id: external_exports.string().min(1),
17350
- kind: external_exports.enum(["task", "monitor", "loop", "subagent"]),
17351
- label: external_exports.string(),
17352
- status: external_exports.enum(["running", "scheduled", "completed", "failed", "cancelled", "unknown"]),
17353
- canStop: external_exports.boolean(),
17354
- /** Existing detached command Item presented by Desktop's native process UI. */
17355
- commandItemId: hostItemIdSchema.optional(),
17356
- schedule: external_exports.string().optional(),
17357
- nextRunAt: external_exports.string().datetime({ offset: true }).optional(),
17358
- relatedActivityId: external_exports.string().optional(),
17359
- threadId: hostThreadIdSchema.optional()
17459
+ // ../../shared-contracts/dist/background-activity.js
17460
+ var backgroundActivitySchema = external_exports.strictObject({
17461
+ id: external_exports.string().min(1),
17462
+ kind: external_exports.enum(["task", "monitor", "loop", "subagent"]),
17463
+ label: external_exports.string(),
17464
+ status: external_exports.enum(["running", "scheduled", "completed", "failed", "cancelled", "unknown"]),
17465
+ canStop: external_exports.boolean(),
17466
+ /** Existing detached command Item presented by Desktop's native process UI. */
17467
+ commandItemId: hostItemIdSchema.optional(),
17468
+ schedule: external_exports.string().optional(),
17469
+ nextRunAt: external_exports.string().datetime({ offset: true }).optional(),
17470
+ relatedActivityId: external_exports.string().optional(),
17471
+ threadId: hostThreadIdSchema.optional()
17360
17472
  });
17361
17473
  var backgroundActivityDetailSchema = external_exports.strictObject({
17362
17474
  activity: backgroundActivitySchema,
@@ -17378,746 +17490,941 @@ var threadActivityStopResultSchema = external_exports.strictObject({
17378
17490
  // ../../shared-contracts/dist/index.js
17379
17491
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
17380
17492
 
17381
- // ../../harness-adapter/dist/session-import.js
17382
- var SessionImportChangedError = class extends Error {
17383
- constructor(message3 = "Native Session changed during discovery; refresh and retry") {
17384
- super(message3);
17385
- this.name = "SessionImportChangedError";
17386
- }
17387
- };
17388
- function isMissingFileError(error51) {
17389
- return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "ENOENT";
17390
- }
17391
- function sameFileFingerprint(left, right) {
17392
- return left === null || right === null ? left === right : left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
17393
- }
17394
- var STORAGE_ACCESS_ERRORS = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EIO", "EMFILE", "ENFILE"]);
17395
- function isStorageAccessError(error51) {
17396
- return typeof error51 === "object" && error51 !== null && "code" in error51 && typeof error51.code === "string" && STORAGE_ACCESS_ERRORS.has(error51.code);
17397
- }
17398
- async function optionalLstat(file2) {
17399
- try {
17400
- return await lstat2(file2);
17401
- } catch (error51) {
17402
- if (isMissingFileError(error51))
17403
- return null;
17404
- throw error51;
17405
- }
17406
- }
17407
- async function readStableFiles(files, read) {
17408
- const before = await Promise.all(files.map(optionalLstat));
17409
- const value = await read(before);
17410
- const after = await Promise.all(files.map(optionalLstat));
17411
- if (before.some((info, index) => !sameFileFingerprint(info, after[index] ?? null)))
17412
- throw new SessionImportChangedError();
17413
- return value;
17493
+ // ../../harness-adapter/dist/approval.js
17494
+ function invalidRequest(message3) {
17495
+ return { code: "invalidRequest", message: message3, retryable: false };
17414
17496
  }
17415
- function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
17416
- if (typeof value !== "string")
17417
- return null;
17418
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
17419
- if (!normalized)
17420
- return null;
17421
- if (normalized.length <= maxLength)
17422
- return normalized;
17423
- const characters = [...normalized];
17424
- if (characters.length <= maxLength)
17425
- return normalized;
17426
- return `${characters.slice(0, maxLength - 1).join("").trimEnd()}…`;
17497
+ function validateHostApprovalResponse(interaction, response) {
17498
+ return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17427
17499
  }
17428
- function sessionImportCandidate(input) {
17429
- const time3 = typeof input.updatedAt === "number" ? input.updatedAt : typeof input.updatedAt === "string" ? Date.parse(input.updatedAt) : Number.NaN;
17430
- const parsed = harnessSessionImportCandidateSchema.safeParse({
17431
- nativeSessionId: input.nativeSessionId,
17432
- cwd: input.cwd,
17433
- title: typeof input.title === "string" && input.title.trim().length > 0 ? input.title : null,
17434
- updatedAt: Math.floor(time3),
17435
- // Unknown must stay unknown; only an explicit boolean is a native statement.
17436
- running: typeof input.running === "boolean" ? input.running : null
17437
- });
17438
- return parsed.success ? parsed.data : null;
17500
+
17501
+ // ../../harness-adapter/dist/question.js
17502
+ function invalidRequest2(message3) {
17503
+ return { code: "invalidRequest", message: message3, retryable: false };
17439
17504
  }
17440
- var SessionImportScope = class {
17441
- #abort = new AbortController();
17442
- #options;
17443
- #pending = /* @__PURE__ */ new Set();
17444
- constructor(options) {
17445
- this.#options = options;
17505
+ function validateHostQuestionResponse(interaction, response) {
17506
+ const questionIds = new Set(interaction.questions.map(({ id }) => id));
17507
+ if (response.cancelled) {
17508
+ return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
17446
17509
  }
17447
- #closed() {
17448
- return {
17449
- ok: false,
17450
- error: { code: "invalidState", message: this.#options.closedMessage, retryable: false }
17451
- };
17510
+ for (const answerId of Object.keys(response.answers)) {
17511
+ if (!questionIds.has(answerId)) {
17512
+ return invalidRequest2("Question Response contains an unknown Question ID");
17513
+ }
17452
17514
  }
17453
- read(operation) {
17454
- const signal = this.#abort.signal;
17455
- if (signal.aborted)
17456
- return Promise.resolve(this.#closed());
17457
- let started;
17458
- try {
17459
- started = operation(signal);
17460
- } catch (error51) {
17461
- started = Promise.reject(error51 instanceof Error ? error51 : new Error("Session read failed"));
17515
+ for (const question of interaction.questions) {
17516
+ const answers = response.answers[question.id] ?? [];
17517
+ if (new Set(answers).size !== answers.length) {
17518
+ return invalidRequest2("Question Response contains duplicate answers");
17462
17519
  }
17463
- const request = started.then((value) => signal.aborted ? this.#closed() : { ok: true, value }).catch(() => signal.aborted ? this.#closed() : {
17464
- ok: false,
17465
- error: {
17466
- code: "unavailable",
17467
- message: this.#options.unavailableMessage,
17468
- retryable: true
17520
+ if (!question.optional && answers.length === 0) {
17521
+ return invalidRequest2("Question Response omits a required answer");
17522
+ }
17523
+ if (question.type === "text") {
17524
+ if (answers.length > 1) {
17525
+ return invalidRequest2("Text Question accepts at most one answer");
17469
17526
  }
17470
- }).finally(() => this.#pending.delete(request));
17471
- this.#pending.add(request);
17472
- return request;
17527
+ continue;
17528
+ }
17529
+ if (!question.multiple && answers.length > 1) {
17530
+ return invalidRequest2("Single-choice Question accepts at most one answer");
17531
+ }
17532
+ const declared = new Set(question.options.map(({ value }) => value));
17533
+ if (!question.allowOther && answers.some((answer) => !declared.has(answer))) {
17534
+ return invalidRequest2("Question Response contains an undeclared choice");
17535
+ }
17473
17536
  }
17474
- /** `read` for `resolveCandidate`: a null source is the selected Session having disappeared. */
17475
- async resolve(operation) {
17476
- const result = await this.read(operation);
17477
- if (!result.ok)
17478
- return result;
17479
- return result.value ? { ok: true, value: result.value } : {
17480
- ok: false,
17481
- error: {
17482
- code: "sessionNotFound",
17483
- message: this.#options.notFoundMessage,
17484
- retryable: false
17537
+ return null;
17538
+ }
17539
+
17540
+ // ../../harness-adapter/dist/output-channel.js
17541
+ var HarnessOutputChannel = class {
17542
+ outputs;
17543
+ #consumerCreated = false;
17544
+ #ended = false;
17545
+ #pending = [];
17546
+ #values = [];
17547
+ constructor() {
17548
+ this.outputs = {
17549
+ [Symbol.asyncIterator]: () => {
17550
+ if (this.#consumerCreated) {
17551
+ throw new Error("Harness outputs allow only one consumer");
17552
+ }
17553
+ this.#consumerCreated = true;
17554
+ return {
17555
+ next: () => this.#next()
17556
+ };
17485
17557
  }
17486
17558
  };
17487
17559
  }
17488
- /** Idempotent. Resolves after every started read has settled. */
17489
- async close() {
17490
- this.#abort.abort();
17491
- await Promise.allSettled(this.#pending);
17560
+ emit(value) {
17561
+ if (this.#ended)
17562
+ return false;
17563
+ const resolve = this.#pending.shift();
17564
+ if (resolve)
17565
+ resolve({ done: false, value });
17566
+ else
17567
+ this.#values.push(value);
17568
+ return true;
17569
+ }
17570
+ end() {
17571
+ if (this.#ended)
17572
+ return;
17573
+ this.#ended = true;
17574
+ if (this.#values.length !== 0)
17575
+ return;
17576
+ for (const resolve of this.#pending.splice(0))
17577
+ resolve({ done: true, value: void 0 });
17578
+ }
17579
+ #next() {
17580
+ const value = this.#values.shift();
17581
+ if (value !== void 0)
17582
+ return Promise.resolve({ done: false, value });
17583
+ if (this.#ended)
17584
+ return Promise.resolve({ done: true, value: void 0 });
17585
+ return new Promise((resolve) => this.#pending.push(resolve));
17492
17586
  }
17493
17587
  };
17494
17588
 
17495
- // dist/session-import.js
17496
- function isRecord(value) {
17497
- return typeof value === "object" && value !== null && !Array.isArray(value);
17498
- }
17499
- function expandDirectory(value, home) {
17500
- return path5.resolve(value === "~" ? home : value.startsWith(`~${path5.sep}`) || value.startsWith("~/") ? path5.join(home, value.slice(2)) : value);
17589
+ // ../../harness-adapter/dist/diagnostics.js
17590
+ var DIAGNOSTIC_TAIL_MAX_LENGTH = 8e3;
17591
+ var SENSITIVE_VALUE_PATTERN = /(api[_-]?key|access[_-]?token|auth(?:orization)?|password|secret)(\s*[:=]\s*)([^\s,;]+)/giu;
17592
+ var BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]+/giu;
17593
+ function sanitizeDiagnosticTail(value) {
17594
+ const redacted = value.replace(BEARER_PATTERN, "Bearer [redacted]").replace(SENSITIVE_VALUE_PATTERN, "$1$2[redacted]");
17595
+ return redacted.length <= DIAGNOSTIC_TAIL_MAX_LENGTH ? redacted : redacted.slice(-DIAGNOSTIC_TAIL_MAX_LENGTH);
17501
17596
  }
17502
- function ompSessionImportDirectory(environment) {
17503
- const home = (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
17504
- const custom2 = environment.PI_CODING_AGENT_SESSION_DIR;
17505
- if (custom2)
17506
- return { directory: expandDirectory(custom2, home), flat: true };
17507
- const agent = environment.PI_CODING_AGENT_DIR;
17597
+
17598
+ // ../../harness-adapter/dist/steer.js
17599
+ function unsupportedSteer(harnessLabel) {
17508
17600
  return {
17509
- directory: path5.join(agent ? expandDirectory(agent, home) : path5.join(home, ".omp", "agent"), "sessions"),
17510
- flat: false
17511
- };
17512
- }
17513
- function messageText(content) {
17514
- if (typeof content === "string")
17515
- return content;
17516
- if (!Array.isArray(content))
17517
- return "";
17518
- return content.filter((part) => isRecord(part) && part.type === "text" && typeof part.text === "string").map((part) => String(part.text)).join(" ");
17519
- }
17520
- async function readFacts(file2, signal) {
17521
- const stream = createReadStream2(file2, { encoding: "utf8", signal });
17522
- const lines = createInterface2({ input: stream, crlfDelay: Infinity });
17523
- let header = null;
17524
- let nativeTitle = null;
17525
- let firstPrompt = null;
17526
- let updatedAt = null;
17527
- let leafHasUser = false;
17528
- const hasUserAncestry = /* @__PURE__ */ new Map();
17529
- try {
17530
- for await (const line of lines) {
17531
- signal.throwIfAborted();
17532
- if (!line.trim())
17533
- continue;
17534
- let entry;
17535
- try {
17536
- entry = JSON.parse(line);
17537
- } catch {
17538
- continue;
17539
- }
17540
- if (!isRecord(entry))
17541
- continue;
17542
- if (entry.type === "title") {
17543
- nativeTitle = sessionImportTitle(entry.title);
17544
- continue;
17545
- }
17546
- if (entry.type === "session") {
17547
- if (header)
17548
- return null;
17549
- if (typeof entry.id !== "string" || entry.id.length === 0 || typeof entry.cwd !== "string" || !path5.isAbsolute(entry.cwd))
17550
- return null;
17551
- header = { id: entry.id, cwd: entry.cwd };
17552
- continue;
17553
- }
17554
- if (typeof entry.id !== "string" || entry.id.length === 0)
17555
- continue;
17556
- const message3 = isRecord(entry.message) ? entry.message : null;
17557
- const isUser = entry.type === "message" && message3?.role === "user";
17558
- if (isUser)
17559
- firstPrompt ??= sessionImportTitle(messageText(message3?.content));
17560
- leafHasUser = isUser || typeof entry.parentId === "string" && hasUserAncestry.get(entry.parentId) === true;
17561
- hasUserAncestry.set(entry.id, leafHasUser);
17562
- if (entry.type === "message" && (message3?.role === "user" || message3?.role === "assistant")) {
17563
- const time3 = typeof message3.timestamp === "number" ? message3.timestamp : typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : Number.NaN;
17564
- if (Number.isFinite(time3) && time3 >= 0)
17565
- updatedAt = time3;
17566
- }
17601
+ ok: false,
17602
+ error: {
17603
+ code: "unsupported",
17604
+ message: `${harnessLabel} cannot steer an active Turn natively`,
17605
+ retryable: false
17567
17606
  }
17568
- } finally {
17569
- lines.close();
17570
- stream.destroy();
17571
- }
17572
- if (!header || !leafHasUser)
17573
- return null;
17574
- return {
17575
- nativeSessionId: header.id,
17576
- cwd: header.cwd,
17577
- title: nativeTitle ?? firstPrompt,
17578
- updatedAt
17579
17607
  };
17580
17608
  }
17581
- var OmpSessionImport = class {
17582
- #location;
17583
- #scope = new SessionImportScope({
17584
- closedMessage: "Omp Session import is closed",
17585
- unavailableMessage: "Omp sessions could not be read; close native clients, check storage access and retry",
17586
- notFoundMessage: "Omp Session is no longer importable"
17587
- });
17588
- constructor(environment) {
17589
- this.#location = ompSessionImportDirectory(environment);
17590
- }
17591
- listCandidates() {
17592
- return this.#scope.read(async (signal) => [...(await this.#sources(signal)).values()].flatMap((sources) => (
17593
- // One identity in two files cannot be resumed unambiguously.
17594
- sources.length === 1 && sources[0] ? [sources[0].candidate] : []
17595
- )));
17596
- }
17597
- resolveCandidate(nativeSessionId) {
17598
- return this.#scope.resolve(async (signal) => {
17599
- const sources = (await this.#sources(signal)).get(nativeSessionId);
17600
- if (sources?.length !== 1 || !sources[0])
17601
- return null;
17602
- const source = await this.#source(sources[0].file, signal);
17603
- return source?.nativeRef.nativeSessionId === nativeSessionId ? { candidate: source.candidate, nativeRef: source.nativeRef } : null;
17604
- });
17609
+
17610
+ // ../../harness-adapter/dist/usage.js
17611
+ var tokenFields = [
17612
+ "inputTokens",
17613
+ "cachedInputTokens",
17614
+ "cacheWriteInputTokens",
17615
+ "outputTokens",
17616
+ "reasoningOutputTokens",
17617
+ "totalTokens",
17618
+ "contextWindowTokens",
17619
+ "contextUsedTokens"
17620
+ ];
17621
+ var safeIntegerFields = [
17622
+ "planFiveHourResetsAtUnix",
17623
+ "planSevenDayResetsAtUnix",
17624
+ "timeToFirstOutputMs"
17625
+ ];
17626
+ var percentFields = [
17627
+ "cacheHitRatePercent",
17628
+ "sessionCacheHitRatePercent",
17629
+ "planFiveHourUsedPercent",
17630
+ "planSevenDayUsedPercent"
17631
+ ];
17632
+ var usageFields = /* @__PURE__ */ new Set([
17633
+ ...tokenFields,
17634
+ ...safeIntegerFields,
17635
+ ...percentFields,
17636
+ "sessionCacheUsage",
17637
+ "composerIndicators",
17638
+ "totalCostUsd",
17639
+ "totalCredits",
17640
+ "contextUsagePercent",
17641
+ "outputTokensPerSecond",
17642
+ "apiOutputTokensPerSecond",
17643
+ "costSource",
17644
+ "unpricedModels"
17645
+ ]);
17646
+ function isRecord(value) {
17647
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17648
+ }
17649
+ function parseHostUsage(value) {
17650
+ if (!isRecord(value))
17651
+ throw new Error("Harness Usage must be an object");
17652
+ const keys = Object.keys(value);
17653
+ if (keys.length === 0)
17654
+ throw new Error("Harness Usage must contain a reliable field");
17655
+ for (const key of keys) {
17656
+ if (!usageFields.has(key)) {
17657
+ throw new Error(`Harness Usage contains unknown field '${key}'`);
17658
+ }
17605
17659
  }
17606
- close() {
17607
- return this.#scope.close();
17660
+ const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
17661
+ for (const field2 of [
17662
+ "totalCredits",
17663
+ "contextUsagePercent",
17664
+ "apiOutputTokensPerSecond"
17665
+ ]) {
17666
+ const candidate = value[field2];
17667
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
17668
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
17669
+ }
17608
17670
  }
17609
- async #sessionFiles(signal) {
17610
- const { directory, flat } = this.#location;
17611
- const info = await optionalLstat(directory);
17612
- if (!info)
17613
- return [];
17614
- if (!info.isDirectory())
17615
- throw new Error("Omp Session store is not a directory");
17616
- const files = [];
17617
- const visit = async (current, projectLevel) => {
17618
- const entries = await opendir2(current).catch((error51) => {
17619
- if (isMissingFileError(error51))
17620
- return null;
17621
- throw error51;
17622
- });
17623
- if (!entries)
17624
- return;
17625
- for await (const entry of entries) {
17626
- signal.throwIfAborted();
17627
- if (projectLevel && entry.isDirectory())
17628
- await visit(path5.join(current, entry.name), false);
17629
- else if (!projectLevel && entry.isFile() && entry.name.endsWith(".jsonl"))
17630
- files.push(path5.join(current, entry.name));
17631
- }
17632
- };
17633
- await visit(directory, !flat);
17634
- return files;
17671
+ for (const field2 of tokenFields) {
17672
+ const candidate = value[field2];
17673
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17674
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
17675
+ }
17635
17676
  }
17636
- /** Session ID to every readable file claiming it. Files changing under the read are skipped. */
17637
- async #sources(signal) {
17638
- const found = /* @__PURE__ */ new Map();
17639
- for (const file2 of await this.#sessionFiles(signal)) {
17640
- signal.throwIfAborted();
17641
- try {
17642
- const source = await this.#source(file2, signal);
17643
- if (!source)
17644
- continue;
17645
- const sources = found.get(source.nativeRef.nativeSessionId) ?? [];
17646
- sources.push(source);
17647
- found.set(source.nativeRef.nativeSessionId, sources);
17648
- } catch (error51) {
17649
- if (!(error51 instanceof SessionImportChangedError))
17650
- throw error51;
17651
- }
17677
+ for (const field2 of safeIntegerFields) {
17678
+ const candidate = value[field2];
17679
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17680
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
17652
17681
  }
17653
- return found;
17654
17682
  }
17655
- async #source(file2, signal) {
17656
- signal.throwIfAborted();
17657
- return readStableFiles([file2], async ([info]) => {
17658
- if (!info?.isFile() || info.size === 0)
17659
- return null;
17660
- try {
17661
- const facts = await readFacts(file2, signal);
17662
- if (!facts)
17663
- return null;
17664
- const cwd = await realpath(facts.cwd);
17665
- if (!(await stat(cwd)).isDirectory())
17666
- return null;
17667
- const candidate = sessionImportCandidate({
17668
- nativeSessionId: facts.nativeSessionId,
17669
- cwd,
17670
- title: facts.title,
17671
- updatedAt: facts.updatedAt ?? info.mtimeMs
17672
- // OMP has no cross-process activity marker: idleness cannot be established.
17673
- });
17674
- if (!candidate)
17675
- return null;
17676
- return {
17677
- file: file2,
17678
- candidate,
17679
- // Resume needs the file itself: OMP is started with `--session <file>`.
17680
- nativeRef: nativeSessionRefSchema.parse({
17681
- harnessId: "omp",
17682
- nativeSessionId: facts.nativeSessionId,
17683
- locator: { sessionFile: await realpath(file2) },
17684
- formatVersion: 1
17685
- })
17686
- };
17687
- } catch (error51) {
17688
- signal.throwIfAborted();
17689
- if (isStorageAccessError(error51))
17690
- throw error51;
17691
- return null;
17692
- }
17693
- });
17683
+ if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
17684
+ throw new Error("Harness Usage 'outputTokensPerSecond' must be a finite non-negative number");
17694
17685
  }
17695
- };
17696
-
17697
- // ../../harness-adapter/dist/approval.js
17698
- function invalidRequest(message3) {
17699
- return { code: "invalidRequest", message: message3, retryable: false };
17700
- }
17701
- function validateHostApprovalResponse(interaction, response) {
17702
- return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17703
- }
17704
-
17705
- // ../../harness-adapter/dist/question.js
17706
- function invalidRequest2(message3) {
17707
- return { code: "invalidRequest", message: message3, retryable: false };
17708
- }
17709
- function validateHostQuestionResponse(interaction, response) {
17710
- const questionIds = new Set(interaction.questions.map(({ id }) => id));
17711
- if (response.cancelled) {
17712
- return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
17686
+ if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
17687
+ throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
17713
17688
  }
17714
- for (const answerId of Object.keys(response.answers)) {
17715
- if (!questionIds.has(answerId)) {
17716
- return invalidRequest2("Question Response contains an unknown Question ID");
17689
+ for (const field2 of percentFields) {
17690
+ const candidate = value[field2];
17691
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
17692
+ throw new Error(`Harness Usage '${field2}' must be between 0 and 100`);
17717
17693
  }
17718
17694
  }
17719
- for (const question of interaction.questions) {
17720
- const answers = response.answers[question.id] ?? [];
17721
- if (new Set(answers).size !== answers.length) {
17722
- return invalidRequest2("Question Response contains duplicate answers");
17695
+ if (value.sessionCacheUsage !== void 0) {
17696
+ const totals2 = value.sessionCacheUsage;
17697
+ 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) {
17698
+ throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
17723
17699
  }
17724
- if (!question.optional && answers.length === 0) {
17725
- return invalidRequest2("Question Response omits a required answer");
17700
+ }
17701
+ const hasContextUsed = value.contextUsedTokens !== void 0;
17702
+ const hasContextWindow = value.contextWindowTokens !== void 0;
17703
+ if (hasContextUsed !== hasContextWindow) {
17704
+ throw new Error("Harness Usage context fields must be provided together");
17705
+ }
17706
+ if (hasContextWindow && value.contextWindowTokens === 0) {
17707
+ throw new Error("Harness Usage 'contextWindowTokens' must be greater than zero");
17708
+ }
17709
+ if (value.planFiveHourResetsAtUnix !== void 0 && value.planFiveHourUsedPercent === void 0) {
17710
+ throw new Error("Harness Usage 'planFiveHourResetsAtUnix' must be provided with 'planFiveHourUsedPercent'");
17711
+ }
17712
+ if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
17713
+ throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
17714
+ }
17715
+ if (value.costSource !== void 0) {
17716
+ if (value.costSource !== "publicPrice" && value.costSource !== "native") {
17717
+ throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
17726
17718
  }
17727
- if (question.type === "text") {
17728
- if (answers.length > 1) {
17729
- return invalidRequest2("Text Question accepts at most one answer");
17730
- }
17731
- continue;
17719
+ if (value.totalCostUsd === void 0) {
17720
+ throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
17732
17721
  }
17733
- if (!question.multiple && answers.length > 1) {
17734
- return invalidRequest2("Single-choice Question accepts at most one answer");
17722
+ }
17723
+ if (value.unpricedModels !== void 0) {
17724
+ const models = value.unpricedModels;
17725
+ if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
17726
+ throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
17735
17727
  }
17736
- const declared = new Set(question.options.map(({ value }) => value));
17737
- if (!question.allowOther && answers.some((answer) => !declared.has(answer))) {
17738
- return invalidRequest2("Question Response contains an undeclared choice");
17728
+ if (value.costSource !== "publicPrice") {
17729
+ throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
17739
17730
  }
17731
+ return { ...value, ...indicators, unpricedModels: [...models] };
17740
17732
  }
17741
- return null;
17733
+ return { ...value, ...indicators };
17742
17734
  }
17743
-
17744
- // ../../harness-adapter/dist/output-channel.js
17745
- var HarnessOutputChannel = class {
17746
- outputs;
17747
- #consumerCreated = false;
17748
- #ended = false;
17749
- #pending = [];
17750
- #values = [];
17751
- constructor() {
17752
- this.outputs = {
17753
- [Symbol.asyncIterator]: () => {
17754
- if (this.#consumerCreated) {
17755
- throw new Error("Harness outputs allow only one consumer");
17756
- }
17757
- this.#consumerCreated = true;
17758
- return {
17759
- next: () => this.#next()
17760
- };
17761
- }
17762
- };
17735
+ var requestTokenFields = [
17736
+ "inputTokens",
17737
+ "cachedInputTokens",
17738
+ "cacheWriteInputTokens",
17739
+ "cacheWrite1hInputTokens",
17740
+ "outputTokens",
17741
+ "reasoningOutputTokens",
17742
+ "startedAtMs",
17743
+ "completedAtMs"
17744
+ ];
17745
+ var requestFields = /* @__PURE__ */ new Set([
17746
+ ...requestTokenFields,
17747
+ "requestId",
17748
+ "historical",
17749
+ "model",
17750
+ "provider"
17751
+ ]);
17752
+ function parseHostUsageRequest(value) {
17753
+ if (!isRecord(value))
17754
+ throw new Error("Harness Usage request must be an object");
17755
+ for (const key of Object.keys(value)) {
17756
+ if (!requestFields.has(key)) {
17757
+ throw new Error(`Harness Usage request contains unknown field '${key}'`);
17758
+ }
17763
17759
  }
17764
- emit(value) {
17765
- if (this.#ended)
17766
- return false;
17767
- const resolve = this.#pending.shift();
17768
- if (resolve)
17769
- resolve({ done: false, value });
17770
- else
17771
- this.#values.push(value);
17772
- return true;
17760
+ if (typeof value.requestId !== "string" || value.requestId.length === 0) {
17761
+ throw new Error("Harness Usage request 'requestId' must be a non-empty string");
17773
17762
  }
17774
- end() {
17775
- if (this.#ended)
17776
- return;
17777
- this.#ended = true;
17778
- if (this.#values.length !== 0)
17779
- return;
17780
- for (const resolve of this.#pending.splice(0))
17781
- resolve({ done: true, value: void 0 });
17763
+ for (const field2 of ["model", "provider"]) {
17764
+ const candidate = value[field2];
17765
+ if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
17766
+ throw new Error(`Harness Usage request '${field2}' must be a non-empty string`);
17767
+ }
17782
17768
  }
17783
- #next() {
17784
- const value = this.#values.shift();
17785
- if (value !== void 0)
17786
- return Promise.resolve({ done: false, value });
17787
- if (this.#ended)
17788
- return Promise.resolve({ done: true, value: void 0 });
17789
- return new Promise((resolve) => this.#pending.push(resolve));
17769
+ if (value.historical !== void 0 && typeof value.historical !== "boolean") {
17770
+ throw new Error("Harness Usage request 'historical' must be a boolean");
17771
+ }
17772
+ for (const field2 of requestTokenFields) {
17773
+ const candidate = value[field2];
17774
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17775
+ throw new Error(`Harness Usage request '${field2}' must be a non-negative safe integer`);
17776
+ }
17777
+ }
17778
+ if (value.inputTokens === void 0 || value.outputTokens === void 0) {
17779
+ throw new Error("Harness Usage request must contain 'inputTokens' and 'outputTokens'");
17780
+ }
17781
+ const request = value;
17782
+ if ((request.cachedInputTokens ?? 0) + (request.cacheWriteInputTokens ?? 0) > request.inputTokens) {
17783
+ throw new Error("Harness Usage request cache Tokens must not exceed 'inputTokens'");
17784
+ }
17785
+ if ((request.reasoningOutputTokens ?? 0) > request.outputTokens) {
17786
+ throw new Error("Harness Usage request 'reasoningOutputTokens' must not exceed 'outputTokens'");
17787
+ }
17788
+ if (request.cacheWrite1hInputTokens !== void 0 && request.cacheWrite1hInputTokens > (request.cacheWriteInputTokens ?? -1)) {
17789
+ throw new Error("Harness Usage request 'cacheWrite1hInputTokens' must not exceed 'cacheWriteInputTokens'");
17790
+ }
17791
+ if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
17792
+ throw new Error("Harness Usage request timing fields must be provided together");
17793
+ }
17794
+ if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
17795
+ throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
17796
+ }
17797
+ return { ...request };
17798
+ }
17799
+
17800
+ // ../../harness-adapter/dist/live-command-catalog.js
17801
+ var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
17802
+ // Session lifecycle
17803
+ "branch",
17804
+ "clear",
17805
+ "exit",
17806
+ "fork",
17807
+ "fresh",
17808
+ "new",
17809
+ "quit",
17810
+ "rename",
17811
+ "rename-chat",
17812
+ "reset",
17813
+ "resume",
17814
+ "rewind",
17815
+ "session",
17816
+ "sessions",
17817
+ // Desktop-owned configuration
17818
+ "autocompact",
17819
+ "color",
17820
+ "config",
17821
+ "effort",
17822
+ "fast",
17823
+ "keybindings",
17824
+ "model",
17825
+ "models",
17826
+ "output-style",
17827
+ "permissions",
17828
+ "settings",
17829
+ "statusline",
17830
+ "terminal-setup",
17831
+ "theme",
17832
+ "vim",
17833
+ // Trust and approval policy
17834
+ "always-approve",
17835
+ "auto-mode-setup",
17836
+ // Native login
17837
+ "login",
17838
+ "logout",
17839
+ // Work outliving the Turn
17840
+ "autopilot",
17841
+ "background",
17842
+ "bg",
17843
+ "goal",
17844
+ "jobs",
17845
+ "loop",
17846
+ "multitask",
17847
+ "queue",
17848
+ "remote-control",
17849
+ "schedule",
17850
+ "steer",
17851
+ // Native terminal UI
17852
+ "copy",
17853
+ "debug",
17854
+ "feedback",
17855
+ "heapdump",
17856
+ "share",
17857
+ "shell",
17858
+ // Plugin and MCP management
17859
+ "marketplace",
17860
+ "mcp",
17861
+ "plugins",
17862
+ "reload-plugins"
17863
+ ]);
17864
+ var COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES = ["__", "hooks-"];
17865
+ function isExcludedLiveCommand(name, extra = {}) {
17866
+ const normalized = name.trim().replace(/^\//u, "");
17867
+ if (new Set(extra.names ?? []).has(normalized))
17868
+ return true;
17869
+ if (extra.prefixes?.some((prefix) => normalized.startsWith(prefix)))
17870
+ return true;
17871
+ return COMMON_EXCLUDED_LIVE_COMMANDS.has(normalized) || COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES.some((prefix) => normalized.startsWith(prefix));
17872
+ }
17873
+ function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
17874
+ if (!commandId.startsWith(idPrefix))
17875
+ return null;
17876
+ const descriptor = catalog.commands.find(({ id }) => id === commandId);
17877
+ if (!descriptor)
17878
+ return null;
17879
+ const text = typeof argumentText === "string" ? argumentText.trim() : "";
17880
+ return text ? `${descriptor.invocation} ${text}` : descriptor.invocation;
17881
+ }
17882
+ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17883
+ if (!live)
17884
+ return builtIns;
17885
+ const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
17886
+ const ids = new Set(builtIns.commands.map(({ id }) => id));
17887
+ const dynamic = [];
17888
+ for (const command of live) {
17889
+ const name = command.name.trim().replace(/^\//u, "");
17890
+ if (!name || /\s/u.test(name))
17891
+ continue;
17892
+ if (isExcludedLiveCommand(name, exclusions))
17893
+ continue;
17894
+ const invocation = `/${name}`;
17895
+ const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
17896
+ if (invocations.has(invocation) || ids.has(id))
17897
+ continue;
17898
+ const description = command.description?.trim().slice(0, 512);
17899
+ const parsed = harnessCommandDescriptorSchema.safeParse({
17900
+ id,
17901
+ invocation,
17902
+ label: name.slice(0, 128),
17903
+ ...description ? { description } : {},
17904
+ argumentMode: "text"
17905
+ });
17906
+ if (!parsed.success)
17907
+ continue;
17908
+ invocations.add(invocation);
17909
+ ids.add(id);
17910
+ dynamic.push(parsed.data);
17790
17911
  }
17791
- };
17792
-
17793
- // ../../harness-adapter/dist/diagnostics.js
17794
- var DIAGNOSTIC_TAIL_MAX_LENGTH = 8e3;
17795
- var SENSITIVE_VALUE_PATTERN = /(api[_-]?key|access[_-]?token|auth(?:orization)?|password|secret)(\s*[:=]\s*)([^\s,;]+)/giu;
17796
- var BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]+/giu;
17797
- function sanitizeDiagnosticTail(value) {
17798
- const redacted = value.replace(BEARER_PATTERN, "Bearer [redacted]").replace(SENSITIVE_VALUE_PATTERN, "$1$2[redacted]");
17799
- return redacted.length <= DIAGNOSTIC_TAIL_MAX_LENGTH ? redacted : redacted.slice(-DIAGNOSTIC_TAIL_MAX_LENGTH);
17912
+ return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
17800
17913
  }
17801
17914
 
17802
- // ../../harness-adapter/dist/steer.js
17803
- function unsupportedSteer(harnessLabel) {
17915
+ // ../../harness-adapter/dist/subagent-configuration.js
17916
+ function subagentConfiguration(value) {
17917
+ if (typeof value !== "object" || value === null || Array.isArray(value))
17918
+ return {};
17919
+ const row = value;
17920
+ const text = (value2) => typeof value2 === "string" && value2.trim() ? value2 : void 0;
17921
+ const model2 = row.model === "inherit" ? void 0 : text(row.model);
17922
+ const reasoningEffort = text(row.reasoningEffort) ?? text(row.reasoning_effort) ?? text(row.thinking);
17923
+ return { ...model2 ? { model: model2 } : {}, ...reasoningEffort ? { reasoningEffort } : {} };
17924
+ }
17925
+ function inheritSubagentConfiguration(child, parent) {
17926
+ const native = subagentConfiguration(child);
17927
+ const model2 = native.model ?? parent.model;
17928
+ const reasoningEffort = native.reasoningEffort ?? parent.reasoningEffort;
17929
+ const next = { ...child };
17930
+ delete next.model;
17931
+ delete next.reasoningEffort;
17932
+ return { ...next, ...model2 ? { model: model2 } : {}, ...reasoningEffort ? { reasoningEffort } : {} };
17933
+ }
17934
+ function configureSubagentEvent(event, parent) {
17935
+ const children = (states) => states.map((child) => inheritSubagentConfiguration(child, parent));
17936
+ if (event.type === "item.started" && event.item.type === "subagentDelegation")
17937
+ return { ...event, item: { ...event.item, subagents: children(event.item.subagents) } };
17938
+ if (event.type === "item.updated" && event.update.type === "subagents.replace")
17939
+ return { ...event, update: { ...event.update, subagents: children(event.update.subagents) } };
17940
+ if (event.type === "item.completed" && event.snapshot.item.type === "subagentDelegation")
17941
+ return {
17942
+ ...event,
17943
+ snapshot: {
17944
+ ...event.snapshot,
17945
+ item: {
17946
+ ...event.snapshot.item,
17947
+ subagents: children(event.snapshot.item.subagents)
17948
+ }
17949
+ }
17950
+ };
17951
+ return event;
17952
+ }
17953
+ function configureSubagentSnapshot(snapshot, parent) {
17804
17954
  return {
17805
- ok: false,
17806
- error: {
17807
- code: "unsupported",
17808
- message: `${harnessLabel} cannot steer an active Turn natively`,
17809
- retryable: false
17810
- }
17955
+ ...snapshot,
17956
+ turns: snapshot.turns.map((turn) => ({
17957
+ ...turn,
17958
+ items: turn.items.map((entry) => entry.item.type === "subagentDelegation" ? {
17959
+ ...entry,
17960
+ item: {
17961
+ ...entry.item,
17962
+ subagents: entry.item.subagents.map((child) => inheritSubagentConfiguration(child, parent))
17963
+ }
17964
+ } : entry)
17965
+ }))
17811
17966
  };
17812
17967
  }
17813
17968
 
17814
- // ../../harness-adapter/dist/usage.js
17815
- var tokenFields = [
17816
- "inputTokens",
17817
- "cachedInputTokens",
17818
- "cacheWriteInputTokens",
17819
- "outputTokens",
17820
- "reasoningOutputTokens",
17821
- "totalTokens",
17822
- "contextWindowTokens",
17823
- "contextUsedTokens"
17824
- ];
17825
- var safeIntegerFields = [
17826
- "planFiveHourResetsAtUnix",
17827
- "planSevenDayResetsAtUnix",
17828
- "timeToFirstOutputMs"
17829
- ];
17830
- var percentFields = [
17831
- "cacheHitRatePercent",
17832
- "sessionCacheHitRatePercent",
17833
- "planFiveHourUsedPercent",
17834
- "planSevenDayUsedPercent"
17835
- ];
17836
- var usageFields = /* @__PURE__ */ new Set([
17837
- ...tokenFields,
17838
- ...safeIntegerFields,
17839
- ...percentFields,
17840
- "sessionCacheUsage",
17841
- "composerIndicators",
17842
- "totalCostUsd",
17843
- "totalCredits",
17844
- "contextUsagePercent",
17845
- "outputTokensPerSecond",
17846
- "apiOutputTokensPerSecond",
17847
- "costSource",
17848
- "unpricedModels"
17849
- ]);
17850
- function isRecord2(value) {
17851
- return typeof value === "object" && value !== null && !Array.isArray(value);
17852
- }
17853
- function parseHostUsage(value) {
17854
- if (!isRecord2(value))
17855
- throw new Error("Harness Usage must be an object");
17856
- const keys = Object.keys(value);
17857
- if (keys.length === 0)
17858
- throw new Error("Harness Usage must contain a reliable field");
17859
- for (const key of keys) {
17860
- if (!usageFields.has(key)) {
17861
- throw new Error(`Harness Usage contains unknown field '${key}'`);
17862
- }
17863
- }
17864
- const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
17865
- for (const field2 of [
17866
- "totalCredits",
17867
- "contextUsagePercent",
17868
- "apiOutputTokensPerSecond"
17869
- ]) {
17870
- const candidate = value[field2];
17871
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
17872
- throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
17873
- }
17874
- }
17875
- for (const field2 of tokenFields) {
17876
- const candidate = value[field2];
17877
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17878
- throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
17879
- }
17969
+ // ../../harness-adapter/dist/usage-statistics.js
17970
+ import { createReadStream } from "node:fs";
17971
+ import { lstat, opendir } from "node:fs/promises";
17972
+ import path4 from "node:path";
17973
+ import { createInterface } from "node:readline";
17974
+ var MAX_SESSION_ID_LENGTH = 512;
17975
+ var MAX_CWD_LENGTH = 4096;
17976
+ var MAX_SESSION_TITLE_LENGTH = 200;
17977
+ function usageSessionTitle(value) {
17978
+ if (typeof value !== "string")
17979
+ return void 0;
17980
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
17981
+ if (!normalized)
17982
+ return void 0;
17983
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
17984
+ return normalized;
17985
+ let title = "";
17986
+ for (const character of normalized) {
17987
+ if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
17988
+ break;
17989
+ title += character;
17880
17990
  }
17881
- for (const field2 of safeIntegerFields) {
17882
- const candidate = value[field2];
17883
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17884
- throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
17991
+ return `${title.trimEnd()}…`;
17992
+ }
17993
+ function sessionIdOk(value) {
17994
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
17995
+ }
17996
+ function cwdOk(value) {
17997
+ 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("\\\\"));
17998
+ }
17999
+ function withUsageSession(entry, session) {
18000
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
18001
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
18002
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
18003
+ if (sessionId === void 0 && cwd === void 0)
18004
+ return entry;
18005
+ return {
18006
+ ...entry,
18007
+ ...sessionId !== void 0 ? { sessionId } : {},
18008
+ ...cwd !== void 0 ? { cwd } : {},
18009
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
18010
+ };
18011
+ }
18012
+ function usageEntryFromRequest(request, occurredAtMs) {
18013
+ if (!Number.isSafeInteger(occurredAtMs) || occurredAtMs <= 0)
18014
+ return null;
18015
+ return {
18016
+ id: request.requestId,
18017
+ occurredAtMs,
18018
+ ...request.model !== void 0 ? { model: request.model } : {},
18019
+ inputTokens: request.inputTokens,
18020
+ ...request.cachedInputTokens !== void 0 ? { cachedInputTokens: request.cachedInputTokens } : {},
18021
+ ...request.cacheWriteInputTokens !== void 0 ? { cacheWriteInputTokens: request.cacheWriteInputTokens } : {},
18022
+ ...request.cacheWrite1hInputTokens !== void 0 ? { cacheWrite1hInputTokens: request.cacheWrite1hInputTokens } : {},
18023
+ outputTokens: request.outputTokens,
18024
+ ...request.reasoningOutputTokens !== void 0 ? { reasoningOutputTokens: request.reasoningOutputTokens } : {}
18025
+ };
18026
+ }
18027
+ async function jsonlUsageSources(root, maxDepth, signal) {
18028
+ const sources = [];
18029
+ const visit = async (directory, depth) => {
18030
+ signal.throwIfAborted();
18031
+ const entries = await opendir(directory).catch((error51) => {
18032
+ if (error51.code === "ENOENT")
18033
+ return null;
18034
+ throw error51;
18035
+ });
18036
+ if (!entries)
18037
+ return;
18038
+ for await (const entry of entries) {
18039
+ signal.throwIfAborted();
18040
+ const file2 = path4.join(directory, entry.name);
18041
+ if (entry.isDirectory()) {
18042
+ if (depth < maxDepth)
18043
+ await visit(file2, depth + 1);
18044
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
18045
+ const info = await lstat(file2).catch(() => null);
18046
+ if (info?.isFile() && info.size > 0) {
18047
+ sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
18048
+ }
18049
+ }
17885
18050
  }
17886
- }
17887
- if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
17888
- throw new Error("Harness Usage 'outputTokensPerSecond' must be a finite non-negative number");
17889
- }
17890
- if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
17891
- throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
17892
- }
17893
- for (const field2 of percentFields) {
17894
- const candidate = value[field2];
17895
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
17896
- throw new Error(`Harness Usage '${field2}' must be between 0 and 100`);
18051
+ };
18052
+ await visit(root, 0);
18053
+ return sources;
18054
+ }
18055
+ async function* jsonlRecords(file2, marker, signal) {
18056
+ const lines = createInterface({
18057
+ input: createReadStream(file2, { encoding: "utf8", signal }),
18058
+ crlfDelay: Infinity
18059
+ });
18060
+ for await (const line of lines) {
18061
+ if (!line.includes(marker))
18062
+ continue;
18063
+ let value;
18064
+ try {
18065
+ value = JSON.parse(line);
18066
+ } catch {
18067
+ continue;
17897
18068
  }
17898
- }
17899
- if (value.sessionCacheUsage !== void 0) {
17900
- const totals2 = value.sessionCacheUsage;
17901
- if (!isRecord2(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) {
17902
- throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
18069
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
18070
+ yield value;
17903
18071
  }
17904
18072
  }
17905
- const hasContextUsed = value.contextUsedTokens !== void 0;
17906
- const hasContextWindow = value.contextWindowTokens !== void 0;
17907
- if (hasContextUsed !== hasContextWindow) {
17908
- throw new Error("Harness Usage context fields must be provided together");
17909
- }
17910
- if (hasContextWindow && value.contextWindowTokens === 0) {
17911
- throw new Error("Harness Usage 'contextWindowTokens' must be greater than zero");
17912
- }
17913
- if (value.planFiveHourResetsAtUnix !== void 0 && value.planFiveHourUsedPercent === void 0) {
17914
- throw new Error("Harness Usage 'planFiveHourResetsAtUnix' must be provided with 'planFiveHourUsedPercent'");
17915
- }
17916
- if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
17917
- throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
17918
- }
17919
- if (value.costSource !== void 0) {
17920
- if (value.costSource !== "publicPrice" && value.costSource !== "native") {
17921
- throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
17922
- }
17923
- if (value.totalCostUsd === void 0) {
17924
- throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
18073
+ }
18074
+ async function jsonlHeader(file2, match, signal, maxLines = 4) {
18075
+ const stream = createReadStream(file2, { encoding: "utf8", signal });
18076
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
18077
+ let seen = 0;
18078
+ try {
18079
+ for await (const line of lines) {
18080
+ if (++seen > maxLines)
18081
+ break;
18082
+ let value;
18083
+ try {
18084
+ value = JSON.parse(line);
18085
+ } catch {
18086
+ continue;
18087
+ }
18088
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
18089
+ const record3 = value;
18090
+ if (match(record3))
18091
+ return record3;
18092
+ }
17925
18093
  }
18094
+ return null;
18095
+ } finally {
18096
+ lines.close();
18097
+ stream.destroy();
17926
18098
  }
17927
- if (value.unpricedModels !== void 0) {
17928
- const models = value.unpricedModels;
17929
- if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
17930
- throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
17931
- }
17932
- if (value.costSource !== "publicPrice") {
17933
- throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
17934
- }
17935
- return { ...value, ...indicators, unpricedModels: [...models] };
18099
+ }
18100
+ function nativeTimeMs(value) {
18101
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
18102
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
18103
+ }
18104
+
18105
+ // dist/session-import.js
18106
+ import { createReadStream as createReadStream2 } from "node:fs";
18107
+ import { opendir as opendir2, realpath, stat } from "node:fs/promises";
18108
+ import os2 from "node:os";
18109
+ import path5 from "node:path";
18110
+ import { createInterface as createInterface2 } from "node:readline";
18111
+
18112
+ // ../../harness-adapter/dist/session-import.js
18113
+ import { lstat as lstat2 } from "node:fs/promises";
18114
+ var SessionImportChangedError = class extends Error {
18115
+ constructor(message3 = "Native Session changed during discovery; refresh and retry") {
18116
+ super(message3);
18117
+ this.name = "SessionImportChangedError";
17936
18118
  }
17937
- return { ...value, ...indicators };
18119
+ };
18120
+ function isMissingFileError(error51) {
18121
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "ENOENT";
17938
18122
  }
17939
- var requestTokenFields = [
17940
- "inputTokens",
17941
- "cachedInputTokens",
17942
- "cacheWriteInputTokens",
17943
- "cacheWrite1hInputTokens",
17944
- "outputTokens",
17945
- "reasoningOutputTokens",
17946
- "startedAtMs",
17947
- "completedAtMs"
17948
- ];
17949
- var requestFields = /* @__PURE__ */ new Set([
17950
- ...requestTokenFields,
17951
- "requestId",
17952
- "historical",
17953
- "model",
17954
- "provider"
17955
- ]);
17956
- function parseHostUsageRequest(value) {
17957
- if (!isRecord2(value))
17958
- throw new Error("Harness Usage request must be an object");
17959
- for (const key of Object.keys(value)) {
17960
- if (!requestFields.has(key)) {
17961
- throw new Error(`Harness Usage request contains unknown field '${key}'`);
17962
- }
18123
+ function sameFileFingerprint(left, right) {
18124
+ return left === null || right === null ? left === right : left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
18125
+ }
18126
+ var STORAGE_ACCESS_ERRORS = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EIO", "EMFILE", "ENFILE"]);
18127
+ function isStorageAccessError(error51) {
18128
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && typeof error51.code === "string" && STORAGE_ACCESS_ERRORS.has(error51.code);
18129
+ }
18130
+ async function optionalLstat(file2) {
18131
+ try {
18132
+ return await lstat2(file2);
18133
+ } catch (error51) {
18134
+ if (isMissingFileError(error51))
18135
+ return null;
18136
+ throw error51;
17963
18137
  }
17964
- if (typeof value.requestId !== "string" || value.requestId.length === 0) {
17965
- throw new Error("Harness Usage request 'requestId' must be a non-empty string");
18138
+ }
18139
+ async function readStableFiles(files, read) {
18140
+ const before = await Promise.all(files.map(optionalLstat));
18141
+ const value = await read(before);
18142
+ const after = await Promise.all(files.map(optionalLstat));
18143
+ if (before.some((info, index) => !sameFileFingerprint(info, after[index] ?? null)))
18144
+ throw new SessionImportChangedError();
18145
+ return value;
18146
+ }
18147
+ function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
18148
+ if (typeof value !== "string")
18149
+ return null;
18150
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
18151
+ if (!normalized)
18152
+ return null;
18153
+ if (normalized.length <= maxLength)
18154
+ return normalized;
18155
+ const characters = [...normalized];
18156
+ if (characters.length <= maxLength)
18157
+ return normalized;
18158
+ return `${characters.slice(0, maxLength - 1).join("").trimEnd()}…`;
18159
+ }
18160
+ function sessionImportCandidate(input) {
18161
+ const time3 = typeof input.updatedAt === "number" ? input.updatedAt : typeof input.updatedAt === "string" ? Date.parse(input.updatedAt) : Number.NaN;
18162
+ const parsed = harnessSessionImportCandidateSchema.safeParse({
18163
+ nativeSessionId: input.nativeSessionId,
18164
+ cwd: input.cwd,
18165
+ title: typeof input.title === "string" && input.title.trim().length > 0 ? input.title : null,
18166
+ updatedAt: Math.floor(time3),
18167
+ // Unknown must stay unknown; only an explicit boolean is a native statement.
18168
+ running: typeof input.running === "boolean" ? input.running : null
18169
+ });
18170
+ return parsed.success ? parsed.data : null;
18171
+ }
18172
+ var SessionImportScope = class {
18173
+ #abort = new AbortController();
18174
+ #options;
18175
+ #pending = /* @__PURE__ */ new Set();
18176
+ constructor(options) {
18177
+ this.#options = options;
17966
18178
  }
17967
- for (const field2 of ["model", "provider"]) {
17968
- const candidate = value[field2];
17969
- if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
17970
- throw new Error(`Harness Usage request '${field2}' must be a non-empty string`);
18179
+ #closed() {
18180
+ return {
18181
+ ok: false,
18182
+ error: { code: "invalidState", message: this.#options.closedMessage, retryable: false }
18183
+ };
18184
+ }
18185
+ read(operation) {
18186
+ const signal = this.#abort.signal;
18187
+ if (signal.aborted)
18188
+ return Promise.resolve(this.#closed());
18189
+ let started;
18190
+ try {
18191
+ started = operation(signal);
18192
+ } catch (error51) {
18193
+ started = Promise.reject(error51 instanceof Error ? error51 : new Error("Session read failed"));
17971
18194
  }
18195
+ const request = started.then((value) => signal.aborted ? this.#closed() : { ok: true, value }).catch(() => signal.aborted ? this.#closed() : {
18196
+ ok: false,
18197
+ error: {
18198
+ code: "unavailable",
18199
+ message: this.#options.unavailableMessage,
18200
+ retryable: true
18201
+ }
18202
+ }).finally(() => this.#pending.delete(request));
18203
+ this.#pending.add(request);
18204
+ return request;
17972
18205
  }
17973
- if (value.historical !== void 0 && typeof value.historical !== "boolean") {
17974
- throw new Error("Harness Usage request 'historical' must be a boolean");
18206
+ /** `read` for `resolveCandidate`: a null source is the selected Session having disappeared. */
18207
+ async resolve(operation) {
18208
+ const result = await this.read(operation);
18209
+ if (!result.ok)
18210
+ return result;
18211
+ return result.value ? { ok: true, value: result.value } : {
18212
+ ok: false,
18213
+ error: {
18214
+ code: "sessionNotFound",
18215
+ message: this.#options.notFoundMessage,
18216
+ retryable: false
18217
+ }
18218
+ };
17975
18219
  }
17976
- for (const field2 of requestTokenFields) {
17977
- const candidate = value[field2];
17978
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17979
- throw new Error(`Harness Usage request '${field2}' must be a non-negative safe integer`);
18220
+ /** Idempotent. Resolves after every started read has settled. */
18221
+ async close() {
18222
+ this.#abort.abort();
18223
+ await Promise.allSettled(this.#pending);
18224
+ }
18225
+ };
18226
+
18227
+ // dist/session-import.js
18228
+ function isRecord2(value) {
18229
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18230
+ }
18231
+ function expandDirectory(value, home) {
18232
+ return path5.resolve(value === "~" ? home : value.startsWith(`~${path5.sep}`) || value.startsWith("~/") ? path5.join(home, value.slice(2)) : value);
18233
+ }
18234
+ function ompSessionImportDirectory(environment) {
18235
+ const home = (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
18236
+ const custom2 = environment.PI_CODING_AGENT_SESSION_DIR;
18237
+ if (custom2)
18238
+ return { directory: expandDirectory(custom2, home), flat: true };
18239
+ const agent = environment.PI_CODING_AGENT_DIR;
18240
+ return {
18241
+ directory: path5.join(agent ? expandDirectory(agent, home) : path5.join(home, ".omp", "agent"), "sessions"),
18242
+ flat: false
18243
+ };
18244
+ }
18245
+ function messageText(content) {
18246
+ if (typeof content === "string")
18247
+ return content;
18248
+ if (!Array.isArray(content))
18249
+ return "";
18250
+ return content.filter((part) => isRecord2(part) && part.type === "text" && typeof part.text === "string").map((part) => String(part.text)).join(" ");
18251
+ }
18252
+ async function readFacts(file2, signal) {
18253
+ const stream = createReadStream2(file2, { encoding: "utf8", signal });
18254
+ const lines = createInterface2({ input: stream, crlfDelay: Infinity });
18255
+ let header = null;
18256
+ let nativeTitle = null;
18257
+ let firstPrompt = null;
18258
+ let updatedAt = null;
18259
+ let leafHasUser = false;
18260
+ const hasUserAncestry = /* @__PURE__ */ new Map();
18261
+ try {
18262
+ for await (const line of lines) {
18263
+ signal.throwIfAborted();
18264
+ if (!line.trim())
18265
+ continue;
18266
+ let entry;
18267
+ try {
18268
+ entry = JSON.parse(line);
18269
+ } catch {
18270
+ continue;
18271
+ }
18272
+ if (!isRecord2(entry))
18273
+ continue;
18274
+ if (entry.type === "title") {
18275
+ nativeTitle = sessionImportTitle(entry.title);
18276
+ continue;
18277
+ }
18278
+ if (entry.type === "session") {
18279
+ if (header)
18280
+ return null;
18281
+ if (typeof entry.id !== "string" || entry.id.length === 0 || typeof entry.cwd !== "string" || !path5.isAbsolute(entry.cwd))
18282
+ return null;
18283
+ header = { id: entry.id, cwd: entry.cwd };
18284
+ continue;
18285
+ }
18286
+ if (typeof entry.id !== "string" || entry.id.length === 0)
18287
+ continue;
18288
+ const message3 = isRecord2(entry.message) ? entry.message : null;
18289
+ const isUser = entry.type === "message" && message3?.role === "user";
18290
+ if (isUser)
18291
+ firstPrompt ??= sessionImportTitle(messageText(message3?.content));
18292
+ leafHasUser = isUser || typeof entry.parentId === "string" && hasUserAncestry.get(entry.parentId) === true;
18293
+ hasUserAncestry.set(entry.id, leafHasUser);
18294
+ if (entry.type === "message" && (message3?.role === "user" || message3?.role === "assistant")) {
18295
+ const time3 = typeof message3.timestamp === "number" ? message3.timestamp : typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : Number.NaN;
18296
+ if (Number.isFinite(time3) && time3 >= 0)
18297
+ updatedAt = time3;
18298
+ }
17980
18299
  }
18300
+ } finally {
18301
+ lines.close();
18302
+ stream.destroy();
17981
18303
  }
17982
- if (value.inputTokens === void 0 || value.outputTokens === void 0) {
17983
- throw new Error("Harness Usage request must contain 'inputTokens' and 'outputTokens'");
18304
+ if (!header || !leafHasUser)
18305
+ return null;
18306
+ return {
18307
+ nativeSessionId: header.id,
18308
+ cwd: header.cwd,
18309
+ title: nativeTitle ?? firstPrompt,
18310
+ updatedAt
18311
+ };
18312
+ }
18313
+ var OmpSessionImport = class {
18314
+ #location;
18315
+ #scope = new SessionImportScope({
18316
+ closedMessage: "Omp Session import is closed",
18317
+ unavailableMessage: "Omp sessions could not be read; close native clients, check storage access and retry",
18318
+ notFoundMessage: "Omp Session is no longer importable"
18319
+ });
18320
+ constructor(environment) {
18321
+ this.#location = ompSessionImportDirectory(environment);
17984
18322
  }
17985
- const request = value;
17986
- if ((request.cachedInputTokens ?? 0) + (request.cacheWriteInputTokens ?? 0) > request.inputTokens) {
17987
- throw new Error("Harness Usage request cache Tokens must not exceed 'inputTokens'");
18323
+ listCandidates() {
18324
+ return this.#scope.read(async (signal) => [...(await this.#sources(signal)).values()].flatMap((sources) => (
18325
+ // One identity in two files cannot be resumed unambiguously.
18326
+ sources.length === 1 && sources[0] ? [sources[0].candidate] : []
18327
+ )));
17988
18328
  }
17989
- if ((request.reasoningOutputTokens ?? 0) > request.outputTokens) {
17990
- throw new Error("Harness Usage request 'reasoningOutputTokens' must not exceed 'outputTokens'");
18329
+ resolveCandidate(nativeSessionId) {
18330
+ return this.#scope.resolve(async (signal) => {
18331
+ const sources = (await this.#sources(signal)).get(nativeSessionId);
18332
+ if (sources?.length !== 1 || !sources[0])
18333
+ return null;
18334
+ const source = await this.#source(sources[0].file, signal);
18335
+ return source?.nativeRef.nativeSessionId === nativeSessionId ? { candidate: source.candidate, nativeRef: source.nativeRef } : null;
18336
+ });
17991
18337
  }
17992
- if (request.cacheWrite1hInputTokens !== void 0 && request.cacheWrite1hInputTokens > (request.cacheWriteInputTokens ?? -1)) {
17993
- throw new Error("Harness Usage request 'cacheWrite1hInputTokens' must not exceed 'cacheWriteInputTokens'");
18338
+ close() {
18339
+ return this.#scope.close();
17994
18340
  }
17995
- if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
17996
- throw new Error("Harness Usage request timing fields must be provided together");
18341
+ async #sessionFiles(signal) {
18342
+ const { directory, flat } = this.#location;
18343
+ const info = await optionalLstat(directory);
18344
+ if (!info)
18345
+ return [];
18346
+ if (!info.isDirectory())
18347
+ throw new Error("Omp Session store is not a directory");
18348
+ const files = [];
18349
+ const visit = async (current, projectLevel) => {
18350
+ const entries = await opendir2(current).catch((error51) => {
18351
+ if (isMissingFileError(error51))
18352
+ return null;
18353
+ throw error51;
18354
+ });
18355
+ if (!entries)
18356
+ return;
18357
+ for await (const entry of entries) {
18358
+ signal.throwIfAborted();
18359
+ if (projectLevel && entry.isDirectory())
18360
+ await visit(path5.join(current, entry.name), false);
18361
+ else if (!projectLevel && entry.isFile() && entry.name.endsWith(".jsonl"))
18362
+ files.push(path5.join(current, entry.name));
18363
+ }
18364
+ };
18365
+ await visit(directory, !flat);
18366
+ return files;
17997
18367
  }
17998
- if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
17999
- throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
18368
+ /** Session ID to every readable file claiming it. Files changing under the read are skipped. */
18369
+ async #sources(signal) {
18370
+ const found = /* @__PURE__ */ new Map();
18371
+ for (const file2 of await this.#sessionFiles(signal)) {
18372
+ signal.throwIfAborted();
18373
+ try {
18374
+ const source = await this.#source(file2, signal);
18375
+ if (!source)
18376
+ continue;
18377
+ const sources = found.get(source.nativeRef.nativeSessionId) ?? [];
18378
+ sources.push(source);
18379
+ found.set(source.nativeRef.nativeSessionId, sources);
18380
+ } catch (error51) {
18381
+ if (!(error51 instanceof SessionImportChangedError))
18382
+ throw error51;
18383
+ }
18384
+ }
18385
+ return found;
18000
18386
  }
18001
- return { ...request };
18002
- }
18003
-
18004
- // ../../harness-adapter/dist/live-command-catalog.js
18005
- var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
18006
- // Session lifecycle
18007
- "branch",
18008
- "clear",
18009
- "exit",
18010
- "fork",
18011
- "fresh",
18012
- "new",
18013
- "quit",
18014
- "rename",
18015
- "rename-chat",
18016
- "reset",
18017
- "resume",
18018
- "rewind",
18019
- "session",
18020
- "sessions",
18021
- // Desktop-owned configuration
18022
- "autocompact",
18023
- "color",
18024
- "config",
18025
- "effort",
18026
- "fast",
18027
- "keybindings",
18028
- "model",
18029
- "models",
18030
- "output-style",
18031
- "permissions",
18032
- "settings",
18033
- "statusline",
18034
- "terminal-setup",
18035
- "theme",
18036
- "vim",
18037
- // Trust and approval policy
18038
- "always-approve",
18039
- "auto-mode-setup",
18040
- // Native login
18041
- "login",
18042
- "logout",
18043
- // Work outliving the Turn
18044
- "autopilot",
18045
- "background",
18046
- "bg",
18047
- "goal",
18048
- "jobs",
18049
- "loop",
18050
- "multitask",
18051
- "queue",
18052
- "remote-control",
18053
- "schedule",
18054
- "steer",
18055
- // Native terminal UI
18056
- "copy",
18057
- "debug",
18058
- "feedback",
18059
- "heapdump",
18060
- "share",
18061
- "shell",
18062
- // Plugin and MCP management
18063
- "marketplace",
18064
- "mcp",
18065
- "plugins",
18066
- "reload-plugins"
18067
- ]);
18068
- var COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES = ["__", "hooks-"];
18069
- function isExcludedLiveCommand(name, kind, extra = {}) {
18070
- const normalized = name.trim().replace(/^\//u, "");
18071
- if (new Set(extra.names ?? []).has(normalized))
18072
- return true;
18073
- if (extra.prefixes?.some((prefix) => normalized.startsWith(prefix)))
18074
- return true;
18075
- if (kind === "skill")
18076
- return false;
18077
- return COMMON_EXCLUDED_LIVE_COMMANDS.has(normalized) || COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES.some((prefix) => normalized.startsWith(prefix));
18078
- }
18079
- function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
18080
- if (!commandId.startsWith(idPrefix))
18081
- return null;
18082
- const descriptor = catalog.commands.find(({ id }) => id === commandId);
18083
- if (!descriptor)
18084
- return null;
18085
- const text = typeof argumentText === "string" ? argumentText.trim() : "";
18086
- return text ? `${descriptor.invocation} ${text}` : descriptor.invocation;
18087
- }
18088
- function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
18089
- if (!live)
18090
- return builtIns;
18091
- const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
18092
- const ids = new Set(builtIns.commands.map(({ id }) => id));
18093
- const dynamic = [];
18094
- for (const command of live) {
18095
- const name = command.name.trim().replace(/^\//u, "");
18096
- if (!name || /\s/u.test(name))
18097
- continue;
18098
- if (isExcludedLiveCommand(name, command.kind, exclusions))
18099
- continue;
18100
- const invocation = `/${name}`;
18101
- const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
18102
- if (invocations.has(invocation) || ids.has(id))
18103
- continue;
18104
- const description = command.description?.trim().slice(0, 512);
18105
- const parsed = harnessCommandDescriptorSchema.safeParse({
18106
- id,
18107
- invocation,
18108
- label: name.slice(0, 128),
18109
- ...description ? { description } : {},
18110
- argumentMode: "text",
18111
- kind: command.kind
18387
+ async #source(file2, signal) {
18388
+ signal.throwIfAborted();
18389
+ return readStableFiles([file2], async ([info]) => {
18390
+ if (!info?.isFile() || info.size === 0)
18391
+ return null;
18392
+ try {
18393
+ const facts = await readFacts(file2, signal);
18394
+ if (!facts)
18395
+ return null;
18396
+ const cwd = await realpath(facts.cwd);
18397
+ if (!(await stat(cwd)).isDirectory())
18398
+ return null;
18399
+ const candidate = sessionImportCandidate({
18400
+ nativeSessionId: facts.nativeSessionId,
18401
+ cwd,
18402
+ title: facts.title,
18403
+ updatedAt: facts.updatedAt ?? info.mtimeMs
18404
+ // OMP has no cross-process activity marker: idleness cannot be established.
18405
+ });
18406
+ if (!candidate)
18407
+ return null;
18408
+ return {
18409
+ file: file2,
18410
+ candidate,
18411
+ // Resume needs the file itself: OMP is started with `--session <file>`.
18412
+ nativeRef: nativeSessionRefSchema.parse({
18413
+ harnessId: "omp",
18414
+ nativeSessionId: facts.nativeSessionId,
18415
+ locator: { sessionFile: await realpath(file2) },
18416
+ formatVersion: 1
18417
+ })
18418
+ };
18419
+ } catch (error51) {
18420
+ signal.throwIfAborted();
18421
+ if (isStorageAccessError(error51))
18422
+ throw error51;
18423
+ return null;
18424
+ }
18112
18425
  });
18113
- if (!parsed.success)
18114
- continue;
18115
- invocations.add(invocation);
18116
- ids.add(id);
18117
- dynamic.push(parsed.data);
18118
18426
  }
18119
- return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
18120
- }
18427
+ };
18121
18428
 
18122
18429
  // dist/omp-model-catalog.js
18123
18430
  var OMP_MODEL_REF_PREFIX = "omp-model-v1.";
@@ -18677,7 +18984,7 @@ var ompDiscoverySpec = {
18677
18984
  "/opt/homebrew/bin",
18678
18985
  "/usr/local/bin"
18679
18986
  ],
18680
- windows: ["${APPDATA}/npm", "~/.local/bin", VERSION_MANAGER_ROOTS]
18987
+ windows: ["${APPDATA}/npm", "${LOCALAPPDATA}/omp", "~/.local/bin", VERSION_MANAGER_ROOTS]
18681
18988
  }
18682
18989
  };
18683
18990
  function resolveOmpExecutable(input, dependencies = {}) {
@@ -18719,10 +19026,9 @@ function parseOmpAvailableCommands(value) {
18719
19026
  });
18720
19027
  }
18721
19028
  function ompLiveCommands(native) {
18722
- return native.filter(({ source, name }) => source !== "builtin" || name === "context").map((command) => ({
19029
+ return native.filter(({ source, name }) => source !== "skill" && (source !== "builtin" || name === "context")).map((command) => ({
18723
19030
  name: command.name,
18724
- description: command.description,
18725
- kind: command.source === "skill" ? "skill" : "command"
19031
+ description: command.description
18726
19032
  }));
18727
19033
  }
18728
19034
 
@@ -18934,6 +19240,9 @@ var OmpRpcUnsupportedCommandError = class extends Error {
18934
19240
  this.name = "OmpRpcUnsupportedCommandError";
18935
19241
  }
18936
19242
  };
19243
+ function hasTurnCompletion(active) {
19244
+ return active.terminalEnd || active.localResult !== null && !active.sawAgentStart;
19245
+ }
18937
19246
  var textDecoder = new TextDecoder("utf-8", { fatal: true });
18938
19247
  function isRecord8(value) {
18939
19248
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -18990,9 +19299,9 @@ function parseSessionStreaming(response) {
18990
19299
  }
18991
19300
  return isStreaming;
18992
19301
  }
18993
- function cancellationSettled(response, terminalEnd) {
19302
+ function sessionSettled(response, completed) {
18994
19303
  const data = sessionStateData(response);
18995
- return !parseSessionStreaming(response) && (data.isSettled === true || data.isSettled === void 0 && terminalEnd) && data.isCompacting !== true && data.hasPendingAsyncWork !== true && !(typeof data.queuedMessageCount === "number" && data.queuedMessageCount > 0);
19304
+ return !parseSessionStreaming(response) && (data.isSettled === true || data.isSettled === void 0 && completed) && data.isCompacting !== true && data.hasPendingAsyncWork !== true && !(typeof data.queuedMessageCount === "number" && data.queuedMessageCount > 0);
18996
19305
  }
18997
19306
  function parseAvailableModels(response) {
18998
19307
  const data = isRecord8(response.data) ? response.data : null;
@@ -19224,6 +19533,9 @@ var OmpRpcSession = class {
19224
19533
  child.stderr.on("data", (chunk) => {
19225
19534
  this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
19226
19535
  });
19536
+ child.stdin.on("error", (error51) => {
19537
+ this.#fail(new OmpRpcFaultError("processExited", `Omp RPC stdin closed: ${error51.message}`, this.stderrTail));
19538
+ });
19227
19539
  child.once("error", (error51) => {
19228
19540
  const kind = isRecord8(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
19229
19541
  this.#fail(new OmpRpcFaultError(kind, `Omp RPC failed to start: ${error51.message}`, this.stderrTail));
@@ -19470,7 +19782,10 @@ var OmpRpcSession = class {
19470
19782
  tools: /* @__PURE__ */ new Map(),
19471
19783
  interactions: /* @__PURE__ */ new Map(),
19472
19784
  settlement: "pending",
19785
+ settledNotice: false,
19786
+ settlementRecheck: null,
19473
19787
  terminalEnd: false,
19788
+ sawAgentStart: false,
19474
19789
  cancellation: "none",
19475
19790
  cancellationTimeout: null,
19476
19791
  cancellationRecheck: null,
@@ -19680,12 +19995,21 @@ var OmpRpcSession = class {
19680
19995
  if (this.#handleSubagentFrame(active, value))
19681
19996
  return;
19682
19997
  this.#observeUsage(value);
19683
- if (value.type === "agent_start" && active)
19998
+ if (value.type === "agent_start" && active) {
19684
19999
  active.terminalEnd = false;
20000
+ active.sawAgentStart = true;
20001
+ }
19685
20002
  if ((value.type === "session_settled" || value.type === "agent_start") && active?.cancellation === "accepted") {
19686
20003
  void this.#confirmCancelledTurn(active);
19687
20004
  return;
19688
20005
  }
20006
+ if (value.type === "session_settled") {
20007
+ if (active && hasTurnCompletion(active)) {
20008
+ active.settledNotice = true;
20009
+ void this.#confirmSettledTurn(active);
20010
+ }
20011
+ return;
20012
+ }
19689
20013
  if (!active) {
19690
20014
  if (value.type === "extension_ui_request" && this.#isBlockingInteraction(value)) {
19691
20015
  this.#fail(new OmpRpcFaultError("protocolError", "Omp RPC requested blocking Extension UI outside an active Turn"));
@@ -19780,9 +20104,6 @@ var OmpRpcSession = class {
19780
20104
  void this.#confirmCancelledTurn(active);
19781
20105
  return;
19782
20106
  }
19783
- if (active.settlement !== "pending")
19784
- return;
19785
- active.settlement = "confirming";
19786
20107
  void this.#confirmSettledTurn(active);
19787
20108
  }
19788
20109
  }
@@ -19834,6 +20155,7 @@ var OmpRpcSession = class {
19834
20155
  const description = nonBlankString(payload.description) ? payload.description : nonBlankString(payload.agent) ? `${payload.agent} delegation` : "Subagent delegation";
19835
20156
  emit?.({
19836
20157
  type: "subagent.started",
20158
+ ...subagentConfiguration(payload),
19837
20159
  callId,
19838
20160
  nativeSubagentId,
19839
20161
  description,
@@ -19866,6 +20188,8 @@ var OmpRpcSession = class {
19866
20188
  const resultSummary = recentOutput.at(-1);
19867
20189
  emit?.({
19868
20190
  type: "subagent.updated",
20191
+ ...subagentConfiguration(payload),
20192
+ ...subagentConfiguration(progress),
19869
20193
  callId,
19870
20194
  nativeSubagentId,
19871
20195
  status,
@@ -20100,7 +20424,7 @@ var OmpRpcSession = class {
20100
20424
  throw new OmpRpcFaultError("protocolError", "Omp cancelled Session reload changed its identity or configuration");
20101
20425
  }
20102
20426
  }
20103
- if (!cancellationSettled(response, active.terminalEnd)) {
20427
+ if (!sessionSettled(response, active.terminalEnd)) {
20104
20428
  active.settlement = "pending";
20105
20429
  active.cancellationRecheck = setTimeout(() => {
20106
20430
  active.cancellationRecheck = null;
@@ -20124,10 +20448,15 @@ var OmpRpcSession = class {
20124
20448
  if (this.#activeTurn !== active || active.settlement !== "pending")
20125
20449
  return;
20126
20450
  active.localResult = result;
20127
- active.settlement = "confirming";
20128
20451
  void this.#confirmSettledTurn(active);
20129
20452
  }
20130
20453
  async #confirmSettledTurn(active) {
20454
+ if (this.#activeTurn !== active || active.settlement !== "pending" || active.cancellation !== "none" || !hasTurnCompletion(active))
20455
+ return;
20456
+ if (active.settlementRecheck)
20457
+ clearTimeout(active.settlementRecheck);
20458
+ active.settlementRecheck = null;
20459
+ active.settlement = "confirming";
20131
20460
  try {
20132
20461
  const response = await this.#send("get_state", {});
20133
20462
  const state = parseSessionState(response);
@@ -20139,8 +20468,21 @@ var OmpRpcSession = class {
20139
20468
  void this.#confirmCancelledTurn(active);
20140
20469
  return;
20141
20470
  }
20142
- if (parseSessionStreaming(response)) {
20143
- throw new OmpRpcFaultError("protocolError", "Omp RPC completed Turn state is still Streaming");
20471
+ if (!hasTurnCompletion(active)) {
20472
+ active.settlement = "pending";
20473
+ active.settledNotice = false;
20474
+ return;
20475
+ }
20476
+ if (!sessionSettled(response, hasTurnCompletion(active))) {
20477
+ active.settlement = "pending";
20478
+ if (active.settledNotice) {
20479
+ active.settledNotice = false;
20480
+ active.settlementRecheck = setTimeout(() => {
20481
+ active.settlementRecheck = null;
20482
+ void this.#confirmSettledTurn(active);
20483
+ }, 50);
20484
+ }
20485
+ return;
20144
20486
  }
20145
20487
  this.#state = state;
20146
20488
  active.settlement = "confirmed";
@@ -20156,6 +20498,9 @@ var OmpRpcSession = class {
20156
20498
  if (this.#activeTurn !== active || active.settlement !== "confirmed" || active.cancellation === "requesting") {
20157
20499
  return;
20158
20500
  }
20501
+ if (active.settlementRecheck)
20502
+ clearTimeout(active.settlementRecheck);
20503
+ active.settlementRecheck = null;
20159
20504
  if (active.cancellationTimeout)
20160
20505
  clearTimeout(active.cancellationTimeout);
20161
20506
  active.cancellationTimeout = null;
@@ -20317,6 +20662,8 @@ var OmpRpcSession = class {
20317
20662
  const active = this.#activeTurn;
20318
20663
  if (!active)
20319
20664
  return;
20665
+ if (active.settlementRecheck)
20666
+ clearTimeout(active.settlementRecheck);
20320
20667
  if (active.cancellationTimeout)
20321
20668
  clearTimeout(active.cancellationTimeout);
20322
20669
  if (active.cancellationRecheck)
@@ -21091,6 +21438,7 @@ var OmpSubagentLifecycle = class {
21091
21438
  subagentId: event.nativeSubagentId,
21092
21439
  nativeSubagentId: event.nativeSubagentId,
21093
21440
  description: event.description,
21441
+ ...subagentConfiguration(event),
21094
21442
  ...event.role ? { role: event.role } : {},
21095
21443
  background: event.background,
21096
21444
  status: "running"
@@ -21115,6 +21463,7 @@ var OmpSubagentLifecycle = class {
21115
21463
  throw new Error("Omp Subagent delegation has no Agent state");
21116
21464
  const subagent = {
21117
21465
  ...current,
21466
+ ...subagentConfiguration(event),
21118
21467
  status: event.status === "interrupted" ? "interrupted" : event.status,
21119
21468
  ...event.description ? { description: event.description } : {},
21120
21469
  ...event.resultSummary ? { resultSummary: event.resultSummary } : {},
@@ -21665,7 +22014,19 @@ var OmpHarnessSession = class {
21665
22014
  ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
21666
22015
  });
21667
22016
  }
22017
+ #subagentConfiguration() {
22018
+ const state = this.#state;
22019
+ const model2 = state.effectiveModel ? decodeOmpModelRef(state.effectiveModel).id : void 0;
22020
+ return {
22021
+ ...model2 ? { model: model2 } : {},
22022
+ ...state.effectiveThinkingOptionId ? { reasoningEffort: state.effectiveThinkingOptionId } : {}
22023
+ };
22024
+ }
21668
22025
  async readSnapshot() {
22026
+ const result = await this.#readSnapshot();
22027
+ return result.ok ? { ok: true, value: configureSubagentSnapshot(result.value, this.#subagentConfiguration()) } : result;
22028
+ }
22029
+ async #readSnapshot() {
21669
22030
  if (this.#phase !== "open" && this.#phase !== "faulted") {
21670
22031
  return { ok: false, error: invalidState("Omp Session is not open") };
21671
22032
  }
@@ -22852,6 +23213,7 @@ var OmpHarnessSession = class {
22852
23213
  }
22853
23214
  }
22854
23215
  #event(event) {
23216
+ event = configureSubagentEvent(event, this.#subagentConfiguration());
22855
23217
  this.#channel.emit({ kind: "event", event });
22856
23218
  }
22857
23219
  #newItemId() {