pi-web-ui 0.114.2 → 0.115.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/CHANGELOG.md +55 -1
- package/bin/pi-web-ui.mjs +69 -7
- package/dist/server/agent-service-daemon.js +440 -32
- package/dist/server/agent-service.js +878 -383
- package/dist/server/canvas/canvas-dispatch.js +13 -1
- package/dist/server/client-state.js +25 -0
- package/dist/server/communicate-tool.js +2 -0
- package/dist/server/context-usage.js +105 -0
- package/dist/server/conversation-communication.js +14 -0
- package/dist/server/conversation-identity.js +27 -0
- package/dist/server/device-center/approval-summary.js +31 -0
- package/dist/server/device-center/bot-catalog.js +21 -7
- package/dist/server/device-center/bot-execution.js +72 -9
- package/dist/server/device-center/bot-presets.js +46 -0
- package/dist/server/device-center/collab-service.js +328 -10
- package/dist/server/device-center/collab-tool.js +738 -12
- package/dist/server/device-center/connector.js +359 -23
- package/dist/server/device-center/desktop-page.js +22 -16
- package/dist/server/device-center/device-integration.js +595 -0
- package/dist/server/device-center/execution-guides.js +32 -0
- package/dist/server/device-center/execution-instructions.js +19 -0
- package/dist/server/device-center/execution-settings.js +100 -0
- package/dist/server/device-center/execution-system-prompt.js +38 -0
- package/dist/server/device-center/execution-workspace.js +20 -0
- package/dist/server/device-center/executor.js +389 -40
- package/dist/server/device-center/file-sync-paths.js +171 -0
- package/dist/server/device-center/file-sync.js +180 -91
- package/dist/server/device-center/group-context-delta.js +37 -0
- package/dist/server/device-center/group-context-message.js +208 -0
- package/dist/server/device-center/group-context.js +109 -0
- package/dist/server/device-center/group-events.js +136 -0
- package/dist/server/device-center/group-plan-guard.js +138 -0
- package/dist/server/device-center/hub-conversations.js +178 -0
- package/dist/server/device-center/hub-deliveries.js +277 -0
- package/dist/server/device-center/hub-integration.js +451 -0
- package/dist/server/device-center/hub.js +1544 -80
- package/dist/server/device-center/human-interaction.js +232 -0
- package/dist/server/device-center/integration-errors.js +25 -0
- package/dist/server/device-center/local-hub.js +18 -0
- package/dist/server/device-center/local.js +356 -40
- package/dist/server/device-center/main.js +11 -1
- package/dist/server/device-center/path-portal.js +11 -3
- package/dist/server/device-center/relay.js +364 -35
- package/dist/server/device-center/report-metadata.js +66 -0
- package/dist/server/device-center/report-upload.js +63 -0
- package/dist/server/device-center/runtime.js +549 -41
- package/dist/server/device-center/store.js +66 -3
- package/dist/server/device-center/task-context-budget.js +161 -0
- package/dist/server/device-center/task-journal.js +385 -0
- package/dist/server/device-center/task-plan.js +33 -0
- package/dist/server/device-center/task-progress.js +141 -0
- package/dist/server/device-center/task-recovery.js +452 -0
- package/dist/server/device-center/task-report-outbox.js +216 -0
- package/dist/server/device-center/task-report.js +384 -0
- package/dist/server/device-center/task-scheduler.js +400 -0
- package/dist/server/device-center/task-state.js +333 -0
- package/dist/server/device-center/transfer-stream.js +1006 -0
- package/dist/server/device-center/transfers.js +815 -8
- package/dist/server/dispatch-domain-handlers.js +21 -3
- package/dist/server/dsh/dsh-agent-service.js +6 -0
- package/dist/server/goal-service.js +10 -5
- package/dist/server/index.js +89 -13
- package/dist/server/message-deletion.js +40 -0
- package/dist/server/message-window.js +9 -0
- package/dist/server/patch-executable-lookup.js +396 -0
- package/dist/server/payload-limits.js +2 -0
- package/dist/server/plugin-llm.js +100 -9
- package/dist/server/plugins.js +1 -0
- package/dist/server/preset-fields.js +24 -0
- package/dist/server/preset-share.js +2 -0
- package/dist/server/prompt-base-store.js +85 -0
- package/dist/server/prompt-composer.js +5 -2
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/protocol.js +2 -2
- package/dist/server/remote-ssh-service.js +22 -9
- package/dist/server/resolve-global-sdk.js +2 -0
- package/dist/server/session-search.js +1 -1
- package/dist/server/settings-service.js +90 -39
- package/dist/server/skill-content-filler.js +29 -8
- package/dist/server/skill-tool.js +12 -3
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagents.js +50 -36
- package/dist/server/tool-host-factories.js +1 -0
- package/dist/server/universal/universal-session.js +5 -0
- package/dist/server/webui-context.js +25 -5
- package/docs/README.md +94 -0
- package/docs/device-center.md +100 -12
- package/docs/dsh-engine.md +10 -10
- package/extensions/webui.ts +43 -1
- package/package.json +1 -1
- package/themes/aetheris.css +5 -0
- package/themes/ayu-light.css +6 -0
- package/themes/bases/flow-base.css +68 -68
- package/themes/catppuccin-latte.css +6 -0
- package/themes/catppuccin.css +6 -0
- package/themes/claude-code-dark.css +5 -0
- package/themes/codex.css +6 -0
- package/themes/cyberpunk.css +6 -0
- package/themes/dark-teal.css +6 -1
- package/themes/dazzle.css +6 -0
- package/themes/everforest-light.css +6 -0
- package/themes/flow-light.css +8 -1
- package/themes/flow.css +6 -1
- package/themes/geist.css +6 -0
- package/themes/gruvbox-light.css +6 -0
- package/themes/kanagawa-lotus.css +6 -0
- package/themes/md-preview.css +6 -0
- package/themes/mist.css +6 -0
- package/themes/nord.css +6 -0
- package/themes/one-dark.css +6 -0
- package/themes/paper.css +6 -0
- package/themes/rose-pine-dawn.css +6 -0
- package/themes/sakura.css +6 -0
- package/themes/solarized-light.css +6 -0
- package/themes/tokyo-night.css +6 -0
- package/themes/translucent.css +6 -0
- package/themes/transparent.css +6 -0
- package/themes/vs-code-dark.css +5 -0
- package/themes/wallpaper-flow.css +5 -1
- package/themes/wallpaper-obsidian.css +6 -0
- package/themes/white.css +6 -0
- package/themes/zhujian-dark.css +6 -1
- package/themes/zhujian.css +6 -1
- package/themes/zhupi-dark.css +6 -1
- package/themes/zhupi.css +6 -1
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/BgTasksModal-BYzPgmoq.js +1 -0
- package/web/dist/assets/BgTasksModal-ni0VTmAQ.js +1 -0
- package/web/dist/assets/{CanvasStudio-B3W6b_rA.js → CanvasStudio-BCUeEf25.js} +3 -3
- package/web/dist/assets/{CanvasStudio-Csv1Sj1-.js → CanvasStudio-DNmDNBod.js} +3 -3
- package/web/dist/assets/DeviceCenter-BcBhRgL6.js +3 -0
- package/web/dist/assets/DeviceCenter-CmL5FZmt.js +3 -0
- package/web/dist/assets/DeviceGroups-CLdpdnI7.js +1 -0
- package/web/dist/assets/DeviceGroups-CgBaDPrD.js +1 -0
- package/web/dist/assets/Dropdown-CGXD0DfT.js +1 -0
- package/web/dist/assets/FilePreview-B8iqnBjy.js +2 -0
- package/web/dist/assets/FilePreview-BqviZKCN.js +2 -0
- package/web/dist/assets/GlobalSearchModal-mevF-ySi.js +1 -0
- package/web/dist/assets/GlobalSearchModal-qL99FN_F.js +1 -0
- package/web/dist/assets/GroupConversation-B88Yy-lt.js +3 -0
- package/web/dist/assets/GroupConversation-BwP5NVOE.js +3 -0
- package/web/dist/assets/HintTip-LHwkS2jV.js +1 -0
- package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +2 -0
- package/web/dist/assets/PiSetupModal-DE5-gEtI.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-6UMARucA.js +1 -0
- package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +2 -0
- package/web/dist/assets/SCMPanel-ezY_ZtCu.js +2 -0
- package/web/dist/assets/SettingsModal-6HgeEsJ8.js +20 -0
- package/web/dist/assets/SettingsModal-CF-7MwqS.js +20 -0
- package/web/dist/assets/TerminalPanel-CTp_BZ4S.js +3 -0
- package/web/dist/assets/TerminalPanel-CkYxC-Gh.js +3 -0
- package/web/dist/assets/TuiOverlayModal-1cRLP8IF.js +1 -0
- package/web/dist/assets/TuiOverlayModal-2xlptqWX.js +1 -0
- package/web/dist/assets/app-globals-DZNa9v8u.js +325 -0
- package/web/dist/assets/canvas-client-Bye9nSFO.js +1 -0
- package/web/dist/assets/{desktop-YguLbrX1.js → desktop-kjBoE3Nu.js} +1 -1
- package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
- package/web/dist/assets/index-CsFs_HMb.css +1 -0
- package/web/dist/assets/index-DHeeHS_l.js +85 -0
- package/web/dist/assets/index-DTZch8uz.js +85 -0
- package/web/dist/assets/plugin-host-C8mNgghx.js +1 -0
- package/web/dist/assets/remote-ssh-client-CeP3CLUW.js +1 -0
- package/web/dist/assets/theme-BXGpyTMh.js +1 -0
- package/web/dist/index.html +10 -9
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/BgTasksModal-BIlQ89vr.js +0 -1
- package/web/dist/assets/BgTasksModal-Ck2sjlPM.js +0 -1
- package/web/dist/assets/DeviceCenter-BQdDcO8A.js +0 -3
- package/web/dist/assets/DeviceCenter-CHRKL0Vy.js +0 -3
- package/web/dist/assets/DeviceGroups-D2rogxEN.js +0 -1
- package/web/dist/assets/Dropdown-ZLS04O8p.js +0 -1
- package/web/dist/assets/FilePreview-B9xoU6ON.js +0 -2
- package/web/dist/assets/FilePreview-DUQpVZkH.js +0 -2
- package/web/dist/assets/GlobalSearchModal-BXEGvUZq.js +0 -1
- package/web/dist/assets/GlobalSearchModal-CnVPmfOI.js +0 -1
- package/web/dist/assets/GroupConversation-CyIpQzDd.js +0 -1
- package/web/dist/assets/GroupConversation-DgYV3uYS.js +0 -1
- package/web/dist/assets/ModelConfigModal-DDZccDYt.js +0 -2
- package/web/dist/assets/PiSetupModal-DHbqfx8T.js +0 -1
- package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +0 -1
- package/web/dist/assets/SCMPanel-imYI2Ecw.js +0 -2
- package/web/dist/assets/SCMPanel-sVZcV7dR.js +0 -2
- package/web/dist/assets/SettingsModal-Xw1Yoi3_.js +0 -20
- package/web/dist/assets/SettingsModal-mb4e34-0.js +0 -20
- package/web/dist/assets/TerminalPanel-CLkJJvxg.js +0 -3
- package/web/dist/assets/TerminalPanel-DpcIellm.js +0 -3
- package/web/dist/assets/TuiOverlayModal-4-fFAZe7.js +0 -1
- package/web/dist/assets/TuiOverlayModal-DCu01lks.js +0 -1
- package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
- package/web/dist/assets/fi-DaSO0Q-m.js +0 -325
- package/web/dist/assets/index-Cdh3sibd.js +0 -85
- package/web/dist/assets/index-DDZMv6LO.css +0 -1
- package/web/dist/assets/index-DWw_SxRq.js +0 -85
- package/web/dist/assets/plugin-host-BRBg6zmQ.js +0 -1
- package/web/dist/assets/theme-DDl-Oy1b.js +0 -1
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { mkdir, readFile, open, rename, unlink } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
|
|
4
|
+
import { projectConversationState, reconcileConversationState, } from "./task-state.js";
|
|
5
|
+
export const taskPending = (task) => !isTerminal(task.status) || !!(task.cancelRequested && !task.stopConfirmed);
|
|
4
6
|
export const isTerminal = (status) => ["completed", "failed", "interrupted"].includes(status);
|
|
5
7
|
export const hashSecret = (secret) => createHash("sha256").update(secret).digest("hex");
|
|
6
8
|
export function secretMatches(secret, hash) {
|
|
@@ -12,9 +14,20 @@ export function publicDevice(device) {
|
|
|
12
14
|
const { credentialHash: _hash, uiCredentialHash: _uiHash, ...visible } = device;
|
|
13
15
|
return visible;
|
|
14
16
|
}
|
|
17
|
+
export function publicTask(task) {
|
|
18
|
+
const { leaseToken: _token, ...visible } = task;
|
|
19
|
+
return visible;
|
|
20
|
+
}
|
|
15
21
|
/** A single process owns a data directory. Transactions publish only after atomic replacement. */
|
|
16
22
|
export class DeviceHubStore {
|
|
17
23
|
state;
|
|
24
|
+
listeners = new Set();
|
|
25
|
+
subscribe(listener) {
|
|
26
|
+
this.listeners.add(listener);
|
|
27
|
+
return () => {
|
|
28
|
+
this.listeners.delete(listener);
|
|
29
|
+
};
|
|
30
|
+
}
|
|
18
31
|
tail = Promise.resolve();
|
|
19
32
|
path;
|
|
20
33
|
constructor(dataDir, state) {
|
|
@@ -45,6 +58,12 @@ export class DeviceHubStore {
|
|
|
45
58
|
throw error;
|
|
46
59
|
state = {
|
|
47
60
|
version: 2,
|
|
61
|
+
conversations: [],
|
|
62
|
+
conversationMessages: [],
|
|
63
|
+
deliveries: [],
|
|
64
|
+
reviews: [],
|
|
65
|
+
deliveryReceipts: [],
|
|
66
|
+
integrations: [],
|
|
48
67
|
accounts: [],
|
|
49
68
|
devices: [],
|
|
50
69
|
bots: [],
|
|
@@ -55,13 +74,40 @@ export class DeviceHubStore {
|
|
|
55
74
|
receipts: [],
|
|
56
75
|
};
|
|
57
76
|
}
|
|
77
|
+
state.conversations ??= [];
|
|
78
|
+
state.conversationMessages ??= [];
|
|
79
|
+
state.deliveries ??= [];
|
|
80
|
+
state.reviews ??= [];
|
|
81
|
+
state.deliveryReceipts ??= [];
|
|
82
|
+
state.integrations ??= [];
|
|
83
|
+
if (![
|
|
84
|
+
state.conversations,
|
|
85
|
+
state.conversationMessages,
|
|
86
|
+
state.deliveries,
|
|
87
|
+
state.reviews,
|
|
88
|
+
state.deliveryReceipts,
|
|
89
|
+
state.integrations,
|
|
90
|
+
].every(Array.isArray))
|
|
91
|
+
throw new Error("Invalid conversation store");
|
|
92
|
+
// Legacy state is a baseline, not evidence that historical transitions were observed.
|
|
93
|
+
for (const conversation of state.conversations) {
|
|
94
|
+
conversation.taskState = projectConversationState(state, conversation);
|
|
95
|
+
conversation.events ??= [];
|
|
96
|
+
}
|
|
58
97
|
const store = new DeviceHubStore(dataDir, state);
|
|
59
|
-
if (state.tasks.some((task) => task.status
|
|
98
|
+
if (state.tasks.some((task) => !isTerminal(task.status))) {
|
|
99
|
+
const now = Date.now();
|
|
100
|
+
const recoveryGraceMs = 60_000;
|
|
60
101
|
await store.transact((draft) => {
|
|
61
102
|
for (const task of draft.tasks)
|
|
62
|
-
if (task.status
|
|
103
|
+
if (!isTerminal(task.status)) {
|
|
63
104
|
task.status = "interrupted";
|
|
64
|
-
task.
|
|
105
|
+
task.report = "Hub restarted before execution was confirmed; submit a new turn to retry.";
|
|
106
|
+
task.updatedAt = now;
|
|
107
|
+
if (task.leaseToken) {
|
|
108
|
+
// Retain recovery grace window for active leases to claim on reconnect!
|
|
109
|
+
task.recoveryUntil = now + recoveryGraceMs;
|
|
110
|
+
}
|
|
65
111
|
}
|
|
66
112
|
});
|
|
67
113
|
}
|
|
@@ -88,8 +134,25 @@ export class DeviceHubStore {
|
|
|
88
134
|
const operation = this.tail.then(async () => {
|
|
89
135
|
const draft = structuredClone(this.state);
|
|
90
136
|
const result = update(draft);
|
|
137
|
+
if (result && (typeof result === "object" || typeof result === "function") && "then" in result) {
|
|
138
|
+
// Transactions only reserve/commit state. External work runs between transactions.
|
|
139
|
+
// Drain a rejected accidental async callback without publishing its detached draft.
|
|
140
|
+
void Promise.resolve(result).catch(() => { });
|
|
141
|
+
throw new Error("Hub transactions require a synchronous update");
|
|
142
|
+
}
|
|
143
|
+
if (typeof reconcileConversationState === "function") {
|
|
144
|
+
reconcileConversationState(this.state, draft);
|
|
145
|
+
}
|
|
91
146
|
await this.persist(draft);
|
|
92
147
|
this.state = draft;
|
|
148
|
+
for (const listener of this.listeners) {
|
|
149
|
+
try {
|
|
150
|
+
listener();
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
/* notification cannot roll back a committed transaction */
|
|
154
|
+
}
|
|
155
|
+
}
|
|
93
156
|
return structuredClone(result);
|
|
94
157
|
});
|
|
95
158
|
this.tail = operation.catch(() => { });
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/** Select optional reference data only. Current task text, handoff and runtime state never pass through here. */
|
|
2
|
+
export function selectTaskContext(source, budget = 12 * 1024) {
|
|
3
|
+
if (!Number.isSafeInteger(budget) || budget < 0)
|
|
4
|
+
throw new RangeError("Task context budget must be a nonnegative safe integer");
|
|
5
|
+
const state = {
|
|
6
|
+
revision: source.revision,
|
|
7
|
+
objective: source.objective,
|
|
8
|
+
currentTaskId: source.currentTaskId,
|
|
9
|
+
phase: source.phase,
|
|
10
|
+
...(source.blocker
|
|
11
|
+
? {
|
|
12
|
+
blocker: {
|
|
13
|
+
attentionId: source.blocker.attentionId,
|
|
14
|
+
taskId: source.blocker.taskId,
|
|
15
|
+
question: source.blocker.question,
|
|
16
|
+
},
|
|
17
|
+
}
|
|
18
|
+
: {}),
|
|
19
|
+
decisions: [],
|
|
20
|
+
artifacts: [],
|
|
21
|
+
};
|
|
22
|
+
const selection = {
|
|
23
|
+
budgetBytes: budget,
|
|
24
|
+
bytes: 0,
|
|
25
|
+
overflow: 0,
|
|
26
|
+
omitted: {
|
|
27
|
+
decisions: source.decisions.length,
|
|
28
|
+
artifacts: source.artifacts.length,
|
|
29
|
+
latestRequest: Number(!!source.latestRequest),
|
|
30
|
+
lastOutcome: Number(!!source.lastOutcome),
|
|
31
|
+
reported: Number(!!source.reported),
|
|
32
|
+
reportedConstraints: source.reported?.constraints.length ?? 0,
|
|
33
|
+
reportedProgress: Number(!!source.reported?.progress),
|
|
34
|
+
reportedBlockers: source.reported?.blockers.length ?? 0,
|
|
35
|
+
reportedNextSteps: source.reported?.nextSteps.length ?? 0,
|
|
36
|
+
},
|
|
37
|
+
textTruncated: {
|
|
38
|
+
objective: false,
|
|
39
|
+
blocker: false,
|
|
40
|
+
decisionQuestions: source.decisions.filter((d) => d.questionTruncated).length,
|
|
41
|
+
decisionAnswers: source.decisions.filter((d) => d.answerTruncated).length,
|
|
42
|
+
},
|
|
43
|
+
lookup: "Optional reference snapshot. Use device_collab task_state for full canonical state, omitted constraints/decisions and current revision before acting.",
|
|
44
|
+
};
|
|
45
|
+
const measure = () => {
|
|
46
|
+
// bytes counts itself, so settle its decimal width before comparing the budget.
|
|
47
|
+
let bytes;
|
|
48
|
+
do {
|
|
49
|
+
bytes = selection.bytes;
|
|
50
|
+
selection.bytes = Buffer.byteLength(JSON.stringify({ taskState: state, taskStateSelection: selection }), "utf8");
|
|
51
|
+
} while (bytes !== selection.bytes);
|
|
52
|
+
};
|
|
53
|
+
measure();
|
|
54
|
+
if (selection.bytes > budget) {
|
|
55
|
+
selection.overflow = 1;
|
|
56
|
+
measure();
|
|
57
|
+
return { state, selection };
|
|
58
|
+
}
|
|
59
|
+
const admit = (apply, undo) => {
|
|
60
|
+
apply();
|
|
61
|
+
measure();
|
|
62
|
+
if (selection.bytes <= budget)
|
|
63
|
+
return true;
|
|
64
|
+
undo();
|
|
65
|
+
measure();
|
|
66
|
+
return false;
|
|
67
|
+
};
|
|
68
|
+
// Newest human decisions first; each question/answer pair is indivisible.
|
|
69
|
+
for (const d of [...source.decisions].reverse()) {
|
|
70
|
+
const decision = {
|
|
71
|
+
attentionId: d.attentionId,
|
|
72
|
+
messageId: d.messageId,
|
|
73
|
+
taskId: d.taskId,
|
|
74
|
+
...(d.question !== undefined ? { question: d.question } : {}),
|
|
75
|
+
...(d.answer !== undefined ? { answer: d.answer } : {}),
|
|
76
|
+
...(d.questionTruncated !== undefined ? { questionTruncated: d.questionTruncated } : {}),
|
|
77
|
+
...(d.answerTruncated !== undefined ? { answerTruncated: d.answerTruncated } : {}),
|
|
78
|
+
};
|
|
79
|
+
admit(() => {
|
|
80
|
+
state.decisions.unshift(decision);
|
|
81
|
+
selection.omitted.decisions--;
|
|
82
|
+
}, () => {
|
|
83
|
+
state.decisions.shift();
|
|
84
|
+
selection.omitted.decisions++;
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
const report = source.reported;
|
|
88
|
+
if (report) {
|
|
89
|
+
const included = admit(() => {
|
|
90
|
+
state.reported = {
|
|
91
|
+
taskId: report.taskId,
|
|
92
|
+
botId: report.botId,
|
|
93
|
+
updatedAt: report.updatedAt,
|
|
94
|
+
provenance: report.provenance,
|
|
95
|
+
constraints: [],
|
|
96
|
+
progress: "",
|
|
97
|
+
blockers: [],
|
|
98
|
+
nextSteps: [],
|
|
99
|
+
};
|
|
100
|
+
selection.omitted.reported--;
|
|
101
|
+
}, () => {
|
|
102
|
+
delete state.reported;
|
|
103
|
+
selection.omitted.reported++;
|
|
104
|
+
});
|
|
105
|
+
if (included) {
|
|
106
|
+
const selected = state.reported;
|
|
107
|
+
for (const key of ["constraints", "blockers", "nextSteps"]) {
|
|
108
|
+
const count = {
|
|
109
|
+
constraints: "reportedConstraints",
|
|
110
|
+
blockers: "reportedBlockers",
|
|
111
|
+
nextSteps: "reportedNextSteps",
|
|
112
|
+
}[key];
|
|
113
|
+
for (const text of report[key])
|
|
114
|
+
admit(() => {
|
|
115
|
+
selected[key].push(text);
|
|
116
|
+
selection.omitted[count]--;
|
|
117
|
+
}, () => {
|
|
118
|
+
selected[key].pop();
|
|
119
|
+
selection.omitted[count]++;
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
if (report.progress)
|
|
123
|
+
admit(() => {
|
|
124
|
+
selected.progress = report.progress;
|
|
125
|
+
selection.omitted.reportedProgress--;
|
|
126
|
+
}, () => {
|
|
127
|
+
selected.progress = "";
|
|
128
|
+
selection.omitted.reportedProgress++;
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (source.latestRequest) {
|
|
133
|
+
const { taskId, sourceId, text } = source.latestRequest;
|
|
134
|
+
admit(() => {
|
|
135
|
+
state.latestRequest = { taskId, sourceId, text };
|
|
136
|
+
selection.omitted.latestRequest--;
|
|
137
|
+
}, () => {
|
|
138
|
+
delete state.latestRequest;
|
|
139
|
+
selection.omitted.latestRequest++;
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
if (source.lastOutcome) {
|
|
143
|
+
const { taskId, status, text } = source.lastOutcome;
|
|
144
|
+
admit(() => {
|
|
145
|
+
state.lastOutcome = { taskId, status, ...(text !== undefined ? { text } : {}) };
|
|
146
|
+
selection.omitted.lastOutcome--;
|
|
147
|
+
}, () => {
|
|
148
|
+
delete state.lastOutcome;
|
|
149
|
+
selection.omitted.lastOutcome++;
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
for (const { deliveryId, taskId } of source.artifacts)
|
|
153
|
+
admit(() => {
|
|
154
|
+
state.artifacts.push({ deliveryId, taskId });
|
|
155
|
+
selection.omitted.artifacts--;
|
|
156
|
+
}, () => {
|
|
157
|
+
state.artifacts.pop();
|
|
158
|
+
selection.omitted.artifacts++;
|
|
159
|
+
});
|
|
160
|
+
return { state, selection };
|
|
161
|
+
}
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import { mkdir, readFile, readdir, unlink, appendFile, writeFile, stat } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
import { sanitizeTextForJournal, sanitizeToolParameters } from "./task-progress.js";
|
|
5
|
+
export const MAX_JOURNAL_SEGMENT_ENTRIES = 50;
|
|
6
|
+
export const MAX_JOURNAL_SEGMENT_BYTES = 64 * 1024; // 64 KiB
|
|
7
|
+
export const MAX_JOURNAL_RETAINED_SEGMENTS = 20; // 20 segments * 50 entries = up to 1000 events
|
|
8
|
+
function sha256Hex(data) {
|
|
9
|
+
return createHash("sha256").update(data).digest("hex");
|
|
10
|
+
}
|
|
11
|
+
function safeTaskDirName(taskId) {
|
|
12
|
+
if (!taskId || typeof taskId !== "string")
|
|
13
|
+
throw new Error("Invalid taskId");
|
|
14
|
+
return sha256Hex(taskId).slice(0, 32);
|
|
15
|
+
}
|
|
16
|
+
export function encodeJournalCursor(taskId, attemptId, sequence) {
|
|
17
|
+
const raw = JSON.stringify({ taskId, attemptId, sequence });
|
|
18
|
+
return Buffer.from(raw, "utf8").toString("base64url");
|
|
19
|
+
}
|
|
20
|
+
export function decodeJournalCursor(cursorStr) {
|
|
21
|
+
try {
|
|
22
|
+
const raw = Buffer.from(cursorStr, "base64url").toString("utf8");
|
|
23
|
+
const obj = JSON.parse(raw);
|
|
24
|
+
if (typeof obj.taskId === "string" &&
|
|
25
|
+
typeof obj.attemptId === "string" &&
|
|
26
|
+
typeof obj.sequence === "number" &&
|
|
27
|
+
Number.isSafeInteger(obj.sequence) &&
|
|
28
|
+
obj.sequence >= 0) {
|
|
29
|
+
return { taskId: obj.taskId, attemptId: obj.attemptId, sequence: obj.sequence };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
// invalid cursor
|
|
34
|
+
}
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
async function writeAtomicAsync(filePath, content) {
|
|
38
|
+
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${randomUUID().slice(0, 8)}.tmp`;
|
|
39
|
+
await writeFile(tmpPath, content, "utf8");
|
|
40
|
+
try {
|
|
41
|
+
const { rename } = await import("node:fs/promises");
|
|
42
|
+
await rename(tmpPath, filePath);
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
await unlink(tmpPath).catch(() => { });
|
|
46
|
+
throw err;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export function createTaskJournalManager(baseDir) {
|
|
50
|
+
const rootDir = join(baseDir, "task-journals");
|
|
51
|
+
let closed = false;
|
|
52
|
+
// In-memory active task state cache to avoid repeated disk reads on progress loops
|
|
53
|
+
const activeTasks = new Map();
|
|
54
|
+
// Asynchronous serialization tail Promise per task
|
|
55
|
+
const taskLocks = new Map();
|
|
56
|
+
function taskDir(taskId) {
|
|
57
|
+
return join(rootDir, safeTaskDirName(taskId));
|
|
58
|
+
}
|
|
59
|
+
function segmentFileName(index) {
|
|
60
|
+
return `segment-${String(index).padStart(6, "0")}.jsonl`;
|
|
61
|
+
}
|
|
62
|
+
async function loadMetaFromDisk(dir) {
|
|
63
|
+
const metaPath = join(dir, "meta.json");
|
|
64
|
+
try {
|
|
65
|
+
const data = await readFile(metaPath, "utf8");
|
|
66
|
+
return JSON.parse(data);
|
|
67
|
+
}
|
|
68
|
+
catch (cause) {
|
|
69
|
+
if (cause?.code === "ENOENT")
|
|
70
|
+
return null;
|
|
71
|
+
throw new Error("Task journal metadata is corrupted: " + String(cause));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
async function getOrInitTaskState(taskId, context) {
|
|
75
|
+
const cached = activeTasks.get(taskId);
|
|
76
|
+
if (cached)
|
|
77
|
+
return cached;
|
|
78
|
+
const dir = taskDir(taskId);
|
|
79
|
+
let meta = await loadMetaFromDisk(dir);
|
|
80
|
+
if (!meta) {
|
|
81
|
+
if (!context)
|
|
82
|
+
throw new Error("Missing initial context to initialize task journal");
|
|
83
|
+
const now = Date.now();
|
|
84
|
+
meta = {
|
|
85
|
+
taskId,
|
|
86
|
+
roomId: context.roomId,
|
|
87
|
+
accountId: context.accountId,
|
|
88
|
+
botId: context.botId,
|
|
89
|
+
attemptId: context.attemptId,
|
|
90
|
+
createdAt: now,
|
|
91
|
+
updatedAt: now,
|
|
92
|
+
totalEvents: 0,
|
|
93
|
+
nextSequence: 1,
|
|
94
|
+
segmentCount: 1,
|
|
95
|
+
activeSegmentIndex: 0,
|
|
96
|
+
minRetainedSequence: 1,
|
|
97
|
+
truncated: false,
|
|
98
|
+
droppedCount: 0,
|
|
99
|
+
journalRef: safeTaskDirName(taskId),
|
|
100
|
+
};
|
|
101
|
+
await mkdir(dir, { recursive: true });
|
|
102
|
+
await writeAtomicAsync(join(dir, "meta.json"), JSON.stringify(meta, null, 2));
|
|
103
|
+
}
|
|
104
|
+
// Stat current active segment to track bytes and lines without full read
|
|
105
|
+
const segPath = join(dir, segmentFileName(meta.activeSegmentIndex));
|
|
106
|
+
let bytes = 0;
|
|
107
|
+
let lines = 0;
|
|
108
|
+
try {
|
|
109
|
+
const s = await stat(segPath);
|
|
110
|
+
bytes = s.size;
|
|
111
|
+
const content = await readFile(segPath, "utf8");
|
|
112
|
+
lines = content.split("\n").filter((l) => l.trim().length > 0).length;
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
// Segment does not exist yet
|
|
116
|
+
}
|
|
117
|
+
const state = {
|
|
118
|
+
meta,
|
|
119
|
+
currentSegBytes: bytes,
|
|
120
|
+
currentSegLines: lines,
|
|
121
|
+
};
|
|
122
|
+
activeTasks.set(taskId, state);
|
|
123
|
+
return state;
|
|
124
|
+
}
|
|
125
|
+
function sanitizeMetadata(input) {
|
|
126
|
+
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
127
|
+
return;
|
|
128
|
+
const result = {};
|
|
129
|
+
for (const [k, v] of Object.entries(input)) {
|
|
130
|
+
if (/^[A-Za-z0-9_-]{1,64}$/.test(k)) {
|
|
131
|
+
if (typeof v === "string") {
|
|
132
|
+
result[k] = sanitizeTextForJournal(v).slice(0, 256);
|
|
133
|
+
}
|
|
134
|
+
else if (typeof v === "number" && Number.isFinite(v)) {
|
|
135
|
+
result[k] = v;
|
|
136
|
+
}
|
|
137
|
+
else if (typeof v === "boolean") {
|
|
138
|
+
result[k] = v;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return Object.keys(result).length > 0 ? result : undefined;
|
|
143
|
+
}
|
|
144
|
+
function withTaskQueue(taskId, fn) {
|
|
145
|
+
const tail = taskLocks.get(taskId) ?? Promise.resolve();
|
|
146
|
+
const next = tail.then(fn, fn);
|
|
147
|
+
taskLocks.set(taskId, next);
|
|
148
|
+
next.finally(() => {
|
|
149
|
+
if (taskLocks.get(taskId) === next)
|
|
150
|
+
taskLocks.delete(taskId);
|
|
151
|
+
});
|
|
152
|
+
return next;
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
async append(taskId, entryInput, context) {
|
|
156
|
+
if (closed) {
|
|
157
|
+
throw new Error("Task journal manager is closed");
|
|
158
|
+
}
|
|
159
|
+
if (!taskId || !context?.roomId || !context?.accountId) {
|
|
160
|
+
throw new Error("Missing required binding context for journal append");
|
|
161
|
+
}
|
|
162
|
+
return withTaskQueue(taskId, async () => {
|
|
163
|
+
const dir = taskDir(taskId);
|
|
164
|
+
const taskState = await getOrInitTaskState(taskId, {
|
|
165
|
+
roomId: context.roomId,
|
|
166
|
+
accountId: context.accountId,
|
|
167
|
+
botId: entryInput.botId,
|
|
168
|
+
attemptId: entryInput.attemptId,
|
|
169
|
+
});
|
|
170
|
+
const meta = taskState.meta;
|
|
171
|
+
if (meta.accountId !== context.accountId || meta.roomId !== context.roomId) {
|
|
172
|
+
throw new Error("Account or room mismatch for existing task journal");
|
|
173
|
+
}
|
|
174
|
+
const seq = meta.nextSequence++;
|
|
175
|
+
const now = Date.now();
|
|
176
|
+
const timestamp = entryInput.timestamp || now;
|
|
177
|
+
const id = `${taskId}-${seq}`;
|
|
178
|
+
// Sanitize output, summary, reason, parameters
|
|
179
|
+
let sanitizedOutput;
|
|
180
|
+
if (typeof entryInput.output === "string") {
|
|
181
|
+
sanitizedOutput = sanitizeTextForJournal(entryInput.output).slice(0, 2048);
|
|
182
|
+
}
|
|
183
|
+
let sanitizedSummary;
|
|
184
|
+
if (typeof entryInput.summary === "string") {
|
|
185
|
+
sanitizedSummary = sanitizeTextForJournal(entryInput.summary).slice(0, 512);
|
|
186
|
+
}
|
|
187
|
+
let sanitizedReason;
|
|
188
|
+
if (typeof entryInput.reason === "string") {
|
|
189
|
+
sanitizedReason = sanitizeTextForJournal(entryInput.reason).slice(0, 512);
|
|
190
|
+
}
|
|
191
|
+
let safeParams;
|
|
192
|
+
if (entryInput.parametersPreview) {
|
|
193
|
+
if (entryInput.toolName && !("action" in entryInput.parametersPreview)) {
|
|
194
|
+
safeParams = sanitizeToolParameters(entryInput.toolName, entryInput.parametersPreview);
|
|
195
|
+
}
|
|
196
|
+
else {
|
|
197
|
+
safeParams = entryInput.parametersPreview;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const safeMeta = sanitizeMetadata(entryInput.metadata);
|
|
201
|
+
const entry = {
|
|
202
|
+
id,
|
|
203
|
+
sequence: seq,
|
|
204
|
+
timestamp,
|
|
205
|
+
taskId,
|
|
206
|
+
botId: entryInput.botId,
|
|
207
|
+
attemptId: entryInput.attemptId,
|
|
208
|
+
type: entryInput.type,
|
|
209
|
+
...(entryInput.phase ? { phase: entryInput.phase } : {}),
|
|
210
|
+
...(entryInput.toolName ? { toolName: entryInput.toolName } : {}),
|
|
211
|
+
...(entryInput.toolCallId ? { toolCallId: entryInput.toolCallId } : {}),
|
|
212
|
+
...(sanitizedSummary ? { summary: sanitizedSummary } : {}),
|
|
213
|
+
...(sanitizedOutput ? { output: sanitizedOutput } : {}),
|
|
214
|
+
...(safeParams ? { parametersPreview: safeParams } : {}),
|
|
215
|
+
...(sanitizedReason ? { reason: sanitizedReason } : {}),
|
|
216
|
+
...(safeMeta ? { metadata: safeMeta } : {}),
|
|
217
|
+
};
|
|
218
|
+
const line = JSON.stringify(entry) + "\n";
|
|
219
|
+
const lineBytes = Buffer.byteLength(line, "utf8");
|
|
220
|
+
// Rotate segment if needed
|
|
221
|
+
if (taskState.currentSegLines >= MAX_JOURNAL_SEGMENT_ENTRIES ||
|
|
222
|
+
taskState.currentSegBytes + lineBytes >= MAX_JOURNAL_SEGMENT_BYTES) {
|
|
223
|
+
meta.activeSegmentIndex++;
|
|
224
|
+
meta.segmentCount++;
|
|
225
|
+
taskState.currentSegBytes = 0;
|
|
226
|
+
taskState.currentSegLines = 0;
|
|
227
|
+
}
|
|
228
|
+
const segPath = join(dir, segmentFileName(meta.activeSegmentIndex));
|
|
229
|
+
// Direct non-blocking append to file, no full segment rewrite
|
|
230
|
+
await appendFile(segPath, line, "utf8");
|
|
231
|
+
taskState.currentSegBytes += lineBytes;
|
|
232
|
+
taskState.currentSegLines++;
|
|
233
|
+
meta.totalEvents++;
|
|
234
|
+
meta.updatedAt = now;
|
|
235
|
+
// Segment bound pruning
|
|
236
|
+
if (meta.segmentCount > MAX_JOURNAL_RETAINED_SEGMENTS) {
|
|
237
|
+
const files = (await readdir(dir)).filter((f) => f.startsWith("segment-") && f.endsWith(".jsonl")).sort();
|
|
238
|
+
if (files.length > MAX_JOURNAL_RETAINED_SEGMENTS) {
|
|
239
|
+
const toDelete = files.slice(0, files.length - MAX_JOURNAL_RETAINED_SEGMENTS);
|
|
240
|
+
for (const f of toDelete) {
|
|
241
|
+
try {
|
|
242
|
+
const oldLines = (await readFile(join(dir, f), "utf8")).split("\n").filter((l) => l.trim().length > 0);
|
|
243
|
+
meta.droppedCount += oldLines.length;
|
|
244
|
+
await unlink(join(dir, f));
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
// ignore
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
meta.truncated = true;
|
|
251
|
+
const remaining = (await readdir(dir))
|
|
252
|
+
.filter((f) => f.startsWith("segment-") && f.endsWith(".jsonl"))
|
|
253
|
+
.sort();
|
|
254
|
+
if (remaining[0]) {
|
|
255
|
+
try {
|
|
256
|
+
const firstLine = (await readFile(join(dir, remaining[0]), "utf8")).split("\n")[0];
|
|
257
|
+
if (firstLine) {
|
|
258
|
+
const parsed = JSON.parse(firstLine);
|
|
259
|
+
meta.minRetainedSequence = parsed.sequence;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
// ignore
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
// Asynchronous metadata atomic write
|
|
269
|
+
await writeAtomicAsync(join(dir, "meta.json"), JSON.stringify(meta, null, 2));
|
|
270
|
+
return entry;
|
|
271
|
+
});
|
|
272
|
+
},
|
|
273
|
+
async getMeta(taskId, accountId, roomId) {
|
|
274
|
+
if (!taskId || !accountId || !roomId)
|
|
275
|
+
return null;
|
|
276
|
+
const cached = activeTasks.get(taskId);
|
|
277
|
+
if (cached) {
|
|
278
|
+
const m = cached.meta;
|
|
279
|
+
if (m.accountId !== accountId || m.roomId !== roomId)
|
|
280
|
+
return null;
|
|
281
|
+
return m;
|
|
282
|
+
}
|
|
283
|
+
const dir = taskDir(taskId);
|
|
284
|
+
const metaPath = join(dir, "meta.json");
|
|
285
|
+
try {
|
|
286
|
+
const data = await readFile(metaPath, "utf8");
|
|
287
|
+
const parsed = JSON.parse(data);
|
|
288
|
+
if (!parsed.accountId || parsed.accountId !== accountId || !parsed.roomId || parsed.roomId !== roomId) {
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
return parsed;
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
},
|
|
297
|
+
async getPage(taskId, accountId, roomId, options = {}) {
|
|
298
|
+
const meta = await this.getMeta(taskId, accountId, roomId);
|
|
299
|
+
if (!meta)
|
|
300
|
+
return null;
|
|
301
|
+
const dir = taskDir(taskId);
|
|
302
|
+
const limit = Math.min(Math.max(options.limit ?? 20, 1), 100);
|
|
303
|
+
const direction = options.direction === "backward" ? "backward" : "forward";
|
|
304
|
+
let cursorSeq;
|
|
305
|
+
let cursorExpired = false;
|
|
306
|
+
if (options.cursor) {
|
|
307
|
+
const decoded = decodeJournalCursor(options.cursor);
|
|
308
|
+
if (decoded && decoded.taskId === taskId) {
|
|
309
|
+
cursorSeq = decoded.sequence;
|
|
310
|
+
if (meta.truncated && cursorSeq < meta.minRetainedSequence) {
|
|
311
|
+
cursorExpired = true;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
else {
|
|
315
|
+
return {
|
|
316
|
+
taskId,
|
|
317
|
+
items: [],
|
|
318
|
+
hasMore: false,
|
|
319
|
+
totalEvents: meta.totalEvents,
|
|
320
|
+
truncated: meta.truncated,
|
|
321
|
+
droppedCount: meta.droppedCount,
|
|
322
|
+
cursorExpired: true,
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
// Read retained segment entries asynchronously
|
|
327
|
+
const files = (await readdir(dir)).filter((f) => f.startsWith("segment-") && f.endsWith(".jsonl")).sort();
|
|
328
|
+
const allEntries = [];
|
|
329
|
+
let corrupted = false;
|
|
330
|
+
for (const file of files) {
|
|
331
|
+
try {
|
|
332
|
+
const content = await readFile(join(dir, file), "utf8");
|
|
333
|
+
const lines = content.split("\n").filter((l) => l.trim().length > 0);
|
|
334
|
+
for (const line of lines) {
|
|
335
|
+
try {
|
|
336
|
+
allEntries.push(JSON.parse(line));
|
|
337
|
+
}
|
|
338
|
+
catch {
|
|
339
|
+
corrupted = true;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
catch {
|
|
344
|
+
corrupted = true;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
allEntries.sort((a, b) => a.sequence - b.sequence);
|
|
348
|
+
let filtered;
|
|
349
|
+
if (direction === "forward") {
|
|
350
|
+
filtered = cursorSeq !== undefined ? allEntries.filter((e) => e.sequence > cursorSeq) : allEntries;
|
|
351
|
+
}
|
|
352
|
+
else {
|
|
353
|
+
filtered = cursorSeq !== undefined ? allEntries.filter((e) => e.sequence < cursorSeq) : allEntries;
|
|
354
|
+
filtered.reverse();
|
|
355
|
+
}
|
|
356
|
+
const pageItems = filtered.slice(0, limit);
|
|
357
|
+
const hasMore = filtered.length > limit;
|
|
358
|
+
let nextCursor;
|
|
359
|
+
if (hasMore && pageItems.length > 0) {
|
|
360
|
+
const lastItem = pageItems[pageItems.length - 1];
|
|
361
|
+
nextCursor = encodeJournalCursor(taskId, meta.attemptId, lastItem.sequence);
|
|
362
|
+
}
|
|
363
|
+
return {
|
|
364
|
+
taskId,
|
|
365
|
+
items: pageItems,
|
|
366
|
+
...(nextCursor ? { nextCursor } : {}),
|
|
367
|
+
hasMore,
|
|
368
|
+
totalEvents: meta.totalEvents,
|
|
369
|
+
truncated: meta.truncated,
|
|
370
|
+
droppedCount: meta.droppedCount,
|
|
371
|
+
...(cursorExpired ? { cursorExpired: true } : {}),
|
|
372
|
+
...(corrupted ? { corrupted: true } : {}),
|
|
373
|
+
};
|
|
374
|
+
},
|
|
375
|
+
async close() {
|
|
376
|
+
closed = true;
|
|
377
|
+
while (taskLocks.size > 0) {
|
|
378
|
+
const inFlight = Array.from(taskLocks.values());
|
|
379
|
+
await Promise.allSettled(inFlight);
|
|
380
|
+
}
|
|
381
|
+
activeTasks.clear();
|
|
382
|
+
taskLocks.clear();
|
|
383
|
+
},
|
|
384
|
+
};
|
|
385
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Reject invalid plans whole; never turn truncated or defaulted steps into an approval target. */
|
|
2
|
+
export function validateTaskPlan(value) {
|
|
3
|
+
if (!value || typeof value !== "object")
|
|
4
|
+
return;
|
|
5
|
+
const plan = value;
|
|
6
|
+
if (plan.state !== "ready" || !Array.isArray(plan.steps) || plan.steps.length < 1 || plan.steps.length > 32)
|
|
7
|
+
return;
|
|
8
|
+
if (plan.summary !== undefined && (typeof plan.summary !== "string" || plan.summary.length > 500))
|
|
9
|
+
return;
|
|
10
|
+
const ids = new Set();
|
|
11
|
+
const steps = [];
|
|
12
|
+
for (const raw of plan.steps) {
|
|
13
|
+
if (!raw || typeof raw !== "object")
|
|
14
|
+
return;
|
|
15
|
+
const step = raw;
|
|
16
|
+
if (typeof step.id !== "string" || !step.id.trim() || step.id.length > 64 || ids.has(step.id.trim()))
|
|
17
|
+
return;
|
|
18
|
+
if (typeof step.title !== "string" || !step.title.trim() || step.title.length > 200)
|
|
19
|
+
return;
|
|
20
|
+
if (!["pending", "in_progress", "done", "failed"].includes(step.status))
|
|
21
|
+
return;
|
|
22
|
+
if (step.description !== undefined && (typeof step.description !== "string" || step.description.length > 1000))
|
|
23
|
+
return;
|
|
24
|
+
ids.add(step.id.trim());
|
|
25
|
+
steps.push({
|
|
26
|
+
id: step.id.trim(),
|
|
27
|
+
title: step.title.trim(),
|
|
28
|
+
status: step.status,
|
|
29
|
+
...(step.description === undefined ? {} : { description: step.description }),
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
return { state: "ready", steps, ...(plan.summary === undefined ? {} : { summary: plan.summary }) };
|
|
33
|
+
}
|