@1agents/acp-service 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +42 -2
  2. package/dist/bin/a2a.js +3 -2
  3. package/dist/bin/acp-service.js +0 -0
  4. package/dist/src/a2a/executor.d.ts +2 -0
  5. package/dist/src/a2a/executor.js +96 -18
  6. package/dist/src/a2a/gateway.d.ts +407 -14
  7. package/dist/src/a2a/gateway.js +719 -37
  8. package/dist/src/a2a/index.d.ts +9 -1
  9. package/dist/src/a2a/index.js +5 -0
  10. package/dist/src/a2a/lease.d.ts +13 -0
  11. package/dist/src/a2a/lease.js +149 -0
  12. package/dist/src/a2a/notices.d.ts +24 -0
  13. package/dist/src/a2a/notices.js +56 -0
  14. package/dist/src/a2a/preflight.d.ts +52 -0
  15. package/dist/src/a2a/preflight.js +153 -0
  16. package/dist/src/a2a/request-id.d.ts +2 -0
  17. package/dist/src/a2a/request-id.js +6 -0
  18. package/dist/src/a2a/result-metadata.d.ts +59 -0
  19. package/dist/src/a2a/result-metadata.js +156 -0
  20. package/dist/src/a2a/server.js +43 -1
  21. package/dist/src/a2a/session-delivery.d.ts +69 -0
  22. package/dist/src/a2a/session-delivery.js +260 -0
  23. package/dist/src/a2a/session-hosts.d.ts +34 -0
  24. package/dist/src/a2a/session-hosts.js +211 -0
  25. package/dist/src/a2a/store.d.ts +4 -6
  26. package/dist/src/a2a/store.js +17 -115
  27. package/dist/src/a2a/types.d.ts +42 -0
  28. package/dist/src/acp-connection.d.ts +2 -1
  29. package/dist/src/acp-connection.js +52 -9
  30. package/dist/src/bridge.js +38 -39
  31. package/dist/src/execution/delivery-progress.d.ts +108 -0
  32. package/dist/src/execution/delivery-progress.js +57 -0
  33. package/dist/src/execution/ledger.d.ts +235 -0
  34. package/dist/src/execution/ledger.js +396 -0
  35. package/dist/src/execution/ppt-delivery.d.ts +231 -0
  36. package/dist/src/execution/ppt-delivery.js +625 -0
  37. package/dist/src/execution/targets.d.ts +349 -0
  38. package/dist/src/execution/targets.js +428 -0
  39. package/package.json +13 -13
  40. package/skills/acp-service/SKILL.md +9 -2
  41. package/skills/acp-service/references/a2a.md +72 -4
  42. package/vendor/dsh/README.md +12 -2
  43. package/vendor/dsh/a2a-executor.d.ts +9 -2
  44. package/vendor/dsh/a2a-executor.js +84 -16
  45. package/vendor/dsh/a2a.d.ts +2 -1
  46. package/vendor/dsh/a2a.js +10 -5
  47. package/vendor/dsh/adapter.d.ts +3 -1
  48. package/vendor/dsh/adapter.js +144 -16
  49. package/vendor/dsh/client.js +11 -3
  50. package/vendor/dsh/diagnostics.d.ts +42 -0
  51. package/vendor/dsh/diagnostics.js +176 -0
  52. package/vendor/dsh/index.d.ts +1 -0
  53. package/vendor/dsh/index.js +16 -4
  54. package/vendor/runtime/dist/{agent-registry-CMg8LHKY.js → agent-registry-R7A3MSpr.js} +9 -1
  55. package/vendor/runtime/dist/agent-registry-R7A3MSpr.js.map +1 -0
  56. package/vendor/runtime/dist/agent-registry.d.ts +1 -0
  57. package/vendor/runtime/dist/agent-registry.d.ts.map +1 -1
  58. package/vendor/runtime/dist/agent-registry.js +1 -2
  59. package/vendor/runtime/dist/{cli-DUHyAADv.js → cli-DeOpE2Xz.js} +4 -4
  60. package/vendor/runtime/dist/{cli-DUHyAADv.js.map → cli-DeOpE2Xz.js.map} +1 -1
  61. package/vendor/runtime/dist/cli.d.ts +2 -1
  62. package/vendor/runtime/dist/cli.js +10 -10
  63. package/vendor/runtime/dist/cli.js.map +1 -1
  64. package/vendor/runtime/dist/{client-DjkWknf7.d.ts → client-VQsqcIOJ.d.ts} +2 -2
  65. package/vendor/runtime/dist/{client-DjkWknf7.d.ts.map → client-VQsqcIOJ.d.ts.map} +1 -1
  66. package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
  67. package/vendor/runtime/dist/docs-site/CLI.html +833 -0
  68. package/vendor/runtime/dist/docs-site/VISION.html +415 -0
  69. package/vendor/runtime/dist/docs-site/agents.html +391 -0
  70. package/vendor/runtime/dist/docs-site/compare.html +359 -0
  71. package/vendor/runtime/dist/docs-site/config.html +450 -0
  72. package/vendor/runtime/dist/docs-site/custom-agents.html +408 -0
  73. package/vendor/runtime/dist/docs-site/exit-codes.html +347 -0
  74. package/vendor/runtime/dist/docs-site/favicon.svg +21 -0
  75. package/vendor/runtime/dist/docs-site/flows.html +498 -0
  76. package/vendor/runtime/dist/docs-site/index.html +367 -0
  77. package/vendor/runtime/dist/docs-site/install.html +386 -0
  78. package/vendor/runtime/dist/docs-site/llms.txt +36 -0
  79. package/vendor/runtime/dist/docs-site/output-formats.html +407 -0
  80. package/vendor/runtime/dist/docs-site/permissions.html +422 -0
  81. package/vendor/runtime/dist/docs-site/prompting.html +460 -0
  82. package/vendor/runtime/dist/docs-site/quickstart.html +382 -0
  83. package/vendor/runtime/dist/docs-site/releasing.html +341 -0
  84. package/vendor/runtime/dist/docs-site/runtime-environment.html +329 -0
  85. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +335 -0
  86. package/vendor/runtime/dist/docs-site/safe-errors.html +323 -0
  87. package/vendor/runtime/dist/docs-site/session-control.html +408 -0
  88. package/vendor/runtime/dist/docs-site/session-watch.html +354 -0
  89. package/vendor/runtime/dist/docs-site/sessions.html +488 -0
  90. package/vendor/runtime/dist/docs-site/shared-sessions.html +377 -0
  91. package/vendor/runtime/dist/{flows-CiJSCy4D.js → flows-oaBGn31w.js} +5 -5
  92. package/vendor/runtime/dist/{flows-CiJSCy4D.js.map → flows-oaBGn31w.js.map} +1 -1
  93. package/vendor/runtime/dist/flows.d.ts +2 -2
  94. package/vendor/runtime/dist/flows.d.ts.map +1 -1
  95. package/vendor/runtime/dist/flows.js +1 -2
  96. package/vendor/runtime/dist/{invocation-options-BlIySxIw.js → invocation-options-CUDEE8vW.js} +5 -5
  97. package/vendor/runtime/dist/{invocation-options-BlIySxIw.js.map → invocation-options-CUDEE8vW.js.map} +1 -1
  98. package/vendor/runtime/dist/{ipc-BlljKR2b.js → ipc-BQQpcEdP.js} +356 -20
  99. package/vendor/runtime/dist/ipc-BQQpcEdP.js.map +1 -0
  100. package/vendor/runtime/dist/{output-BzXQKArM.js → output-CFv3jcOQ.js} +86 -22
  101. package/vendor/runtime/dist/output-CFv3jcOQ.js.map +1 -0
  102. package/vendor/runtime/dist/{queue-owner-runtime-DSFdsS_y.js → queue-owner-runtime-DvMJiGbP.js} +86 -27
  103. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +1 -0
  104. package/vendor/runtime/dist/runtime.d.ts +28 -15
  105. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  106. package/vendor/runtime/dist/runtime.js +131 -63
  107. package/vendor/runtime/dist/runtime.js.map +1 -1
  108. package/vendor/runtime/dist/{session-options-ORCchZGk.d.ts → session-options-NjpFwf-c.d.ts} +22 -2
  109. package/vendor/runtime/dist/session-options-NjpFwf-c.d.ts.map +1 -0
  110. package/vendor/runtime/dist/{session-watch-BiBTBMz4.js → session-watch-Di-wIdCH.js} +4 -4
  111. package/vendor/runtime/dist/{session-watch-BiBTBMz4.js.map → session-watch-Di-wIdCH.js.map} +1 -1
  112. package/vendor/runtime/dist/{watch-iYiP-lOo.js → watch-CIpoMaWD.js} +2 -2
  113. package/vendor/runtime/dist/{watch-iYiP-lOo.js.map → watch-CIpoMaWD.js.map} +1 -1
  114. package/vendor/runtime/package.json +1 -1
  115. package/vendor/runtime/skills/acpx/SKILL.md +8 -2
  116. package/vendor/runtime/dist/agent-registry-CMg8LHKY.js.map +0 -1
  117. package/vendor/runtime/dist/ipc-BlljKR2b.js.map +0 -1
  118. package/vendor/runtime/dist/output-BzXQKArM.js.map +0 -1
  119. package/vendor/runtime/dist/queue-owner-runtime-DSFdsS_y.js.map +0 -1
  120. package/vendor/runtime/dist/session-options-ORCchZGk.d.ts.map +0 -1
