@1agents/acp-service 0.8.2 → 0.9.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.
- package/README.md +6 -0
- package/dist/bin/a2a.js +10 -2
- package/dist/bin/acp-service.js +6 -0
- package/dist/bin/roles.d.ts +1 -0
- package/dist/bin/roles.js +24 -0
- package/dist/src/a2a/executor.d.ts +16 -1
- package/dist/src/a2a/executor.js +205 -19
- package/dist/src/a2a/gateway.d.ts +77 -0
- package/dist/src/a2a/gateway.js +349 -27
- package/dist/src/a2a/index.d.ts +7 -1
- package/dist/src/a2a/index.js +4 -0
- package/dist/src/a2a/result-metadata.d.ts +3 -0
- package/dist/src/a2a/result-metadata.js +2 -1
- package/dist/src/a2a/server.js +2 -1
- package/dist/src/a2a/store.js +7 -1
- package/dist/src/a2a/types.d.ts +32 -1
- package/dist/src/a2a/types.js +11 -1
- package/dist/src/acp-connection.js +93 -12
- package/dist/src/bridge.js +127 -4
- package/dist/src/capacity-lifecycle.d.ts +5 -0
- package/dist/src/capacity-lifecycle.js +57 -0
- package/dist/src/capacity-queue.d.ts +23 -0
- package/dist/src/capacity-queue.js +251 -0
- package/dist/src/capacity.d.ts +76 -0
- package/dist/src/capacity.js +377 -0
- package/dist/src/execution/human-review.d.ts +103 -0
- package/dist/src/execution/human-review.js +87 -0
- package/dist/src/execution/ledger.d.ts +5 -0
- package/dist/src/execution/ledger.js +39 -8
- package/dist/src/execution/ppt-delivery.d.ts +36 -3
- package/dist/src/execution/ppt-delivery.js +243 -53
- package/dist/src/execution/project-discovery.d.ts +56 -0
- package/dist/src/execution/project-discovery.js +429 -0
- package/dist/src/execution/report-review.d.ts +60 -0
- package/dist/src/execution/report-review.js +173 -0
- package/dist/src/execution/targets.d.ts +5 -0
- package/dist/src/execution/targets.js +1 -0
- package/dist/src/execution/workbench.d.ts +131 -0
- package/dist/src/execution/workbench.js +265 -0
- package/dist/src/index.d.ts +4 -0
- package/dist/src/index.js +3 -0
- package/dist/src/roles/index.d.ts +1 -0
- package/dist/src/roles/index.js +1 -0
- package/dist/src/roles/skills.d.ts +71 -0
- package/dist/src/roles/skills.js +427 -0
- package/package.json +5 -1
- package/skills/acp-service/SKILL.md +21 -7
- package/skills/acp-service/references/a2a.md +9 -5
- package/skills/acp-service/references/async-caller.md +48 -0
- package/skills/acp-service/references/roles-and-tasks.md +120 -0
- package/skills/acp-service/scripts/a2a-caller.py +242 -0
- package/vendor/dsh/README.md +2 -0
- package/vendor/dsh/a2a-executor.d.ts +4 -1
- package/vendor/dsh/a2a-executor.js +46 -2
- package/vendor/dsh/adapter.d.ts +10 -0
- package/vendor/dsh/adapter.js +67 -3
- package/vendor/dsh/client.js +84 -24
- package/vendor/dsh/index.js +2 -1
- package/vendor/runtime/dist/{cli-DeOpE2Xz.js → cli-DXmYwv3U.js} +4 -4
- package/vendor/runtime/dist/{cli-DeOpE2Xz.js.map → cli-DXmYwv3U.js.map} +1 -1
- package/vendor/runtime/dist/cli.js +7 -7
- package/vendor/runtime/dist/client-VQsqcIOJ.d.ts.map +1 -1
- package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +1 -0
- package/vendor/runtime/dist/{flows-oaBGn31w.js → flows-DJ17ajbw.js} +3 -3
- package/vendor/runtime/dist/{flows-oaBGn31w.js.map → flows-DJ17ajbw.js.map} +1 -1
- package/vendor/runtime/dist/flows.js +1 -1
- package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js → invocation-options-PBfCgrdi.js} +3 -3
- package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js.map → invocation-options-PBfCgrdi.js.map} +1 -1
- package/vendor/runtime/dist/{output-CFv3jcOQ.js → output-B3MDn7kv.js} +2 -2
- package/vendor/runtime/dist/{output-CFv3jcOQ.js.map → output-B3MDn7kv.js.map} +1 -1
- package/vendor/runtime/dist/{queue-owner-runtime-DvMJiGbP.js → queue-owner-runtime-DXCVngwU.js} +15 -8
- package/vendor/runtime/dist/queue-owner-runtime-DXCVngwU.js.map +1 -0
- package/vendor/runtime/dist/runtime.js +1 -1
- package/vendor/runtime/dist/{session-watch-Di-wIdCH.js → session-watch-DURyCw31.js} +2 -2
- package/vendor/runtime/dist/{session-watch-Di-wIdCH.js.map → session-watch-DURyCw31.js.map} +1 -1
- package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +0 -1
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/** A temporary author, a deterministic file check, and a final human gate. No model reviewer. */
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { mkdir, open, realpath, writeFile } from 'node:fs/promises';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { createHumanReview, markHumanReviewApplied } from './human-review.js';
|
|
8
|
+
const absolute = z.string().min(1).refine(path.isAbsolute, 'Expected an absolute path');
|
|
9
|
+
export const reportReviewPolicySchema = z.object({
|
|
10
|
+
workspaceRoot: absolute, allowedProjectRoots: z.array(absolute).min(1),
|
|
11
|
+
allowedRemotes: z.array(z.string().min(1)).min(1),
|
|
12
|
+
}).strict();
|
|
13
|
+
export const reportReviewInputSchema = z.object({
|
|
14
|
+
fileName: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,120}\.md$/).default('architecture-report.md'),
|
|
15
|
+
}).strict();
|
|
16
|
+
const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
17
|
+
const terminal = new Set(['completed', 'failed', 'canceled', 'rejected']);
|
|
18
|
+
export const reportRevision = (run) => `report-v${run.revision}`;
|
|
19
|
+
function within(root, file) {
|
|
20
|
+
const relative = path.relative(root, file);
|
|
21
|
+
return relative === '' || relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
22
|
+
}
|
|
23
|
+
export async function createReportReviewRun(input, policy, report) {
|
|
24
|
+
if (!policy.allowedRemotes.includes(input.remote))
|
|
25
|
+
throw new Error('Report checks require an explicitly configured shared-filesystem remote');
|
|
26
|
+
const cwd = await realpath(input.cwd), roots = await Promise.all(policy.allowedProjectRoots.map(root => realpath(root)));
|
|
27
|
+
if (!roots.some(root => within(root, cwd)))
|
|
28
|
+
throw new Error('Report project is outside allowedProjectRoots');
|
|
29
|
+
const { fileName } = reportReviewInputSchema.parse(report);
|
|
30
|
+
await mkdir(policy.workspaceRoot, { recursive: true });
|
|
31
|
+
const workspace = await realpath(policy.workspaceRoot);
|
|
32
|
+
const directory = path.join(workspace, input.jobId, input.attemptId);
|
|
33
|
+
await mkdir(directory, { recursive: true });
|
|
34
|
+
if (!within(workspace, await realpath(directory)))
|
|
35
|
+
throw new Error('Report output escaped its workspace');
|
|
36
|
+
const version = path.join(directory, 'report-v1');
|
|
37
|
+
await mkdir(version);
|
|
38
|
+
const at = new Date().toISOString();
|
|
39
|
+
return { ...input, cwd, directory, reportPath: path.join(version, fileName), revision: 1,
|
|
40
|
+
stage: 'research', phase: 'author_pending', executionStatus: 'working', humanReviews: [], createdAt: at, updatedAt: at };
|
|
41
|
+
}
|
|
42
|
+
/** Read bounded regular bytes without following symlinks or accepting linked aliases. */
|
|
43
|
+
export async function readReportFile(file) {
|
|
44
|
+
const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
45
|
+
try {
|
|
46
|
+
const stat = await handle.stat();
|
|
47
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size === 0 || stat.size > 256 * 1024)
|
|
48
|
+
throw new Error('Expected a nonempty regular Markdown report of at most 256 KiB');
|
|
49
|
+
const bytes = Buffer.alloc(stat.size + 1);
|
|
50
|
+
const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
|
|
51
|
+
if (bytesRead !== stat.size)
|
|
52
|
+
throw new Error('Report changed during file check');
|
|
53
|
+
const result = bytes.subarray(0, bytesRead);
|
|
54
|
+
const text = new TextDecoder('utf-8', { fatal: true }).decode(result);
|
|
55
|
+
if (!text.trim())
|
|
56
|
+
throw new Error('Report is empty');
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
await handle.close();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export async function reportBindingDigest(run) {
|
|
64
|
+
if (!run.snapshotPath)
|
|
65
|
+
throw new Error('Report snapshot is unavailable');
|
|
66
|
+
const bytes = await readReportFile(run.reportPath), snapshot = await readReportFile(run.snapshotPath);
|
|
67
|
+
if (hash(bytes) !== hash(snapshot))
|
|
68
|
+
throw new Error('Report bytes differ from the reviewed snapshot');
|
|
69
|
+
return hash(snapshot);
|
|
70
|
+
}
|
|
71
|
+
function authorPrompt(run, feedback) {
|
|
72
|
+
return `${String(run.authorInput.prompt)}\n\n任务源目录(只读):${run.cwd}。当前执行工作区为 ${run.directory},先记录真实 pwd。\n仅将任务要求的 Markdown 产物写入 ${run.reportPath}。语言与内容按任务说明执行。不得修改源目录、安装依赖、启动服务或创建其他任务。\n${feedback ? `这是同一任务的修订,保留旧版;用户意见:${feedback}\n` : ''}写入完成后立即结束。协调器检查文件,用户做最终确认。`;
|
|
73
|
+
}
|
|
74
|
+
export async function advanceReportReview(run, adapter) {
|
|
75
|
+
const save = () => { run.updatedAt = new Date().toISOString(); adapter.persist(run); adapter.update(run); };
|
|
76
|
+
if (terminal.has(run.executionStatus)) {
|
|
77
|
+
adapter.update(run);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const review = run.humanReviews.at(-1), decision = review?.resume;
|
|
81
|
+
if (decision?.status === 'pending') {
|
|
82
|
+
if (decision.action === 'approve') {
|
|
83
|
+
if (await reportBindingDigest(run) !== review.digest)
|
|
84
|
+
throw new Error('Approved report version changed');
|
|
85
|
+
run.executionStatus = 'completed';
|
|
86
|
+
run.stage = 'finished';
|
|
87
|
+
run.phase = 'human_approved';
|
|
88
|
+
run.resultSummary = `人工已通过 ${reportRevision(run)}。报告:${run.reportPath}`;
|
|
89
|
+
}
|
|
90
|
+
else if (decision.action === 'cancel') {
|
|
91
|
+
run.executionStatus = 'canceled';
|
|
92
|
+
run.phase = 'human_canceled';
|
|
93
|
+
run.resultSummary = '用户已放弃报告任务,保留产物与审核历史。';
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
run.revision++;
|
|
97
|
+
const version = path.join(run.directory, reportRevision(run));
|
|
98
|
+
await mkdir(version, { recursive: true });
|
|
99
|
+
run.reportPath = path.join(version, path.basename(run.reportPath));
|
|
100
|
+
delete run.digest;
|
|
101
|
+
delete run.snapshotPath;
|
|
102
|
+
delete run.fileCheck;
|
|
103
|
+
run.executionStatus = 'working';
|
|
104
|
+
run.stage = 'research';
|
|
105
|
+
run.phase = 'revision_pending';
|
|
106
|
+
}
|
|
107
|
+
run.humanReviews[run.humanReviews.length - 1] = markHumanReviewApplied(review, decision.decisionId);
|
|
108
|
+
save();
|
|
109
|
+
}
|
|
110
|
+
if (run.executionStatus !== 'working')
|
|
111
|
+
return;
|
|
112
|
+
if (run.phase === 'author_pending' || run.phase === 'revision_pending') {
|
|
113
|
+
const feedback = run.phase === 'revision_pending' ? review?.history.at(-1)?.note : undefined;
|
|
114
|
+
// The stable submission key allows recovery after an accepted-but-unrecorded child receipt.
|
|
115
|
+
run.child = await adapter.submit(run, authorPrompt(run, feedback), feedback ? run.child : undefined);
|
|
116
|
+
run.phase = 'author_running';
|
|
117
|
+
save();
|
|
118
|
+
}
|
|
119
|
+
if (!run.child)
|
|
120
|
+
throw new Error('Report child has no durable receipt');
|
|
121
|
+
const child = adapter.child(run.child.attemptId);
|
|
122
|
+
if (child.submissionStatus === 'submission_unknown' || child.submissionStatus === 'dispatching') {
|
|
123
|
+
run.executionStatus = 'input_required';
|
|
124
|
+
run.phase = 'child_admission_unknown';
|
|
125
|
+
run.resultSummary = '临时任务受理未知,停止重派,等待核对。';
|
|
126
|
+
save();
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (!terminal.has(child.executionStatus))
|
|
130
|
+
return;
|
|
131
|
+
if (child.executionStatus !== 'completed') {
|
|
132
|
+
run.executionStatus = 'failed';
|
|
133
|
+
run.phase = 'author_failed';
|
|
134
|
+
run.resultSummary = '临时分析任务未完成,请查看子任务。';
|
|
135
|
+
save();
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
run.stage = 'file_check';
|
|
139
|
+
run.phase = 'checking_report';
|
|
140
|
+
save();
|
|
141
|
+
try {
|
|
142
|
+
if (await realpath(path.dirname(run.reportPath)) !== path.dirname(run.reportPath))
|
|
143
|
+
throw new Error('Report directory is not the assigned directory');
|
|
144
|
+
const bytes = await readReportFile(run.reportPath), sha256 = hash(bytes);
|
|
145
|
+
const snapshotPath = path.join(run.directory, `${reportRevision(run)}.review-snapshot.md`);
|
|
146
|
+
try {
|
|
147
|
+
await writeFile(snapshotPath, bytes, { flag: 'wx', mode: 0o400 });
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
if (error.code !== 'EEXIST' || hash(await readReportFile(snapshotPath)) !== sha256)
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
run.fileCheck = { passed: true, path: run.reportPath, checkedAt: new Date().toISOString(), size: bytes.length, sha256 };
|
|
154
|
+
run.digest = sha256;
|
|
155
|
+
run.snapshotPath = snapshotPath;
|
|
156
|
+
run.humanReviews.push(createHumanReview({ jobId: run.jobId, attemptId: run.attemptId, stage: 'report',
|
|
157
|
+
authorJobId: run.child.jobId, authorAttemptId: run.child.attemptId,
|
|
158
|
+
authorSessionId: String(child.backendRunRef?.sessionId ?? run.child.attemptId), reviewerId: run.reviewerId,
|
|
159
|
+
revision: reportRevision(run), digest: sha256, title: run.title,
|
|
160
|
+
preview: { kind: 'markdown', title: run.title, markdown: bytes.toString('utf8'), reportPath: run.reportPath, slides: [] } }));
|
|
161
|
+
run.stage = 'human_review';
|
|
162
|
+
run.phase = 'awaiting_human';
|
|
163
|
+
run.executionStatus = 'input_required';
|
|
164
|
+
run.resultSummary = `报告文件检查通过,等待你确认 ${reportRevision(run)}。人工通过后任务才算完成。`;
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
run.fileCheck = { passed: false, path: run.reportPath, checkedAt: new Date().toISOString(), error: error instanceof Error ? error.message : 'Report check failed' };
|
|
168
|
+
run.executionStatus = 'failed';
|
|
169
|
+
run.phase = 'file_check_failed';
|
|
170
|
+
run.resultSummary = '指定报告文件检查未通过,未进入人工审核。';
|
|
171
|
+
}
|
|
172
|
+
save();
|
|
173
|
+
}
|
|
@@ -38,6 +38,7 @@ export declare const executionTargetBindingSchema: z.ZodObject<{
|
|
|
38
38
|
agentPreset: z.ZodOptional<z.ZodString>;
|
|
39
39
|
roleId: z.ZodOptional<z.ZodString>;
|
|
40
40
|
skillRefs: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
41
|
+
skillPolicy: z.ZodOptional<z.ZodLiteral<"network_pinned">>;
|
|
41
42
|
allowedDirectories: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
42
43
|
allowedPresets: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
43
44
|
flowId: z.ZodOptional<z.ZodString>;
|
|
@@ -69,6 +70,7 @@ export declare const executionTargetConfigSchema: z.ZodObject<{
|
|
|
69
70
|
agentPreset: z.ZodOptional<z.ZodString>;
|
|
70
71
|
roleId: z.ZodOptional<z.ZodString>;
|
|
71
72
|
skillRefs: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
73
|
+
skillPolicy: z.ZodOptional<z.ZodLiteral<"network_pinned">>;
|
|
72
74
|
allowedDirectories: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
73
75
|
allowedPresets: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
74
76
|
flowId: z.ZodOptional<z.ZodString>;
|
|
@@ -101,6 +103,7 @@ export declare const executionTargetSchema: z.ZodObject<{
|
|
|
101
103
|
agentPreset: z.ZodOptional<z.ZodString>;
|
|
102
104
|
roleId: z.ZodOptional<z.ZodString>;
|
|
103
105
|
skillRefs: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
106
|
+
skillPolicy: z.ZodOptional<z.ZodLiteral<"network_pinned">>;
|
|
104
107
|
allowedDirectories: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
105
108
|
allowedPresets: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
106
109
|
flowId: z.ZodOptional<z.ZodString>;
|
|
@@ -236,6 +239,7 @@ export declare const TARGET_METHODS: {
|
|
|
236
239
|
agentPreset: z.ZodOptional<z.ZodString>;
|
|
237
240
|
roleId: z.ZodOptional<z.ZodString>;
|
|
238
241
|
skillRefs: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
242
|
+
skillPolicy: z.ZodOptional<z.ZodLiteral<"network_pinned">>;
|
|
239
243
|
allowedDirectories: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
240
244
|
allowedPresets: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
241
245
|
flowId: z.ZodOptional<z.ZodString>;
|
|
@@ -273,6 +277,7 @@ export declare const TARGET_METHODS: {
|
|
|
273
277
|
agentPreset: z.ZodOptional<z.ZodString>;
|
|
274
278
|
roleId: z.ZodOptional<z.ZodString>;
|
|
275
279
|
skillRefs: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
280
|
+
skillPolicy: z.ZodOptional<z.ZodLiteral<"network_pinned">>;
|
|
276
281
|
allowedDirectories: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
277
282
|
allowedPresets: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
278
283
|
flowId: z.ZodOptional<z.ZodString>;
|
|
@@ -26,6 +26,7 @@ export const executionConnectionSchema = executionConnectionConfigSchema.extend(
|
|
|
26
26
|
export const executionTargetBindingSchema = z.object({
|
|
27
27
|
remote: id.optional(), cwd: absolutePath.optional(), agentPreset: id.optional(),
|
|
28
28
|
roleId: id.optional(), skillRefs: z.array(text).max(100).optional(),
|
|
29
|
+
skillPolicy: z.literal('network_pinned').optional(),
|
|
29
30
|
allowedDirectories: z.array(absolutePath).min(1).max(100).optional(),
|
|
30
31
|
allowedPresets: z.array(id).min(1).max(100).optional(),
|
|
31
32
|
flowId: id.optional(), flowVersion: text.optional(), driver: z.literal('ppt_delivery').optional(),
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/** Human-readable projections of the execution ledger. Reading never dispatches or acknowledges work. */
|
|
2
|
+
import type { JobRef, LedgerAttempt, LedgerEvent, LedgerState } from './ledger.js';
|
|
3
|
+
import type { ReportReviewRun } from './report-review.js';
|
|
4
|
+
import type { PptDeliveryRun } from './ppt-delivery.js';
|
|
5
|
+
import { deliveryProgress } from './delivery-progress.js';
|
|
6
|
+
import type { HumanReviewRequest, HumanReviewStatus } from './human-review.js';
|
|
7
|
+
export interface WorkbenchServiceInfo {
|
|
8
|
+
kind: 'a2a' | 'gateway_workflow' | 'activepieces' | 'unknown';
|
|
9
|
+
source: 'backend_run' | 'target_snapshot' | 'workflow_run' | 'unrecorded';
|
|
10
|
+
host?: string;
|
|
11
|
+
port?: number;
|
|
12
|
+
locality?: 'loopback' | 'network';
|
|
13
|
+
connectionAlias?: string;
|
|
14
|
+
}
|
|
15
|
+
export interface WorkbenchExecution {
|
|
16
|
+
kind: 'temporary' | 'resident' | 'workflow' | 'unknown';
|
|
17
|
+
targetId: string;
|
|
18
|
+
targetName?: string;
|
|
19
|
+
roleId?: string;
|
|
20
|
+
agentPreset?: string;
|
|
21
|
+
presetStatus: 'recorded' | 'host_default' | 'unknown' | 'not_applicable';
|
|
22
|
+
service?: string;
|
|
23
|
+
serviceInfo?: WorkbenchServiceInfo;
|
|
24
|
+
provider?: string;
|
|
25
|
+
connectionId?: string;
|
|
26
|
+
}
|
|
27
|
+
export interface AcpTaskSummary {
|
|
28
|
+
sourceId: string;
|
|
29
|
+
jobId: string;
|
|
30
|
+
title: string;
|
|
31
|
+
originSessionId: string;
|
|
32
|
+
parentJobRef?: JobRef;
|
|
33
|
+
parentAttemptId?: string;
|
|
34
|
+
purpose?: string;
|
|
35
|
+
targetId: string;
|
|
36
|
+
currentAttemptId: string;
|
|
37
|
+
executionStatus: string;
|
|
38
|
+
displayStatus: string;
|
|
39
|
+
phase: string;
|
|
40
|
+
createdAt: string | null;
|
|
41
|
+
updatedAt: string;
|
|
42
|
+
stale: boolean;
|
|
43
|
+
reviewStatus?: HumanReviewStatus;
|
|
44
|
+
pendingReviewId?: string;
|
|
45
|
+
progressSummary: string;
|
|
46
|
+
inFlightAttemptIds: string[];
|
|
47
|
+
unresolvedAttemptIds: string[];
|
|
48
|
+
execution: WorkbenchExecution;
|
|
49
|
+
}
|
|
50
|
+
export interface WorkbenchStage {
|
|
51
|
+
stage: string;
|
|
52
|
+
name: string;
|
|
53
|
+
status: string;
|
|
54
|
+
planned: boolean;
|
|
55
|
+
jobId?: string;
|
|
56
|
+
attemptId?: string;
|
|
57
|
+
}
|
|
58
|
+
export interface WorkbenchProgress {
|
|
59
|
+
stage: string;
|
|
60
|
+
phase: string;
|
|
61
|
+
stages: WorkbenchStage[];
|
|
62
|
+
completedStages: string[];
|
|
63
|
+
remainingStages: string[];
|
|
64
|
+
executionElapsedMs?: number;
|
|
65
|
+
humanWaitingMs?: number;
|
|
66
|
+
updatedAt: string;
|
|
67
|
+
availableResults?: ReturnType<typeof deliveryProgress>['availableResults'];
|
|
68
|
+
}
|
|
69
|
+
export interface WorkbenchDependency {
|
|
70
|
+
from: string;
|
|
71
|
+
to: string;
|
|
72
|
+
kind: 'parent' | 'depends_on' | 'replaces';
|
|
73
|
+
label: string;
|
|
74
|
+
parentAttemptId?: string;
|
|
75
|
+
}
|
|
76
|
+
export type WorkbenchReview = HumanReviewRequest & {
|
|
77
|
+
canReview: boolean;
|
|
78
|
+
resumeStatus?: 'pending' | 'applied';
|
|
79
|
+
resumeError?: string;
|
|
80
|
+
};
|
|
81
|
+
export type WorkbenchAttempt = Omit<LedgerAttempt, 'input' | 'targetSnapshot' | 'backendRunRef'> & {
|
|
82
|
+
backendRunRef?: Record<string, string>;
|
|
83
|
+
execution: WorkbenchExecution;
|
|
84
|
+
};
|
|
85
|
+
export interface AcpTaskDetail extends AcpTaskSummary {
|
|
86
|
+
attempts: WorkbenchAttempt[];
|
|
87
|
+
children: AcpTaskSummary[];
|
|
88
|
+
ancestors: AcpTaskSummary[];
|
|
89
|
+
progress: WorkbenchProgress;
|
|
90
|
+
reviews: WorkbenchReview[];
|
|
91
|
+
events: LedgerEvent[];
|
|
92
|
+
dependencies: WorkbenchDependency[];
|
|
93
|
+
artifacts: {
|
|
94
|
+
revision: string;
|
|
95
|
+
digest?: string;
|
|
96
|
+
artifacts: unknown[];
|
|
97
|
+
}[];
|
|
98
|
+
}
|
|
99
|
+
export interface WorkbenchSource {
|
|
100
|
+
ledger: LedgerState;
|
|
101
|
+
runs: readonly PptDeliveryRun[];
|
|
102
|
+
reviews: readonly HumanReviewRequest[];
|
|
103
|
+
reportRuns?: readonly ReportReviewRun[];
|
|
104
|
+
actorId: string;
|
|
105
|
+
allowedOrigins?: readonly string[];
|
|
106
|
+
now?: number;
|
|
107
|
+
}
|
|
108
|
+
export interface WorkbenchSnapshot {
|
|
109
|
+
sourceId: string;
|
|
110
|
+
tasks: AcpTaskSummary[];
|
|
111
|
+
details: Record<string, AcpTaskDetail>;
|
|
112
|
+
}
|
|
113
|
+
export interface WorkbenchListQuery {
|
|
114
|
+
filter?: 'all' | 'pending' | 'working' | 'failed';
|
|
115
|
+
limit?: number;
|
|
116
|
+
offset?: number;
|
|
117
|
+
}
|
|
118
|
+
export declare function workbenchSnapshot(source: WorkbenchSource): WorkbenchSnapshot;
|
|
119
|
+
export declare function listWorkbenchTasks(snapshot: WorkbenchSnapshot, query?: WorkbenchListQuery): {
|
|
120
|
+
items: AcpTaskSummary[];
|
|
121
|
+
total: number;
|
|
122
|
+
counts: {
|
|
123
|
+
all: number;
|
|
124
|
+
pending: number;
|
|
125
|
+
working: number;
|
|
126
|
+
failed: number;
|
|
127
|
+
};
|
|
128
|
+
offset: number;
|
|
129
|
+
limit: number;
|
|
130
|
+
};
|
|
131
|
+
export declare function getWorkbenchTask(snapshot: WorkbenchSnapshot, jobId: string): AcpTaskDetail;
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { deliveryProgress } from './delivery-progress.js';
|
|
2
|
+
const stageNames = { summary: '文稿生成', human_review: '人工审核', make: '设计制作', validate: '机器校验', review: '独立验收', finished: '交付完成' };
|
|
3
|
+
const purposeNames = { project_script: '文稿生成', ppt_production: '设计制作', independent_review: '独立验收' };
|
|
4
|
+
const terminal = new Set(['completed', 'failed', 'canceled', 'rejected']);
|
|
5
|
+
const stateDescriptions = { not_started: '等待开始执行。', submitted: '任务已提交,等待执行角色开始。', working: '执行角色正在处理任务。',
|
|
6
|
+
input_required: '任务等待补充输入。', auth_required: '任务等待完成认证。', completed: '执行已完成,可查看产物和执行记录。',
|
|
7
|
+
failed: '执行失败,请查看异常原因。', canceled: '任务已取消,已有产物与历史保留。', rejected: '执行请求未被接受。', unknown: '执行状态尚未确认,请核实执行宿主。' };
|
|
8
|
+
function runDescription(run) {
|
|
9
|
+
if (terminal.has(run.executionStatus))
|
|
10
|
+
return stateDescriptions[run.executionStatus];
|
|
11
|
+
if (run.stage === 'make' && !run.currentChild && !run.pending)
|
|
12
|
+
return '文字稿已确认,等待启动设计制作。';
|
|
13
|
+
return ({ summary: '文稿作者正在生成或修订文字稿。', make: '制作角色正在根据确认的文字稿设计 PPT。', validate: '正在检查制作产物的文件与结构。',
|
|
14
|
+
review: '独立验收角色正在核对事实和页面效果。', finished: '交付已完成,可查看最终产物。' })[run.stage];
|
|
15
|
+
}
|
|
16
|
+
function byNewest(items) { return items.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); }
|
|
17
|
+
function latestReview(reviews, job) {
|
|
18
|
+
return byNewest(reviews.filter(r => r.jobId === job.jobId && r.attemptId === job.currentAttemptId).map(r => structuredClone(r)).reverse())[0];
|
|
19
|
+
}
|
|
20
|
+
function metadataText(value) {
|
|
21
|
+
if (typeof value !== 'string')
|
|
22
|
+
return undefined;
|
|
23
|
+
const text = value.trim();
|
|
24
|
+
return text && text.length <= 512 && !/[\u0000-\u001f\u007f]/.test(text) ? text : undefined;
|
|
25
|
+
}
|
|
26
|
+
function metadataObject(value) {
|
|
27
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
28
|
+
}
|
|
29
|
+
function serviceEndpoint(value) {
|
|
30
|
+
if (typeof value !== 'string' || value.length > 8192 || /[\u0000-\u001f\u007f]/.test(value))
|
|
31
|
+
return undefined;
|
|
32
|
+
try {
|
|
33
|
+
const url = new URL(value);
|
|
34
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
|
|
35
|
+
return undefined;
|
|
36
|
+
const host = metadataText(url.hostname.replace(/^\[|\]$/g, ''));
|
|
37
|
+
if (!host)
|
|
38
|
+
return undefined;
|
|
39
|
+
const locality = host === 'localhost' || host === '::1' || /^127\.(?:\d{1,3}\.){2}\d{1,3}$/.test(host) ? 'loopback' : 'network';
|
|
40
|
+
return { host, port: url.port ? Number(url.port) : url.protocol === 'https:' ? 443 : 80, locality };
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** Separate a connection alias from the service this attempt was recorded against. */
|
|
47
|
+
function serviceView(attempt, snapshot, binding, workflow) {
|
|
48
|
+
const backend = attempt?.backendRunRef;
|
|
49
|
+
const connectionAlias = metadataText(backend?.remote) ?? metadataText(snapshot.remote);
|
|
50
|
+
const alias = connectionAlias ? { connectionAlias } : {};
|
|
51
|
+
const recordedWorkflow = workflow || backend?.provider === 'report_review' || backend?.provider === 'resident_role' && Boolean(metadataText(backend.runId));
|
|
52
|
+
if (recordedWorkflow || binding.driver === 'ppt_delivery')
|
|
53
|
+
return { kind: 'gateway_workflow', source: recordedWorkflow ? 'workflow_run' : 'target_snapshot', ...alias };
|
|
54
|
+
const provider = metadataText(backend?.provider) ?? metadataText(snapshot.provider) ?? metadataText(attempt?.provider);
|
|
55
|
+
const kind = provider === 'a2a' ? 'a2a' : provider === 'activepieces' ? 'activepieces' : 'unknown';
|
|
56
|
+
const actual = serviceEndpoint(backend?.endpoint), configured = serviceEndpoint(snapshot.endpoint);
|
|
57
|
+
return { kind, source: actual ? 'backend_run' : configured ? 'target_snapshot' : 'unrecorded', ...(actual ?? configured), ...alias };
|
|
58
|
+
}
|
|
59
|
+
/** Historical identities come only from this execution's frozen facts, never today's target directory. */
|
|
60
|
+
function executionView(attempt, targetId, workflow = false) {
|
|
61
|
+
const snapshot = attempt?.targetSnapshot ?? {}, binding = metadataObject(snapshot.binding);
|
|
62
|
+
const serviceInfo = serviceView(attempt, snapshot, binding, workflow);
|
|
63
|
+
const snapshotRole = metadataText(snapshot.roleId), bindingRole = metadataText(binding.roleId);
|
|
64
|
+
const roleConflict = Boolean(snapshotRole && bindingRole && snapshotRole !== bindingRole);
|
|
65
|
+
const roleId = roleConflict ? undefined : snapshotRole ?? bindingRole;
|
|
66
|
+
const hasRole = Boolean(snapshotRole || bindingRole);
|
|
67
|
+
const targetKind = metadataText(snapshot.targetKind);
|
|
68
|
+
let kind = 'unknown';
|
|
69
|
+
if (serviceInfo.kind === 'gateway_workflow' || targetKind === 'workflow')
|
|
70
|
+
kind = 'workflow';
|
|
71
|
+
else if (roleConflict || targetKind === 'agent_host' && hasRole)
|
|
72
|
+
kind = 'unknown';
|
|
73
|
+
else if (targetKind === 'resident_agent' || hasRole)
|
|
74
|
+
kind = 'resident';
|
|
75
|
+
else if (targetKind === 'agent_host' || targetId.startsWith('legacy:'))
|
|
76
|
+
kind = 'temporary';
|
|
77
|
+
const snapshotPreset = metadataText(snapshot.agentPreset), bindingPreset = metadataText(binding.agentPreset);
|
|
78
|
+
const presetConflict = Boolean(snapshotPreset && bindingPreset && snapshotPreset !== bindingPreset);
|
|
79
|
+
const presetUnusable = snapshot.agentPreset !== undefined && !snapshotPreset || binding.agentPreset !== undefined && !bindingPreset;
|
|
80
|
+
const hasFrozenTarget = Boolean(attempt && metadataText(snapshot.targetId) === targetId);
|
|
81
|
+
const agentPreset = kind === 'workflow' || presetConflict ? undefined : snapshotPreset ?? bindingPreset;
|
|
82
|
+
const presetStatus = kind === 'workflow' ? 'not_applicable'
|
|
83
|
+
: agentPreset ? 'recorded' : kind === 'temporary' && hasFrozenTarget && !presetConflict && !presetUnusable && snapshot.historicalConfigUnknown !== true ? 'host_default' : 'unknown';
|
|
84
|
+
const targetName = metadataText(snapshot.targetName), service = metadataText(snapshot.remote) ?? metadataText(attempt?.backendRunRef?.remote);
|
|
85
|
+
const provider = metadataText(snapshot.provider) ?? metadataText(attempt?.provider) ?? metadataText(attempt?.backendRunRef?.provider);
|
|
86
|
+
const connectionId = metadataText(snapshot.connectionId) ?? metadataText(attempt?.connectionId);
|
|
87
|
+
return { kind, targetId: metadataText(targetId) ?? '', presetStatus, serviceInfo,
|
|
88
|
+
...(targetName ? { targetName } : {}), ...(roleId ? { roleId } : {}), ...(agentPreset ? { agentPreset } : {}),
|
|
89
|
+
...(service ? { service } : {}), ...(provider ? { provider } : {}), ...(connectionId ? { connectionId } : {}) };
|
|
90
|
+
}
|
|
91
|
+
function safeArtifact(input) {
|
|
92
|
+
if (typeof input === 'string') {
|
|
93
|
+
try {
|
|
94
|
+
const url = new URL(input);
|
|
95
|
+
return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password ? input : undefined;
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (!input || typeof input !== 'object')
|
|
102
|
+
return undefined;
|
|
103
|
+
const value = input;
|
|
104
|
+
if (typeof value.url !== 'string' || !safeArtifact(value.url))
|
|
105
|
+
return undefined;
|
|
106
|
+
const result = { url: value.url };
|
|
107
|
+
for (const key of ['name', 'path', 'mediaType', 'size', 'sha256'])
|
|
108
|
+
if (['string', 'number'].includes(typeof value[key]))
|
|
109
|
+
result[key] = value[key];
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
function attemptView(attempt, workflow = false) {
|
|
113
|
+
const { input: _input, targetSnapshot: _snapshot, backendRunRef, ...view } = structuredClone(attempt);
|
|
114
|
+
const refs = {};
|
|
115
|
+
for (const key of ['provider', 'remote', 'taskId', 'contextId', 'sessionId', 'flowRunId', 'runId'])
|
|
116
|
+
if (typeof backendRunRef?.[key] === 'string')
|
|
117
|
+
refs[key] = backendRunRef[key];
|
|
118
|
+
for (const result of [view.result, ...view.resultHistory ?? []])
|
|
119
|
+
if (result) {
|
|
120
|
+
result.artifactLinks = result.artifactLinks.map(safeArtifact).filter(item => item !== undefined);
|
|
121
|
+
if (result.resultArtifacts)
|
|
122
|
+
result.resultArtifacts = result.resultArtifacts.map(safeArtifact).filter(item => item !== undefined);
|
|
123
|
+
delete result.structuredResultRef;
|
|
124
|
+
}
|
|
125
|
+
return { ...view, ...(Object.keys(refs).length ? { backendRunRef: refs } : {}), execution: executionView(attempt, attempt.targetId, workflow) };
|
|
126
|
+
}
|
|
127
|
+
function eventView(event) {
|
|
128
|
+
const clean = (value) => {
|
|
129
|
+
if (Array.isArray(value))
|
|
130
|
+
return value.map(clean);
|
|
131
|
+
if (value && typeof value === 'object')
|
|
132
|
+
return Object.fromEntries(Object.entries(value).filter(([key]) => !/token|password|secret|authorization|apiKey|input|prompt|endpoint/i.test(key)).map(([key, item]) => [key, clean(item)]));
|
|
133
|
+
return value;
|
|
134
|
+
};
|
|
135
|
+
return { ...structuredClone(event), ...(event.data === undefined ? {} : { data: clean(event.data) }) };
|
|
136
|
+
}
|
|
137
|
+
function progress(job, run, reviews, attempt, now) {
|
|
138
|
+
if (!run) {
|
|
139
|
+
const name = purposeNames[job.purpose ?? ''] ?? '任务执行', status = attempt?.executionStatus ?? job.executionStatus;
|
|
140
|
+
return { stage: job.purpose ?? 'execution', phase: attempt?.phase ?? '', stages: [{ stage: job.purpose ?? 'execution', name, status, planned: false, jobId: job.jobId, attemptId: job.currentAttemptId }],
|
|
141
|
+
completedStages: status === 'completed' ? [name] : [], remainingStages: status === 'completed' ? [] : [name], updatedAt: job.updatedAt };
|
|
142
|
+
}
|
|
143
|
+
const review = latestReview(reviews, job), latest = (purpose) => [...run.children].reverse().find(child => child.purpose === purpose);
|
|
144
|
+
const script = latest('project_script'), maker = latest('ppt_production'), reviewer = latest('independent_review');
|
|
145
|
+
const stage = (key, child, status) => ({ stage: key, name: stageNames[key], status: status ?? child?.child.executionStatus ?? 'not_started',
|
|
146
|
+
planned: !child, ...(child ? { jobId: child.child.jobId, attemptId: child.child.attemptId } : {}) });
|
|
147
|
+
const stages = [stage('summary', script)];
|
|
148
|
+
const human = run;
|
|
149
|
+
const requireReview = run.policy.requireHumanReview;
|
|
150
|
+
if (review || requireReview)
|
|
151
|
+
stages.push({ stage: 'human_review', name: stageNames.human_review, status: review?.status ?? 'not_started', planned: !review, jobId: job.jobId, attemptId: job.currentAttemptId });
|
|
152
|
+
stages.push(stage('make', maker), { stage: 'validate', name: stageNames.validate, status: run.validation ? 'completed' : run.stage === 'validate' ? run.executionStatus : 'not_started', planned: !run.validation && run.stage !== 'validate' }, stage('review', reviewer, run.review?.verdict === 'passed' ? 'completed' : run.review?.verdict === 'changes_requested' ? 'changes_requested' : reviewer?.child.executionStatus));
|
|
153
|
+
const complete = (s) => ['completed', 'approved'].includes(s.status);
|
|
154
|
+
return { stage: review?.status === 'pending' && !terminal.has(job.executionStatus) && !terminal.has(run.executionStatus) ? 'human_review' : run.stage, phase: run.phase, stages,
|
|
155
|
+
completedStages: stages.filter(complete).map(s => s.name), remainingStages: stages.filter(s => !complete(s)).map(s => s.name),
|
|
156
|
+
executionElapsedMs: run.metrics.elapsedMs, humanWaitingMs: (human.humanWaitingMs ?? 0) + (human.humanWaitStartedAt && Number.isFinite(Date.parse(human.humanWaitStartedAt)) ? Math.max(0, now - Date.parse(human.humanWaitStartedAt)) : 0),
|
|
157
|
+
availableResults: deliveryProgress(run).availableResults, updatedAt: run.updatedAt };
|
|
158
|
+
}
|
|
159
|
+
function summary(job, run, reviews, ledger, actorId) {
|
|
160
|
+
const attempt = ledger.attempts[job.currentAttemptId], review = latestReview(reviews, job), pending = review?.status === 'pending' && !terminal.has(job.executionStatus) && (!run || !terminal.has(run.executionStatus));
|
|
161
|
+
const awaitingResume = review?.resume?.status === 'pending' && !terminal.has(job.executionStatus);
|
|
162
|
+
const resumeError = awaitingResume ? run?.diagnostics?.findLast(item => item.startsWith('Human continuation deferred:')) : undefined;
|
|
163
|
+
const displayStatus = pending ? 'awaiting_human' : awaitingResume && !resumeError ? 'resuming' : review?.status === 'changes_requested' && !terminal.has(job.executionStatus) ? 'changes_requested' : job.executionStatus;
|
|
164
|
+
const phase = pending ? 'human_review' : awaitingResume ? 'human_resume' : run?.phase ?? attempt?.phase ?? job.purpose ?? '';
|
|
165
|
+
const progressSummary = pending ? `${review.title}已形成,等待确认 ${review.revision};通过后开始设计制作。`
|
|
166
|
+
: awaitingResume ? resumeError ? `决定已保存,继续执行受阻:${resumeError.slice('Human continuation deferred:'.length).trim()}` : '本版决定已保存,等待系统继续处理。'
|
|
167
|
+
: review?.status === 'changes_requested' && !terminal.has(job.executionStatus) ? run?.summaryRevisionPending ? '修改意见已保存,正在提交原作者。' : '修改意见已提交原作者,等待新版本。'
|
|
168
|
+
: attempt?.diagnostic || (run ? runDescription(run) : attempt?.result?.resultSummary || stateDescriptions[job.executionStatus] || '等待同步执行进展。');
|
|
169
|
+
return { sourceId: job.sourceId, jobId: job.jobId, title: job.title ?? `${purposeNames[job.purpose ?? ''] ?? '执行任务'} ${job.jobId.slice(0, 8)}`,
|
|
170
|
+
originSessionId: job.originSessionId, ...(job.parentJobRef ? { parentJobRef: job.parentJobRef } : {}), ...(job.parentAttemptId ? { parentAttemptId: job.parentAttemptId } : {}),
|
|
171
|
+
...(job.purpose ? { purpose: job.purpose } : {}), targetId: job.targetId, currentAttemptId: job.currentAttemptId, executionStatus: job.executionStatus, displayStatus, phase,
|
|
172
|
+
createdAt: job.createdAt, updatedAt: review && review.updatedAt > job.updatedAt ? review.updatedAt : job.updatedAt, stale: attempt?.stale ?? true,
|
|
173
|
+
inFlightAttemptIds: [...job.inFlightAttemptIds], unresolvedAttemptIds: [...job.unresolvedAttemptIds], execution: executionView(attempt, job.targetId, Boolean(run)),
|
|
174
|
+
...(review ? { reviewStatus: review.status } : {}), ...(pending && review.reviewerId === actorId ? { pendingReviewId: review.reviewId } : {}), progressSummary };
|
|
175
|
+
}
|
|
176
|
+
export function workbenchSnapshot(source) {
|
|
177
|
+
const { ledger, actorId } = source, allowed = source.allowedOrigins ? new Set(source.allowedOrigins) : undefined;
|
|
178
|
+
const jobs = Object.values(ledger.jobs).filter(job => !allowed || allowed.has(job.originSessionId));
|
|
179
|
+
const visible = new Set(jobs.map(job => job.jobId)), runFor = (job) => source.runs.find(run => run.jobId === job.jobId && run.attemptId === job.currentAttemptId);
|
|
180
|
+
const summaries = new Map(jobs.map(job => [job.jobId, summary(job, runFor(job), source.reviews, ledger, actorId)]));
|
|
181
|
+
const details = {};
|
|
182
|
+
for (const job of jobs) {
|
|
183
|
+
const run = runFor(job), ownReviews = source.reviews.filter(r => r.jobId === job.jobId || r.authorJobId === job.jobId && visible.has(r.jobId));
|
|
184
|
+
const ancestors = [], visited = new Set([job.jobId]);
|
|
185
|
+
let parent = job.parentJobRef;
|
|
186
|
+
while (parent?.sourceId === ledger.sourceId && visible.has(parent.jobId) && !visited.has(parent.jobId)) {
|
|
187
|
+
visited.add(parent.jobId);
|
|
188
|
+
ancestors.unshift(summaries.get(parent.jobId));
|
|
189
|
+
parent = ledger.jobs[parent.jobId]?.parentJobRef;
|
|
190
|
+
}
|
|
191
|
+
const children = jobs.filter(child => child.parentJobRef?.sourceId === ledger.sourceId && child.parentJobRef.jobId === job.jobId).map(child => summaries.get(child.jobId));
|
|
192
|
+
const dependencies = children.map(child => ({ from: job.jobId, to: child.jobId, kind: 'parent', label: '子任务', parentAttemptId: child.parentAttemptId }));
|
|
193
|
+
if (job.parentJobRef?.sourceId === ledger.sourceId && visible.has(job.parentJobRef.jobId))
|
|
194
|
+
dependencies.unshift({ from: job.parentJobRef.jobId, to: job.jobId, kind: 'parent', label: '子任务', parentAttemptId: job.parentAttemptId });
|
|
195
|
+
for (const related of jobs.filter(item => item.jobId === job.jobId || item.parentJobRef?.jobId === job.jobId)) {
|
|
196
|
+
if (related.replacesJobRef?.sourceId === ledger.sourceId && visible.has(related.replacesJobRef.jobId))
|
|
197
|
+
dependencies.push({ from: related.replacesJobRef.jobId, to: related.jobId, kind: 'replaces', label: '接替执行' });
|
|
198
|
+
}
|
|
199
|
+
// Only this explicit domain workflow supplies ordering. Parent refs alone never imply dependencies.
|
|
200
|
+
if (run) {
|
|
201
|
+
const last = (purpose) => [...run.children].reverse().find(item => item.purpose === purpose)?.child.jobId;
|
|
202
|
+
const chain = [last('project_script'), last('ppt_production'), last('independent_review')].filter((id) => Boolean(id && visible.has(id)));
|
|
203
|
+
for (let index = 1; index < chain.length; index++)
|
|
204
|
+
dependencies.push({ from: chain[index - 1], to: chain[index], kind: 'depends_on', label: '阶段依赖' });
|
|
205
|
+
}
|
|
206
|
+
const artifacts = [];
|
|
207
|
+
for (const item of [...(run?.artifactHistory ?? []), ...(run?.validation ? [{ revision: run.revision, validation: run.validation }] : [])]) {
|
|
208
|
+
if (!artifacts.some(a => a.revision === `revision-${item.revision}` && a.digest === item.validation.artifactDigest))
|
|
209
|
+
artifacts.push({ revision: `revision-${item.revision}`, digest: item.validation.artifactDigest, artifacts: item.validation.artifacts.map(safeArtifact).filter(a => a !== undefined) });
|
|
210
|
+
}
|
|
211
|
+
const attempts = Object.values(ledger.attempts).filter(attempt => attempt.jobId === job.jobId)
|
|
212
|
+
.map(attempt => attemptView(attempt, source.runs.some(item => item.jobId === job.jobId && item.attemptId === attempt.attemptId)));
|
|
213
|
+
if (!run)
|
|
214
|
+
for (const attempt of attempts)
|
|
215
|
+
if (attempt.result?.artifactLinks.length)
|
|
216
|
+
artifacts.push({ revision: attempt.result.resultRevision ?? attempt.attemptId, digest: attempt.result.resultDigest, artifacts: attempt.result.artifactLinks });
|
|
217
|
+
const humanEvents = ownReviews.flatMap(review => review.history.map((decision, index) => ({ eventId: decision.decisionId, sourceId: ledger.sourceId, sequence: -(index + 1), jobId: review.jobId,
|
|
218
|
+
attemptId: review.attemptId, jobVersion: 0, type: `human_review.${decision.action}`, observedAt: decision.at,
|
|
219
|
+
data: { reviewId: review.reviewId, revision: review.revision, actor: decision.actor, ...(decision.note ? { note: decision.note } : {}) } })));
|
|
220
|
+
details[job.jobId] = { ...summaries.get(job.jobId), attempts, children, ancestors, progress: progress(job, run, source.reviews, ledger.attempts[job.currentAttemptId], source.now ?? Date.now()),
|
|
221
|
+
reviews: ownReviews.map(review => {
|
|
222
|
+
const ownerRun = source.runs.find(item => item.jobId === review.jobId && item.attemptId === review.attemptId);
|
|
223
|
+
const resumeError = review.resume?.status === 'pending' ? ownerRun?.diagnostics?.findLast(item => item.startsWith('Human continuation deferred:')) : undefined;
|
|
224
|
+
return { ...structuredClone(review), canReview: review.status === 'pending' && review.reviewerId === actorId && ledger.jobs[review.jobId]?.currentAttemptId === review.attemptId && !terminal.has(ledger.jobs[review.jobId].executionStatus)
|
|
225
|
+
&& !ownerRun?.cancellationRequestedAt && (!ownerRun || !terminal.has(ownerRun.executionStatus))
|
|
226
|
+
&& latestReview(source.reviews, ledger.jobs[review.jobId])?.reviewId === review.reviewId,
|
|
227
|
+
...(review.resume ? { resumeStatus: review.resume.status } : {}), ...(resumeError ? { resumeError: resumeError.slice('Human continuation deferred:'.length).trim() } : {}) };
|
|
228
|
+
}),
|
|
229
|
+
events: [...ledger.events.filter(event => event.jobId === job.jobId).map(eventView), ...humanEvents].sort((a, b) => a.observedAt.localeCompare(b.observedAt)), dependencies, artifacts };
|
|
230
|
+
}
|
|
231
|
+
for (const report of source.reportRuns ?? []) {
|
|
232
|
+
const detail = details[report.jobId], task = summaries.get(report.jobId);
|
|
233
|
+
if (!detail || !task || detail.currentAttemptId !== report.attemptId)
|
|
234
|
+
continue;
|
|
235
|
+
const pending = report.humanReviews.at(-1), author = report.child;
|
|
236
|
+
const stages = [
|
|
237
|
+
{ stage: 'research', name: '临时智能体分析', status: author ? ledger.attempts[author.attemptId]?.executionStatus ?? 'unknown' : 'not_started', planned: !author,
|
|
238
|
+
...(author ? { jobId: author.jobId, attemptId: author.attemptId } : {}) },
|
|
239
|
+
{ stage: 'file_check', name: '报告文件检查', status: report.fileCheck ? report.fileCheck.passed ? 'completed' : 'failed' : 'not_started', planned: !report.fileCheck },
|
|
240
|
+
{ stage: 'human_review', name: '人工最终确认', status: pending?.status ?? 'not_started', planned: !pending, jobId: report.jobId, attemptId: report.attemptId },
|
|
241
|
+
];
|
|
242
|
+
task.progressSummary = report.resultSummary ?? '临时智能体正在分析项目,输出报告后进行文件检查与人工最终确认。';
|
|
243
|
+
detail.progressSummary = task.progressSummary;
|
|
244
|
+
detail.progress = { stage: report.stage, phase: report.phase, stages,
|
|
245
|
+
completedStages: stages.filter(stage => ['completed', 'approved'].includes(stage.status)).map(stage => stage.name),
|
|
246
|
+
remainingStages: stages.filter(stage => !['completed', 'approved'].includes(stage.status)).map(stage => stage.name), updatedAt: report.updatedAt };
|
|
247
|
+
}
|
|
248
|
+
return structuredClone({ sourceId: ledger.sourceId, tasks: byNewest([...summaries.values()]), details });
|
|
249
|
+
}
|
|
250
|
+
export function listWorkbenchTasks(snapshot, query = {}) {
|
|
251
|
+
const filter = query.filter ?? 'all', offset = Math.max(0, Math.trunc(query.offset ?? 0)), limit = Math.min(200, Math.max(1, Math.trunc(query.limit ?? 50)));
|
|
252
|
+
const rootIds = new Set(snapshot.tasks.filter(task => !task.parentJobRef || !Object.hasOwn(snapshot.details, task.parentJobRef.jobId)).map(task => task.jobId));
|
|
253
|
+
const isWorking = (task) => task.displayStatus === 'resuming' || !task.pendingReviewId && ['working', 'submitted', 'not_started'].includes(task.executionStatus);
|
|
254
|
+
const isFailed = (task) => task.unresolvedAttemptIds.length > 0 || ['failed', 'rejected', 'unknown', 'auth_required', 'input_required'].includes(task.executionStatus) && !['awaiting_human', 'resuming'].includes(task.displayStatus);
|
|
255
|
+
const roots = snapshot.tasks.filter(task => rootIds.has(task.jobId));
|
|
256
|
+
const counts = { all: roots.length, pending: roots.filter(task => Boolean(task.pendingReviewId)).length, working: roots.filter(isWorking).length, failed: roots.filter(isFailed).length };
|
|
257
|
+
const matches = snapshot.tasks.filter(task => filter === 'all' ? true : filter === 'pending' ? Boolean(task.pendingReviewId) : filter === 'working' ? isWorking(task) : isFailed(task));
|
|
258
|
+
return { items: structuredClone(matches.slice(offset, offset + limit)), total: matches.length, counts, offset, limit };
|
|
259
|
+
}
|
|
260
|
+
export function getWorkbenchTask(snapshot, jobId) {
|
|
261
|
+
const detail = Object.hasOwn(snapshot.details, jobId) ? snapshot.details[jobId] : undefined;
|
|
262
|
+
if (!detail)
|
|
263
|
+
throw new Error('Task not found in authorized scope');
|
|
264
|
+
return structuredClone(detail);
|
|
265
|
+
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -10,3 +10,7 @@ export type { ServerOptions } from './server.js';
|
|
|
10
10
|
export { attachBridgeServer, activeSessions, sessionBackgroundTasks, killAllManagedAgents } from './bridge.js';
|
|
11
11
|
export { discoverAgents } from './catalog.js';
|
|
12
12
|
export type { AgentStatus, DiscoveryOptions } from './catalog.js';
|
|
13
|
+
export { CapacityGovernor, CapacityError } from './capacity.js';
|
|
14
|
+
export type { CapacityOptions, CapacityLease, CapacitySnapshot } from './capacity.js';
|
|
15
|
+
export { createCapacityLifecycle } from './capacity-lifecycle.js';
|
|
16
|
+
export { CapacityQueue } from './capacity-queue.js';
|
package/dist/src/index.js
CHANGED
|
@@ -7,3 +7,6 @@ export { buildManifest, ACP_CAPABILITIES, DEFAULT_ACP_PORT } from './manifest.js
|
|
|
7
7
|
export { createAcpServer, serveAcpService } from './server.js';
|
|
8
8
|
export { attachBridgeServer, activeSessions, sessionBackgroundTasks, killAllManagedAgents } from './bridge.js';
|
|
9
9
|
export { discoverAgents } from './catalog.js';
|
|
10
|
+
export { CapacityGovernor, CapacityError } from './capacity.js';
|
|
11
|
+
export { createCapacityLifecycle } from './capacity-lifecycle.js';
|
|
12
|
+
export { CapacityQueue } from './capacity-queue.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { resolveRoleSkills, roleSkillProfileSchema, roleSkillLockSchema, skillContentRevision, type RoleSkillProfile, type RoleSkillLock } from './skills.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { resolveRoleSkills, roleSkillProfileSchema, roleSkillLockSchema, skillContentRevision } from './skills.js';
|