@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
@@ -5,7 +5,7 @@ import * as path from "node:path";
5
5
  import { WebSocketServer } from "ws";
6
6
  import { attachAcpConnection } from "./acp-connection.js";
7
7
  import { createServiceAgentRegistry } from "./catalog.js";
8
- import { createAcpRuntime, createRuntimeStore, createTurnJournal, } from "@1agents/acp-service/runtime";
8
+ import { createAcpRuntime, createRuntimeStore, createTurnJournal, toSafeError, } from "@1agents/acp-service/runtime";
9
9
  import { historyToolInput, resolveRuntimeTurnId, stampHistoryTurnIds, } from "./history-turn-ids.js";
10
10
  // ----------------------------------------------------
11
11
  // Configurations
@@ -930,6 +930,7 @@ function sendSummaryTerminal(ws, session, sessionId, payload) {
930
930
  sessionReaderPort: 7777,
931
931
  };
932
932
  const resultText = payload.resultText || "";
933
+ const error = payload.error ? toSafeError(payload.error, { origin: "service" }) : undefined;
933
934
  ws.send(JSON.stringify({
934
935
  event: "turn_complete",
935
936
  sessionId,
@@ -939,7 +940,7 @@ function sendSummaryTerminal(ws, session, sessionId, payload) {
939
940
  finalAnswer: resultText,
940
941
  sessionRef,
941
942
  completedAt: new Date().toISOString(),
942
- ...(payload.error ? { error: payload.error } : {}),
943
+ ...(error ? { error } : {}),
943
944
  }));
944
945
  ws.send(JSON.stringify({
945
946
  event: "done",
@@ -954,6 +955,7 @@ function sendSummaryTerminal(ws, session, sessionId, payload) {
954
955
  ? "Execution failed."
955
956
  : "Execution completed successfully."),
956
957
  ...(payload.stopped ? { stopped: true } : {}),
958
+ ...(error ? { error } : {}),
957
959
  }));
958
960
  }
959
961
  function sendTurnState(ws, sessionId, turn, queuePosition, acceptedNew = false) {
@@ -2160,7 +2162,21 @@ export async function dispatchCommand(ws, payload) {
2160
2162
  }
2161
2163
  }
2162
2164
  catch (err) {
2163
- console.error(`[acpx-server] Action execution failed:`, err);
2165
+ if (action === "prompt") {
2166
+ const error = toSafeError(err, { origin: "service", operationId: payload.requestId });
2167
+ console.error("[acpx-server] Prompt dispatch failed:", error);
2168
+ const session = activeSessions.get(sessionId);
2169
+ if (resolveResponsePolicy(payload.responsePolicy, session?.responsePolicy) === "summary") {
2170
+ sendSummaryTerminal(ws, session, sessionId, {
2171
+ status: "failed", resultText: "", turnId: payload.turnId || payload.requestId, error,
2172
+ });
2173
+ }
2174
+ else {
2175
+ ws.send(JSON.stringify({ event: "error", sessionId, scope: "turn", ...error }));
2176
+ }
2177
+ return;
2178
+ }
2179
+ console.error(`[acpx-server] Action execution failed:`, toSafeError(err, { origin: "service", operationId: payload.requestId }));
2164
2180
  // An AgentStartupError with exit 127 / "command not found" means the
2165
2181
  // agent's ACP adapter binary could not be launched — almost always
2166
2182
  // because the adapter package isn't installed for 1acp (the bare
@@ -2545,12 +2561,12 @@ async function runPromptTurn(session, sessionId, promptItem) {
2545
2561
  }
2546
2562
  }
2547
2563
  else if (event.type === "error") {
2564
+ const error = toSafeError(event, { origin: "service", operationId: requestId, trustedProjection: true });
2548
2565
  sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2549
2566
  event: "error",
2550
2567
  scope: "turn",
2551
2568
  terminal: false,
2552
- code: event.code,
2553
- message: event.message,
2569
+ ...error,
2554
2570
  });
2555
2571
  }