@@ -1,4 +1,4 @@
1
- import { C as PROCESS_HELPER_MAX_BUFFER_BYTES, D as isChildProcessRunning, F as splitCommandLine, P as runTimedExecFile, n as AGENT_REGISTRY, r as BUILT_IN_AGENT_PACKAGES, t as AGENT_ARGV_REGISTRY, w as PROCESS_HELPER_TIMEOUT_MS } from "./agent-registry-CMg8LHKY.js";
1
+ import { C as PROCESS_HELPER_MAX_BUFFER_BYTES, D as isChildProcessRunning, F as splitCommandLine, P as runTimedExecFile, n as AGENT_REGISTRY, r as BUILT_IN_AGENT_PACKAGES, t as AGENT_ARGV_REGISTRY, w as PROCESS_HELPER_TIMEOUT_MS } from "./agent-registry-R7A3MSpr.js";
2
2
  import fs, { statSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import fs$1 from "node:fs/promises";
@@ -191,6 +191,21 @@ var PermissionPromptUnavailableError = class extends AcpxOperationalError {
191
191
  }
192
192
  };
193
193
  //#endregion
194
+ //#region src/runtime/public/errors.ts
195
+ var AcpRuntimeError = class extends Error {
196
+ code;
197
+ cause;
198
+ constructor(code, message, options) {
199
+ super(message);
200
+ this.name = "AcpRuntimeError";
201
+ this.code = code;
202
+ this.cause = options?.cause;
203
+ }
204
+ };
205
+ function isAcpRuntimeError(value) {
206
+ return value instanceof AcpRuntimeError;
207
+ }
208
+ //#endregion
194
209
  //#region src/types.ts
