@picassohq/cli 0.0.0-stage → 1.0.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.
- package/agents/browser_agent.yaml +53 -0
- package/agents/code_reviewer.yaml +49 -0
- package/agents/codebase_investigator.yaml +70 -0
- package/agents/design_auditor.yaml +50 -0
- package/agents/devex_auditor.yaml +50 -0
- package/agents/doc_writer.yaml +54 -0
- package/agents/engineering_architect.yaml +51 -0
- package/agents/generalist.yaml +55 -0
- package/agents/migration_planner.yaml +51 -0
- package/agents/product_reviewer.yaml +48 -0
- package/agents/qa_operator.yaml +52 -0
- package/agents/release_engineer.yaml +50 -0
- package/agents/security_auditor.yaml +62 -0
- package/agents/test_writer.yaml +52 -0
- package/assets/first-light-lockup.png +0 -0
- package/assets/first-light-tagline.png +0 -0
- package/assets/house/README.md +26 -0
- package/assets/house/auraone-banner.png +0 -0
- package/assets/house/auraone-logo.png +0 -0
- package/assets/house/kiro-prism-banner.png +0 -0
- package/assets/house/kiro-prism-logo.png +0 -0
- package/assets/house/picasso-banner.png +0 -0
- package/assets/house/picasso-logo.png +0 -0
- package/assets/wordmark-app.png +0 -0
- package/assets/wordmark-tight.png +0 -0
- package/assets/wordmark.png +0 -0
- package/design/styles.css +1042 -0
- package/dist/build-info.json +37 -0
- package/dist/index.js +3062 -0
- package/goals/cli-hardening.yaml +40 -0
- package/goals/repo-maintenance.yaml +40 -0
- package/package.json +49 -4
- package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
- package/runtime/dsh/picasso-ecosystem.community.json +185 -0
- package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
- package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
- package/runtime/dsh/picasso-isolation.patch.yml +25 -0
- package/runtime/dsh/picasso-providers.patch.yml +373 -0
- package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
- package/runtime/dsh/picasso-sdk.patch.yml +204 -0
- package/runtime/engine-manifest.json +215 -0
- package/runtime/package.json +6 -0
- package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
- package/runtime/packages/picasso-cache-probe/index.js +477 -0
- package/runtime/packages/picasso-cache-probe/package.json +38 -0
- package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-commands/fresh-review.js +573 -0
- package/runtime/packages/picasso-commands/index.js +497 -0
- package/runtime/packages/picasso-commands/package.json +28 -0
- package/runtime/packages/picasso-instructions/conflicts.js +115 -0
- package/runtime/packages/picasso-instructions/formats.js +145 -0
- package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
- package/runtime/packages/picasso-instructions/glob.js +114 -0
- package/runtime/packages/picasso-instructions/globals.js +90 -0
- package/runtime/packages/picasso-instructions/imports.js +123 -0
- package/runtime/packages/picasso-instructions/index.js +326 -0
- package/runtime/packages/picasso-instructions/modes.js +64 -0
- package/runtime/packages/picasso-instructions/package.json +30 -0
- package/runtime/packages/picasso-instructions/parse.js +134 -0
- package/runtime/packages/picasso-instructions/report.js +161 -0
- package/runtime/packages/picasso-instructions/resolve.js +939 -0
- package/runtime/packages/picasso-instructions/scan.js +181 -0
- package/runtime/packages/picasso-instructions/settings.js +150 -0
- package/runtime/packages/picasso-instructions/skills.js +345 -0
- package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
- package/runtime/packages/picasso-lean-context/index.js +6280 -0
- package/runtime/packages/picasso-lean-context/package.json +26 -0
- package/runtime/packages/picasso-lean-context/read-image-recovery.js +306 -0
- package/runtime/packages/picasso-lean-context/timeline.js +418 -0
- package/runtime/packages/picasso-librarian/classify.js +146 -0
- package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-librarian/index.js +878 -0
- package/runtime/packages/picasso-librarian/notes.js +159 -0
- package/runtime/packages/picasso-librarian/package.json +34 -0
- package/runtime/packages/picasso-librarian/state.js +478 -0
- package/runtime/packages/picasso-memory/index.js +1184 -0
- package/runtime/packages/picasso-memory/package.json +21 -0
- package/runtime/packages/picasso-model-router/connections.js +912 -0
- package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
- package/runtime/packages/picasso-model-router/index.js +1083 -0
- package/runtime/packages/picasso-model-router/package.json +30 -0
- package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-options/index.js +263 -0
- package/runtime/packages/picasso-options/package.json +28 -0
- package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-progress-reports/index.js +267 -0
- package/runtime/packages/picasso-progress-reports/package.json +30 -0
- package/runtime/packages/picasso-progress-reports/report.js +235 -0
- package/runtime/packages/picasso-sdk-server/aside.js +142 -0
- package/runtime/packages/picasso-sdk-server/connections.js +38 -0
- package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
- package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
- package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
- package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
- package/runtime/packages/picasso-sdk-server/goal.js +131 -0
- package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
- package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
- package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
- package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
- package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
- package/runtime/packages/picasso-sdk-server/index.js +891 -0
- package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
- package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
- package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
- package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
- package/runtime/packages/picasso-sdk-server/package.json +50 -0
- package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
- package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
- package/runtime/packages/picasso-sdk-server/queue.js +322 -0
- package/runtime/packages/picasso-sdk-server/requester.js +43 -0
- package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
- package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
- package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
- package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
- package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
- package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
- package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
- package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
- package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
- package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
- package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
- package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
- package/runtime/packages/picasso-web-search/backends.js +412 -0
- package/runtime/packages/picasso-web-search/config.js +121 -0
- package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
- package/runtime/packages/picasso-web-search/failure.js +116 -0
- package/runtime/packages/picasso-web-search/format.js +42 -0
- package/runtime/packages/picasso-web-search/index.js +71 -0
- package/runtime/packages/picasso-web-search/package.json +38 -0
- package/runtime/packages/picasso-web-search/router.js +156 -0
- package/runtime/packages/picasso-x-reader/circle.js +324 -0
- package/runtime/packages/picasso-x-reader/command.js +169 -0
- package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
- package/runtime/packages/picasso-x-reader/index.js +170 -0
- package/runtime/packages/picasso-x-reader/package.json +39 -0
- package/runtime/packages/picasso-x-reader/read.js +370 -0
- package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
- package/runtime/packages/picasso-x-reader/settings.js +131 -0
- package/runtime/packages/picasso-x-reader/urls.js +154 -0
- package/runtime/packages/picasso-x-reader/xmd.js +512 -0
- package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
- package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
- package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
- package/runtime/plugins/picasso-auto-approve/package.json +28 -0
- package/runtime/plugins/picasso-browser/index.js +424 -0
- package/runtime/plugins/picasso-browser/package.json +28 -0
- package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
- package/runtime/plugins/picasso-checkpoints/index.js +885 -0
- package/runtime/plugins/picasso-checkpoints/package.json +29 -0
- package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
- package/runtime/plugins/picasso-commands/index.js +497 -0
- package/runtime/plugins/picasso-commands/package.json +28 -0
- package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
- package/runtime/plugins/picasso-instructions/formats.js +145 -0
- package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
- package/runtime/plugins/picasso-instructions/glob.js +114 -0
- package/runtime/plugins/picasso-instructions/globals.js +90 -0
- package/runtime/plugins/picasso-instructions/imports.js +123 -0
- package/runtime/plugins/picasso-instructions/index.js +326 -0
- package/runtime/plugins/picasso-instructions/modes.js +64 -0
- package/runtime/plugins/picasso-instructions/package.json +30 -0
- package/runtime/plugins/picasso-instructions/parse.js +134 -0
- package/runtime/plugins/picasso-instructions/report.js +161 -0
- package/runtime/plugins/picasso-instructions/resolve.js +939 -0
- package/runtime/plugins/picasso-instructions/scan.js +181 -0
- package/runtime/plugins/picasso-instructions/settings.js +150 -0
- package/runtime/plugins/picasso-instructions/skills.js +345 -0
- package/runtime/plugins/picasso-lean-context/index.js +6280 -0
- package/runtime/plugins/picasso-lean-context/package.json +26 -0
- package/runtime/plugins/picasso-lean-context/read-image-recovery.js +306 -0
- package/runtime/plugins/picasso-lean-context/timeline.js +418 -0
- package/runtime/plugins/picasso-librarian/classify.js +146 -0
- package/runtime/plugins/picasso-librarian/index.js +878 -0
- package/runtime/plugins/picasso-librarian/notes.js +159 -0
- package/runtime/plugins/picasso-librarian/package.json +34 -0
- package/runtime/plugins/picasso-librarian/state.js +478 -0
- package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
- package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
- package/runtime/plugins/picasso-mail/inbox.js +207 -0
- package/runtime/plugins/picasso-mail/index.js +293 -0
- package/runtime/plugins/picasso-mail/package.json +22 -0
- package/runtime/plugins/picasso-memory/index.js +1184 -0
- package/runtime/plugins/picasso-memory/package.json +21 -0
- package/runtime/plugins/picasso-model-router/connections.js +912 -0
- package/runtime/plugins/picasso-model-router/index.js +1083 -0
- package/runtime/plugins/picasso-model-router/package.json +30 -0
- package/runtime/plugins/picasso-options/index.js +263 -0
- package/runtime/plugins/picasso-options/package.json +28 -0
- package/runtime/plugins/picasso-progress-reports/index.js +267 -0
- package/runtime/plugins/picasso-progress-reports/package.json +30 -0
- package/runtime/plugins/picasso-progress-reports/report.js +235 -0
- package/runtime/plugins/picasso-provider-models/index.js +436 -0
- package/runtime/plugins/picasso-provider-models/package.json +28 -0
- package/runtime/plugins/picasso-repo-index/index.js +1850 -0
- package/runtime/plugins/picasso-repo-index/package.json +28 -0
- package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
- package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
- package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
- package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
- package/runtime/plugins/picasso-trackers/index.js +895 -0
- package/runtime/plugins/picasso-trackers/package.json +28 -0
- package/runtime/plugins/picasso-web-search/backends.js +412 -0
- package/runtime/plugins/picasso-web-search/config.js +121 -0
- package/runtime/plugins/picasso-web-search/failure.js +116 -0
- package/runtime/plugins/picasso-web-search/format.js +42 -0
- package/runtime/plugins/picasso-web-search/index.js +71 -0
- package/runtime/plugins/picasso-web-search/package.json +38 -0
- package/runtime/plugins/picasso-web-search/router.js +156 -0
- package/runtime/plugins/picasso-x-reader/circle.js +324 -0
- package/runtime/plugins/picasso-x-reader/command.js +169 -0
- package/runtime/plugins/picasso-x-reader/index.js +170 -0
- package/runtime/plugins/picasso-x-reader/package.json +39 -0
- package/runtime/plugins/picasso-x-reader/read.js +370 -0
- package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
- package/runtime/plugins/picasso-x-reader/settings.js +131 -0
- package/runtime/plugins/picasso-x-reader/urls.js +154 -0
- package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
- package/runtime/relay/attachment-text.mjs +737 -0
- package/runtime/relay/companion/companion.css +126 -0
- package/runtime/relay/companion/companion.js +648 -0
- package/runtime/relay/companion/icon.svg +5 -0
- package/runtime/relay/companion/index.html +25 -0
- package/runtime/relay/companion/manifest.json +13 -0
- package/runtime/relay/companion/sw.js +41 -0
- package/runtime/relay/main.mjs +38580 -0
- package/runtime/relay/model-listing.mjs +614 -0
- package/runtime/relay/versions-routes.mjs +1400 -0
- package/runtime/verify-plugins.mjs +205 -0
- package/runtime-lock/package-lock.json +10779 -0
- package/runtime-lock/package.json +7 -0
- package/scripts/install-runtime.mjs +400 -0
- package/README.md +0 -3
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
// Message queueing and steering while a turn runs, mirroring dsh's own web app
|
|
2
|
+
// controller (`dsh-api-session-controller` `prompt` + `updateQueue`):
|
|
3
|
+
//
|
|
4
|
+
// session/queue { sessionId, content, mode: 'followup' | 'steer' | 'interrupt' }
|
|
5
|
+
// -> { accepted, itemId, target, status }
|
|
6
|
+
// `followup` is `agent.followup(message)` (the next-turn inbox), `steer` is
|
|
7
|
+
// `agent.steer(message)` (the next-step inbox: the running turn sees it at
|
|
8
|
+
// its next step boundary). Exactly like dsh's prompt admission, an idle
|
|
9
|
+
// agent is woken: a followup on an idle session starts a turn at once (the
|
|
10
|
+
// same as `session/prompt`), so clients may use one method for both.
|
|
11
|
+
// Admission is atomic with respect to idle: the status is read in the same
|
|
12
|
+
// synchronous step that hands the message over, and a followup admitted
|
|
13
|
+
// while idle is started through `session/prompt`'s own path and answered
|
|
14
|
+
// with `started: true` (`status: 'idle'`, `itemId` = the prompt's message
|
|
15
|
+
// id), so the client follows that turn like a prompt (session/wait) and no
|
|
16
|
+
// queued message can start a turn nobody follows. `started: false` means
|
|
17
|
+
// the message is pending in the inbox of the running turn.
|
|
18
|
+
// `interrupt` stops the running step (dsh's own `agent.cancel({kind:'user'},
|
|
19
|
+
// {keepInbox: true})`, the user stop) and runs this message as the very next
|
|
20
|
+
// turn, ahead of anything already queued (`interruptWith`). The queued
|
|
21
|
+
// turns keep their ids and order and run after it. On an idle agent it is
|
|
22
|
+
// a prompt that jumps the queue. The open `session/wait` keeps following:
|
|
23
|
+
// the message is admitted while the aborted turn unwinds, so dsh latches
|
|
24
|
+
// the wake and starts it the moment the turn converges.
|
|
25
|
+
// session/queue/list { sessionId } -> { status, items }
|
|
26
|
+
// session/queue/update { sessionId, itemId, action: { kind: 'edit', content } | { kind: 'remove' } | { kind: 'steer' } | { kind: 'interrupt' } | { kind: 'move', index } }
|
|
27
|
+
// -> { accepted } (`interrupt` adds `interrupted`: whether a running step was stopped)
|
|
28
|
+
// `steer` promotes a pending next-turn item into the running turn and is
|
|
29
|
+
// refused with `session/steer-unavailable` unless the item is next-turn and
|
|
30
|
+
// the agent is running (dsh's rule). A steer waits for the step boundary:
|
|
31
|
+
// a long foreground tool call (a polling `bash` loop) holds it until the
|
|
32
|
+
// call returns. `interrupt` is the way out for any pending item (queued or
|
|
33
|
+
// already steering): it leaves the inbox (a canceled removal) and runs as
|
|
34
|
+
// the very next turn through `interruptWith`, the running step stopped —
|
|
35
|
+
// one synchronous section, so no claim can deliver it twice. On an idle
|
|
36
|
+
// agent it simply starts. `move` reorders one next-turn item to
|
|
37
|
+
// `index` (clamped) in a single inbox splice; ids, content and attachments
|
|
38
|
+
// are kept (`moveQueued`).
|
|
39
|
+
//
|
|
40
|
+
// Every inbox change (`agent/inbox/spliced`, including the claim that consumes
|
|
41
|
+
// a queued or steered message) is followed by a `session.queue` notification
|
|
42
|
+
// carrying the authoritative pending list, so a UI renders without polling.
|
|
43
|
+
//
|
|
44
|
+
// Errors carry dsh's codes as a `code: message` prefix (the SDK transport only
|
|
45
|
+
// forwards the message): session/not-found, session/agent-busy,
|
|
46
|
+
// session/queue-item-not-found, session/steer-unavailable, gateway/bad-request.
|
|
47
|
+
|
|
48
|
+
export const QUEUE_METHODS = Object.freeze(['session/queue', 'session/queue/list', 'session/queue/update']);
|
|
49
|
+
/** The `session/queue` delivery modes. */
|
|
50
|
+
export const QUEUE_MODES = Object.freeze(['followup', 'steer', 'interrupt']);
|
|
51
|
+
/** The `session/queue/update` actions. */
|
|
52
|
+
export const QUEUE_ACTIONS = Object.freeze(['edit', 'remove', 'steer', 'interrupt', 'move']);
|
|
53
|
+
export const QUEUE_NOTIFICATION = 'session.queue';
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Splice through the inbox without discarding: the removed messages are not
|
|
57
|
+
* canceled (no `outcome: 'canceled'`, no `agent/inbox/discarded`), because they
|
|
58
|
+
* come straight back — a goal round or a question reply that is only moved must
|
|
59
|
+
* not read as withdrawn. dsh's own claim uses the same non-discarding mutation.
|
|
60
|
+
*/
|
|
61
|
+
function spliceKeeping(inbox, target, start, deleteCount, inserted) {
|
|
62
|
+
if (typeof inbox.mutate === 'function') return inbox.mutate(target, start, deleteCount, inserted, false);
|
|
63
|
+
return inbox.splice(target, start, deleteCount, inserted);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Move one pending `next-turn` message to `index` (clamped) with a single
|
|
68
|
+
* splice over the span it crosses. Returns false when the id is not a pending
|
|
69
|
+
* next-turn item; a no-op move succeeds without logging anything.
|
|
70
|
+
*/
|
|
71
|
+
export function moveQueued(agent, itemId, index) {
|
|
72
|
+
const inbox = agent.inbox;
|
|
73
|
+
const list = inbox.nextTurn;
|
|
74
|
+
const from = list.findIndex((message) => String(message.id) === String(itemId));
|
|
75
|
+
if (from < 0) return false;
|
|
76
|
+
const to = Math.max(0, Math.min(list.length - 1, Math.trunc(Number(index))));
|
|
77
|
+
if (!Number.isFinite(to) || to === from) return true;
|
|
78
|
+
const low = Math.min(from, to);
|
|
79
|
+
const span = list.slice(low, Math.max(from, to) + 1);
|
|
80
|
+
const moved = span.splice(from - low, 1)[0];
|
|
81
|
+
span.splice(to - low, 0, moved);
|
|
82
|
+
spliceKeeping(inbox, 'next-turn', low, span.length, span);
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Interrupt: stop the running step and run `message` next. The queued turns
|
|
88
|
+
* are lifted out (not canceled), the turn is aborted the way the user's stop
|
|
89
|
+
* aborts it (pending work kept), `message` is admitted — while the turn
|
|
90
|
+
* unwinds dsh latches the wake, on an idle agent it starts at once — and the
|
|
91
|
+
* lifted turns go back behind it in their order. All synchronous, so nothing
|
|
92
|
+
* can claim in between. `admit(message)` defaults to `agent.followup`.
|
|
93
|
+
*/
|
|
94
|
+
export function interruptWith(agent, message, admit = (m) => agent.followup(m)) {
|
|
95
|
+
const inbox = agent.inbox;
|
|
96
|
+
const waiting = inbox.nextTurn.length;
|
|
97
|
+
const parked = waiting > 0 ? spliceKeeping(inbox, 'next-turn', 0, waiting, []) : [];
|
|
98
|
+
const wasRunning = agent.status === 'running';
|
|
99
|
+
try {
|
|
100
|
+
if (wasRunning) agent.cancel({ kind: 'user' }, { keepInbox: true });
|
|
101
|
+
admit(message);
|
|
102
|
+
} finally {
|
|
103
|
+
if (parked.length > 0) {
|
|
104
|
+
if (agent.status === 'idle' && inbox.nextTurn.length === 0) {
|
|
105
|
+
// Nothing woke (the admission failed on an idle agent): the queue goes back as it was, unwoken.
|
|
106
|
+
spliceKeeping(inbox, 'next-turn', 0, 0, parked);
|
|
107
|
+
} else {
|
|
108
|
+
spliceKeeping(inbox, 'next-turn', inbox.nextTurn.length, 0, parked);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return { interrupted: wasRunning };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export class QueueError extends Error {
|
|
116
|
+
constructor(code, message, data = {}) {
|
|
117
|
+
super(`${code}: ${message}`);
|
|
118
|
+
this.name = 'QueueError';
|
|
119
|
+
this.code = code;
|
|
120
|
+
this.data = data;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function textOf(content) {
|
|
125
|
+
if (!Array.isArray(content)) return '';
|
|
126
|
+
return content.map((block) => (block?.type === 'text' && typeof block.text === 'string' ? block.text : '')).join('');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Text-only prompt content from a string or content blocks; rejects blank or non-text input. */
|
|
130
|
+
function textContent(content, what) {
|
|
131
|
+
const blocks = typeof content === 'string' ? [{ type: 'text', text: content }] : content;
|
|
132
|
+
if (!Array.isArray(blocks)) throw new QueueError('gateway/bad-request', `${what} must be a string or text content blocks`);
|
|
133
|
+
if (blocks.some((block) => block?.type !== 'text' || typeof block.text !== 'string')) {
|
|
134
|
+
throw new QueueError('session/attachment-invalid', `${what} accepts text content only`, { reason: 'QUEUE_EDIT_NON_TEXT' });
|
|
135
|
+
}
|
|
136
|
+
if (!blocks.some((block) => block.text.trim().length > 0)) {
|
|
137
|
+
throw new QueueError('gateway/bad-request', `${what} must include non-whitespace text`);
|
|
138
|
+
}
|
|
139
|
+
return blocks.map((block) => ({ type: 'text', text: block.text }));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** An image already admitted to dsh's attachment store (`{ type: 'image', attachment: { attachmentId, mediaType, ... } }`). */
|
|
143
|
+
function isAttachedImage(block) {
|
|
144
|
+
const attachment = block?.attachment;
|
|
145
|
+
return block?.type === 'image' && attachment !== null && typeof attachment === 'object' && typeof attachment.attachmentId === 'string' && attachment.attachmentId.length > 0 && typeof attachment.mediaType === 'string';
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** A file already admitted to dsh's attachment store (`{ type: 'file', attachment: { attachmentId, name, bytes } }`, T4.1). */
|
|
149
|
+
function isAttachedFile(block) {
|
|
150
|
+
const attachment = block?.attachment;
|
|
151
|
+
return block?.type === 'file' && attachment !== null && typeof attachment === 'object' && typeof attachment.attachmentId === 'string' && attachment.attachmentId.length > 0 && typeof attachment.name === 'string' && typeof attachment.bytes === 'number';
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Attachments a queued message may carry (stored image or file references). */
|
|
155
|
+
function isAttached(block) {
|
|
156
|
+
return isAttachedImage(block) || isAttachedFile(block);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Queued prompt content: text blocks plus attachments already in dsh's
|
|
161
|
+
* attachment store (the same durable form `session/prompt` hands dsh), so a
|
|
162
|
+
* message queued with a screenshot or an `@file:` attach keeps it. Encoded
|
|
163
|
+
* image bytes are refused.
|
|
164
|
+
*/
|
|
165
|
+
function queuedContent(content, what) {
|
|
166
|
+
if (typeof content === 'string' || !Array.isArray(content) || !content.some((block) => block?.type === 'image' || block?.type === 'file')) return textContent(content, what);
|
|
167
|
+
if (content.some((block) => !(block?.type === 'text' && typeof block.text === 'string') && !isAttached(block))) {
|
|
168
|
+
throw new QueueError('session/attachment-invalid', `${what} accepts text and stored image/file attachments only`, { reason: 'QUEUE_ATTACHMENT_INVALID' });
|
|
169
|
+
}
|
|
170
|
+
return content.map((block) => (block.type === 'text' ? { type: 'text', text: block.text } : { type: block.type, attachment: { ...block.attachment } }));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The pending inbox of one agent as wire items (next-step first: it lands before any queued turn). */
|
|
174
|
+
export function queueItems(agent) {
|
|
175
|
+
const inbox = agent?.inbox;
|
|
176
|
+
if (inbox === undefined) return [];
|
|
177
|
+
const item = (target) => (message) => ({
|
|
178
|
+
itemId: String(message.id),
|
|
179
|
+
target,
|
|
180
|
+
text: textOf(message.content),
|
|
181
|
+
...(typeof message.source?.kind === 'string' ? { source: message.source.kind } : {}),
|
|
182
|
+
});
|
|
183
|
+
return [...inbox.nextStep.map(item('next-step')), ...inbox.nextTurn.map(item('next-turn'))];
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* @param {object} deps
|
|
188
|
+
* @param {(sessionId: string) => any} deps.agentFor - the live agent (undefined when not attached).
|
|
189
|
+
* @param {(input: { content: unknown[], source: object }) => any} deps.createUserMessage - dsh-llm's message factory.
|
|
190
|
+
* @param {(message: any) => any} [deps.freezeMessage] - dsh-llm's freezer (edits keep the message identity).
|
|
191
|
+
* @param {(agent: any) => Promise<void>} [deps.ready] - awaited before admission (sandbox/plan readiness).
|
|
192
|
+
* @param {(method: string, params: object) => void} deps.notify - server -> client notification.
|
|
193
|
+
* @param {(sessionId: string, content: unknown[]) => Promise<{ messageId: string }>} [deps.prompt] - `session/prompt`'s admission, used when a followup lands on an idle agent.
|
|
194
|
+
*/
|
|
195
|
+
export function createQueue({ agentFor, createUserMessage, freezeMessage = (message) => Object.freeze(message), ready = async () => {}, notify, prompt }) {
|
|
196
|
+
const requireAgent = (params) => {
|
|
197
|
+
if (typeof params?.sessionId !== 'string' || params.sessionId.length === 0) {
|
|
198
|
+
throw new QueueError('gateway/bad-request', 'a non-empty sessionId is required');
|
|
199
|
+
}
|
|
200
|
+
const agent = agentFor(params.sessionId);
|
|
201
|
+
if (agent === undefined) throw new QueueError('session/not-found', `session "${params.sessionId}" not found (not attached)`, { sessionId: params.sessionId });
|
|
202
|
+
return agent;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
const publish = (sessionId, agent, seq) => {
|
|
206
|
+
notify(QUEUE_NOTIFICATION, {
|
|
207
|
+
sessionId: String(sessionId),
|
|
208
|
+
status: agent?.status ?? 'idle',
|
|
209
|
+
items: queueItems(agent),
|
|
210
|
+
...(typeof seq === 'number' ? { seq } : {}),
|
|
211
|
+
});
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
const methods = {
|
|
215
|
+
async 'session/queue'(params) {
|
|
216
|
+
const agent = requireAgent(params);
|
|
217
|
+
const mode = params.mode ?? 'followup';
|
|
218
|
+
if (!QUEUE_MODES.includes(mode)) throw new QueueError('gateway/bad-request', `unknown queue mode "${mode}" (followup | steer | interrupt)`);
|
|
219
|
+
const content = queuedContent(params.content, 'queued content');
|
|
220
|
+
await ready(agent);
|
|
221
|
+
if (agentFor(params.sessionId) !== agent) throw new QueueError('session/not-found', `session "${params.sessionId}" was disposed during queue admission`, { sessionId: params.sessionId });
|
|
222
|
+
const status = agent.status;
|
|
223
|
+
if (mode === 'interrupt') {
|
|
224
|
+
if (status === 'idle' && agent.inbox.nextTurn.length === 0 && prompt !== undefined) {
|
|
225
|
+
// Nothing to stop and nothing to jump ahead of: a plain prompt the client follows (session/wait).
|
|
226
|
+
let started;
|
|
227
|
+
try {
|
|
228
|
+
started = await prompt(params.sessionId, content);
|
|
229
|
+
} catch (error) {
|
|
230
|
+
throw new QueueError('session/agent-busy', 'prompt rejected', { reason: String(error) });
|
|
231
|
+
}
|
|
232
|
+
return { accepted: true, itemId: String(started.messageId), target: 'next-turn', status, started: true, interrupted: false };
|
|
233
|
+
}
|
|
234
|
+
const message = createUserMessage({ content, source: { kind: 'user' } });
|
|
235
|
+
let interrupted;
|
|
236
|
+
try {
|
|
237
|
+
({ interrupted } = interruptWith(agent, message));
|
|
238
|
+
} catch (error) {
|
|
239
|
+
throw new QueueError('session/agent-busy', 'interrupt rejected', { reason: String(error) });
|
|
240
|
+
}
|
|
241
|
+
return { accepted: true, itemId: String(message.id), target: 'next-turn', status, started: status === 'idle', interrupted };
|
|
242
|
+
}
|
|
243
|
+
if (mode === 'followup' && status === 'idle' && prompt !== undefined) {
|
|
244
|
+
let started;
|
|
245
|
+
try {
|
|
246
|
+
started = await prompt(params.sessionId, content);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
throw new QueueError('session/agent-busy', 'prompt rejected', { reason: String(error) });
|
|
249
|
+
}
|
|
250
|
+
return { accepted: true, itemId: String(started.messageId), target: 'next-turn', status, started: true };
|
|
251
|
+
}
|
|
252
|
+
const message = createUserMessage({ content, source: { kind: 'user' } });
|
|
253
|
+
try {
|
|
254
|
+
if (mode === 'steer') agent.steer(message);
|
|
255
|
+
else agent.followup(message);
|
|
256
|
+
} catch (error) {
|
|
257
|
+
throw new QueueError('session/agent-busy', 'prompt rejected', { reason: String(error) });
|
|
258
|
+
}
|
|
259
|
+
return { accepted: true, itemId: String(message.id), target: mode === 'steer' ? 'next-step' : 'next-turn', status, started: mode === 'followup' && status === 'idle' };
|
|
260
|
+
},
|
|
261
|
+
async 'session/queue/list'(params) {
|
|
262
|
+
const agent = requireAgent(params);
|
|
263
|
+
return { status: agent.status, items: queueItems(agent) };
|
|
264
|
+
},
|
|
265
|
+
async 'session/queue/update'(params) {
|
|
266
|
+
const action = params?.action;
|
|
267
|
+
if (action === null || typeof action !== 'object' || !QUEUE_ACTIONS.includes(action.kind)) {
|
|
268
|
+
throw new QueueError('gateway/bad-request', 'action must be { kind: "edit", content } | { kind: "remove" } | { kind: "steer" } | { kind: "interrupt" } | { kind: "move", index }');
|
|
269
|
+
}
|
|
270
|
+
if (action.kind === 'move' && !Number.isSafeInteger(action.index)) {
|
|
271
|
+
throw new QueueError('gateway/bad-request', 'a move needs an integer index');
|
|
272
|
+
}
|
|
273
|
+
const content = action.kind === 'edit' ? textContent(action.content, 'queue edit content') : undefined;
|
|
274
|
+
const agent = requireAgent(params);
|
|
275
|
+
const itemId = String(params.itemId ?? '');
|
|
276
|
+
const nextTurn = agent.inbox.nextTurn.find((message) => message.id === itemId);
|
|
277
|
+
const nextStep = agent.inbox.nextStep.find((message) => message.id === itemId);
|
|
278
|
+
const target = nextTurn !== undefined ? 'next-turn' : nextStep !== undefined ? 'next-step' : undefined;
|
|
279
|
+
const message = nextTurn ?? nextStep;
|
|
280
|
+
if (target === undefined) throw new QueueError('session/queue-item-not-found', 'queued item is no longer pending', { itemId });
|
|
281
|
+
if (action.kind === 'steer' && (target !== 'next-turn' || agent.status !== 'running')) {
|
|
282
|
+
throw new QueueError('session/steer-unavailable', 'current turn no longer accepts steering', { itemId });
|
|
283
|
+
}
|
|
284
|
+
if (action.kind === 'interrupt') {
|
|
285
|
+
// Out of the inbox first (canceled: it is not a claim, nothing reads it as delivered), then the very next
|
|
286
|
+
// turn, the running step stopped; the same message id, content and attachments.
|
|
287
|
+
let interrupted;
|
|
288
|
+
try {
|
|
289
|
+
agent.inbox.remove(itemId);
|
|
290
|
+
({ interrupted } = interruptWith(agent, message));
|
|
291
|
+
} catch (error) {
|
|
292
|
+
throw new QueueError('session/agent-busy', 'interrupt rejected', { reason: String(error) });
|
|
293
|
+
}
|
|
294
|
+
return { accepted: true, interrupted };
|
|
295
|
+
}
|
|
296
|
+
if (action.kind === 'move') {
|
|
297
|
+
if (target !== 'next-turn') throw new QueueError('session/queue-item-not-found', 'only a queued turn can move', { itemId });
|
|
298
|
+
moveQueued(agent, itemId, action.index);
|
|
299
|
+
} else if (action.kind === 'edit') {
|
|
300
|
+
if (!agent.inbox.replace(itemId, freezeMessage({ ...message, content: [...content, ...(Array.isArray(message.content) ? message.content.filter(isAttached) : [])] }))) {
|
|
301
|
+
throw new QueueError('session/queue-item-not-found', 'queued item is no longer pending', { itemId });
|
|
302
|
+
}
|
|
303
|
+
} else if (action.kind === 'remove') {
|
|
304
|
+
agent.inbox.remove(itemId);
|
|
305
|
+
} else {
|
|
306
|
+
agent.inbox.remove(itemId);
|
|
307
|
+
agent.steer(message);
|
|
308
|
+
}
|
|
309
|
+
return { accepted: true };
|
|
310
|
+
},
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
/** Feed every `session/event`; publishes the pending list after each inbox splice. */
|
|
314
|
+
const observe = (session, event) => {
|
|
315
|
+
if (event?.type !== 'agent/inbox/spliced') return;
|
|
316
|
+
const agent = agentFor(session.id);
|
|
317
|
+
if (agent === undefined) return;
|
|
318
|
+
publish(session.id, agent, event.seq);
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
return { methods, observe, publish };
|
|
322
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Who asks for an approval when it is not the thread itself. A subagent inherits its parent's approval policy
|
|
2
|
+
// (the subagent approval loader), so a child's blocked call asks the person too; the card has to say which
|
|
3
|
+
// subagent is asking ("WP-3 subagent wants to run bash"). The child's session header names its parent
|
|
4
|
+
// (`origin: 'subagent'`, `parentSession`) and its own log carries the `subagent/descriptor` event whose `label` is
|
|
5
|
+
// what the spawner called it (the `subagent` tool's `description`, a workflow's work-package name). The Mac relay
|
|
6
|
+
// reads the same label from the child's `session/list` row (`projections.values.subagent.label`, relay.ts
|
|
7
|
+
// `approvalRequesterOf`); both produce the same `{requester, requesterLabel}` fields.
|
|
8
|
+
|
|
9
|
+
const MAX_NAME = 80;
|
|
10
|
+
|
|
11
|
+
/** The newest `subagent/descriptor` label in a session log, scanned from the end (a fork inherits its parent's). */
|
|
12
|
+
function descriptorLabel(session) {
|
|
13
|
+
try {
|
|
14
|
+
if (typeof session?.eventAt !== 'function' || !Number.isSafeInteger(session.seq)) return undefined;
|
|
15
|
+
for (let seq = session.seq - 1; seq >= 0; seq -= 1) {
|
|
16
|
+
const event = session.eventAt(seq);
|
|
17
|
+
if (event?.type !== 'subagent/descriptor') continue;
|
|
18
|
+
return typeof event.data?.label === 'string' ? event.data.label : undefined;
|
|
19
|
+
}
|
|
20
|
+
} catch {
|
|
21
|
+
// An unreadable log only loses the name; the requester is still a subagent.
|
|
22
|
+
}
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* `{kind: 'subagent', sessionId, parentSessionId, name?, label}` for an ask a subagent makes; `undefined` for a
|
|
28
|
+
* top-level session. `label` is the display line ("WP-3 subagent", or "Subagent" without a name).
|
|
29
|
+
*/
|
|
30
|
+
export function approvalRequester(agent) {
|
|
31
|
+
const session = agent?.session;
|
|
32
|
+
const header = session?.header;
|
|
33
|
+
if (header?.origin !== 'subagent' || typeof header.parentSession !== 'string' || header.parentSession === '') return undefined;
|
|
34
|
+
const sessionId = typeof session.id === 'string' ? session.id : typeof header.id === 'string' ? header.id : undefined;
|
|
35
|
+
if (sessionId === undefined) return undefined;
|
|
36
|
+
const name = descriptorLabel(session)?.replace(/\s+/gu, ' ').trim().slice(0, MAX_NAME) || undefined;
|
|
37
|
+
return { kind: 'subagent', sessionId, parentSessionId: header.parentSession, ...(name ? { name } : {}), label: name ? `${name} subagent` : 'Subagent' };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The approval-request fields a requester adds (nothing for a top-level session). */
|
|
41
|
+
export function requesterFields(requester) {
|
|
42
|
+
return requester === undefined ? {} : { requester, requesterLabel: requester.label, parentSessionId: requester.parentSessionId };
|
|
43
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// Atomic rewind: the conversation forks at the end of the turn before `turn`
|
|
2
|
+
// and the work tree returns to its state before `turn`, or nothing changes.
|
|
3
|
+
//
|
|
4
|
+
// session/rewind { sessionId, turn, newSessionId? }
|
|
5
|
+
// -> { forkId, boundary, restored, snapshot? }
|
|
6
|
+
//
|
|
7
|
+
// Order: the fork boundary is computed and the workspace restore is planned
|
|
8
|
+
// (every snapshot object, covered path and symlink parent is checked) before
|
|
9
|
+
// any file is written; the current contents of every affected path are copied;
|
|
10
|
+
// the files are restored; only then is the fork created. When the restore or
|
|
11
|
+
// the fork fails, the copied contents are written back, so a failed rewind
|
|
12
|
+
// leaves both the work tree and the source session as they were.
|
|
13
|
+
// `session/fork` and `workspace/restore` stay available on their own.
|
|
14
|
+
|
|
15
|
+
import { forkBoundary } from './session-state.js';
|
|
16
|
+
import { applyWorkspaceRestore, planWorkspaceRestore, rollbackWorktree, snapshotWorktree } from './workspace-restore.js';
|
|
17
|
+
|
|
18
|
+
export const REWIND_METHODS = Object.freeze(['session/rewind']);
|
|
19
|
+
|
|
20
|
+
/** Events that admit the next turn's input; a rewind boundary sits before them. */
|
|
21
|
+
function admitsTurn(event) {
|
|
22
|
+
return event.type === 'agent/inbox/spliced' || (event.type === 'user/message' && event.surfaceOp === 'append');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The seq a rewind to before `turn` forks at: the end of turn `turn - 1`
|
|
27
|
+
* (dsh's completed-prefix rule), or for the first turn the last event before
|
|
28
|
+
* its input was admitted. Undefined when nothing precedes the turn.
|
|
29
|
+
*/
|
|
30
|
+
export function rewindBoundary(events, turn) {
|
|
31
|
+
if (!Number.isSafeInteger(turn) || turn < 1) throw new TypeError('turn must be a positive integer');
|
|
32
|
+
const start = events.findIndex((event) => event.type === 'turn/start' && event.data?.turn === turn);
|
|
33
|
+
if (start < 0) throw new Error(`turn ${turn} is not in the session log`);
|
|
34
|
+
if (turn > 1) {
|
|
35
|
+
const boundary = forkBoundary(events, { turn: turn - 1 });
|
|
36
|
+
if (boundary !== undefined) return boundary;
|
|
37
|
+
}
|
|
38
|
+
let index = start;
|
|
39
|
+
while (index > 0 && admitsTurn(events[index - 1])) index -= 1;
|
|
40
|
+
return index === 0 ? undefined : events[index - 1].seq;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @param {object} deps
|
|
45
|
+
* @param {(sessionId: string) => any} deps.agentFor - the live agent (undefined when not attached).
|
|
46
|
+
* @param {(sessionId: string) => Promise<void>} deps.hydrate - load `changeSeqs` from the durable log.
|
|
47
|
+
* @param {Map<string, { turn?: number, seq: number }[]>} deps.changeSeqs - `workspace/changes` seqs per session.
|
|
48
|
+
* @param {(sessionId: string) => Promise<readonly any[]>} deps.readEvents - the session's durable events.
|
|
49
|
+
* @param {(params: { sessionId: string, newSessionId: string, atSeq: number }) => Promise<{ sessionId: string, boundary: number }>} deps.fork
|
|
50
|
+
* @param {(sessionId: string, seq: number) => Promise<any>} deps.summaryFor
|
|
51
|
+
* @param {any} deps.archive
|
|
52
|
+
* @param {(tree: string) => string | undefined} deps.findObjects
|
|
53
|
+
* @param {(sessionId: string) => string} [deps.newId]
|
|
54
|
+
* @param {(cwd: string, absolutePath: string) => boolean} [deps.isIgnored] - `.picassoignore` paths a restore never touches.
|
|
55
|
+
*/
|
|
56
|
+
export function createRewind({ agentFor, hydrate, changeSeqs, readEvents, fork, summaryFor, archive, findObjects, newId, isIgnored }) {
|
|
57
|
+
const mintId = newId ?? ((sessionId) => `${sessionId}-rewind-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`);
|
|
58
|
+
const methods = {
|
|
59
|
+
async 'session/rewind'(params) {
|
|
60
|
+
if (typeof params?.sessionId !== 'string' || params.sessionId.length === 0) throw new TypeError('a non-empty sessionId is required');
|
|
61
|
+
const { sessionId, turn } = params;
|
|
62
|
+
if (!Number.isSafeInteger(turn) || turn < 1) throw new TypeError('session/rewind requires a positive integer turn');
|
|
63
|
+
const agent = agentFor(sessionId);
|
|
64
|
+
if (agent === undefined) throw new Error(`unknown or not-live session: ${sessionId}`);
|
|
65
|
+
if (agent.status !== 'idle') throw new Error('cannot rewind while the session is running');
|
|
66
|
+
const newSessionId = typeof params.newSessionId === 'string' && params.newSessionId.length > 0 ? params.newSessionId : mintId(sessionId);
|
|
67
|
+
await hydrate(sessionId);
|
|
68
|
+
const events = await readEvents(sessionId);
|
|
69
|
+
const boundary = rewindBoundary(events, turn);
|
|
70
|
+
if (boundary === undefined || events.find((event) => event.seq === boundary) === undefined) throw new Error(`nothing precedes turn ${turn} to rewind to`);
|
|
71
|
+
const entry = (changeSeqs.get(sessionId) ?? []).find((item) => typeof item.turn === 'number' && item.turn >= turn);
|
|
72
|
+
const plan = entry === undefined
|
|
73
|
+
? undefined
|
|
74
|
+
: await planWorkspaceRestore({ sessionId, seq: entry.seq, side: 'before', summaryFor, changeSeqs, archive, findObjects, isIgnored });
|
|
75
|
+
const backup = plan === undefined ? undefined : await snapshotWorktree(plan.root, plan.paths);
|
|
76
|
+
let restored = [];
|
|
77
|
+
const rollback = async (error) => {
|
|
78
|
+
if (backup === undefined) throw error;
|
|
79
|
+
const { failed } = await rollbackWorktree(backup);
|
|
80
|
+
if (failed.length > 0) {
|
|
81
|
+
throw new Error(`rewind failed (${error instanceof Error ? error.message : String(error)}) and these files could not be rolled back: ${failed.join(', ')}`, { cause: error });
|
|
82
|
+
}
|
|
83
|
+
throw error;
|
|
84
|
+
};
|
|
85
|
+
if (plan !== undefined) {
|
|
86
|
+
try {
|
|
87
|
+
restored = (await applyWorkspaceRestore(plan)).restored;
|
|
88
|
+
} catch (error) {
|
|
89
|
+
await rollback(error);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
let forked;
|
|
93
|
+
try {
|
|
94
|
+
if (agentFor(sessionId) !== agent || agent.status !== 'idle') throw new Error('the session started running during the rewind');
|
|
95
|
+
forked = await fork({ sessionId, newSessionId, atSeq: boundary });
|
|
96
|
+
} catch (error) {
|
|
97
|
+
await rollback(error);
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
forkId: forked.sessionId,
|
|
101
|
+
boundary: forked.boundary,
|
|
102
|
+
restored,
|
|
103
|
+
...(plan === undefined ? {} : { snapshot: plan.tree }),
|
|
104
|
+
};
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
return { methods };
|
|
108
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// Durable per-session schedules over the mounted schedule service
|
|
2
|
+
// (`ctx.schedule`, @deepseek-ai/dsh-schedule ScheduleService — mounted only
|
|
3
|
+
// when the profile brings its storageDomain + sessionController chain).
|
|
4
|
+
//
|
|
5
|
+
// The engine pin (0.2.2-rc.2) reworked that service: `create({title, prompt,
|
|
6
|
+
// timing, target}, actorSessionId)`, `edit({id, action: 'update'|'delete',
|
|
7
|
+
// patch, expectedUpdatedAt}, actorSessionId)`, `catalog()`, `history({id,
|
|
8
|
+
// limit, before})`; there is no per-session `list`, `update` or `delete` any
|
|
9
|
+
// more, and rows carry a `target` instead of a `sessionId`. This module keeps
|
|
10
|
+
// the wire shape clients already speak (below) and maps it onto that API:
|
|
11
|
+
// a create's single rule field becomes `timing`, `expected` becomes
|
|
12
|
+
// `expectedUpdatedAt`, `change` becomes `patch.timing`, and results fold back
|
|
13
|
+
// into `{id, updated, record}` / `{id, deleted}` unions.
|
|
14
|
+
//
|
|
15
|
+
// schedule/list { sessionId } -> { schedules }
|
|
16
|
+
// schedule/create { sessionId, prompt, title, <rule> } -> { schedule }
|
|
17
|
+
// schedule/update { sessionId, id, expected, ...patch } -> ScheduleUpdateResult
|
|
18
|
+
// schedule/delete { sessionId, id } -> ScheduleDeleteResult
|
|
19
|
+
// schedule/catalog { sessionId? } -> { schedules } (host-wide; sessionId filters client-side)
|
|
20
|
+
// schedule/history { sessionId, id, limit, before? } -> ScheduleDeliveryHistoryResult
|
|
21
|
+
//
|
|
22
|
+
// `schedule/unavailable` reports a runtime without the service mounted (or an
|
|
23
|
+
// engine older than 0.2.2), so clients can gate on `picasso/capabilities`
|
|
24
|
+
// advertising the method names.
|
|
25
|
+
//
|
|
26
|
+
// Session fencing: the session-bound verbs require `sessionId` to name a live
|
|
27
|
+
// attached session (`session/not-found` otherwise, queue.js's convention) —
|
|
28
|
+
// the attached client manages its own session's durable set. Detached
|
|
29
|
+
// sessions' reminders stay armed and still deliver; the client manages them
|
|
30
|
+
// after re-attaching (or reads them host-wide through `schedule/catalog`,
|
|
31
|
+
// which needs no session binding).
|
|
32
|
+
|
|
33
|
+
export const SCHEDULE_METHODS = Object.freeze([
|
|
34
|
+
'schedule/list',
|
|
35
|
+
'schedule/create',
|
|
36
|
+
'schedule/update',
|
|
37
|
+
'schedule/delete',
|
|
38
|
+
'schedule/catalog',
|
|
39
|
+
'schedule/history',
|
|
40
|
+
]);
|
|
41
|
+
|
|
42
|
+
/** An honest JSON-RPC refusal; `code` prefixes the message (queue.js's convention) and `data` carries structured context. */
|
|
43
|
+
export class ScheduleError extends Error {
|
|
44
|
+
constructor(code, message, data = {}) {
|
|
45
|
+
super(`${code}: ${message}`);
|
|
46
|
+
this.name = 'ScheduleError';
|
|
47
|
+
this.code = code;
|
|
48
|
+
this.data = data;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const RULE_FIELDS = Object.freeze(['after_seconds', 'at', 'every_seconds', 'daily', 'weekly', 'cron']);
|
|
53
|
+
/** The create-style rule field → 0.2.2 `timing.kind`. */
|
|
54
|
+
const RULE_KIND = Object.freeze({ after_seconds: 'after', at: 'at', every_seconds: 'every', daily: 'daily', weekly: 'weekly', cron: 'cron' });
|
|
55
|
+
|
|
56
|
+
/** The Session a 0.2.2 row delivers into (its `target`), else the first involved one. */
|
|
57
|
+
export function sessionOfRow(row) {
|
|
58
|
+
if (typeof row?.sessionId === 'string') return row.sessionId;
|
|
59
|
+
if (typeof row?.target?.sessionId === 'string') return row.target.sessionId;
|
|
60
|
+
return Array.isArray(row?.involvedSessionIds) && typeof row.involvedSessionIds[0] === 'string' ? row.involvedSessionIds[0] : undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const involves = (row, sessionId) =>
|
|
64
|
+
sessionOfRow(row) === sessionId || (Array.isArray(row?.involvedSessionIds) && row.involvedSessionIds.includes(sessionId));
|
|
65
|
+
|
|
66
|
+
/** A 0.2.2 row with the top-level `sessionId` older clients read. */
|
|
67
|
+
const withSession = (row) => {
|
|
68
|
+
const sessionId = sessionOfRow(row);
|
|
69
|
+
return sessionId === undefined || row.sessionId === sessionId ? row : { ...row, sessionId };
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/** One create-style rule field as 0.2.2 timing. */
|
|
73
|
+
export function timingFor(field, value) {
|
|
74
|
+
return { kind: RULE_KIND[field], [field]: value };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* @param {object} deps
|
|
79
|
+
* @param {() => any} deps.schedule - resolves the mounted ScheduleService (or
|
|
80
|
+
* undefined). Resolved per call so this plugin boots before the service and
|
|
81
|
+
* reports `schedule/unavailable` instead of failing construction.
|
|
82
|
+
* @param {(sessionId: string) => any} deps.agentFor - the live-session lookup
|
|
83
|
+
* (index.js's `agentFor`); session-bound verbs require an attached session.
|
|
84
|
+
*/
|
|
85
|
+
export function createSchedule({ schedule, agentFor }) {
|
|
86
|
+
const service = () => {
|
|
87
|
+
const svc = schedule();
|
|
88
|
+
if (svc === undefined || typeof svc.edit !== 'function' || typeof svc.catalog !== 'function') {
|
|
89
|
+
throw new ScheduleError('schedule/unavailable', 'Schedules are not available in this runtime.');
|
|
90
|
+
}
|
|
91
|
+
return svc;
|
|
92
|
+
};
|
|
93
|
+
const requireSession = (params, method) => {
|
|
94
|
+
if (typeof params?.sessionId !== 'string' || params.sessionId.length === 0) {
|
|
95
|
+
throw new ScheduleError('gateway/bad-request', `${method} requires a non-empty sessionId`);
|
|
96
|
+
}
|
|
97
|
+
if (agentFor(params.sessionId) === undefined) {
|
|
98
|
+
throw new ScheduleError('session/not-found', `session "${params.sessionId}" not found (not attached)`, { sessionId: params.sessionId });
|
|
99
|
+
}
|
|
100
|
+
return params.sessionId;
|
|
101
|
+
};
|
|
102
|
+
const requireId = (params, method) => {
|
|
103
|
+
if (typeof params?.id !== 'string' || params.id.length === 0) {
|
|
104
|
+
throw new ScheduleError('gateway/bad-request', `${method} requires a non-empty schedule id`);
|
|
105
|
+
}
|
|
106
|
+
return params.id;
|
|
107
|
+
};
|
|
108
|
+
const methods = {
|
|
109
|
+
async 'schedule/list'(params) {
|
|
110
|
+
const sessionId = requireSession(params, 'schedule/list');
|
|
111
|
+
const rows = await service().catalog();
|
|
112
|
+
return { schedules: rows.filter((row) => involves(row, sessionId) && row.status !== 'ended').map(withSession) };
|
|
113
|
+
},
|
|
114
|
+
async 'schedule/create'(params) {
|
|
115
|
+
const sessionId = requireSession(params, 'schedule/create');
|
|
116
|
+
if (typeof params?.title !== 'string' || params.title.trim().length === 0) {
|
|
117
|
+
throw new ScheduleError('gateway/bad-request', 'schedule/create requires a non-empty title');
|
|
118
|
+
}
|
|
119
|
+
if (typeof params?.prompt !== 'string' || params.prompt.trim().length === 0) {
|
|
120
|
+
throw new ScheduleError('gateway/bad-request', 'schedule/create requires a non-empty prompt');
|
|
121
|
+
}
|
|
122
|
+
const rules = RULE_FIELDS.filter((field) => params[field] !== undefined);
|
|
123
|
+
const given = rules.length + (params.timing === undefined ? 0 : 1);
|
|
124
|
+
if (given !== 1 || (params.timing !== undefined && (typeof params.timing !== 'object' || params.timing === null))) {
|
|
125
|
+
throw new ScheduleError(
|
|
126
|
+
'gateway/bad-request',
|
|
127
|
+
`schedule/create needs exactly one rule (${RULE_FIELDS.join(' | ')} | timing), got ${given}`,
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
const timing = params.timing ?? timingFor(rules[0], params[rules[0]]);
|
|
131
|
+
// Default: deliver into this session. `target: {kind: 'new'}` starts a fresh thread each time.
|
|
132
|
+
const target = params.target ?? { kind: 'session', sessionId };
|
|
133
|
+
const record = await service().create({ title: params.title, prompt: params.prompt, timing, target }, sessionId);
|
|
134
|
+
return { schedule: withSession(record) };
|
|
135
|
+
},
|
|
136
|
+
async 'schedule/update'(params) {
|
|
137
|
+
const sessionId = requireSession(params, 'schedule/update');
|
|
138
|
+
const id = requireId(params, 'schedule/update');
|
|
139
|
+
if (params?.expected === undefined || typeof params.expected !== 'object' || params.expected === null) {
|
|
140
|
+
throw new ScheduleError(
|
|
141
|
+
'gateway/bad-request',
|
|
142
|
+
'schedule/update requires expected — the complete schedule record observed by a prior list/catalog',
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
const patch = {
|
|
146
|
+
...(params.title === undefined ? {} : { title: params.title }),
|
|
147
|
+
...(params.prompt === undefined ? {} : { prompt: params.prompt }),
|
|
148
|
+
...(params.change === undefined ? {} : { timing: params.change }),
|
|
149
|
+
...(params.target === undefined ? {} : { target: params.target }),
|
|
150
|
+
...(typeof params.active === 'boolean' ? { active: params.active } : {}),
|
|
151
|
+
};
|
|
152
|
+
if (Object.keys(patch).length === 0) {
|
|
153
|
+
throw new ScheduleError('gateway/bad-request', 'schedule/update needs at least one of title, prompt, change, target or active');
|
|
154
|
+
}
|
|
155
|
+
const result = await service().edit({ id, action: 'update', patch, expectedUpdatedAt: params.expected.updatedAt ?? null }, sessionId);
|
|
156
|
+
if (typeof result?.code === 'string' && result.kind === undefined) return { id, updated: false, code: result.code };
|
|
157
|
+
return { id, updated: true, record: withSession(result) };
|
|
158
|
+
},
|
|
159
|
+
async 'schedule/delete'(params) {
|
|
160
|
+
const sessionId = requireSession(params, 'schedule/delete');
|
|
161
|
+
const id = requireId(params, 'schedule/delete');
|
|
162
|
+
const result = await service().edit({ id, action: 'delete' }, sessionId);
|
|
163
|
+
if (result?.deleted === true) return { id, deleted: true };
|
|
164
|
+
return { id, deleted: false, code: typeof result?.code === 'string' ? result.code : 'schedule_not_found' };
|
|
165
|
+
},
|
|
166
|
+
async 'schedule/catalog'(params) {
|
|
167
|
+
const schedules = (await service().catalog()).map(withSession);
|
|
168
|
+
const sessionId = typeof params?.sessionId === 'string' && params.sessionId.length > 0 ? params.sessionId : undefined;
|
|
169
|
+
return { schedules: sessionId === undefined ? schedules : schedules.filter((entry) => involves(entry, sessionId)) };
|
|
170
|
+
},
|
|
171
|
+
async 'schedule/history'(params) {
|
|
172
|
+
requireSession(params, 'schedule/history');
|
|
173
|
+
const id = requireId(params, 'schedule/history');
|
|
174
|
+
const limit = params?.limit;
|
|
175
|
+
if (typeof limit !== 'number' || !Number.isSafeInteger(limit) || limit < 1 || limit > 100) {
|
|
176
|
+
throw new ScheduleError('gateway/bad-request', 'schedule/history requires a limit of 1 through 100');
|
|
177
|
+
}
|
|
178
|
+
const request = {
|
|
179
|
+
id,
|
|
180
|
+
limit,
|
|
181
|
+
...(typeof params.before === 'string' && params.before.length > 0 ? { before: params.before } : {}),
|
|
182
|
+
};
|
|
183
|
+
return service().history(request);
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
return { methods };
|
|
187
|
+
}
|