2556
2572
  else if (event.type === "status" &&
@@ -2607,6 +2623,9 @@ async function runPromptTurn(session, sessionId, promptItem) {
2607
2623
  // Otherwise select only final-answer phases, while retaining every message
2608
2624
  // in the execution log. Unphased agents keep their legacy stream fallback.
2609
2625
  const finalResultText = result.finalAnswer ?? (hasMessagePhase ? finalAnswer : accumulatedAnswer);
2626
+ const error = result.status === "failed"
2627
+ ? toSafeError(result.error, { origin: "service", operationId: requestId, trustedProjection: true })
2628
+ : undefined;
2610
2629
  const journalTerminal = turn.hostTurnId
2611
2630
  ? await turnJournal.record({
2612
2631
  sessionId,
@@ -2616,8 +2635,8 @@ async function runPromptTurn(session, sessionId, promptItem) {
2616
2635
  promptText: promptItem.text,
2617
2636
  agentType: currentSession?.agentType || session.agentType,
2618
2637
  finalAnswer: finalResultText,
2619
- errorCode: result.status === "failed" ? result.error?.code || "ACP_PROMPT_FAILED" : undefined,
2620
- errorText: result.status === "failed" ? result.error?.message : undefined,
2638
+ errorCode: error?.providerCode || error?.code,
2639
+ errorText: error?.message,
2621
2640
  runtimeRecordId: currentSession?.handle?.acpxRecordId || session.handle?.acpxRecordId || sessionId,
2622
2641
  runtimeRequestId: result.runtimeRequestId || requestId,
2623
2642
  promptMessageId: result.promptMessageId || requestId,
@@ -2630,12 +2649,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2630
2649
  status: result.status,
2631
2650
  resultText: finalResultText,
2632
2651
  turnId: turn.hostTurnId || result.agentTurnId || result.runtimeRequestId || requestId,
2633
- error: result.status === "failed"
2634
- ? {
2635
- code: result.error?.code || "ACP_PROMPT_FAILED",
2636
- message: result.error?.message || "Turn execution failed",
2637
- }
2638
- : undefined,
2652
+ error,
2639
2653
  stopped: result.status === "cancelled",
2640
2654
  });
2641
2655
  if (targetWs && targetWs.readyState === 1 /* OPEN */) {
@@ -2655,14 +2669,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2655
2669
  runtimeRequestId: result.runtimeRequestId || requestId,
2656
2670
  promptMessageId: result.promptMessageId || requestId,
2657
2671
  completedAt: new Date().toISOString(),
2658
- ...(result.status === "failed"
2659
- ? {
2660
- error: {
2661
- code: result.error?.code || "ACP_PROMPT_FAILED",
2662
- message: result.error?.message || "Turn execution failed",
2663
- },
2664
- }
2665
- : {}),
2672
+ ...(error ? { error } : {}),
2666
2673
  });
2667
2674
  terminalSent = true;
2668
2675
  void sendSessionMeta(targetWs, sessionId, currentSession.handle);
@@ -2672,7 +2679,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2672
2679
  event: "error",
2673
2680
  scope: "turn",
2674
2681
  sessionId,
2675
- message: result.error?.message || "Turn execution failed",
2682
+ ...error,
2676
2683
  }));
2677
2684
  }
2678
2685
  else {
@@ -2708,7 +2715,8 @@ async function runPromptTurn(session, sessionId, promptItem) {
2708
2715
  }
2709
2716
  }
2710
2717
  catch (err) {
2711
- console.error(`[acpx-server] Error executing turn:`, err);
2718
+ const error = toSafeError(err, { origin: "service", operationId: requestId });
2719
+ console.error(`[acpx-server] Error executing turn:`, error);
2712
2720
  const currentSession = activeSessions.get(sessionId);
2713
2721
  const targetWs = currentSession ? currentSession.ws : null;
2714
2722
  if (turn.hostTurnId && !terminalSent) {
@@ -2720,8 +2728,8 @@ async function runPromptTurn(session, sessionId, promptItem) {
2720
2728
  status: "failed",
2721
2729
  promptText: promptItem.text,
2722
2730
  agentType: currentSession?.agentType,
2723
- errorCode: "ACP_PROMPT_FAILED",
2724
- errorText: err?.message || String(err),
2731
+ errorCode: error.providerCode || error.code,
2732
+ errorText: error.message,
2725
2733
  runtimeRecordId: currentSession?.handle?.acpxRecordId || sessionId,
2726
2734
  runtimeRequestId: requestId,
2727
2735
  promptMessageId: requestId,
@@ -2733,10 +2741,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2733
2741
  status: "failed",
2734
2742
  resultText: accumulatedAnswer,
2735
2743
  turnId: turn.hostTurnId,
2736
- error: {
2737
- code: "ACP_PROMPT_FAILED",
2738
- message: err?.message || String(err),
2739
- },
2744
+ error,
2740
2745
  });
2741
2746
  }