195
210
  const EXIT_CODES = {
196
211
  SUCCESS: 0,
@@ -233,6 +248,23 @@ const OUTPUT_ERROR_ORIGINS = [
233
248
  "queue",
234
249
  "acp"
235
250
  ];
251
+ const QUEUE_ERROR_DETAIL_CODES = [
252
+ "QUEUE_OWNER_CLOSED",
253
+ "QUEUE_OWNER_SHUTTING_DOWN",
254
+ "QUEUE_OWNER_OVERLOADED",
255
+ "QUEUE_OWNER_GENERATION_MISMATCH",
256
+ "QUEUE_REQUEST_INVALID",
257
+ "QUEUE_REQUEST_PAYLOAD_INVALID_JSON",
258
+ "QUEUE_ACK_MISSING",
259
+ "QUEUE_DISCONNECTED_BEFORE_ACK",
260
+ "QUEUE_DISCONNECTED_BEFORE_COMPLETION",
261
+ "QUEUE_PROTOCOL_INVALID_JSON",
262
+ "QUEUE_PROTOCOL_MALFORMED_MESSAGE",
263
+ "QUEUE_PROTOCOL_UNEXPECTED_RESPONSE",
264
+ "QUEUE_NOT_ACCEPTING_REQUESTS",
265
+ "QUEUE_CONTROL_REQUEST_FAILED",
266
+ "QUEUE_RUNTIME_PROMPT_FAILED"
267
+ ];
236
268
  const SESSION_RECORD_SCHEMA = "acpx.session.v1";
237
269
  //#endregion
238
270
  //#region src/acp/error-shapes.ts
@@ -365,6 +397,9 @@ function readOutputErrorMeta(error) {
365
397
  function isTimeoutLike(error) {
366
398
  return error instanceof Error && error.name === "TimeoutError";
367
399
  }
400
+ function isLocalAbortOrTimeoutError(error) {
401
+ return error instanceof Error && error.name === "AbortError" || isTimeoutLike(error);
402
+ }
368
403
  function isNoSessionLike(error) {
369
404
  return error instanceof Error && error.name === "NoSessionError";
370
405
  }
@@ -437,6 +472,229 @@ function exitCodeForOutputErrorCode(code) {
437
472
  default: return EXIT_CODES.ERROR;
438
473
  }
439
474
  }
475
+ const PROVIDER_SIGNALS = {
476
+ usageLimitExceeded: "quota",
477
+ quota_exhausted: "quota",
478
+ insufficient_quota: "quota",
479
+ rateLimitExceeded: "rate_limit",
480
+ rate_limited: "rate_limit",
481
+ rate_limit_exceeded: "rate_limit",
482
+ sessionBudgetExceeded: "budget",
483
+ budget_exhausted: "budget",
484
+ unauthorized: "auth",
485
+ auth_required: "auth",
486
+ authentication_required: "auth"
487
+ };
488
+ const SAFE_MESSAGES = {
489
+ quota: "Provider quota exhausted.",
490
+ rate_limit: "Provider rate limit reached.",
491
+ budget: "Provider session budget exhausted.",
492
+ auth: "Provider authentication required.",
493
+ cancelled: "ACP execution cancelled.",
494
+ timeout: "ACP execution timed out.",
495
+ permission: "ACP permission denied.",
496
+ unknown: "ACP execution failed."
497
+ };
498
+ const SAFE_CODES = /* @__PURE__ */ new Set([
499
+ ...OUTPUT_ERROR_CODES,
500
+ "ACP_BACKEND_MISSING",
501
+ "ACP_BACKEND_UNAVAILABLE",
502
+ "ACP_BACKEND_UNSUPPORTED_CONTROL",
503
+ "ACP_DISPATCH_DISABLED",
504
+ "ACP_INVALID_RUNTIME_OPTION",
505
+ "ACP_SESSION_INIT_FAILED",
506
+ "ACP_TURN_FAILED",
507
+ "ABORTED"
508
+ ]);
509
+ const SAFE_DETAILS = /* @__PURE__ */ new Set([
510
+ ...QUEUE_ERROR_DETAIL_CODES,
511
+ "AUTH_REQUIRED",
512
+ "AGENT_DISCONNECTED",
513
+ "AGENT_SPAWN_ENOENT",
514
+ "AGENT_STARTUP_FAILED",
515
+ "SESSION_RESUME_REQUIRED",
516
+ "SESSION_MODE_REPLAY_FAILED",
517
+ "SESSION_MODEL_REPLAY_FAILED",
518
+ "SESSION_CONFIG_OPTION_REPLAY_FAILED",
519
+ "UNSUPPORTED_PROMPT_CONTENT",
520
+ "WATCH_OUTCOME_UNKNOWN"
521
+ ]);
522
+ const SAFE_ORIGINS = /* @__PURE__ */ new Set([
523
+ ...OUTPUT_ERROR_ORIGINS,
524
+ "service",
525
+ "transport",
526
+ "dsh",
527
+ "a2a"
528
+ ]);
529
+ const safeProjections = /* @__PURE__ */ new WeakSet();
530
+ /** Only known envelope edges are visited, with both depth and node limits. */
531
+ function safeErrorRecords(error) {
532
+ const records = [];
533
+ const seen = /* @__PURE__ */ new Set();
534
+ const pending = [{
535
+ value: error,
536
+ depth: 0
537
+ }];
538
+ while (pending.length && records.length < 24) {
539
+ const entry = pending.shift();
540
+ if (!entry || entry.depth > 5 || seen.has(entry.value)) continue;
541
+ seen.add(entry.value);
542
+ const record = asRecord$4(entry.value);
543
+ if (!record) continue;
544
+ records.push(record);
545
+ for (const key of [
546
+ "error",
547
+ "acp",
548
+ "cause",
549
+ "data"
550
+ ]) pending.push({
551
+ value: record[key],
552
+ depth: entry.depth + 1
553
+ });
554
+ }
555
+ return records;
556
+ }
557
+ function providerSignal(value) {
558
+ return typeof value === "string" && Object.hasOwn(PROVIDER_SIGNALS, value) ? PROVIDER_SIGNALS[value] : void 0;
559
+ }
560
+ function collectProviderSignal(state, key, value) {
561
+ if (value === void 0) return;
562
+ const candidate = providerSignal(value);
563
+ if (!candidate) {
564
+ state.conflict ||= !isNeutralErrorSignal(key, value);
565
+ return;
566
+ }
567
+ state.conflict ||= state.category !== void 0 && state.category !== candidate;
568
+ state.category = candidate;
569
+ state.providerCode ??= value;
570
+ }
571
+ function safeProviderCause(records, projected) {
572
+ const state = {};
573
+ for (const record of records) for (const key of [
574
+ "codexErrorInfo",
575
+ "providerCode",
576
+ "code",
577
+ "type"
578
+ ]) {
579
+ if (key === "providerCode" && record !== projected) continue;
580
+ collectProviderSignal(state, key, record[key]);
581
+ }
582
+ return state.conflict ? { conflict: true } : state;
583
+ }
584
+ function isNeutralErrorSignal(key, value) {
585
+ if (key === "code" && (value === -32603 || value === -32e3)) return true;
586
+ if (key === "code" && typeof value === "string" && SAFE_CODES.has(value)) return true;
587
+ return key === "type" && value === "error";
588
+ }
589
+ function safeStringField(records, key, allowed) {
590
+ for (const record of records) {
591
+ const value = record[key];
592
+ if (typeof value === "string" && allowed.has(value)) return value;
593
+ }
594
+ }
595
+ function safeOperationId(value) {
596
+ return typeof value === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/u.test(value) ? value : void 0;
597
+ }
598
+ function hasProjectionFields(record) {
599
+ if (typeof record.category !== "string" || !Object.hasOwn(SAFE_MESSAGES, record.category)) return false;
600
+ if (typeof record.origin !== "string" || !SAFE_ORIGINS.has(record.origin)) return false;
601
+ return typeof record.retryable === "boolean" && typeof record.outcomeUnknown === "boolean";
602
+ }
603
+ function projectedRecord(error, options) {
604
+ const record = asRecord$4(error);
605
+ if (!record || !safeProjections.has(record) && options.trustedProjection !== true || !hasProjectionFields(record)) return;
606
+ return record;
607
+ }
608
+ function safeLocalCode(error) {
609
+ if (error instanceof Error && error.name === "AbortError") return "ABORTED";
610
+ if (error instanceof PermissionPromptUnavailableError) return "PERMISSION_PROMPT_UNAVAILABLE";
611
+ if (error instanceof PermissionDeniedError) return "PERMISSION_DENIED";
612
+ if (isTimeoutLike(error)) return "TIMEOUT";
613
+ if (isNoSessionLike(error)) return "NO_SESSION";
614
+ if (isUsageLike(error)) return "USAGE";
615
+ }
616
+ function localSafeCategory(error, code, detailCode) {
617
+ if (error instanceof AuthPolicyError) return "auth";
618
+ if (isTimeoutLike(error)) return "timeout";
619
+ if (error instanceof Error && error.name === "AbortError") return "cancelled";
620
+ return {
621
+ AUTH_REQUIRED: "auth",
622
+ TIMEOUT: "timeout",
623
+ PERMISSION_DENIED: "permission",
624
+ PERMISSION_PROMPT_UNAVAILABLE: "permission",
625
+ ABORTED: "cancelled"
626
+ }[detailCode ?? code ?? ""] ?? "unknown";
627
+ }
628
+ function safeCategory(error, projected, provider, code, detailCode) {
629
+ const local = localSafeCategory(error, code, detailCode);
630
+ if (local !== "unknown") return local;
631
+ if (provider.conflict) return "unknown";
632
+ return provider.category ?? projected?.category ?? "unknown";
633
+ }
634
+ function safeOutcomeUnknown(projected, options, detailCode) {
635
+ return options.outcomeUnknown === true || projected?.outcomeUnknown === true || (/* @__PURE__ */ new Set(["WATCH_OUTCOME_UNKNOWN", "AGENT_DISCONNECTED"])).has(detailCode ?? "");
636
+ }
637
+ function safeOrigin(error, records, options, projected) {
638
+ const local = error instanceof AcpxOperationalError ? error.origin : void 0;
639
+ const preserved = projected?.origin;
640
+ if (preserved) return preserved;
641
+ if (local) return local;
642
+ const fallbackOrigin = options.origin ?? "runtime";
643
+ if (isLocalAbortOrTimeoutError(error)) return fallbackOrigin;
644
+ if (records.some((record) => typeof record.code === "number")) return "acp";
645
+ return fallbackOrigin;
646
+ }
647
+ function localErrorRecord(error, projected) {
648
+ if (!projected && error instanceof AcpRuntimeError) return { code: error.code };
649
+ return projected ?? (error instanceof AcpxOperationalError ? asRecord$4(error) : void 0);
650
+ }
651
+ function safeCode(error, projected) {
652
+ const local = localErrorRecord(error, projected);
653
+ const records = local ? [local] : [];
654
+ return safeStringField(records, "outputCode", SAFE_CODES) ?? safeStringField(records, "code", SAFE_CODES) ?? safeLocalCode(error);
655
+ }
656
+ function safeDetailCode(error, projected) {
657
+ const record = localErrorRecord(error, projected);
658
+ return safeStringField(record ? [record] : [], "detailCode", SAFE_DETAILS);
659
+ }
660
+ function safeOptionalFields(projected, options, provider, code, detailCode) {
661
+ const operationId = safeOperationId(options.operationId) ?? safeOperationId(projected?.operationId);
662
+ return {
663
+ ...provider.providerCode ? { providerCode: provider.providerCode } : {},
664
+ ...operationId ? { operationId } : {},
665
+ ...code ? { code } : {},
666
+ ...detailCode ? { detailCode } : {}
667
+ };
668
+ }
669
+ /**
670
+ * Public bridge projection. No provider text, URLs, arbitrary data or unknown
671
+ * codes are copied. Resource categories describe failures, not retry policy.
672
+ */
673
+ function toSafeError(error, options = {}) {
674
+ const projected = projectedRecord(error, options);
675
+ const records = projected ? [projected] : safeErrorRecords(error);
676
+ const provider = safeProviderCause(records, projected);
677
+ const code = safeCode(error, projected);
678
+ const detailCode = safeDetailCode(error, projected);
679
+ const category = safeCategory(error, projected, provider, code, detailCode);
680
+ const safe = {
681
+ ...safeOptionalFields(projected, options, provider, code, detailCode),
682
+ message: SAFE_MESSAGES[category],
683
+ category,
684
+ retryable: projected?.retryable === true || error instanceof AcpxOperationalError && error.retryable === true,
685
+ outcomeUnknown: safeOutcomeUnknown(projected, options, detailCode),
686
+ origin: safeOrigin(error, records, options, projected)
687
+ };
688
+ safeProjections.add(safe);
689
+ return safe;
690
+ }
691
+ /** Keep projection provenance when the runtime exposes a promise rejection. */
692
+ function safeErrorRejection(error) {
693
+ const safe = toSafeError(error);
694
+ const rejection = Object.assign(new Error(safe.message), safe);
695
+ safeProjections.add(rejection);
696
+ return rejection;
697
+ }
440
698
  //#endregion
441
699
  //#region src/process-liveness.ts
442
700
  function isProcessAlive(pid) {
@@ -458,7 +716,7 @@ function isProcessDefinitelyDead(pid) {
458
716
  }
459
717
  }
460
718
  //#endregion
461
- //#region \0@oxc-project+runtime@0.149.0/helpers/esm/usingCtx.js
719
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/usingCtx.js
462
720
  function _usingCtx() {
463
721
  var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
464
722
  var n = Error();
@@ -550,6 +808,16 @@ async function writePrivateJsonFile(filePath, value) {
550
808
  //#endregion
551
809
  //#region src/session/event-log.ts
552
810
  const DEFAULT_EVENT_SEGMENT_MAX_BYTES = 67108864;
811
+ /** Upper bound stored for a newly imported journal. */
812
+ const MAX_EVENT_SEGMENTS = 1024;
813
+ function retainedEventMaxSegments(value) {
814
+ if (!Number.isFinite(value) || value < 1) return 0;
815
+ return Math.floor(value);
816
+ }
817
+ function boundedEventMaxSegments(value) {
818
+ if (!Number.isFinite(value) || value < 1) return 0;
819
+ return Math.min(Math.floor(value), MAX_EVENT_SEGMENTS);
820
+ }
553
821
  function sessionBaseDir() {
554
822
  return path.join(os.homedir(), ".acpx", "sessions");
555
823
  }
@@ -565,6 +833,42 @@ function sessionEventSegmentPath(sessionId, segment) {
565
833
  function sessionEventLockPath(sessionId) {
566
834
  return path.join(sessionBaseDir(), `${safeSessionId(sessionId)}.stream.lock`);
567
835
  }
836
+ async function existingEventSegmentIndices(sessionId) {
837
+ return (await sessionEventFiles(sessionId)).indices;
838
+ }
839
+ async function sessionEventFiles(sessionId) {
840
+ const activeName = `${safeSessionId(sessionId)}.stream.ndjson`;
841
+ const indices = [];
842
+ let active = false;
843
+ for (const name of await readSessionDirNames()) {
844
+ if (name === activeName) {
845
+ active = true;
846
+ continue;
847
+ }
848
+ const index = eventSegmentIndex(sessionId, name);
849
+ if (index !== void 0) indices.push(index);
850
+ }
851
+ return {
852
+ indices,
853
+ active
854
+ };
855
+ }
856
+ async function readSessionDirNames() {
857
+ try {
858
+ return await fs$1.readdir(sessionBaseDir());
859
+ } catch (error) {
860
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
861
+ throw error;
862
+ }
863
+ }
864
+ function eventSegmentIndex(sessionId, name) {
865
+ const prefix = `${safeSessionId(sessionId)}.stream.`;
866
+ if (!name.startsWith(prefix) || !name.endsWith(".ndjson")) return;
867
+ const middle = name.slice(prefix.length, -7);
868
+ if (!/^[1-9]\d*$/.test(middle)) return;
869
+ const index = Number(middle);
870
+ return Number.isSafeInteger(index) ? index : void 0;
871
+ }
568
872
  function defaultSessionEventLog(sessionId) {
569
873
  return {
570
874
  active_path: sessionEventActivePath(sessionId),
@@ -832,6 +1136,21 @@ async function pathIdentity(filePath) {
832
1136
  throw error;
833
1137
  }
834
1138
  }
1139
+ function boundedJournalPaths(sessionId, saved) {
1140
+ const paths = [];
1141
+ for (let index = saved; index > 0; index -= 1) paths.push(sessionEventSegmentPath(sessionId, index));
1142
+ paths.push(sessionEventActivePath(sessionId));
1143
+ return paths;
1144
+ }
1145
+ function sparseRotationHoles(indices, present, saved) {
1146
+ const holes = [];
1147
+ if (!present.has(1)) holes.push(1);
1148
+ for (const index of indices) {
1149
+ const next = index + 1;
1150
+ if (index < saved && next <= saved && !present.has(next)) holes.push(next);
1151
+ }
1152
+ return holes;
1153
+ }
835
1154
  function emptySegment() {
836
1155
  return {
837
1156
  offset: 0,
@@ -850,19 +1169,34 @@ var SessionJournalReader = class {
850
1169
  constructor(record) {
851
1170
  this.record = record;
852
1171
  }
853
- paths() {
854
- const paths = [];
855
- for (let index = this.record.eventLog.max_segments; index > 0; index -= 1) paths.push(sessionEventSegmentPath(this.record.acpxRecordId, index));
856
- paths.push(sessionEventActivePath(this.record.acpxRecordId));
857
- return paths;
1172
+ async discoverPaths() {
1173
+ const saved = retainedEventMaxSegments(this.record.eventLog.max_segments);
1174
+ if (saved > 1024) return await this.discoverSparsePaths(saved);
1175
+ return { paths: boundedJournalPaths(this.record.acpxRecordId, saved) };
1176
+ }
1177
+ async discoverSparsePaths(saved) {
1178
+ const id = this.record.acpxRecordId;
1179
+ const files = await sessionEventFiles(id);
1180
+ const indices = files.indices.filter((index) => index <= saved);
1181
+ const holeIndices = sparseRotationHoles(indices, new Set(indices), saved);
1182
+ const paths = [.../* @__PURE__ */ new Set([...indices, ...holeIndices])].toSorted((left, right) => right - left).map((index) => sessionEventSegmentPath(id, index));
1183
+ const active = sessionEventActivePath(id);
1184
+ paths.push(active);
1185
+ const holes = new Set(holeIndices.map((index) => sessionEventSegmentPath(id, index)));
1186
+ if (!files.active) holes.add(active);
1187
+ return {
1188
+ paths,
1189
+ holes
1190
+ };
858
1191
  }
859
1192
  async openSnapshot(signal) {
860
1193
  for (;;) {
861
1194
  signal?.throwIfAborted();
862
1195
  const segments = [];
863
1196
  try {
864
- const paths = await this.openPresentSegments(segments);
865
- if (await this.matchesSnapshot(paths, segments)) return segments;
1197
+ const scan = await this.discoverPaths();
1198
+ const paths = await this.openPresentSegments(segments, scan.paths);
1199
+ if (await this.matchesSnapshot(paths, segments, scan.holes)) return segments;
866
1200
  } catch (error) {
867
1201
  if (!retryableSnapshotError(error)) {
868
1202
  await this.closeSnapshot(segments);
@@ -873,16 +1207,12 @@ var SessionJournalReader = class {
873
1207
  await setTimeout$1(5, void 0, { signal });
874
1208
  }
875
1209
  }
876
- async openPresentSegments(segments) {
877
- const paths = this.paths();
1210
+ async openPresentSegments(segments, paths) {
878
1211
  const present = await Promise.all(paths.map((filePath) => statRegularFile(filePath)));
879
1212
  if (present.every((entry) => entry.missing)) return paths;
880
1213
  const directory = await root(path.dirname(paths[0]));
881
1214
  const results = await Promise.allSettled(paths.filter((_, index) => !present[index].missing).map(async (filePath) => {
882
- const opened = await directory.open(path.basename(filePath), {
883
- symlinks: "reject",
884
- nonBlockingRead: true
885
- });
1215
+ const opened = await directory.open(path.basename(filePath), { symlinks: "reject" });
886
1216
  try {
887
1217
  return {
888
1218
  filePath,
@@ -903,10 +1233,14 @@ var SessionJournalReader = class {
903
1233
  async closeSnapshot(segments) {
904
1234
  await Promise.all(segments.map(({ opened }) => opened[Symbol.asyncDispose]()));
905
1235
  }
906
- async matchesSnapshot(paths, segments) {
1236
+ async matchesSnapshot(paths, segments, holes) {
907
1237
  const current = await Promise.all(paths.map(pathIdentity));
908
1238
  const identities = new Map(segments.map((entry) => [entry.filePath, entry.identity]));
909
- return paths.every((filePath, index) => current[index] === identities.get(filePath));
1239
+ return paths.every((filePath, index) => {
1240
+ const expected = identities.get(filePath);
1241
+ if (current[index] !== expected) return false;
1242
+ return holes === void 0 || expected !== void 0 || holes.has(filePath);
1243
+ });
910
1244
  }
911
1245
  async withSnapshot(read, signal) {
912
1246
  for (;;) {
@@ -916,7 +1250,8 @@ var SessionJournalReader = class {
916
1250
  if (!(error instanceof SessionWatchError) || error.code !== "WATCH_JOURNAL_CORRUPT") throw error;
917
1251
  return { error };
918
1252
  });
919
- if (await this.matchesSnapshot(this.paths(), segments)) {
1253
+ const scan = await this.discoverPaths();
1254
+ if (await this.matchesSnapshot(scan.paths, segments, scan.holes)) {
920
1255
  signal?.throwIfAborted();
921
1256
  if ("error" in outcome) throw outcome.error;
922
1257
  return outcome.value;
@@ -1598,6 +1933,7 @@ function parseAcpxState(raw) {
1598
1933
  const record = asRecord$2(raw);
1599
1934
  if (!record) return;
1600
1935
  const state = {};
1936
+ if (record.session_origin === "new" || record.session_origin === "resume") state.session_origin = record.session_origin;
1601
1937
  if (record.reset_on_next_ensure === true) state.reset_on_next_ensure = true;
1602
1938
  assignStringState(state, "current_mode_id", record.current_mode_id);
1603
1939
  assignStringState(state, "desired_mode_id", record.desired_mode_id);
@@ -5331,6 +5667,6 @@ async function trySetConfigOptionOnRunningOwner(sessionId, configId, value, time
5331
5667
  });
5332
5668
  }
5333
5669
  //#endregion
5334
- export { resetPerfMetrics as $, findSession as A, PERMISSION_MODES as At, assertPersistedKeyPolicy as B, GeminiAcpStartupTimeoutError as Bt, textPrompt as C, normalizeOutputError as Ct, DEFAULT_HISTORY_LIMIT as D, EXIT_CODES as Dt, observeProcessIncarnation as E, AUTH_POLICIES as Et, normalizeName as F, AgentSpawnError as Ft, SESSION_JOURNAL_SCHEMA as G, SessionModeReplayError as Gt, serializeSessionRecordForDisk as H, PermissionPromptUnavailableError as Ht, pruneSessions as I, AgentStartupError as It, watchSession as J, SessionResumeRequiredError as Jt, SessionJournalReader as K, SessionModelReplayError as Kt, readSessionRecord as L, AuthPolicyError as Lt, isoNow as M, SESSION_RECORD_SCHEMA as Mt, listSessions as N, AcpxOperationalError as Nt, absolutePath as O, NON_INTERACTIVE_PERMISSION_POLICIES as Ot, listSessionsForAgent as P, AgentDisconnectedError as Pt, measurePerf as Q, resolveSessionRecord as R, ClaudeAcpSessionCreateTimeoutError as Rt, promptToDisplayText as S, isRetryablePromptError as St, lockOwnerPid as T, isAcpResourceNotFoundError as Tt, extractAgentSessionId as U, QueueConnectionError as Ut, parseSessionRecord as V, PermissionDeniedError as Vt, normalizeAgentSessionId as W, SessionConfigOptionReplayError as Wt, getPerfMetricsSnapshot as X, formatPerfMetric as Y, UnsupportedPromptContentError as Yt, incrementPerfCounter as Z, ProcessDescendants as _, _usingCtx as _t, trySetModelOnRunningOwner as a, isSessionUpdateNotification as at, mergePromptSourceWithText as b, formatErrorMessage as bt, probeQueueOwnerHealth as c, parsePromptStopReason as ct, releaseQueueOwnerLease as d, sessionBaseDir as dt, setPerfGauge as et, terminateProcess as f, sessionEventActivePath as ft, QueueLeaseGuardSettlementError as g, writePrivateJsonFile as gt, waitMs as h, writePrivateFile as ht, trySetModeOnRunningOwner as i, isAcpMessageObject as it, findSessionByDirectoryWalk as j, PERMISSION_POLICY_ACTIONS as jt, findGitRepositoryRoot as k, OUTPUT_FORMATS as kt, readQueueOwnerRecord as l, DEFAULT_EVENT_SEGMENT_MAX_BYTES as lt, tryAcquireQueueOwnerLease as m, sessionEventSegmentPath as mt, tryCloseSessionOnRunningOwner as n, extractSessionUpdateNotification as nt, trySubmitToRunningOwner as o, parseJsonRpcErrorMessage as ot, terminateQueueOwnerForSession as p, sessionEventLockPath as pt, SessionWatchError as q, SessionNotFoundError as qt, trySetConfigOptionOnRunningOwner as r, isAcpJsonRpcMessage as rt, SessionQueueOwner as s, parsePermissionNotice as st, tryCancelOnRunningOwner as t, startPerfTimer as tt, refreshQueueOwnerLease as u, defaultSessionEventLog as ut, PromptInputValidationError as v, isProcessAlive as vt, createLockOwner as w, extractAcpError as wt, parsePromptSource as x, isAcpQueryClosedBeforeResponseError as xt, getUnsupportedPromptContentMessage as y, exitCodeForOutputErrorCode as yt, writeSessionRecord as z, CopilotAcpUnsupportedError as zt };
5670
+ export { measurePerf as $, SessionModeReplayError as $t, findSession as A, extractAcpError as At, assertPersistedKeyPolicy as B, isAcpRuntimeError as Bt, textPrompt as C, exitCodeForOutputErrorCode as Ct, DEFAULT_HISTORY_LIMIT as D, normalizeOutputError as Dt, observeProcessIncarnation as E, isRetryablePromptError as Et, normalizeName as F, OUTPUT_FORMATS as Ft, normalizeAgentSessionId as G, AuthPolicyError as Gt, canonicalAgentCommand as H, AgentDisconnectedError as Ht, pruneSessions as I, PERMISSION_MODES as It, SessionWatchError as J, GeminiAcpStartupTimeoutError as Jt, SESSION_JOURNAL_SCHEMA as K, ClaudeAcpSessionCreateTimeoutError as Kt, readSessionRecord as L, PERMISSION_POLICY_ACTIONS as Lt, isoNow as M, AUTH_POLICIES as Mt, listSessions as N, EXIT_CODES as Nt, absolutePath as O, safeErrorRejection as Ot, listSessionsForAgent as P, NON_INTERACTIVE_PERMISSION_POLICIES as Pt, incrementPerfCounter as Q, SessionConfigOptionReplayError as Qt, resolveSessionRecord as R, SESSION_RECORD_SCHEMA as Rt, promptToDisplayText as S, isProcessAlive as St, lockOwnerPid as T, isAcpQueryClosedBeforeResponseError as Tt, serializeSessionRecordForDisk as U, AgentSpawnError as Ut, parseSessionRecord as V, AcpxOperationalError as Vt, extractAgentSessionId as W, AgentStartupError as Wt, formatPerfMetric as X, PermissionPromptUnavailableError as Xt, watchSession as Y, PermissionDeniedError as Yt, getPerfMetricsSnapshot as Z, QueueConnectionError as Zt, ProcessDescendants as _, sessionEventLockPath as _t, trySetModelOnRunningOwner as a, isAcpMessageObject as at, mergePromptSourceWithText as b, writePrivateJsonFile as bt, probeQueueOwnerHealth as c, parsePermissionNotice as ct, releaseQueueOwnerLease as d, boundedEventMaxSegments as dt, SessionModelReplayError as en, resetPerfMetrics as et, terminateProcess as f, defaultSessionEventLog as ft, QueueLeaseGuardSettlementError as g, sessionEventActivePath as gt, waitMs as h, sessionBaseDir as ht, trySetModeOnRunningOwner as i, isAcpJsonRpcMessage as it, findSessionByDirectoryWalk as j, isAcpResourceNotFoundError as jt, findGitRepositoryRoot as k, toSafeError as kt, readQueueOwnerRecord as l, parsePromptStopReason as lt, tryAcquireQueueOwnerLease as m, retainedEventMaxSegments as mt, tryCloseSessionOnRunningOwner as n, SessionResumeRequiredError as nn, startPerfTimer as nt, trySubmitToRunningOwner as o, isSessionUpdateNotification as ot, terminateQueueOwnerForSession as p, existingEventSegmentIndices as pt, SessionJournalReader as q, CopilotAcpUnsupportedError as qt, trySetConfigOptionOnRunningOwner as r, UnsupportedPromptContentError as rn, extractSessionUpdateNotification as rt, SessionQueueOwner as s, parseJsonRpcErrorMessage as st, tryCancelOnRunningOwner as t, SessionNotFoundError as tn, setPerfGauge as tt, refreshQueueOwnerLease as u, DEFAULT_EVENT_SEGMENT_MAX_BYTES as ut, PromptInputValidationError as v, sessionEventSegmentPath as vt, createLockOwner as w, formatErrorMessage as wt, parsePromptSource as x, _usingCtx as xt, getUnsupportedPromptContentMessage as y, writePrivateFile as yt, writeSessionRecord as z, AcpRuntimeError as zt };
5335
5671
 
5336
- //# sourceMappingURL=ipc-BlljKR2b.js.map
5672
+ //# sourceMappingURL=ipc-BQQpcEdP.js.map