@phren/cli 0.3.67 → 0.3.69
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/dist/bridge/agent-hook-callback.js +11 -2
- package/dist/bridge/agent-hooks.d.ts +11 -1
- package/dist/bridge/agent-hooks.js +259 -40
- package/dist/bridge/changes.d.ts +2 -2
- package/dist/bridge/changes.js +11 -9
- package/dist/bridge/checkpoints.d.ts +24 -0
- package/dist/bridge/checkpoints.js +423 -0
- package/dist/bridge/claude-input-state.d.ts +14 -0
- package/dist/bridge/claude-input-state.js +58 -0
- package/dist/bridge/claude-queue.js +5 -2
- package/dist/bridge/claude-suggestion.d.ts +3 -0
- package/dist/bridge/claude-suggestion.js +10 -0
- package/dist/bridge/codex-threads.d.ts +7 -1
- package/dist/bridge/codex-threads.js +185 -56
- package/dist/bridge/conversation-search.d.ts +20 -0
- package/dist/bridge/conversation-search.js +928 -0
- package/dist/bridge/git-watch.d.ts +46 -0
- package/dist/bridge/git-watch.js +351 -0
- package/dist/bridge/git-worktree-remove.d.ts +44 -0
- package/dist/bridge/git-worktree-remove.js +140 -0
- package/dist/bridge/git-worktrees.d.ts +14 -0
- package/dist/bridge/git-worktrees.js +7 -3
- package/dist/bridge/git-write-policy.js +1 -1
- package/dist/bridge/gitboy-webhooks.d.ts +3 -1
- package/dist/bridge/gitboy-webhooks.js +26 -2
- package/dist/bridge/herdr.d.ts +6 -1
- package/dist/bridge/herdr.js +56 -10
- package/dist/bridge/hook-fast.js +13 -1
- package/dist/bridge/input-classification.d.ts +33 -0
- package/dist/bridge/input-classification.js +84 -0
- package/dist/bridge/pane-status.d.ts +3 -3
- package/dist/bridge/pane-status.js +16 -8
- package/dist/bridge/prompt-deliveries.d.ts +30 -4
- package/dist/bridge/prompt-deliveries.js +365 -13
- package/dist/bridge/prompt-identity.d.ts +8 -0
- package/dist/bridge/prompt-identity.js +15 -0
- package/dist/bridge/request-origin.js +2 -1
- package/dist/bridge/schedule-events.d.ts +17 -0
- package/dist/bridge/schedule-events.js +53 -0
- package/dist/bridge/schedule-format.d.ts +22 -2
- package/dist/bridge/schedule-format.js +40 -5
- package/dist/bridge/schedule-update.js +2 -1
- package/dist/bridge/schedule-watch.js +15 -5
- package/dist/bridge/schedules.d.ts +9 -0
- package/dist/bridge/schedules.js +120 -7
- package/dist/bridge/server-pane-routes.d.ts +7 -8
- package/dist/bridge/server-pane-routes.js +186 -82
- package/dist/bridge/server-routes.d.ts +26 -2
- package/dist/bridge/server-routes.js +180 -56
- package/dist/bridge/server-stream.js +66 -15
- package/dist/bridge/server.js +25 -7
- package/dist/bridge/session-activity.d.ts +49 -4
- package/dist/bridge/session-activity.js +47 -0
- package/dist/bridge/session-evidence.d.ts +18 -0
- package/dist/bridge/session-evidence.js +72 -0
- package/dist/bridge/session-seen.d.ts +23 -0
- package/dist/bridge/session-seen.js +69 -0
- package/dist/bridge/tab-activity.d.ts +26 -1
- package/dist/bridge/tab-activity.js +64 -9
- package/dist/bridge/terminal-resolve.d.ts +20 -0
- package/dist/bridge/terminal-resolve.js +145 -0
- package/dist/bridge/terminal-tmux.d.ts +8 -3
- package/dist/bridge/terminal-tmux.js +59 -7
- package/dist/bridge/transcript-claude.d.ts +12 -2
- package/dist/bridge/transcript-claude.js +91 -13
- package/dist/bridge/transcript-index.d.ts +4 -2
- package/dist/bridge/transcript-index.js +6 -5
- package/dist/bridge/transcript-preview.d.ts +16 -1
- package/dist/bridge/transcript-preview.js +171 -27
- package/dist/bridge/transcripts.d.ts +41 -1
- package/dist/bridge/transcripts.js +181 -23
- package/dist/bridge/turn-queue-pane.d.ts +6 -0
- package/dist/bridge/turn-queue-pane.js +30 -0
- package/dist/bridge/turn-queue.d.ts +86 -0
- package/dist/bridge/turn-queue.js +280 -0
- package/dist/bridge/turn-records.d.ts +18 -0
- package/dist/bridge/turn-records.js +77 -5
- package/dist/bridge-hook.mjs +7074 -3173
- package/dist/cli/config-shared.js +2 -1
- package/dist/cli/schedules.js +6 -1
- package/dist/content/secrets.js +1 -1
- package/dist/modules/registry.js +12 -11
- package/package.json +1 -1
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// The owner's unsent prompts, bound to a pane AND its current conversation.
|
|
2
|
+
// Delivery settlement belongs to PromptDeliveries; this file owns admission,
|
|
3
|
+
// editing, cancellation and consumption of exactly one item per Stop boundary.
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { atomicInPrivateDir, BridgeError, targetSchema } from "./protocol.js";
|
|
7
|
+
import { agentNotReady } from "./terminal.js";
|
|
8
|
+
import { turnPhase } from "./turn-records.js";
|
|
9
|
+
const itemId = z.string().regex(/^[A-Za-z0-9_-]{8,64}$/);
|
|
10
|
+
const textSchema = z.string().min(1).max(32768).refine(text => !!text.trim() && !/[\x00-\x08\x0b-\x1f\x7f]/.test(text));
|
|
11
|
+
const itemSchema = z.object({
|
|
12
|
+
id: itemId, target: targetSchema, terminal: z.string().min(1).max(200), text: textSchema,
|
|
13
|
+
state: z.enum(["queued", "sending", "delivered", "failed", "cancelled", "unknown"]),
|
|
14
|
+
reason: z.enum(["pane-closed", "agent-restarted", "conversation-changed", "delivery-failed"]).optional(),
|
|
15
|
+
detail: z.string().max(500).optional(), createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
|
|
16
|
+
});
|
|
17
|
+
const boundarySchema = z.object({ terminal: z.string(), source: z.string(), session: z.string(), stop: z.number(), at: z.string() });
|
|
18
|
+
const storeSchema = z.object({ items: z.array(itemSchema).max(512), boundaries: z.record(z.string(), boundarySchema).default({}) });
|
|
19
|
+
const paneKey = (target) => JSON.stringify([target.server, target.pane]);
|
|
20
|
+
const sameTarget = (a, b) => a.server === b.server && a.pane === b.pane && a.source === b.source && a.session === b.session;
|
|
21
|
+
const boundary = (record) => ({ terminal: record.terminal, source: record.source, session: record.session, stop: record.stop.seq, at: record.stop.at });
|
|
22
|
+
const RETENTION_MS = 24 * 3_600_000;
|
|
23
|
+
export class TurnQueue {
|
|
24
|
+
file;
|
|
25
|
+
deps;
|
|
26
|
+
items = [];
|
|
27
|
+
boundaries = {};
|
|
28
|
+
serial = Promise.resolve();
|
|
29
|
+
ticking;
|
|
30
|
+
constructor(file, deps) {
|
|
31
|
+
this.file = file;
|
|
32
|
+
this.deps = deps;
|
|
33
|
+
try {
|
|
34
|
+
const saved = storeSchema.parse(JSON.parse(readFileSync(file, "utf8")));
|
|
35
|
+
this.items = saved.items.map(item => item.state === "sending" ? { ...item, state: "unknown" } : item);
|
|
36
|
+
this.boundaries = saved.boundaries;
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (error.code !== "ENOENT")
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
run(action) {
|
|
44
|
+
const result = this.serial.then(action);
|
|
45
|
+
this.serial = result.catch(() => undefined);
|
|
46
|
+
return result;
|
|
47
|
+
}
|
|
48
|
+
async save() {
|
|
49
|
+
await atomicInPrivateDir(this.file, { items: this.items, boundaries: this.boundaries });
|
|
50
|
+
}
|
|
51
|
+
prune() {
|
|
52
|
+
this.items = this.items.filter(item => ["queued", "sending", "unknown"].includes(item.state) || Date.now() - Date.parse(item.updatedAt) < RETENTION_MS);
|
|
53
|
+
// Keep consumed boundaries while any item still belongs to that pane.
|
|
54
|
+
const panes = new Set(this.items.map(item => paneKey(item.target)));
|
|
55
|
+
for (const key of Object.keys(this.boundaries))
|
|
56
|
+
if (!panes.has(key))
|
|
57
|
+
delete this.boundaries[key];
|
|
58
|
+
}
|
|
59
|
+
count(server, pane) { return this.items.filter(item => item.target.server === server && item.target.pane === pane && item.state === "queued").length; }
|
|
60
|
+
list(target) { return structuredClone(this.items.filter(item => item.target.server === target.server && item.target.pane === target.pane)); }
|
|
61
|
+
find(target, id) {
|
|
62
|
+
const item = this.items.find(item => item.id === id && sameTarget(item.target, target));
|
|
63
|
+
if (!item)
|
|
64
|
+
throw new BridgeError(404, "No queued prompt with that id belongs to this target.");
|
|
65
|
+
return item;
|
|
66
|
+
}
|
|
67
|
+
enqueue(target, id, text) {
|
|
68
|
+
return this.run(async () => {
|
|
69
|
+
this.prune();
|
|
70
|
+
const prior = this.items.find(item => item.id === id);
|
|
71
|
+
if (prior) {
|
|
72
|
+
if (!sameTarget(prior.target, target))
|
|
73
|
+
throw new BridgeError(409, "This queue id belongs to another target.");
|
|
74
|
+
return structuredClone(prior);
|
|
75
|
+
}
|
|
76
|
+
if (this.deps.delivery(target, id).state !== "unknown")
|
|
77
|
+
throw new BridgeError(409, "This id already belongs to a prompt delivery.");
|
|
78
|
+
if (this.items.length >= 512 || this.count(target.server, target.pane) >= 20)
|
|
79
|
+
throw new BridgeError(409, "The prompt queue is full.");
|
|
80
|
+
const current = await this.deps.current(target);
|
|
81
|
+
if (!current)
|
|
82
|
+
throw new BridgeError(404, "The pane is closed.");
|
|
83
|
+
if (current.source !== target.source || current.session !== target.session)
|
|
84
|
+
throw new BridgeError(409, "The conversation changed.");
|
|
85
|
+
const at = new Date().toISOString();
|
|
86
|
+
const item = { id, target, terminal: current.terminal, text, state: "queued", createdAt: at, updatedAt: at };
|
|
87
|
+
this.items.push(item);
|
|
88
|
+
try {
|
|
89
|
+
await this.save();
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
this.items.pop();
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
return structuredClone(item);
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
change(target, id, text) {
|
|
99
|
+
return this.run(async () => {
|
|
100
|
+
const item = this.find(target, id);
|
|
101
|
+
if (item.state !== "queued")
|
|
102
|
+
throw new BridgeError(409, "Only a queued prompt can be edited or cancelled.");
|
|
103
|
+
const candidate = { ...item, ...(text === undefined ? { state: "cancelled" } : { text }), updatedAt: new Date().toISOString() };
|
|
104
|
+
await atomicInPrivateDir(this.file, { items: this.items.map(row => row === item ? candidate : row), boundaries: this.boundaries });
|
|
105
|
+
Object.assign(item, candidate);
|
|
106
|
+
return structuredClone(item);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
fail(item, reason, detail) {
|
|
110
|
+
item.state = "failed";
|
|
111
|
+
item.reason = reason;
|
|
112
|
+
item.updatedAt = new Date().toISOString();
|
|
113
|
+
if (detail)
|
|
114
|
+
item.detail = detail.slice(0, 500);
|
|
115
|
+
}
|
|
116
|
+
async settle(item) {
|
|
117
|
+
const delivery = this.deps.delivery(item.target, item.id);
|
|
118
|
+
if (delivery.state === "delivered") {
|
|
119
|
+
item.state = "delivered";
|
|
120
|
+
item.updatedAt = new Date().toISOString();
|
|
121
|
+
delete item.reason;
|
|
122
|
+
delete item.detail;
|
|
123
|
+
await this.save();
|
|
124
|
+
}
|
|
125
|
+
else if (delivery.state === "failed" && (item.state !== "failed" || item.detail !== delivery.reason)) {
|
|
126
|
+
this.fail(item, "delivery-failed", delivery.reason);
|
|
127
|
+
await this.save();
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
eligible(item, current, excludeOwn = false, allowConsumed = false) {
|
|
131
|
+
const record = current.record;
|
|
132
|
+
const previous = this.boundaries[paneKey(item.target)];
|
|
133
|
+
// Duplicate Stop callbacks do not create another turn. Require a prompt
|
|
134
|
+
// after the consumed Stop before releasing another item in this conversation.
|
|
135
|
+
const consumed = previous && record && previous.terminal === record.terminal && previous.source === record.source && previous.session === record.session
|
|
136
|
+
&& (!record.prompt || (record.source === "opencode"
|
|
137
|
+
? Date.parse(record.prompt.at) <= Date.parse(previous.at)
|
|
138
|
+
: record.prompt.seq <= previous.stop));
|
|
139
|
+
return (allowConsumed || !consumed) && !!record && record.terminal === item.terminal && record.source === item.target.source && record.session === item.target.session
|
|
140
|
+
&& turnPhase(record).phase === "ended" && !current.background && !current.held && current.ready
|
|
141
|
+
&& !this.deps.holding(item.target, excludeOwn ? item.id : undefined);
|
|
142
|
+
}
|
|
143
|
+
tick() {
|
|
144
|
+
if (this.ticking)
|
|
145
|
+
return this.ticking;
|
|
146
|
+
this.ticking = this.drain().finally(() => { this.ticking = undefined; });
|
|
147
|
+
return this.ticking;
|
|
148
|
+
}
|
|
149
|
+
reconcilable(item) {
|
|
150
|
+
return ["sending", "unknown"].includes(item.state) || (item.state === "failed" && item.reason === "delivery-failed");
|
|
151
|
+
}
|
|
152
|
+
async drain() {
|
|
153
|
+
// Serialise mutations, but never hold the lock across a prompt delivery:
|
|
154
|
+
// hooks must still be able to settle it and clients see sending immediately.
|
|
155
|
+
const panes = new Set(this.items.filter(item => item.state === "queued" || this.reconcilable(item)).map(item => paneKey(item.target)));
|
|
156
|
+
for (const key of panes) {
|
|
157
|
+
try {
|
|
158
|
+
const send = await this.run(async () => {
|
|
159
|
+
for (const item of this.items.filter(item => paneKey(item.target) === key && this.reconcilable(item)))
|
|
160
|
+
await this.settle(item);
|
|
161
|
+
const queued = this.items.filter(item => paneKey(item.target) === key && item.state === "queued");
|
|
162
|
+
let head, current;
|
|
163
|
+
for (const item of queued) {
|
|
164
|
+
current = await this.deps.current(item.target);
|
|
165
|
+
const reason = !current ? "pane-closed" : current.terminal !== item.terminal || current.source !== item.target.source ? "agent-restarted"
|
|
166
|
+
: current.session && current.session !== item.target.session ? "conversation-changed" : undefined;
|
|
167
|
+
if (reason) {
|
|
168
|
+
this.fail(item, reason);
|
|
169
|
+
await this.save();
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
head = item;
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
if (this.items.some(item => paneKey(item.target) === key && ["sending", "unknown"].includes(item.state)))
|
|
176
|
+
return;
|
|
177
|
+
if (!head || !current || !this.eligible(head, current))
|
|
178
|
+
return;
|
|
179
|
+
return { item: head, text: head.text, boundary: boundary(current.record) };
|
|
180
|
+
});
|
|
181
|
+
if (!send)
|
|
182
|
+
continue;
|
|
183
|
+
let attempted = false;
|
|
184
|
+
const previous = this.boundaries[key];
|
|
185
|
+
try {
|
|
186
|
+
const reply = await this.deps.send(send.item.target, send.text, send.item.id, () => this.run(async () => {
|
|
187
|
+
// Recheck after prompt routing's asynchronous identity/model guards.
|
|
188
|
+
const current = await this.deps.current(send.item.target);
|
|
189
|
+
if (send.item.state !== (attempted ? "sending" : "queued") || send.item.text !== send.text || !current || !this.eligible(send.item, current, true, attempted) || JSON.stringify(boundary(current.record)) !== JSON.stringify(send.boundary)) {
|
|
190
|
+
// A second typing callback is a fallback after the API path
|
|
191
|
+
// confirmed it sent nothing. Refusing it also sends nothing;
|
|
192
|
+
// retain the item for a fresh binding check on the next tick.
|
|
193
|
+
throw new BridgeError(409, "The queued prompt no longer has a safe turn boundary.", attempted ? { promptNotSent: true, promptRetry: true } : undefined);
|
|
194
|
+
}
|
|
195
|
+
if (attempted)
|
|
196
|
+
return; // rechecked a definite-refusal fallback; keep the same consumed boundary
|
|
197
|
+
send.item.state = "sending";
|
|
198
|
+
send.item.updatedAt = new Date().toISOString();
|
|
199
|
+
this.boundaries[key] = send.boundary;
|
|
200
|
+
try {
|
|
201
|
+
await this.save();
|
|
202
|
+
}
|
|
203
|
+
catch (error) {
|
|
204
|
+
send.item.state = "queued";
|
|
205
|
+
if (previous === undefined)
|
|
206
|
+
delete this.boundaries[key];
|
|
207
|
+
else
|
|
208
|
+
this.boundaries[key] = previous;
|
|
209
|
+
throw error;
|
|
210
|
+
} // write-ahead: no typing unless this succeeds
|
|
211
|
+
attempted = true;
|
|
212
|
+
}));
|
|
213
|
+
await this.run(async () => {
|
|
214
|
+
if (!attempted)
|
|
215
|
+
return;
|
|
216
|
+
await this.settle(send.item);
|
|
217
|
+
if (send.item.state === "sending" && reply.delivered === true) {
|
|
218
|
+
send.item.state = "delivered";
|
|
219
|
+
send.item.updatedAt = new Date().toISOString();
|
|
220
|
+
await this.save();
|
|
221
|
+
}
|
|
222
|
+
else if (send.item.state === "sending" && this.deps.delivery(send.item.target, send.item.id).state === "unknown") {
|
|
223
|
+
send.item.state = "unknown";
|
|
224
|
+
send.item.updatedAt = new Date().toISOString();
|
|
225
|
+
await this.save();
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
if (attempted)
|
|
231
|
+
await this.run(async () => {
|
|
232
|
+
await this.settle(send.item);
|
|
233
|
+
if (send.item.state !== "sending")
|
|
234
|
+
return;
|
|
235
|
+
if (error instanceof BridgeError && error.details?.promptNotSent === true) {
|
|
236
|
+
// The delivery path aborted its reservation: no bytes reached
|
|
237
|
+
// the agent. This Stop is still available for a later send.
|
|
238
|
+
if (previous === undefined)
|
|
239
|
+
delete this.boundaries[key];
|
|
240
|
+
else
|
|
241
|
+
this.boundaries[key] = previous;
|
|
242
|
+
if (agentNotReady(error) || error.details.promptRetry === true) {
|
|
243
|
+
send.item.state = "queued";
|
|
244
|
+
send.item.updatedAt = new Date().toISOString();
|
|
245
|
+
}
|
|
246
|
+
else
|
|
247
|
+
this.fail(send.item, "delivery-failed", error.message);
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
send.item.state = "unknown";
|
|
251
|
+
send.item.updatedAt = new Date().toISOString();
|
|
252
|
+
}
|
|
253
|
+
await this.save();
|
|
254
|
+
});
|
|
255
|
+
// Before typing, a busy guard is retried at the next tick. Other
|
|
256
|
+
// definite refusals are visible failures rather than stuck items.
|
|
257
|
+
else if (error instanceof BridgeError && error.status !== 409)
|
|
258
|
+
await this.run(async () => { this.fail(send.item, "delivery-failed", error.message); await this.save(); });
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
catch { /* Offline or unreadable: preserve the queue and try next tick. */ }
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
/** POST siblings of /v1/prompt, with its full authenticated target contract.
|
|
266
|
+
* Listing/editing/cancelling use the original target even after its pane closes. */
|
|
267
|
+
export async function turnQueueRoute(queue, route, data) {
|
|
268
|
+
const input = z.object({ target: targetSchema, id: itemId.optional(), text: textSchema.optional() }).strict().parse(data);
|
|
269
|
+
if (route === "/v1/prompt/after-turn/list")
|
|
270
|
+
return { items: queue.list(input.target) };
|
|
271
|
+
if (!input.id)
|
|
272
|
+
throw new BridgeError(400, "Name the queued prompt by id.");
|
|
273
|
+
if (route === "/v1/prompt/after-turn/cancel")
|
|
274
|
+
return { item: await queue.change(input.target, input.id) };
|
|
275
|
+
if (route !== "/v1/prompt/after-turn" && route !== "/v1/prompt/after-turn/edit")
|
|
276
|
+
throw new BridgeError(404, "Unknown prompt queue route.");
|
|
277
|
+
if (input.text === undefined)
|
|
278
|
+
throw new BridgeError(400, "Supply the queued prompt text.");
|
|
279
|
+
return { item: route.endsWith("/edit") ? await queue.change(input.target, input.id, input.text) : await queue.enqueue(input.target, input.id, input.text) };
|
|
280
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import type { InputCategory } from "./input-classification.js";
|
|
2
3
|
import { type Provider } from "./protocol.js";
|
|
3
4
|
/** Longest final reply kept from a Stop payload, in UTF-8 bytes (the receipt's limit). */
|
|
4
5
|
export declare const TURN_REPLY_LIMIT = 4000;
|
|
@@ -21,6 +22,11 @@ declare const turnRecordSchema: z.ZodObject<{
|
|
|
21
22
|
seq: z.ZodNumber;
|
|
22
23
|
at: z.ZodString;
|
|
23
24
|
}, z.core.$strip>>;
|
|
25
|
+
notification: z.ZodOptional<z.ZodObject<{
|
|
26
|
+
seq: z.ZodNumber;
|
|
27
|
+
at: z.ZodString;
|
|
28
|
+
reason: z.ZodOptional<z.ZodString>;
|
|
29
|
+
}, z.core.$strip>>;
|
|
24
30
|
stop: z.ZodOptional<z.ZodObject<{
|
|
25
31
|
seq: z.ZodNumber;
|
|
26
32
|
at: z.ZodString;
|
|
@@ -46,6 +52,18 @@ export interface TurnEvent {
|
|
|
46
52
|
dispatch?: string;
|
|
47
53
|
/** SessionStart only: how the session started, as the harness names it (Claude: startup, resume, clear, compact). */
|
|
48
54
|
start?: string;
|
|
55
|
+
/** UserPromptSubmit: whose input this is. Trusted turn writers omit this for owner input;
|
|
56
|
+
* the callback endpoint explicitly classifies automatic and unresolved submissions. */
|
|
57
|
+
input?: InputCategory;
|
|
58
|
+
/** Deferred classification of an already recorded submission, preserving
|
|
59
|
+
* its original order relative to Stops and intervening owner prompts. */
|
|
60
|
+
resolvePrompt?: {
|
|
61
|
+
seq: number;
|
|
62
|
+
at: string;
|
|
63
|
+
previous: number;
|
|
64
|
+
};
|
|
65
|
+
/** Stop: this Stop belongs to background activity, not to a foreground turn that is still running. */
|
|
66
|
+
notificationStop?: boolean;
|
|
49
67
|
/** Stop only: the harness's count of in-flight background tasks, when it reports one. */
|
|
50
68
|
background?: number;
|
|
51
69
|
/** Stop only: the background tasks it listed, `{id, running}` each (validated here). */
|
|
@@ -39,6 +39,10 @@ const turnRecordSchema = z.object({
|
|
|
39
39
|
dispatch: briefId.optional(),
|
|
40
40
|
startedAt: z.string().datetime().optional(),
|
|
41
41
|
prompt: stamp.optional(),
|
|
42
|
+
/** Automatic input (a task notification, a teammate message, a harness
|
|
43
|
+
* envelope) seen in this conversation. It is activity, never a new prompt:
|
|
44
|
+
* the owner's `prompt` and its generation stay put. */
|
|
45
|
+
notification: stamp.extend({ reason: z.string().max(80).optional() }).optional(),
|
|
42
46
|
stop: stamp.extend({
|
|
43
47
|
/** Background tasks (shells, subagents, monitors) the harness still ran when the turn stopped. */
|
|
44
48
|
background: z.number().int().min(0).max(999).optional(),
|
|
@@ -89,6 +93,13 @@ export function nextTurn(previous, event) {
|
|
|
89
93
|
const at = new Date(event.at ?? Date.now()).toISOString();
|
|
90
94
|
const same = previous && previous.terminal === event.terminal && previous.source === event.source && previous.session === event.session;
|
|
91
95
|
const record = same ? structuredClone(previous) : { terminal: event.terminal, source: event.source, session: event.session, seq: 0, at };
|
|
96
|
+
// Another deferred owner may have resolved since submission. Promote past
|
|
97
|
+
// that earlier owner, but never replace an equal/newer owner. Recheck here
|
|
98
|
+
// inside noteTurn's serialized write, after callback-side discovery awaits.
|
|
99
|
+
if (event.resolvePrompt && (!same || !record.prompt || record.prompt.seq < event.resolvePrompt.previous
|
|
100
|
+
|| record.prompt.seq >= event.resolvePrompt.seq || event.resolvePrompt.seq > record.seq
|
|
101
|
+
|| event.resolvePrompt.seq <= event.resolvePrompt.previous))
|
|
102
|
+
return undefined;
|
|
92
103
|
record.seq++;
|
|
93
104
|
record.at = at;
|
|
94
105
|
if (event.dispatch && briefId.safeParse(event.dispatch).success)
|
|
@@ -102,8 +113,22 @@ export function nextTurn(previous, event) {
|
|
|
102
113
|
delete record.stop.tasks;
|
|
103
114
|
}
|
|
104
115
|
}
|
|
105
|
-
else if (event.event === "UserPromptSubmit")
|
|
106
|
-
|
|
116
|
+
else if (event.event === "UserPromptSubmit") {
|
|
117
|
+
// Only the owner moves the logical prompt generation. A notification or a
|
|
118
|
+
// harness envelope is activity in the same turn; it may not replace the
|
|
119
|
+
// owner's anchor, completion identity or preview turn.
|
|
120
|
+
if (event.input === "owner" || event.input === undefined)
|
|
121
|
+
record.prompt = event.resolvePrompt ? { seq: event.resolvePrompt.seq, at: event.resolvePrompt.at } : { seq: record.seq, at };
|
|
122
|
+
else
|
|
123
|
+
record.notification = { seq: record.seq, at, reason: `input:${event.input ?? "unresolved"}` };
|
|
124
|
+
if (event.resolvePrompt && record.notification?.seq === event.resolvePrompt.seq)
|
|
125
|
+
delete record.notification;
|
|
126
|
+
}
|
|
127
|
+
else if (event.notificationStop) {
|
|
128
|
+
// A Stop tied to background notification traffic does not end the
|
|
129
|
+
// foreground turn that is still running.
|
|
130
|
+
record.notification = { seq: record.seq, at, reason: "stop:notification" };
|
|
131
|
+
}
|
|
107
132
|
else {
|
|
108
133
|
const reply = event.reply?.trim() ? truncateUtf8(event.reply.trim()) : undefined;
|
|
109
134
|
const tasks = stopTasks(event.backgroundTasks);
|
|
@@ -220,9 +245,56 @@ export async function opencodeTurn(pids, terminal) {
|
|
|
220
245
|
if (!stamps)
|
|
221
246
|
return undefined;
|
|
222
247
|
const busy = stamps.busyAt ? Date.parse(stamps.busyAt) : NaN, idle = stamps.idleAt ? Date.parse(stamps.idleAt) : NaN;
|
|
223
|
-
const
|
|
224
|
-
|
|
248
|
+
const idleAt = stamps.idleAt;
|
|
249
|
+
let stopSeq;
|
|
250
|
+
if (typeof idleAt === "string" && Number.isFinite(idle) && !(idle < busy)) {
|
|
251
|
+
stopSeq = await opencodeStopSeq(stamps.session, idleAt);
|
|
252
|
+
// An older stamp describes a turn already recorded: do not turn it into a working prompt.
|
|
253
|
+
if (stopSeq === undefined)
|
|
254
|
+
return undefined;
|
|
255
|
+
}
|
|
256
|
+
const parsed = turnRecordSchema.safeParse({ terminal, source: "opencode", session: stamps.session, seq: stopSeq ?? 2, at: stamps.at,
|
|
257
|
+
...(Number.isFinite(busy) ? { prompt: { seq: stopSeq !== undefined ? stopSeq - 1 : 1, at: stamps.busyAt } } : {}),
|
|
225
258
|
// The plugin stamps idle after busy; an idle stamp older than the busy one belongs to an earlier turn.
|
|
226
|
-
...(
|
|
259
|
+
...(stopSeq !== undefined ? { stop: { seq: stopSeq, at: idleAt } } : {}) });
|
|
227
260
|
return parsed.success ? parsed.data : undefined;
|
|
228
261
|
}
|
|
262
|
+
const OPENCODE_SEQ_START = 2;
|
|
263
|
+
const opencodeSeqSchema = z.object({ session: sessionId, idleAt: z.string().datetime(), seq: z.number().int().min(OPENCODE_SEQ_START) });
|
|
264
|
+
/** The advancing Stop sequence for OpenCode conversation `session`, keyed by
|
|
265
|
+
* its latest idle stamp: a new idle stamp is a new turn, and the sequence is
|
|
266
|
+
* persisted so a Hook restart keeps the same completion ids. */
|
|
267
|
+
const opencodeSeqPath = (session) => path.join(bridgeRoot(), "opencode-turns", encodeURIComponent(session) + ".json");
|
|
268
|
+
async function readOpencodeSeq(file) {
|
|
269
|
+
try {
|
|
270
|
+
const info = await lstat(file);
|
|
271
|
+
if (!info.isFile() || info.size > 1_024)
|
|
272
|
+
return undefined;
|
|
273
|
+
const parsed = opencodeSeqSchema.safeParse(JSON.parse(await readFile(file, "utf8")));
|
|
274
|
+
return parsed.success ? parsed.data : undefined;
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
return undefined;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
let opencodeWrites = Promise.resolve();
|
|
281
|
+
function opencodeStopSeq(session, idleAt) {
|
|
282
|
+
const run = opencodeWrites.then(async () => {
|
|
283
|
+
const file = opencodeSeqPath(session), previous = await readOpencodeSeq(file);
|
|
284
|
+
if (previous?.session !== session) {
|
|
285
|
+
await atomicInPrivateDir(file, { session, idleAt, seq: OPENCODE_SEQ_START });
|
|
286
|
+
return OPENCODE_SEQ_START;
|
|
287
|
+
}
|
|
288
|
+
const previousAt = Date.parse(previous.idleAt), incomingAt = Date.parse(idleAt);
|
|
289
|
+
if (incomingAt === previousAt)
|
|
290
|
+
return previous.seq;
|
|
291
|
+
// An overlapping read can enqueue an older stamp after a newer one: it is not a new turn.
|
|
292
|
+
if (incomingAt < previousAt)
|
|
293
|
+
return undefined;
|
|
294
|
+
const seq = previous.seq + 2;
|
|
295
|
+
await atomicInPrivateDir(file, { session, idleAt, seq });
|
|
296
|
+
return seq;
|
|
297
|
+
});
|
|
298
|
+
opencodeWrites = run.catch(() => undefined);
|
|
299
|
+
return run;
|
|
300
|
+
}
|