2742
2747
  else {
@@ -2749,16 +2754,13 @@ async function runPromptTurn(session, sessionId, promptItem) {
2749
2754
  runtimeRequestId: requestId,
2750
2755
  promptMessageId: requestId,
2751
2756
  completedAt: new Date().toISOString(),
2752
- error: {
2753
- code: "ACP_PROMPT_FAILED",
2754
- message: err?.message || String(err),
2755
- },
2757
+ error,
2756
2758
  });
2757
2759
  }
2758
2760
  terminalSent = true;
2759
2761
  }
2760
2762
  catch (journalError) {
2761
- sendError(targetWs, sessionId, "TURN_JOURNAL_FAILED", journalError?.message || String(journalError));
2763
+ sendError(targetWs, sessionId, "TURN_JOURNAL_FAILED", toSafeError(journalError, { origin: "service", operationId: requestId }).message);
2762
2764
  }
2763
2765
  }
2764
2766
  else if (isSummaryMode) {
@@ -2766,10 +2768,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2766
2768
  status: "failed",
2767
2769
  resultText: accumulatedAnswer,
2768
2770
  turnId: turn.hostTurnId || requestId,
2769
- error: {
2770
- code: "ACP_PROMPT_FAILED",
2771
- message: err?.message || String(err),
2772
- },
2771
+ error,
2773
2772
  });
2774
2773
  }
2775
2774
  else if (targetWs && targetWs.readyState === 1 /* OPEN */) {
@@ -2777,7 +2776,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2777
2776
  event: "error",
2778
2777
  scope: "turn",
2779
2778
  sessionId,
2780
- message: err.message,
2779
+ ...error,
2781
2780
  }));
2782
2781
  }
2783
2782
  }
@@ -0,0 +1,108 @@
1
+ import type { PptDeliveryArtifact, PptDeliveryRun } from './ppt-delivery.js';
2
+ export declare const deliveryStageNames: {
3
+ readonly summary: "项目总结与脚本";
4
+ readonly make: "PPT制作";
5
+ readonly validate: "机器校验";
6
+ readonly review: "独立验收";
7
+ };
8
+ /** Persisted facts projected for readers; producing a projection never schedules work or a notification. */
9
+ export declare function deliveryProgress(run: PptDeliveryRun): {
10
+ stage: "summary" | "make" | "validate" | "review" | "finished";
11
+ phase: string;
12
+ revision: string;
13
+ executionStatus: "failed" | "completed" | "canceled" | "working" | "input_required";
14
+ stages: ({
15
+ jobId?: string | undefined;
16
+ attemptId?: string | undefined;
17
+ sessionId?: string | undefined;
18
+ stage: string;
19
+ name: "项目总结与脚本";
20
+ status: string;
21
+ } | {
22
+ jobId?: string | undefined;
23
+ attemptId?: string | undefined;
24
+ sessionId?: string | undefined;
25
+ stage: string;
26
+ name: "PPT制作";
27
+ status: string;
28
+ } | {
29
+ jobId?: string | undefined;
30
+ attemptId?: string | undefined;
31
+ sessionId?: string | undefined;
32
+ stage: string;
33
+ name: "机器校验";
34
+ status: string;
35
+ } | {
36
+ jobId?: string | undefined;
37
+ attemptId?: string | undefined;
38
+ sessionId?: string | undefined;
39
+ stage: string;
40
+ name: "独立验收";
41
+ status: string;
42
+ })[];
43
+ completedStages: ("项目总结与脚本" | "PPT制作" | "机器校验" | "独立验收")[];
44
+ remainingStages: ("项目总结与脚本" | "PPT制作" | "机器校验" | "独立验收")[];
45
+ availableResults: {
46
+ revision: string;
47
+ artifactDigest: string;
48
+ artifacts: PptDeliveryArtifact[];
49
+ validation: "machine_passed" | "producer_host_verified";
50
+ independentReview: string;
51
+ deliveryReady: boolean;
52
+ }[];
53
+ cancellationRequestedAt: string | undefined;
54
+ updatedAt: string;
55
+ stageCompletionWakeups: false;
56
+ };
57
+ export declare function deliveryException(run: PptDeliveryRun, reason: string): {
58
+ progress: {
59
+ stage: "summary" | "make" | "validate" | "review" | "finished";
60
+ phase: string;
61
+ revision: string;
62
+ executionStatus: "failed" | "completed" | "canceled" | "working" | "input_required";
63
+ stages: ({
64
+ jobId?: string | undefined;
65
+ attemptId?: string | undefined;
66
+ sessionId?: string | undefined;
67
+ stage: string;
68
+ name: "项目总结与脚本";
69
+ status: string;
70
+ } | {
71
+ jobId?: string | undefined;
72
+ attemptId?: string | undefined;
73
+ sessionId?: string | undefined;
74
+ stage: string;
75
+ name: "PPT制作";
76
+ status: string;
77
+ } | {
78
+ jobId?: string | undefined;
79
+ attemptId?: string | undefined;
80
+ sessionId?: string | undefined;
81
+ stage: string;
82
+ name: "机器校验";
83
+ status: string;
84
+ } | {
85
+ jobId?: string | undefined;
86
+ attemptId?: string | undefined;
87
+ sessionId?: string | undefined;
88
+ stage: string;
89
+ name: "独立验收";
90
+ status: string;
91
+ })[];
92
+ completedStages: ("项目总结与脚本" | "PPT制作" | "机器校验" | "独立验收")[];
93
+ remainingStages: ("项目总结与脚本" | "PPT制作" | "机器校验" | "独立验收")[];
94
+ availableResults: {
95
+ revision: string;
96
+ artifactDigest: string;
97
+ artifacts: PptDeliveryArtifact[];
98
+ validation: "machine_passed" | "producer_host_verified";
99
+ independentReview: string;
100
+ deliveryReady: boolean;
101
+ }[];
102
+ cancellationRequestedAt: string | undefined;
103
+ updatedAt: string;
104
+ stageCompletionWakeups: false;
105
+ };
106
+ summary: string;
107
+ artifacts: PptDeliveryArtifact[];
108
+ };
@@ -0,0 +1,57 @@
1
+ export const deliveryStageNames = {
2
+ summary: '项目总结与脚本', make: 'PPT制作', validate: '机器校验', review: '独立验收',
3
+ };
4
+ /** Persisted facts projected for readers; producing a projection never schedules work or a notification. */
5
+ export function deliveryProgress(run) {
6
+ const latest = (purpose) => [...run.children].reverse().find(item => item.purpose === purpose);
7
+ const summary = latest('project_script'), maker = latest('ppt_production'), reviewer = latest('independent_review');
8
+ const status = (child) => child?.child.executionStatus ?? 'not_started';
9
+ const stages = [
10
+ { stage: 'summary', name: deliveryStageNames.summary, status: status(summary) === 'completed' && !run.scriptDigest ? 'awaiting_validation' : status(summary), child: summary?.child },
11
+ { stage: 'make', name: deliveryStageNames.make, status: status(maker), child: maker?.child },
12
+ { stage: 'validate', name: deliveryStageNames.validate, status: run.validation ? 'completed' : run.stage === 'validate' ? run.executionStatus : 'not_started', child: undefined },
13
+ { stage: 'review', name: deliveryStageNames.review, status: run.review?.verdict === 'passed' ? 'completed'
14
+ : run.review?.verdict === 'changes_requested' ? 'changes_requested' : status(reviewer) === 'completed' ? 'awaiting_validation' : status(reviewer), child: reviewer?.child },
15
+ ].map(({ child, ...stage }) => ({ ...stage, ...(child ? { jobId: child.jobId, attemptId: child.attemptId, sessionId: child.sessionId } : {}) }));
16
+ const versions = new Map();
17
+ for (const entry of run.artifactHistory ?? [])
18
+ versions.set(`${entry.revision}:${entry.validation.artifactDigest}`, entry);
19
+ if (run.validation)
20
+ versions.set(`${run.revision}:${run.validation.artifactDigest}`, { revision: run.revision, validation: run.validation });
21
+ const availableResults = [...versions.values()].map(({ revision, validation }) => ({
22
+ revision: `revision-${revision}`, artifactDigest: validation.artifactDigest, artifacts: validation.artifacts,
23
+ validation: 'machine_passed',
24
+ independentReview: revision === run.revision && run.review?.artifactDigest === validation.artifactDigest ? run.review.verdict : 'not_completed',
25
+ deliveryReady: run.executionStatus === 'completed' && revision === run.revision && run.review?.verdict === 'passed'
26
+ && run.review.artifactDigest === validation.artifactDigest,
27
+ }));
28
+ // A completed producer's host-authored receipt can expose a draft before the parent's machine check.
29
+ const metadata = maker?.child.resultMetadata;
30
+ if (maker && metadata?.producer === '1agents/a2a-host' && metadata.outcome === 'completed' && metadata.validation?.status === 'passed'
31
+ && metadata.taskId === maker.child.backendRunRef?.taskId && !availableResults.some(item => item.revision === `revision-${maker.revision}`)) {
32
+ const artifacts = (Array.isArray(metadata.artifacts) ? metadata.artifacts : []).filter(a => {
33
+ try {
34
+ const url = new URL(a.url ?? '');
35
+ return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password
36
+ && typeof a.mediaType === 'string' && typeof a.path === 'string' && Number.isSafeInteger(a.size) && a.size > 0 && /^[a-f0-9]{64}$/.test(a.sha256);
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ });
42
+ if (artifacts.length)
43
+ availableResults.push({ revision: `revision-${maker.revision}`, artifactDigest: '', artifacts,
44
+ validation: 'producer_host_verified', independentReview: 'not_completed', deliveryReady: false });
45
+ }
46
+ return { stage: run.stage, phase: run.phase, revision: `revision-${run.revision}`, executionStatus: run.executionStatus,
47
+ stages, completedStages: stages.filter(stage => stage.status === 'completed').map(stage => stage.name),
48
+ remainingStages: stages.filter(stage => stage.status !== 'completed').map(stage => stage.name),
49
+ availableResults, cancellationRequestedAt: run.cancellationRequestedAt, updatedAt: run.updatedAt,
50
+ stageCompletionWakeups: false };
51
+ }
52
+ export function deliveryException(run, reason) {
53
+ const progress = deliveryProgress(run), candidate = progress.availableResults.at(-1);
54
+ const summary = `${reason}\n\n已完成:${progress.completedStages.join('、') || '暂无'}。\n未完成:${progress.remainingStages.join('、') || '无'}。`
55
+ + (candidate ? `\n已有产物:${candidate.revision};${candidate.validation === 'machine_passed' ? '机器校验通过' : '仅制作端文件校验通过'},独立验收状态:${candidate.independentReview}。以下为已有制作稿,尚非最终交付。` : '');
56
+ return { progress, summary, artifacts: candidate?.artifacts ?? [] };
57
+ }
@@ -0,0 +1,235 @@
1
+ export type ExecutionStatus = 'not_started' | 'submitted' | 'working' | 'input_required' | 'auth_required' | 'completed' | 'failed' | 'canceled' | 'rejected' | 'unknown';
2
+ export type SubmissionStatus = 'prepared' | 'dispatching' | 'accepted' | 'known_not_submitted' | 'submission_unknown';
3
+ export interface JobRef {
4
+ sourceId: string;
5
+ jobId: string;
6
+ }
7
+ export interface LedgerTargetSnapshot {
8
+ targetId: string;
9
+ configVersion?: number;
10
+ targetConfigVersion?: number;
11
+ connectionId?: string;
12
+ connectionVersion?: number;
13
+ provider?: string;
14
+ roleId?: string;
15
+ [key: string]: unknown;
16
+ }
17
+ export interface BackendRunRef {
18
+ provider?: string;
19
+ remote?: string;
20
+ taskId?: string;
21
+ contextId?: string;
22
+ sessionId?: string;
23
+ flowRunId?: string;
24
+ [key: string]: unknown;
25
+ }
26
+ export interface LedgerResult {
27
+ attemptId: string;
28
+ resultSummary?: string;
29
+ structuredResultRef?: unknown;
30
+ resultDigest?: string;
31
+ resultRevision?: string;
32
+ artifactLinks: unknown[];
33
+ resultAvailable: boolean;
34
+ observedAt: string;
35
+ }
36
+ export interface BusinessAcceptance {
37
+ attemptId: string;
38
+ resultRevision: string;
39
+ resultDigest: string;
40
+ reviewStatus: 'pending' | 'accepted' | 'changes_requested';
41
+ note?: string;
42
+ recordedAt: string;
43
+ }
44
+ export interface LedgerAttempt {
45
+ attemptId: string;
46
+ jobId: string;
47
+ operation: string;
48
+ clientRequestId?: string;
49
+ requestDigest: string;
50
+ targetId: string;
51
+ targetConfigVersion?: number;
52
+ connectionId?: string;
53
+ connectionVersion?: number;
54
+ provider: string;
55
+ targetSnapshot: LedgerTargetSnapshot;
56
+ input: unknown;
57
+ previousAttemptId?: string;
58
+ backendRunRef?: BackendRunRef;
59
+ submissionStatus: SubmissionStatus;
60
+ executionStatus: ExecutionStatus;
61
+ providerState?: string;
62
+ phase?: string;
63
+ cancellationRequestedAt?: string;
64
+ checkedAt?: string;
65
+ stale: boolean;
66
+ createdAt: string | null;
67
+ updatedAt: string;
68
+ diagnostic?: string;
69
+ result?: LedgerResult;
70
+ }
71
+ export interface LedgerJob {
72
+ sourceId: string;
73
+ jobId: string;
74
+ title?: string;
75
+ originSessionId: string;
76
+ accessScopeRef: string;
77
+ originKind: 'session' | 'legacy';
78
+ originRef: string;
79
+ targetId: string;
80
+ roleId?: string;
81
+ currentAttemptId: string;
82
+ executionStatus: ExecutionStatus;
83
+ inFlightAttemptIds: string[];
84
+ unresolvedAttemptIds: string[];
85
+ parentJobRef?: JobRef;
86
+ parentAttemptId?: string;
87
+ purpose?: string;
88
+ resultRevision?: string;
89
+ replacesJobRef?: JobRef;
90
+ jobVersion: number;
91
+ createdAt: string | null;
92
+ updatedAt: string;
93
+ provenance: 'native' | 'legacy';
94
+ migratedAt?: string;
95
+ }
96
+ export interface LedgerEvent {
97
+ eventId: string;
98
+ sourceId: string;
99
+ sequence: number;
100
+ jobId: string;
101
+ attemptId?: string;
102
+ jobVersion: number;
103
+ type: string;
104
+ observedAt: string;
105
+ data?: unknown;
106
+ }
107
+ interface RequestRecord {
108
+ digest: string;
109
+ jobId: string;
110
+ attemptId: string;
111
+ }
112
+ export interface LedgerState {
113
+ version: 1;
114
+ sourceId: string;
115
+ jobs: Record<string, LedgerJob>;
116
+ attempts: Record<string, LedgerAttempt>;
117
+ requests: Record<string, RequestRecord>;
118
+ events: LedgerEvent[];
119
+ nextSequence: number;
120
+ acceptances: Record<string, BusinessAcceptance[]>;
121
+ }
122
+ export interface LedgerPrepareInput {
123
+ originSessionId: string;
124
+ targetSnapshot: LedgerTargetSnapshot;
125
+ input: unknown;
126
+ clientRequestId?: string;
127
+ /** Trusted adapter only: hash the caller request before adding current-attempt defaults. */
128
+ requestDigestInput?: unknown;
129
+ jobId?: string;
130
+ parentJobRef?: JobRef;
131
+ parentAttemptId?: string;
132
+ purpose?: string;
133
+ title?: string;
134
+ operation?: string;
135
+ resultRevision?: string;
136
+ replacesJobRef?: JobRef;
137
+ }
138
+ export interface LedgerObservation {
139
+ executionStatus?: ExecutionStatus;
140
+ providerState?: string;
141
+ phase?: string;
142
+ checkedAt?: string;
143
+ stale?: boolean;
144
+ resultSummary?: string;
145
+ structuredResultRef?: unknown;
146
+ resultDigest?: string;
147
+ resultRevision?: string;
148
+ artifactLinks?: unknown[];
149
+ resultAvailable?: boolean;
150
+ diagnostic?: string;
151
+ }
152
+ export interface LegacyLedgerRecord {
153
+ originSessionId: string;
154
+ remote: string;
155
+ taskId: string;
156
+ contextId?: string;
157
+ sessionId?: string;
158
+ cwd?: string;
159
+ agentPreset?: string;
160
+ title?: string;
161
+ executionStatus?: ExecutionStatus;
162
+ providerState?: string;
163
+ resultSummary?: string;
164
+ artifactLinks?: unknown[];
165
+ createdAt?: string | null;
166
+ checkedAt?: string;
167
+ stale?: boolean;
168
+ targetSnapshot?: LedgerTargetSnapshot;
169
+ }
170
+ export interface LedgerJobView extends LedgerJob {
171
+ attempts: LedgerAttempt[];
172
+ children: LedgerJob[];
173
+ result?: LedgerResult;
174
+ businessAcceptance?: BusinessAcceptance;
175
+ acceptanceHistory: BusinessAcceptance[];
176
+ }
177
+ export declare class JobLedger {
178
+ private readonly persist;
179
+ private state;
180
+ constructor(initial: LedgerState | undefined, persist: (next: LedgerState) => void);
181
+ snapshot(): LedgerState;
182
+ /** Trusted adapter use only; public reads must call scoped get/list. */
183
+ getAttempt(attemptId: string): LedgerAttempt;
184
+ get sourceId(): string;
185
+ /** A crash during dispatch proves neither acceptance nor rejection; never silently send it again. */
186
+ recoverAfterRestart(): string[];
187
+ private mutate;
188
+ private job;
189
+ private attempt;
190
+ private event;
191
+ private refresh;
192
+ private checkRef;
193
+ private requestIdentity;
194
+ /** Read-only idempotency check before resolving current target configuration or contacting a Provider. */
195
+ replay(input: LedgerPrepareInput): {
196
+ job: LedgerJob;
197
+ attempt: LedgerAttempt;
198
+ idempotent: true;
199
+ } | undefined;
200
+ prepare(input: LedgerPrepareInput): {
201
+ job: LedgerJob;
202
+ attempt: LedgerAttempt;
203
+ idempotent: boolean;
204
+ };
205
+ markDispatching(attemptId: string): LedgerAttempt;
206
+ accept(attemptId: string, backendRunRef: BackendRunRef, observation?: LedgerObservation): LedgerAttempt;
207
+ knownNotSubmitted(attemptId: string, input: {
208
+ executionStatus: 'failed' | 'rejected' | 'canceled';
209
+ diagnostic?: string;
210
+ }): LedgerAttempt;
211
+ markUnknown(attemptId: string, diagnostic?: string): LedgerAttempt;
212
+ private applyObservation;
213
+ observe(attemptId: string, input: LedgerObservation): LedgerAttempt;
214
+ requestCancellation(attemptId: string): LedgerAttempt;
215
+ get(originSessionId: string, jobId: string): LedgerJobView;
216
+ list(originSessionId: string): LedgerJobView[];
217
+ events(originSessionId: string, jobId?: string, afterSequence?: number): LedgerEvent[];
218
+ findByBackend(originSessionId: string, ref: {
219
+ remote?: string;
220
+ taskId?: string;
221
+ flowRunId?: string;
222
+ }): {
223
+ job: LedgerJob;
224
+ attempt: LedgerAttempt;
225
+ } | undefined;
226
+ acceptance(originSessionId: string, jobId: string, input: Omit<BusinessAcceptance, 'recordedAt'>): BusinessAcceptance;
227
+ /** Each old Task gets one legacy Job; matching context IDs never merge jobs. */
228
+ migrateLegacy(records: LegacyLedgerRecord[]): Array<{
229
+ remote: string;
230
+ taskId: string;
231
+ jobId: string;
232
+ attemptId: string;
233
+ }>;
234
+ }
235
+ export {};