@howaboua/pi-durable-pulses 0.0.0-stage → 0.10.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/LICENSE +21 -0
- package/NOTICE +20 -0
- package/README.md +50 -2
- package/dist/activation.d.ts +5 -0
- package/dist/activation.js +1255 -0
- package/dist/admission.d.ts +9 -0
- package/dist/authoring.d.ts +1 -0
- package/dist/contract.d.ts +51 -0
- package/dist/definitions.d.ts +27 -0
- package/dist/execution.d.ts +14 -0
- package/dist/frontmatter.d.ts +5 -0
- package/dist/index.d.ts +132 -0
- package/dist/index.js +1213 -0
- package/dist/occurrences.d.ts +6 -0
- package/dist/schedule.d.ts +24 -0
- package/dist/state.d.ts +47 -0
- package/dist/tasks.d.ts +28 -0
- package/dist/tool.d.ts +38 -0
- package/package.json +64 -5
- package/skills/pulses-ops/SKILL.md +14 -0
|
@@ -0,0 +1,1255 @@
|
|
|
1
|
+
// packages/pulses/src/activation.ts
|
|
2
|
+
import {
|
|
3
|
+
defineCapability,
|
|
4
|
+
isCapabilityObject,
|
|
5
|
+
schedulingCapability
|
|
6
|
+
} from "@howaboua/pi-durable-components";
|
|
7
|
+
|
|
8
|
+
// packages/pulses/src/index.ts
|
|
9
|
+
import {
|
|
10
|
+
defineExtension
|
|
11
|
+
} from "@earendil-works/pi-durable";
|
|
12
|
+
|
|
13
|
+
// packages/pulses/src/admission.ts
|
|
14
|
+
import {
|
|
15
|
+
InboxDoc,
|
|
16
|
+
LiveDoc as LiveDoc2
|
|
17
|
+
} from "@earendil-works/pi-durable";
|
|
18
|
+
|
|
19
|
+
// packages/pulses/src/schedule.ts
|
|
20
|
+
var DURATION_PATTERN = /^(\d+)\s*(m|min|mins|minute|minutes|h|hr|hour|hours|d|day|days)$/iu;
|
|
21
|
+
var EVERY_PATTERN = /^every\s+(.+)$/iu;
|
|
22
|
+
var DAILY_PATTERN = /^daily\s+(\d{1,2}):(\d{2})$/iu;
|
|
23
|
+
var WEEKLY_PATTERN = /^weekly\s+(sun|mon|tue|wed|thu|fri|sat|sunday|monday|tuesday|wednesday|thursday|friday|saturday)\s+(\d{1,2}):(\d{2})$/iu;
|
|
24
|
+
var AT_PATTERN = /^at\s+(.+)$/iu;
|
|
25
|
+
var QUIET_HOURS_PATTERN = /^(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})$/u;
|
|
26
|
+
var DAY_INDEX = {
|
|
27
|
+
sun: 0,
|
|
28
|
+
sunday: 0,
|
|
29
|
+
mon: 1,
|
|
30
|
+
monday: 1,
|
|
31
|
+
tue: 2,
|
|
32
|
+
tuesday: 2,
|
|
33
|
+
wed: 3,
|
|
34
|
+
wednesday: 3,
|
|
35
|
+
thu: 4,
|
|
36
|
+
thursday: 4,
|
|
37
|
+
fri: 5,
|
|
38
|
+
friday: 5,
|
|
39
|
+
sat: 6,
|
|
40
|
+
saturday: 6
|
|
41
|
+
};
|
|
42
|
+
function parseDurationMs(raw) {
|
|
43
|
+
const match = DURATION_PATTERN.exec(raw.trim());
|
|
44
|
+
if (!match)
|
|
45
|
+
return null;
|
|
46
|
+
const amount = Number(match[1]);
|
|
47
|
+
const unit = match[2]?.toLowerCase();
|
|
48
|
+
if (!Number.isFinite(amount) || amount <= 0 || !unit)
|
|
49
|
+
return null;
|
|
50
|
+
if (unit.startsWith("m"))
|
|
51
|
+
return amount * 60000;
|
|
52
|
+
if (unit === "h" || unit === "hr" || unit.startsWith("hour"))
|
|
53
|
+
return amount * 3600000;
|
|
54
|
+
if (unit.startsWith("d"))
|
|
55
|
+
return amount * 86400000;
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
function validTime(hour, minute) {
|
|
59
|
+
return Number.isInteger(hour) && Number.isInteger(minute) && hour >= 0 && hour < 24 && minute >= 0 && minute < 60;
|
|
60
|
+
}
|
|
61
|
+
function parsePulseQuietHours(raw) {
|
|
62
|
+
const match = QUIET_HOURS_PATTERN.exec(raw.trim());
|
|
63
|
+
if (!(match?.[1] && match[2] && match[3] && match[4]))
|
|
64
|
+
return null;
|
|
65
|
+
const startHour = Number(match[1]);
|
|
66
|
+
const startMinute = Number(match[2]);
|
|
67
|
+
const endHour = Number(match[3]);
|
|
68
|
+
const endMinute = Number(match[4]);
|
|
69
|
+
if (!(validTime(startHour, startMinute) && validTime(endHour, endMinute)))
|
|
70
|
+
return null;
|
|
71
|
+
const start = startHour * 60 + startMinute;
|
|
72
|
+
const end = endHour * 60 + endMinute;
|
|
73
|
+
return start === end ? null : { startMinute: start, endMinute: end };
|
|
74
|
+
}
|
|
75
|
+
function isPulseQuietAt(quietHours, nowMs) {
|
|
76
|
+
const now = new Date(nowMs);
|
|
77
|
+
const minute = now.getHours() * 60 + now.getMinutes();
|
|
78
|
+
if (quietHours.startMinute < quietHours.endMinute) {
|
|
79
|
+
return minute >= quietHours.startMinute && minute < quietHours.endMinute;
|
|
80
|
+
}
|
|
81
|
+
return minute >= quietHours.startMinute || minute < quietHours.endMinute;
|
|
82
|
+
}
|
|
83
|
+
function parsePulseSchedule(raw) {
|
|
84
|
+
const text = raw.trim();
|
|
85
|
+
if (text === "")
|
|
86
|
+
return null;
|
|
87
|
+
if (text.toLowerCase() === "manual")
|
|
88
|
+
return { kind: "manual" };
|
|
89
|
+
return parseIntervalSchedule(text) ?? parseDailySchedule(text) ?? parseWeeklySchedule(text) ?? parseAtSchedule(text);
|
|
90
|
+
}
|
|
91
|
+
function parseIntervalSchedule(text) {
|
|
92
|
+
const every = EVERY_PATTERN.exec(text);
|
|
93
|
+
if (every?.[1]) {
|
|
94
|
+
const everyMs = parseDurationMs(every[1]);
|
|
95
|
+
return everyMs ? { kind: "interval", everyMs } : null;
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
function parseDailySchedule(text) {
|
|
100
|
+
const daily = DAILY_PATTERN.exec(text);
|
|
101
|
+
if (daily?.[1] && daily[2]) {
|
|
102
|
+
const hour = Number(daily[1]);
|
|
103
|
+
const minute = Number(daily[2]);
|
|
104
|
+
return validTime(hour, minute) ? { kind: "daily", hour, minute } : null;
|
|
105
|
+
}
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
function parseWeeklySchedule(text) {
|
|
109
|
+
const weekly = WEEKLY_PATTERN.exec(text);
|
|
110
|
+
if (weekly?.[1] && weekly[2] && weekly[3]) {
|
|
111
|
+
const day = DAY_INDEX[weekly[1].toLowerCase()];
|
|
112
|
+
const hour = Number(weekly[2]);
|
|
113
|
+
const minute = Number(weekly[3]);
|
|
114
|
+
return day !== undefined && validTime(hour, minute) ? { kind: "weekly", day, hour, minute } : null;
|
|
115
|
+
}
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
function parseAtSchedule(text) {
|
|
119
|
+
const at = AT_PATTERN.exec(text);
|
|
120
|
+
if (at?.[1]) {
|
|
121
|
+
const atMs = Date.parse(at[1]);
|
|
122
|
+
return Number.isFinite(atMs) ? { kind: "at", atMs } : null;
|
|
123
|
+
}
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
function pulseDueKey(schedule, nowMs) {
|
|
127
|
+
if (schedule.kind === "manual")
|
|
128
|
+
return null;
|
|
129
|
+
const now = new Date(nowMs);
|
|
130
|
+
if (schedule.kind === "interval")
|
|
131
|
+
return `interval:${Math.floor(nowMs / schedule.everyMs)}`;
|
|
132
|
+
if (schedule.kind === "at")
|
|
133
|
+
return nowMs >= schedule.atMs ? `at:${schedule.atMs}` : null;
|
|
134
|
+
const slot = new Date(now);
|
|
135
|
+
slot.setHours(schedule.hour, schedule.minute, 0, 0);
|
|
136
|
+
if (schedule.kind === "daily") {
|
|
137
|
+
if (nowMs < slot.getTime())
|
|
138
|
+
slot.setDate(slot.getDate() - 1);
|
|
139
|
+
return `daily:${slot.toISOString().slice(0, 10)}:${schedule.hour}:${schedule.minute}`;
|
|
140
|
+
}
|
|
141
|
+
const diff = (now.getDay() - schedule.day + 7) % 7;
|
|
142
|
+
slot.setDate(slot.getDate() - diff);
|
|
143
|
+
if (nowMs < slot.getTime())
|
|
144
|
+
return null;
|
|
145
|
+
return `weekly:${slot.toISOString().slice(0, 10)}:${schedule.day}:${schedule.hour}:${schedule.minute}`;
|
|
146
|
+
}
|
|
147
|
+
function nextPulseDue(schedule, after) {
|
|
148
|
+
if (schedule.kind === "manual")
|
|
149
|
+
return;
|
|
150
|
+
if (schedule.kind === "interval")
|
|
151
|
+
return after + schedule.everyMs;
|
|
152
|
+
if (schedule.kind === "at")
|
|
153
|
+
return schedule.atMs > after ? schedule.atMs : undefined;
|
|
154
|
+
const slot = new Date(after);
|
|
155
|
+
slot.setHours(schedule.hour, schedule.minute, 0, 0);
|
|
156
|
+
if (schedule.kind === "weekly") {
|
|
157
|
+
slot.setDate(slot.getDate() + (schedule.day - slot.getDay() + 7) % 7);
|
|
158
|
+
slot.setHours(schedule.hour, schedule.minute, 0, 0);
|
|
159
|
+
}
|
|
160
|
+
if (slot.getTime() <= after) {
|
|
161
|
+
slot.setDate(slot.getDate() + (schedule.kind === "weekly" ? 7 : 1));
|
|
162
|
+
slot.setHours(schedule.hour, schedule.minute, 0, 0);
|
|
163
|
+
}
|
|
164
|
+
return slot.getTime();
|
|
165
|
+
}
|
|
166
|
+
function pulseOccurrences(schedule, first, now) {
|
|
167
|
+
if (first > now || schedule.kind === "manual")
|
|
168
|
+
return;
|
|
169
|
+
if (schedule.kind === "at")
|
|
170
|
+
return { count: 1, startAt: first, endAt: first };
|
|
171
|
+
if (schedule.kind === "interval") {
|
|
172
|
+
const count = Math.floor((now - first) / schedule.everyMs) + 1;
|
|
173
|
+
return {
|
|
174
|
+
count,
|
|
175
|
+
startAt: first,
|
|
176
|
+
endAt: first + (count - 1) * schedule.everyMs
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
const last = new Date(now);
|
|
180
|
+
last.setHours(schedule.hour, schedule.minute, 0, 0);
|
|
181
|
+
if (schedule.kind === "weekly") {
|
|
182
|
+
last.setDate(last.getDate() - (last.getDay() - schedule.day + 7) % 7);
|
|
183
|
+
last.setHours(schedule.hour, schedule.minute, 0, 0);
|
|
184
|
+
}
|
|
185
|
+
if (last.getTime() > now) {
|
|
186
|
+
last.setDate(last.getDate() - (schedule.kind === "weekly" ? 7 : 1));
|
|
187
|
+
last.setHours(schedule.hour, schedule.minute, 0, 0);
|
|
188
|
+
}
|
|
189
|
+
if (last.getTime() < first)
|
|
190
|
+
return;
|
|
191
|
+
const day = (date) => Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / 86400000;
|
|
192
|
+
const count = Math.round((day(last) - day(new Date(first))) / (schedule.kind === "weekly" ? 7 : 1)) + 1;
|
|
193
|
+
return { count, startAt: first, endAt: last.getTime() };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// packages/pulses/src/state.ts
|
|
197
|
+
import {
|
|
198
|
+
defineDoc
|
|
199
|
+
} from "@earendil-works/pi-durable";
|
|
200
|
+
var Checkpoints = defineDoc({
|
|
201
|
+
kind: "howaboua.pulses.checkpoints",
|
|
202
|
+
version: 1,
|
|
203
|
+
scope: "session",
|
|
204
|
+
checkpointWhen: (_value, _ops, { deltasSinceBase }) => deltasSinceBase >= 64,
|
|
205
|
+
initial: () => ({ pulses: {} })
|
|
206
|
+
});
|
|
207
|
+
var pulseKey = (bindingKey, id) => JSON.stringify([bindingKey, id]);
|
|
208
|
+
async function restoreMissingReferences(tx) {
|
|
209
|
+
const state = await tx.doc(Checkpoints);
|
|
210
|
+
const missing = new Set(Object.entries(state.pulses).filter(([, checkpoint]) => !checkpoint.current && checkpoint.activeTask === undefined && checkpoint.history.length === 0).map(([key]) => key));
|
|
211
|
+
if (missing.size === 0)
|
|
212
|
+
return;
|
|
213
|
+
let cursor;
|
|
214
|
+
do {
|
|
215
|
+
const page = await tx.scanTasks({ kind: "howaboua.pulses.run", order: "descending" }, 100, cursor);
|
|
216
|
+
for (const task of page.items) {
|
|
217
|
+
const input = task.input;
|
|
218
|
+
if (typeof input !== "object" || input === null || Array.isArray(input))
|
|
219
|
+
throw new Error("Invalid admitted pulse input");
|
|
220
|
+
const binding = input["binding"];
|
|
221
|
+
const definition = input["definition"];
|
|
222
|
+
if (typeof binding !== "object" || binding === null || Array.isArray(binding) || typeof binding["key"] !== "string" || typeof definition !== "object" || definition === null || Array.isArray(definition) || typeof definition["id"] !== "string")
|
|
223
|
+
throw new Error("Invalid admitted pulse identity");
|
|
224
|
+
const key = pulseKey(binding["key"], definition["id"]);
|
|
225
|
+
if (!missing.has(key))
|
|
226
|
+
continue;
|
|
227
|
+
const reference = input["reference"];
|
|
228
|
+
if (typeof reference !== "object" || reference === null || Array.isArray(reference) || reference["conversationId"] !== task.conversationId || typeof reference["root"] !== "string" || typeof reference["pulseHome"] !== "string")
|
|
229
|
+
throw new Error("Invalid admitted pulse conversation reference");
|
|
230
|
+
const conversation = await tx.conversation(task.conversationId);
|
|
231
|
+
const resident = definition["target"] === "resident";
|
|
232
|
+
if (!conversation || (resident ? conversation.id !== binding["parentConversationId"] : reference["parentConversationId"] !== conversation.owner?.conversationId))
|
|
233
|
+
throw new Error("Admitted pulse conversation ownership is unavailable");
|
|
234
|
+
const checkpoint = state.pulses[key];
|
|
235
|
+
if (!checkpoint)
|
|
236
|
+
throw new Error("Missing pulse reference checkpoint");
|
|
237
|
+
const restored = {
|
|
238
|
+
conversationId: conversation.id,
|
|
239
|
+
root: reference["root"],
|
|
240
|
+
pulseHome: reference["pulseHome"],
|
|
241
|
+
...resident ? { target: "resident" } : {},
|
|
242
|
+
...!resident && conversation.owner ? { parentConversationId: conversation.owner.conversationId } : {}
|
|
243
|
+
};
|
|
244
|
+
checkpoint.current = restored;
|
|
245
|
+
checkpoint.history.push(restored);
|
|
246
|
+
checkpoint.activeTask = task.id;
|
|
247
|
+
missing.delete(key);
|
|
248
|
+
if (missing.size === 0)
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
cursor = page.next;
|
|
252
|
+
} while (cursor !== undefined);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// packages/pulses/src/tasks.ts
|
|
256
|
+
import {
|
|
257
|
+
ConversationBusy,
|
|
258
|
+
defineTask,
|
|
259
|
+
LiveDoc
|
|
260
|
+
} from "@earendil-works/pi-durable";
|
|
261
|
+
var completed = {
|
|
262
|
+
status: "terminal",
|
|
263
|
+
outcome: { status: "completed", result: null }
|
|
264
|
+
};
|
|
265
|
+
var aborted = { status: "terminal", outcome: { status: "aborted" } };
|
|
266
|
+
var resultGuidance = "Use appropriate available tools or destinations for substantive task results and logs. Your final assistant message to the main agent should briefly confirm completion and point to the outcome, without repeating it. Report failures, ambiguities or suggested improvements to the pulse procedure only in that final assistant message, separately from the completion summary. Do not put this procedural feedback in task logs, notes or boards. Do not edit the pulse definition unless its instructions explicitly authorise it.";
|
|
267
|
+
var Anchor = defineTask({
|
|
268
|
+
name: "howaboua.pulses.anchor",
|
|
269
|
+
version: 1,
|
|
270
|
+
initial: () => ({ phase: "done" }),
|
|
271
|
+
phases: {
|
|
272
|
+
done: (_task, runtime, context) => runtime.commit(() => completed, context)
|
|
273
|
+
},
|
|
274
|
+
abort: (_task, runtime, context) => runtime.commit(() => aborted, context)
|
|
275
|
+
});
|
|
276
|
+
var pulseInputRequestId = (taskId) => `pulse-input:${taskId}`;
|
|
277
|
+
function createRunTask(host, options) {
|
|
278
|
+
return defineTask({
|
|
279
|
+
name: "howaboua.pulses.run",
|
|
280
|
+
version: 1,
|
|
281
|
+
initial: () => ({ phase: "dispatch" }),
|
|
282
|
+
phases: {
|
|
283
|
+
dispatch: async (task, runtime, context) => {
|
|
284
|
+
const conversation = await runtime.conversation(task.input.reference.conversationId, context);
|
|
285
|
+
if (!conversation)
|
|
286
|
+
throw new Error("Missing pulse conversation");
|
|
287
|
+
const { definition, trigger, occurrence } = task.input;
|
|
288
|
+
const period = occurrence ? `
|
|
289
|
+
Scheduled occurrences coalesced: ${occurrence.count}. Period: ${new Date(occurrence.startAt).toISOString()} through ${new Date(occurrence.endAt).toISOString()}. Cover relevant work since the start of this period in one fresh run; do not replay each occurrence.` : "";
|
|
290
|
+
const content = `[Pulse: ${definition.title}; ${trigger}]
|
|
291
|
+
Workspace: ${definition.root}
|
|
292
|
+
Pulse home: ${definition.pulseHome}
|
|
293
|
+
Definition: ${definition.path}${period}
|
|
294
|
+
Before work, read applicable instructions including ${definition.pulseHome}/AGENTS.md if present. Preserve the pulse folder and use its existing journal/artifact conventions.
|
|
295
|
+
|
|
296
|
+
${definition.body}
|
|
297
|
+
|
|
298
|
+
${resultGuidance}`;
|
|
299
|
+
const requestId = pulseInputRequestId(task.id);
|
|
300
|
+
const outcome = await (async () => {
|
|
301
|
+
const previous = await host().commit((tx) => tx.submissionByRequest(task.input.reference.conversationId, requestId), context);
|
|
302
|
+
if (previous) {
|
|
303
|
+
const submission = await host().submission(previous.id, context);
|
|
304
|
+
if (!submission)
|
|
305
|
+
throw new Error("Missing admitted pulse submission");
|
|
306
|
+
return submission.wait(context);
|
|
307
|
+
}
|
|
308
|
+
if (options.submitInput)
|
|
309
|
+
return options.submitInput({
|
|
310
|
+
conversationId: task.input.reference.conversationId,
|
|
311
|
+
taskId: task.id,
|
|
312
|
+
requestId,
|
|
313
|
+
content
|
|
314
|
+
}, context);
|
|
315
|
+
const submission = await conversation.submit({ type: "input", requestId, whenBusy: "reject", content }, context);
|
|
316
|
+
return submission.wait(context);
|
|
317
|
+
})().catch(async (error) => {
|
|
318
|
+
if (!(error instanceof ConversationBusy))
|
|
319
|
+
throw error;
|
|
320
|
+
await runtime.commit(() => ({
|
|
321
|
+
status: "running",
|
|
322
|
+
checkpoint: { phase: "retry", after: runtime.now() + 5000 }
|
|
323
|
+
}), context);
|
|
324
|
+
return;
|
|
325
|
+
});
|
|
326
|
+
if (!outcome)
|
|
327
|
+
return;
|
|
328
|
+
if (outcome.type !== "input" || outcome.requestId !== requestId || outcome.conversationId !== task.input.reference.conversationId)
|
|
329
|
+
throw new Error("Pulse delivery returned a different native input receipt");
|
|
330
|
+
await runtime.commit(() => ({
|
|
331
|
+
status: "running",
|
|
332
|
+
checkpoint: { phase: "deliver", outcome }
|
|
333
|
+
}), context);
|
|
334
|
+
},
|
|
335
|
+
retry: async (task, runtime, context) => {
|
|
336
|
+
await runtime.sleepUntil(task.state.checkpoint.after, { phase: "dispatch" }, context);
|
|
337
|
+
},
|
|
338
|
+
deliver: async (task, runtime, context) => {
|
|
339
|
+
const outcome = task.state.checkpoint.outcome;
|
|
340
|
+
const parentConversationId = task.input.reference.parentConversationId;
|
|
341
|
+
if (parentConversationId !== undefined) {
|
|
342
|
+
const delivery = {
|
|
343
|
+
parentConversationId,
|
|
344
|
+
conversationId: task.input.reference.conversationId,
|
|
345
|
+
taskId: task.id,
|
|
346
|
+
outcome,
|
|
347
|
+
requestId: `pulse-result:${task.id}`,
|
|
348
|
+
title: task.input.definition.title,
|
|
349
|
+
text: await resultText(host(), outcome, context),
|
|
350
|
+
...task.input.occurrence ? { occurrence: task.input.occurrence } : {}
|
|
351
|
+
};
|
|
352
|
+
const receipt = await runtime.memo("passive-receipt", context) ?? (options.writeResult ? await options.writeResult(delivery, context) : await passiveResult(host(), delivery, context));
|
|
353
|
+
if (receipt.type !== "write" || receipt.status !== "done" || receipt.requestId !== delivery.requestId || receipt.conversationId !== parentConversationId)
|
|
354
|
+
throw new Error(`Pulse passive delivery did not settle: ${receipt.status}`);
|
|
355
|
+
await runtime.memo("passive-receipt", receipt, context);
|
|
356
|
+
}
|
|
357
|
+
await runtime.commit(() => ({
|
|
358
|
+
status: "terminal",
|
|
359
|
+
outcome: { status: "completed", result: outcome }
|
|
360
|
+
}), context);
|
|
361
|
+
}
|
|
362
|
+
},
|
|
363
|
+
abort: async (task, runtime, context) => {
|
|
364
|
+
const harness = host();
|
|
365
|
+
const { native, run } = await harness.commit(async (tx) => {
|
|
366
|
+
const native = await tx.submissionByRequest(task.input.reference.conversationId, `pulse-input:${task.id}`);
|
|
367
|
+
const live = await tx.doc(LiveDoc, task.input.reference.conversationId);
|
|
368
|
+
return {
|
|
369
|
+
native: native === undefined ? undefined : { ...native },
|
|
370
|
+
run: native?.status === "placed" && live.run?.inputs.includes(native.id) ? live.run.taskId : undefined
|
|
371
|
+
};
|
|
372
|
+
}, context);
|
|
373
|
+
if (run !== undefined) {
|
|
374
|
+
await harness.abortTask(run, context);
|
|
375
|
+
await harness.waitForTask(run, context);
|
|
376
|
+
}
|
|
377
|
+
let outcome = { status: "aborted" };
|
|
378
|
+
if (native !== undefined) {
|
|
379
|
+
const submission = await harness.submission(native.id, context);
|
|
380
|
+
if (!submission)
|
|
381
|
+
throw new Error("Missing aborted pulse submission");
|
|
382
|
+
outcome = await submission.wait(context);
|
|
383
|
+
}
|
|
384
|
+
const parentConversationId = task.input.reference.parentConversationId;
|
|
385
|
+
if (parentConversationId !== undefined) {
|
|
386
|
+
const delivery = {
|
|
387
|
+
parentConversationId,
|
|
388
|
+
conversationId: task.input.reference.conversationId,
|
|
389
|
+
taskId: task.id,
|
|
390
|
+
outcome,
|
|
391
|
+
title: task.input.definition.title,
|
|
392
|
+
text: await resultText(harness, outcome, context),
|
|
393
|
+
requestId: `pulse-result:${task.id}`,
|
|
394
|
+
...task.input.occurrence ? { occurrence: task.input.occurrence } : {}
|
|
395
|
+
};
|
|
396
|
+
const receipt = await runtime.memo("passive-receipt", context) ?? (options.writeResult ? await options.writeResult(delivery, context) : await passiveResult(harness, delivery, context));
|
|
397
|
+
if (receipt.type !== "write" || receipt.status !== "done" || receipt.requestId !== delivery.requestId || receipt.conversationId !== parentConversationId)
|
|
398
|
+
throw new Error("Aborted pulse passive delivery did not settle");
|
|
399
|
+
await runtime.memo("passive-receipt", receipt, context);
|
|
400
|
+
}
|
|
401
|
+
await runtime.commit(() => aborted, context);
|
|
402
|
+
}
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
async function passiveResult(harness, delivery, context) {
|
|
406
|
+
const parent = await harness.conversation(delivery.parentConversationId, context);
|
|
407
|
+
if (!parent)
|
|
408
|
+
throw new Error("Missing pulse result recipient");
|
|
409
|
+
const text = `[Pulse result: ${delivery.title}; conversation ${delivery.conversationId}; task ${delivery.taskId}; ${delivery.outcome.status}]
|
|
410
|
+
${delivery.text}`;
|
|
411
|
+
const submission = await parent.submit({
|
|
412
|
+
type: "write",
|
|
413
|
+
requestId: delivery.requestId,
|
|
414
|
+
entry: {
|
|
415
|
+
kind: "howaboua.pulses.result",
|
|
416
|
+
data: delivery,
|
|
417
|
+
model: [{ role: "user", content: text, timestamp: Date.now() }]
|
|
418
|
+
}
|
|
419
|
+
}, context);
|
|
420
|
+
return submission.wait(context);
|
|
421
|
+
}
|
|
422
|
+
async function resultText(harness, outcome, context) {
|
|
423
|
+
if (!("type" in outcome) || outcome.type !== "input" || outcome.status !== "done")
|
|
424
|
+
return JSON.stringify(outcome);
|
|
425
|
+
const answer = outcome.answer;
|
|
426
|
+
const entry = await harness.commit((tx) => tx.entry(answer), context);
|
|
427
|
+
if (!entry)
|
|
428
|
+
throw new Error(`Missing pulse answer ${answer}`);
|
|
429
|
+
return (entry.model ?? []).filter((message) => message.role === "assistant").flatMap((message) => typeof message.content === "string" ? [message.content] : message.content.flatMap((part) => part.type === "text" ? [part.text] : [])).join(`
|
|
430
|
+
`);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// packages/pulses/src/admission.ts
|
|
434
|
+
async function admitted(tx, bindingKey, pulseId, requestId) {
|
|
435
|
+
let cursor;
|
|
436
|
+
do {
|
|
437
|
+
const page = await tx.scanTasks({ kind: "howaboua.pulses.run", order: "descending" }, 100, cursor);
|
|
438
|
+
for (const task of page.items) {
|
|
439
|
+
const input = task.input;
|
|
440
|
+
if (typeof input !== "object" || input === null || Array.isArray(input))
|
|
441
|
+
continue;
|
|
442
|
+
const binding = input["binding"];
|
|
443
|
+
const definition = input["definition"];
|
|
444
|
+
if (typeof binding !== "object" || binding === null || Array.isArray(binding) || typeof definition !== "object" || definition === null || Array.isArray(definition))
|
|
445
|
+
continue;
|
|
446
|
+
if (binding["key"] === bindingKey && definition["id"] === pulseId && input["requestId"] === requestId)
|
|
447
|
+
return task.id;
|
|
448
|
+
}
|
|
449
|
+
cursor = page.next;
|
|
450
|
+
} while (cursor !== undefined);
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
async function capacity(tx) {
|
|
454
|
+
let cursor;
|
|
455
|
+
let active = 0;
|
|
456
|
+
let backoffUntil = 0;
|
|
457
|
+
do {
|
|
458
|
+
const page = await tx.scanTasks({ kind: "howaboua.pulses.run" }, 100, cursor);
|
|
459
|
+
for (const task of page.items) {
|
|
460
|
+
if (task.state.status === "terminal")
|
|
461
|
+
continue;
|
|
462
|
+
active++;
|
|
463
|
+
const live = await tx.doc(LiveDoc2, task.conversationId);
|
|
464
|
+
backoffUntil = Math.max(backoffUntil, live.generation?.retry?.at ?? 0);
|
|
465
|
+
}
|
|
466
|
+
cursor = page.next;
|
|
467
|
+
} while (cursor !== undefined);
|
|
468
|
+
return { active, backoffUntil };
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
class AdmissionBlocked extends Error {
|
|
472
|
+
decision;
|
|
473
|
+
constructor(decision) {
|
|
474
|
+
super(decision.reason);
|
|
475
|
+
this.decision = decision;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
function validateConcurrency(limit) {
|
|
479
|
+
if (!Number.isSafeInteger(limit) || limit < 1)
|
|
480
|
+
throw new Error("Pulse concurrency must be a positive safe integer");
|
|
481
|
+
return limit;
|
|
482
|
+
}
|
|
483
|
+
function createAdmission(host, options, Run, accepting) {
|
|
484
|
+
return async function dispatch(definition, trigger, requestId, context) {
|
|
485
|
+
const receipt = await host().commit((tx) => admitted(tx, definition.bindingKey, definition.id, requestId), context);
|
|
486
|
+
if (receipt !== undefined)
|
|
487
|
+
return receipt;
|
|
488
|
+
const binding = (await options.getBindings(context)).find((value) => value.key === definition.bindingKey);
|
|
489
|
+
if (!binding || binding.root !== definition.root)
|
|
490
|
+
throw new Error("Pulse binding changed; rescan before admission");
|
|
491
|
+
await options.admit(binding, definition, trigger, context);
|
|
492
|
+
if (!accepting())
|
|
493
|
+
throw new Error("Pulses admission has stopped");
|
|
494
|
+
const now = Date.now();
|
|
495
|
+
try {
|
|
496
|
+
const id = await host().commit(async (tx) => {
|
|
497
|
+
const existing = await admitted(tx, binding.key, definition.id, requestId);
|
|
498
|
+
if (existing !== undefined)
|
|
499
|
+
return existing;
|
|
500
|
+
const state = await tx.doc(Checkpoints);
|
|
501
|
+
const key = pulseKey(binding.key, definition.id);
|
|
502
|
+
state.pulses[key] ??= { firstSeenAt: now, history: [] };
|
|
503
|
+
const checkpoint = state.pulses[key];
|
|
504
|
+
if (!checkpoint)
|
|
505
|
+
throw new Error("Missing initialized pulse checkpoint");
|
|
506
|
+
if (checkpoint.activeTask !== undefined) {
|
|
507
|
+
const active = await tx.task(checkpoint.activeTask);
|
|
508
|
+
if (!active)
|
|
509
|
+
throw new Error("Missing pulse task");
|
|
510
|
+
if (active.state.status !== "terminal")
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
if (definition.expiresAt !== undefined && definition.expiresAt <= now)
|
|
514
|
+
throw new Error("Pulse definition expired");
|
|
515
|
+
if (trigger === "scheduled" && (!definition.enabled || !checkpoint.pending))
|
|
516
|
+
return;
|
|
517
|
+
if (trigger === "scheduled" && definition.quietHours && isPulseQuietAt(definition.quietHours, now)) {
|
|
518
|
+
checkpoint.blocked = { reason: "Pulse quiet hours" };
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
const slots = await capacity(tx);
|
|
522
|
+
state.backoffUntil = Math.max(state.backoffUntil ?? 0, slots.backoffUntil);
|
|
523
|
+
if ((state.backoffUntil ?? 0) > now) {
|
|
524
|
+
checkpoint.blocked = {
|
|
525
|
+
reason: "Native provider generation backoff",
|
|
526
|
+
retryAt: state.backoffUntil
|
|
527
|
+
};
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
if (slots.active >= (state.concurrency ?? options.concurrency ?? 2)) {
|
|
531
|
+
checkpoint.blocked = { reason: "Pulse execution concurrency limit" };
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
const resident = definition.target === "resident";
|
|
535
|
+
const current = checkpoint.current;
|
|
536
|
+
const reusable = current && (resident ? current.target === "resident" && current.conversationId === binding.parentConversationId : current.target !== "resident" && current.parentConversationId === binding.parentConversationId);
|
|
537
|
+
const conversationId = resident ? binding.parentConversationId : reusable ? current.conversationId : undefined;
|
|
538
|
+
if (resident && conversationId === undefined)
|
|
539
|
+
throw new Error("Resident pulse requires an explicit resident binding");
|
|
540
|
+
if (conversationId !== undefined) {
|
|
541
|
+
if (!await tx.conversation(conversationId))
|
|
542
|
+
throw new Error("Missing pulse target conversation");
|
|
543
|
+
const live = await tx.doc(LiveDoc2, conversationId);
|
|
544
|
+
const inbox = await tx.doc(InboxDoc, conversationId);
|
|
545
|
+
if (live.run !== undefined || inbox.items.length > 0) {
|
|
546
|
+
checkpoint.blocked = {
|
|
547
|
+
reason: "Pulse target conversation is busy"
|
|
548
|
+
};
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
let reference;
|
|
553
|
+
let created = false;
|
|
554
|
+
if (resident) {
|
|
555
|
+
if (conversationId === undefined)
|
|
556
|
+
throw new Error("Missing resident pulse target");
|
|
557
|
+
reference = {
|
|
558
|
+
conversationId,
|
|
559
|
+
target: "resident",
|
|
560
|
+
root: binding.root,
|
|
561
|
+
pulseHome: definition.pulseHome
|
|
562
|
+
};
|
|
563
|
+
} else if (reusable) {
|
|
564
|
+
reference = {
|
|
565
|
+
...current,
|
|
566
|
+
root: binding.root,
|
|
567
|
+
pulseHome: definition.pulseHome
|
|
568
|
+
};
|
|
569
|
+
} else {
|
|
570
|
+
created = true;
|
|
571
|
+
const ownership = binding.parentConversationId === undefined ? { kind: "ownerless" } : {
|
|
572
|
+
kind: "task",
|
|
573
|
+
taskId: await tx.createTask(Anchor, null, {
|
|
574
|
+
ownership: { kind: "conversation" },
|
|
575
|
+
conversationId: binding.parentConversationId,
|
|
576
|
+
background: true
|
|
577
|
+
})
|
|
578
|
+
};
|
|
579
|
+
const conversation = await tx.createConversation({ ownership });
|
|
580
|
+
reference = {
|
|
581
|
+
conversationId: conversation.id,
|
|
582
|
+
root: binding.root,
|
|
583
|
+
pulseHome: definition.pulseHome,
|
|
584
|
+
...binding.parentConversationId === undefined ? {} : { parentConversationId: binding.parentConversationId }
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
checkpoint.current = reference;
|
|
588
|
+
const historical = checkpoint.history.findIndex((item) => item.conversationId === reference.conversationId);
|
|
589
|
+
if (historical < 0)
|
|
590
|
+
checkpoint.history.push(reference);
|
|
591
|
+
else
|
|
592
|
+
checkpoint.history[historical] = reference;
|
|
593
|
+
if (!resident)
|
|
594
|
+
await options.configure(tx, reference.conversationId, binding, definition, { created });
|
|
595
|
+
const occurrence = trigger === "scheduled" && checkpoint.pending ? { ...checkpoint.pending } : undefined;
|
|
596
|
+
const taskId = await tx.createTask(Run, {
|
|
597
|
+
binding: { ...binding },
|
|
598
|
+
definition: { ...definition },
|
|
599
|
+
reference,
|
|
600
|
+
trigger,
|
|
601
|
+
requestId,
|
|
602
|
+
...occurrence ? { occurrence } : {}
|
|
603
|
+
}, {
|
|
604
|
+
ownership: { kind: "conversation" },
|
|
605
|
+
conversationId: reference.conversationId,
|
|
606
|
+
background: true
|
|
607
|
+
});
|
|
608
|
+
const decision = await options.admitTransaction?.(tx, {
|
|
609
|
+
binding,
|
|
610
|
+
definition,
|
|
611
|
+
trigger,
|
|
612
|
+
requestId,
|
|
613
|
+
taskId,
|
|
614
|
+
conversationId: reference.conversationId,
|
|
615
|
+
...occurrence ? { occurrence } : {}
|
|
616
|
+
}, context);
|
|
617
|
+
if (decision?.status === "blocked")
|
|
618
|
+
throw new AdmissionBlocked(decision);
|
|
619
|
+
checkpoint.activeTask = taskId;
|
|
620
|
+
delete checkpoint.blocked;
|
|
621
|
+
if (trigger === "scheduled") {
|
|
622
|
+
checkpoint.lastRunAt = now;
|
|
623
|
+
const dueKey = pulseDueKey(definition.schedule, now);
|
|
624
|
+
if (dueKey !== null)
|
|
625
|
+
checkpoint.lastDueKey = dueKey;
|
|
626
|
+
delete checkpoint.pending;
|
|
627
|
+
}
|
|
628
|
+
return taskId;
|
|
629
|
+
}, context);
|
|
630
|
+
return id;
|
|
631
|
+
} catch (error) {
|
|
632
|
+
if (!(error instanceof AdmissionBlocked))
|
|
633
|
+
throw error;
|
|
634
|
+
await host().commit(async (tx) => {
|
|
635
|
+
const checkpoint = (await tx.doc(Checkpoints)).pulses[pulseKey(binding.key, definition.id)];
|
|
636
|
+
if (checkpoint)
|
|
637
|
+
checkpoint.blocked = {
|
|
638
|
+
reason: error.decision.reason,
|
|
639
|
+
...error.decision.retryAt === undefined ? {} : { retryAt: error.decision.retryAt }
|
|
640
|
+
};
|
|
641
|
+
}, context);
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// packages/pulses/src/frontmatter.ts
|
|
648
|
+
var FRONTMATTER_START = "---";
|
|
649
|
+
function parseValue(raw) {
|
|
650
|
+
const value = raw.trim().replace(/^['"]|['"]$/g, "");
|
|
651
|
+
if (value === "true")
|
|
652
|
+
return true;
|
|
653
|
+
if (value === "false")
|
|
654
|
+
return false;
|
|
655
|
+
return value;
|
|
656
|
+
}
|
|
657
|
+
function parsePulseFrontmatter(text) {
|
|
658
|
+
const normalized = text.replace(/\r\n/g, `
|
|
659
|
+
`);
|
|
660
|
+
if (!normalized.startsWith(`${FRONTMATTER_START}
|
|
661
|
+
`))
|
|
662
|
+
return { data: {}, body: text };
|
|
663
|
+
const end = normalized.indexOf(`
|
|
664
|
+
${FRONTMATTER_START}
|
|
665
|
+
`, FRONTMATTER_START.length + 1);
|
|
666
|
+
if (end < 0)
|
|
667
|
+
return { data: {}, body: text };
|
|
668
|
+
const raw = normalized.slice(FRONTMATTER_START.length + 1, end);
|
|
669
|
+
const data = {};
|
|
670
|
+
for (const line of raw.split(`
|
|
671
|
+
`)) {
|
|
672
|
+
const trimmed = line.trim();
|
|
673
|
+
if (!trimmed || trimmed.startsWith("#"))
|
|
674
|
+
continue;
|
|
675
|
+
const colon = trimmed.indexOf(":");
|
|
676
|
+
if (colon < 0)
|
|
677
|
+
continue;
|
|
678
|
+
const key = trimmed.slice(0, colon).trim();
|
|
679
|
+
if (!key)
|
|
680
|
+
continue;
|
|
681
|
+
data[key] = parseValue(trimmed.slice(colon + 1));
|
|
682
|
+
}
|
|
683
|
+
return {
|
|
684
|
+
data,
|
|
685
|
+
body: normalized.slice(end + FRONTMATTER_START.length + 2).trimStart()
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// packages/pulses/src/definitions.ts
|
|
690
|
+
function parsePulseDefinition(binding, source) {
|
|
691
|
+
const pulseHome = `${binding.root.replace(/\/$/u, "")}/pulses/${source.id}`;
|
|
692
|
+
const paths = {
|
|
693
|
+
id: source.id,
|
|
694
|
+
bindingKey: binding.key,
|
|
695
|
+
root: binding.root,
|
|
696
|
+
pulseHome,
|
|
697
|
+
path: `${pulseHome}/PULSE.md`
|
|
698
|
+
};
|
|
699
|
+
const invalid = (error) => ({
|
|
700
|
+
...paths,
|
|
701
|
+
status: "invalid",
|
|
702
|
+
title: `Invalid pulse: ${source.id}`,
|
|
703
|
+
error
|
|
704
|
+
});
|
|
705
|
+
if (!/^[a-z0-9][a-z0-9-]*$/u.test(source.id))
|
|
706
|
+
return invalid("pulse folder name must be kebab-case");
|
|
707
|
+
if (source.error !== undefined)
|
|
708
|
+
return invalid(source.error);
|
|
709
|
+
if (!source.text.trim())
|
|
710
|
+
return invalid("PULSE.md is empty");
|
|
711
|
+
const { data, body } = parsePulseFrontmatter(source.text);
|
|
712
|
+
if (!(typeof data["title"] === "string" && data["title"].trim()))
|
|
713
|
+
return invalid("frontmatter must include title");
|
|
714
|
+
const trigger = data["trigger"];
|
|
715
|
+
if (trigger !== undefined && trigger !== "manual" && trigger !== "time")
|
|
716
|
+
return invalid(`unsupported trigger: ${trigger}`);
|
|
717
|
+
const scheduleText = trigger === "manual" ? "manual" : typeof data["schedule"] === "string" ? data["schedule"].trim() : "";
|
|
718
|
+
const schedule = parsePulseSchedule(scheduleText);
|
|
719
|
+
if (!schedule)
|
|
720
|
+
return invalid(scheduleText ? `invalid schedule: ${scheduleText}` : "frontmatter must include schedule");
|
|
721
|
+
const rawQuiet = data["quietHours"];
|
|
722
|
+
const target = data["target"];
|
|
723
|
+
if (target !== undefined && target !== "child" && target !== "resident")
|
|
724
|
+
return invalid("target must be child or resident");
|
|
725
|
+
const rawExpiry = data["expiresAt"];
|
|
726
|
+
const expiresAt = typeof rawExpiry === "string" ? Date.parse(rawExpiry) : NaN;
|
|
727
|
+
if (rawExpiry !== undefined && !Number.isFinite(expiresAt))
|
|
728
|
+
return invalid("expiresAt must be a datetime");
|
|
729
|
+
const quietHours = typeof rawQuiet === "string" ? parsePulseQuietHours(rawQuiet) : undefined;
|
|
730
|
+
if (rawQuiet !== undefined && !quietHours)
|
|
731
|
+
return invalid("quietHours must use HH:MM-HH:MM");
|
|
732
|
+
return {
|
|
733
|
+
...paths,
|
|
734
|
+
status: "valid",
|
|
735
|
+
title: data["title"].trim(),
|
|
736
|
+
scheduleText,
|
|
737
|
+
schedule,
|
|
738
|
+
enabled: data["enabled"] !== false,
|
|
739
|
+
...target === undefined ? {} : { target },
|
|
740
|
+
...rawExpiry === undefined ? {} : { expiresAt },
|
|
741
|
+
body,
|
|
742
|
+
...quietHours ? { quietHours } : {}
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// packages/pulses/src/execution.ts
|
|
747
|
+
async function execution(tx, request) {
|
|
748
|
+
let cursor;
|
|
749
|
+
do {
|
|
750
|
+
const page = await tx.scanTasks({
|
|
751
|
+
kind: "howaboua.pulses.run",
|
|
752
|
+
conversationId: request.conversationId,
|
|
753
|
+
order: "descending"
|
|
754
|
+
}, 100, cursor);
|
|
755
|
+
for (const task of page.items) {
|
|
756
|
+
const input = task.input;
|
|
757
|
+
if (typeof input !== "object" || input === null || Array.isArray(input))
|
|
758
|
+
throw new Error("Invalid admitted pulse input");
|
|
759
|
+
const binding = input["binding"];
|
|
760
|
+
const definition = input["definition"];
|
|
761
|
+
if (typeof binding !== "object" || binding === null || Array.isArray(binding) || typeof definition !== "object" || definition === null || Array.isArray(definition))
|
|
762
|
+
throw new Error("Invalid admitted pulse identity");
|
|
763
|
+
if (binding["key"] !== request.bindingKey || definition["id"] !== request.pulseId)
|
|
764
|
+
continue;
|
|
765
|
+
const reference = input["reference"];
|
|
766
|
+
if (typeof reference !== "object" || reference === null || Array.isArray(reference) || reference["conversationId"] !== task.conversationId)
|
|
767
|
+
throw new Error("Invalid admitted pulse conversation reference");
|
|
768
|
+
const submission = await tx.submissionByRequest(task.conversationId, pulseInputRequestId(task.id));
|
|
769
|
+
if (submission !== undefined && submission.type !== "input")
|
|
770
|
+
throw new Error("Invalid pulse input submission");
|
|
771
|
+
return { task, submission };
|
|
772
|
+
}
|
|
773
|
+
cursor = page.next;
|
|
774
|
+
} while (cursor !== undefined);
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// packages/pulses/src/occurrences.ts
|
|
779
|
+
function discardPending(checkpoint, status, reason, now) {
|
|
780
|
+
if (checkpoint.pending) {
|
|
781
|
+
checkpoint.disposition = {
|
|
782
|
+
status,
|
|
783
|
+
reason,
|
|
784
|
+
at: now,
|
|
785
|
+
occurrence: { ...checkpoint.pending }
|
|
786
|
+
};
|
|
787
|
+
delete checkpoint.pending;
|
|
788
|
+
}
|
|
789
|
+
delete checkpoint.blocked;
|
|
790
|
+
}
|
|
791
|
+
function collectDue(checkpoint, now) {
|
|
792
|
+
if (!checkpoint.scheduledEligible || !checkpoint.trackedSchedule || checkpoint.nextDueAt === undefined)
|
|
793
|
+
return;
|
|
794
|
+
const due = pulseOccurrences(checkpoint.trackedSchedule, checkpoint.nextDueAt, Math.min(now, checkpoint.expiresAt ?? now));
|
|
795
|
+
if (!due)
|
|
796
|
+
return;
|
|
797
|
+
checkpoint.pending = checkpoint.pending ? {
|
|
798
|
+
count: checkpoint.pending.count + due.count,
|
|
799
|
+
startAt: checkpoint.pending.startAt,
|
|
800
|
+
endAt: due.endAt
|
|
801
|
+
} : due;
|
|
802
|
+
const next = nextPulseDue(checkpoint.trackedSchedule, due.endAt);
|
|
803
|
+
if (next === undefined)
|
|
804
|
+
delete checkpoint.nextDueAt;
|
|
805
|
+
else
|
|
806
|
+
checkpoint.nextDueAt = next;
|
|
807
|
+
}
|
|
808
|
+
async function reconcileSchedules(tx, definitions, now) {
|
|
809
|
+
const state = await tx.doc(Checkpoints);
|
|
810
|
+
for (const checkpoint of Object.values(state.pulses))
|
|
811
|
+
collectDue(checkpoint, now);
|
|
812
|
+
const eligible = new Set;
|
|
813
|
+
for (const definition of definitions) {
|
|
814
|
+
const key = pulseKey(definition.bindingKey, definition.id);
|
|
815
|
+
if (definition.status !== "valid" || !definition.enabled || definition.schedule.kind === "manual" || definition.expiresAt !== undefined && definition.expiresAt <= now)
|
|
816
|
+
continue;
|
|
817
|
+
eligible.add(key);
|
|
818
|
+
state.pulses[key] ??= { firstSeenAt: now, history: [] };
|
|
819
|
+
const checkpoint = state.pulses[key];
|
|
820
|
+
if (!checkpoint)
|
|
821
|
+
throw new Error("Missing initialized pulse checkpoint");
|
|
822
|
+
const scheduleKey = JSON.stringify({
|
|
823
|
+
schedule: definition.schedule,
|
|
824
|
+
target: definition.target ?? "child"
|
|
825
|
+
});
|
|
826
|
+
if (!checkpoint.scheduledEligible || checkpoint.scheduleKey !== scheduleKey || checkpoint.trackedAt === undefined) {
|
|
827
|
+
discardPending(checkpoint, "superseded", "Schedule or execution target changed", now);
|
|
828
|
+
checkpoint.firstSeenAt = now;
|
|
829
|
+
checkpoint.trackedAt = now;
|
|
830
|
+
checkpoint.trackedSchedule = definition.schedule;
|
|
831
|
+
delete checkpoint.lastRunAt;
|
|
832
|
+
delete checkpoint.lastDueKey;
|
|
833
|
+
delete checkpoint.nextDueAt;
|
|
834
|
+
const seed = pulseDueKey(definition.schedule, now);
|
|
835
|
+
if (seed !== null)
|
|
836
|
+
checkpoint.lastDueKey = seed;
|
|
837
|
+
const next = nextPulseDue(definition.schedule, now);
|
|
838
|
+
if (next !== undefined)
|
|
839
|
+
checkpoint.nextDueAt = next;
|
|
840
|
+
checkpoint.scheduledEligible = true;
|
|
841
|
+
checkpoint.scheduleKey = scheduleKey;
|
|
842
|
+
}
|
|
843
|
+
if (definition.expiresAt === undefined)
|
|
844
|
+
delete checkpoint.expiresAt;
|
|
845
|
+
else
|
|
846
|
+
checkpoint.expiresAt = definition.expiresAt;
|
|
847
|
+
if (definition.quietHours === undefined)
|
|
848
|
+
delete checkpoint.quietHours;
|
|
849
|
+
else
|
|
850
|
+
checkpoint.quietHours = definition.quietHours;
|
|
851
|
+
}
|
|
852
|
+
for (const [key, checkpoint] of Object.entries(state.pulses)) {
|
|
853
|
+
if (eligible.has(key))
|
|
854
|
+
continue;
|
|
855
|
+
const definition = definitions.find((value) => pulseKey(value.bindingKey, value.id) === key);
|
|
856
|
+
const reason = !definition ? "Definition removed" : definition.status === "invalid" ? `Invalid definition: ${definition.error}` : !definition.enabled ? "Definition disabled" : definition.expiresAt !== undefined && definition.expiresAt <= now ? "Definition expired" : "Schedule made manual";
|
|
857
|
+
discardPending(checkpoint, "obsolete", reason, now);
|
|
858
|
+
checkpoint.scheduledEligible = false;
|
|
859
|
+
delete checkpoint.nextDueAt;
|
|
860
|
+
delete checkpoint.lastRunAt;
|
|
861
|
+
delete checkpoint.lastDueKey;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
async function explicitReady(tx, bindingKey, now) {
|
|
865
|
+
const state = await tx.doc(Checkpoints);
|
|
866
|
+
if ((state.backoffUntil ?? 0) > now)
|
|
867
|
+
return false;
|
|
868
|
+
return Object.entries(state.pulses).some(([key, checkpoint]) => {
|
|
869
|
+
const identity = JSON.parse(key);
|
|
870
|
+
return Array.isArray(identity) && identity[0] === bindingKey && checkpoint.scheduledEligible && (checkpoint.expiresAt === undefined || checkpoint.expiresAt > now) && (checkpoint.quietHours === undefined || !isPulseQuietAt(checkpoint.quietHours, now)) && (checkpoint.pending !== undefined || checkpoint.nextDueAt !== undefined && checkpoint.nextDueAt <= now);
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
// packages/pulses/src/tool.ts
|
|
875
|
+
import {
|
|
876
|
+
defineTool
|
|
877
|
+
} from "@earendil-works/pi-durable";
|
|
878
|
+
import { Type } from "typebox";
|
|
879
|
+
|
|
880
|
+
// packages/pulses/src/authoring.ts
|
|
881
|
+
var pulseAuthoring = `Create pulses/<self-explanatory-name>/PULSE.md in the workspace shown by pulses({}). Use a lowercase kebab-case folder name. Preserve its AGENTS.md, existing journals and artifacts. Read applicable workspace and pulse-local instructions. Native cwd remains the workspace root; use the explicit pulse-home path for local files.
|
|
882
|
+
|
|
883
|
+
Example PULSE.md:
|
|
884
|
+
---
|
|
885
|
+
title: Check agreed sources
|
|
886
|
+
schedule: every 5h
|
|
887
|
+
enabled: true
|
|
888
|
+
quietHours: 22:00-08:00
|
|
889
|
+
---
|
|
890
|
+
Check the agreed sources for changes since the previous run.
|
|
891
|
+
Post actionable findings to the designated available destination.
|
|
892
|
+
|
|
893
|
+
title and schedule are required. Schedules: manual, every 30m, every 5h, every 2d, daily 09:00, weekly fri 17:00 or at <datetime>. Use an explicit timezone offset for a one-time timestamp when timezone matters. Daily and weekly times and quietHours use the runtime's local timezone. Checks run every five minutes. Existing trigger: manual needs no schedule; trigger: time requires one.
|
|
894
|
+
|
|
895
|
+
enabled defaults to true. Set false to pause both scheduled and manual runs. quietHours is optional and accepts HH:MM-HH:MM, including overnight ranges. Manual runs bypass quiet hours without consuming recurrence checkpoints. Optional expiresAt stops new admissions at that datetime. Child execution is the default; target: resident requires an explicit host-supplied continuing resident. Leave unrelated frontmatter keys, comments and body conventions untouched.
|
|
896
|
+
|
|
897
|
+
Keep the body a short SOP: the actual task, sources, destination and consequential limits. Do not duplicate general skill guidance or require skills the task does not need. Define concrete destinations only when available. The worker receives the body plus standard result-routing and procedural-feedback instructions; do not repeat them in definitions.
|
|
898
|
+
|
|
899
|
+
Use ordinary file tools to edit definitions. Disable routines worth keeping for later; delete obsolete definitions without deleting their journals or artifacts. There is no authoring configuration API. pulses({}) lists paths and invalid-definition diagnostics. pulses({run: "name"}) requests an immediate run. Admission is not completion. Inspect native task and submission outcomes through the consuming app. Child results are passive context and never wake the parent; resident work reports in that conversation.
|
|
900
|
+
|
|
901
|
+
Tracked missed occurrences coalesce into one run per job with a count and period. Cover that period rather than replaying each occurrence. Host restrictions, concurrency and active responsibility can hold admission. Reenabling or readding seeds the current slot, not disabled history. Removed, expired or superseded pending work stays inspectable. Retrying the same native tool task rejoins its accepted request, even after definition edits or deletion. An interrupted external side effect may have an uncertain outcome; report that uncertainty rather than repeat it. Stop uses the consuming app's native controls. It aborts only the coordinator and its owned input, then settles its passive report. Removing a definition or component never deletes files or native history.`;
|
|
902
|
+
|
|
903
|
+
// packages/pulses/src/tool.ts
|
|
904
|
+
function createPulsesTool(options, operations) {
|
|
905
|
+
const registration = defineTool({
|
|
906
|
+
name: "pulses",
|
|
907
|
+
description: "Run a saved routine",
|
|
908
|
+
parameters: Type.Object({
|
|
909
|
+
run: Type.Optional(Type.String({ minLength: 1 })),
|
|
910
|
+
skill: Type.Optional(Type.Literal(true))
|
|
911
|
+
}, { additionalProperties: false }),
|
|
912
|
+
replay: "safe",
|
|
913
|
+
executionMode: "sequential",
|
|
914
|
+
outputLimits: {
|
|
915
|
+
maxBytes: Number.MAX_SAFE_INTEGER,
|
|
916
|
+
maxLines: Number.MAX_SAFE_INTEGER
|
|
917
|
+
},
|
|
918
|
+
async execute(args, api, context) {
|
|
919
|
+
if (args.run !== undefined && args.skill !== undefined)
|
|
920
|
+
throw new Error("Supply run or skill, not both.");
|
|
921
|
+
if (args.run !== undefined && !/^[a-z0-9][a-z0-9-]*$/u.test(args.run))
|
|
922
|
+
throw new Error("Use a pulse folder name. Call pulses with no arguments to see valid paths.");
|
|
923
|
+
context.abortSignal?.throwIfAborted();
|
|
924
|
+
if (args.skill)
|
|
925
|
+
return { output: [{ type: "text", text: pulseAuthoring }] };
|
|
926
|
+
let route = args.run ? await api.memo("pulse-route", context) : undefined;
|
|
927
|
+
if (!route) {
|
|
928
|
+
if (!api.env)
|
|
929
|
+
throw new Error("Pulses requires the conversation's execution environment");
|
|
930
|
+
if (!options.resolveToolBinding)
|
|
931
|
+
throw new Error("Pulses tools require a host-provided conversation binding");
|
|
932
|
+
const bindingKey = await options.resolveToolBinding(api, context);
|
|
933
|
+
if (!bindingKey.trim())
|
|
934
|
+
throw new Error("Missing pulse binding key");
|
|
935
|
+
route = args.run ? await api.memo("pulse-route", { bindingKey }, context) : { bindingKey };
|
|
936
|
+
}
|
|
937
|
+
let text;
|
|
938
|
+
if (args.run !== undefined) {
|
|
939
|
+
const taskId = await operations.run({
|
|
940
|
+
bindingKey: route.bindingKey,
|
|
941
|
+
pulseId: args.run,
|
|
942
|
+
requestId: `tool:${api.taskId}`
|
|
943
|
+
}, context, api);
|
|
944
|
+
text = taskId === undefined ? "Not admitted: the pulse is busy, capacity is occupied or admission is held. No new run was requested." : `Requested pulses/${args.run}/PULSE.md. Native task: ${taskId}. Admission is not completion. Child results are passive context; resident work reports in its conversation.`;
|
|
945
|
+
} else {
|
|
946
|
+
const items = await operations.catalog(context, route.bindingKey);
|
|
947
|
+
text = [
|
|
948
|
+
'Run: {run:"check-new-issues"}; authoring: {skill:true}',
|
|
949
|
+
...items.filter((item) => item.status === "valid").map((item) => item.path),
|
|
950
|
+
...items.filter((item) => item.status === "invalid").map((item) => `${item.path} (invalid: ${item.error})`)
|
|
951
|
+
].join(`
|
|
952
|
+
`);
|
|
953
|
+
}
|
|
954
|
+
return { output: [{ type: "text", text }] };
|
|
955
|
+
}
|
|
956
|
+
});
|
|
957
|
+
return { ...registration, executionHints: { discovery: "help" } };
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
// packages/pulses/src/index.ts
|
|
961
|
+
function createPulses(options) {
|
|
962
|
+
const initialConcurrency = validateConcurrency(options.concurrency ?? 2);
|
|
963
|
+
let harness;
|
|
964
|
+
let timer;
|
|
965
|
+
let accepting = false;
|
|
966
|
+
let scanFlight;
|
|
967
|
+
let unsubscribeClose;
|
|
968
|
+
let unsubscribeCommits;
|
|
969
|
+
let bindingFlight;
|
|
970
|
+
let releaseScanQueued = false;
|
|
971
|
+
let pending = Promise.resolve();
|
|
972
|
+
const host = () => {
|
|
973
|
+
if (!harness)
|
|
974
|
+
throw new Error("Bind Pulses before use");
|
|
975
|
+
return harness;
|
|
976
|
+
};
|
|
977
|
+
const Run = createRunTask(host, options);
|
|
978
|
+
const exclusive = (work) => {
|
|
979
|
+
const result = pending.then(() => {
|
|
980
|
+
if (!accepting)
|
|
981
|
+
throw new Error("Pulses admission is not bound or has stopped");
|
|
982
|
+
return work();
|
|
983
|
+
});
|
|
984
|
+
pending = result.then(() => {}, () => {});
|
|
985
|
+
return result;
|
|
986
|
+
};
|
|
987
|
+
async function catalog(context, bindingKey) {
|
|
988
|
+
const bindings = await options.getBindings(context);
|
|
989
|
+
if (new Set(bindings.map((binding) => binding.key)).size !== bindings.length)
|
|
990
|
+
throw new Error("Duplicate pulse binding key");
|
|
991
|
+
if (bindingKey !== undefined && !bindings.some((binding) => binding.key === bindingKey))
|
|
992
|
+
throw new Error("Pulse not found");
|
|
993
|
+
return (await Promise.all(bindings.filter((binding) => bindingKey === undefined || binding.key === bindingKey).map(async (binding) => {
|
|
994
|
+
const sources = await options.readDefinitions(binding, context);
|
|
995
|
+
if (new Set(sources.map((source) => source.id)).size !== sources.length)
|
|
996
|
+
throw new Error(`Duplicate pulse ID in ${binding.key}`);
|
|
997
|
+
return sources.map((source) => parsePulseDefinition(binding, source));
|
|
998
|
+
}))).flat();
|
|
999
|
+
}
|
|
1000
|
+
const dispatch = createAdmission(host, options, Run, () => accepting);
|
|
1001
|
+
function releaseCapacity(context) {
|
|
1002
|
+
if (!accepting || releaseScanQueued)
|
|
1003
|
+
return;
|
|
1004
|
+
releaseScanQueued = true;
|
|
1005
|
+
queueMicrotask(() => {
|
|
1006
|
+
const rescan = () => {
|
|
1007
|
+
releaseScanQueued = false;
|
|
1008
|
+
if (accepting)
|
|
1009
|
+
return scan(context);
|
|
1010
|
+
return;
|
|
1011
|
+
};
|
|
1012
|
+
(scanFlight ?? Promise.resolve()).then(rescan, rescan).catch(options.onError);
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
function scan(context) {
|
|
1016
|
+
if (scanFlight !== undefined)
|
|
1017
|
+
return scanFlight;
|
|
1018
|
+
scanFlight = exclusive(async () => {
|
|
1019
|
+
const definitions = await catalog(context);
|
|
1020
|
+
const now = Date.now();
|
|
1021
|
+
await host().commit((tx) => reconcileSchedules(tx, definitions, now), context);
|
|
1022
|
+
const checkpoints = (await host().snapshot(Checkpoints, context))?.pulses ?? {};
|
|
1023
|
+
const ready = definitions.filter((definition) => definition.status === "valid" && definition.enabled && checkpoints[pulseKey(definition.bindingKey, definition.id)]?.pending !== undefined).sort((a, b) => (checkpoints[pulseKey(a.bindingKey, a.id)]?.pending?.startAt ?? 0) - (checkpoints[pulseKey(b.bindingKey, b.id)]?.pending?.startAt ?? 0));
|
|
1024
|
+
for (const definition of ready) {
|
|
1025
|
+
const checkpoint = checkpoints[pulseKey(definition.bindingKey, definition.id)];
|
|
1026
|
+
if (!checkpoint?.pending)
|
|
1027
|
+
continue;
|
|
1028
|
+
try {
|
|
1029
|
+
await dispatch(definition, "scheduled", `scheduled:${pulseKey(definition.bindingKey, definition.id)}:${checkpoint.trackedAt}:${checkpoint.pending.startAt}:${checkpoint.pending.endAt}`, context);
|
|
1030
|
+
} catch (error) {
|
|
1031
|
+
options.onError(error);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
return definitions;
|
|
1035
|
+
}).finally(() => {
|
|
1036
|
+
scanFlight = undefined;
|
|
1037
|
+
});
|
|
1038
|
+
return scanFlight;
|
|
1039
|
+
}
|
|
1040
|
+
async function manualRun(request, context, api) {
|
|
1041
|
+
if (!request.requestId.trim())
|
|
1042
|
+
throw new Error("A stable requestId is required");
|
|
1043
|
+
const requestId = `manual:${request.requestId}`;
|
|
1044
|
+
const rejoin = () => host().commit((tx) => admitted(tx, request.bindingKey, request.pulseId, requestId), context);
|
|
1045
|
+
const run = () => exclusive(async () => {
|
|
1046
|
+
const receipt = await rejoin();
|
|
1047
|
+
if (receipt !== undefined)
|
|
1048
|
+
return receipt;
|
|
1049
|
+
const definitions = await catalog(context);
|
|
1050
|
+
await host().commit((tx) => reconcileSchedules(tx, definitions, Date.now()), context);
|
|
1051
|
+
const definition = definitions.find((value) => value.bindingKey === request.bindingKey && value.id === request.pulseId);
|
|
1052
|
+
if (!definition)
|
|
1053
|
+
throw new Error("Pulse not found");
|
|
1054
|
+
if (definition.status === "invalid")
|
|
1055
|
+
throw new Error(definition.error);
|
|
1056
|
+
if (!definition.enabled)
|
|
1057
|
+
throw new Error(`Pulse is disabled: ${definition.id}`);
|
|
1058
|
+
return dispatch(definition, "manual", requestId, context);
|
|
1059
|
+
});
|
|
1060
|
+
if (!api || !options.withToolRunAuthorization)
|
|
1061
|
+
return run();
|
|
1062
|
+
if (!accepting)
|
|
1063
|
+
throw new Error("Pulses admission is not bound or has stopped");
|
|
1064
|
+
const receipt = await rejoin();
|
|
1065
|
+
if (receipt !== undefined)
|
|
1066
|
+
return receipt;
|
|
1067
|
+
return options.withToolRunAuthorization(api, { ...request }, run, context);
|
|
1068
|
+
}
|
|
1069
|
+
const tool = createPulsesTool(options, { catalog, run: manualRun });
|
|
1070
|
+
const component = {
|
|
1071
|
+
extension: defineExtension({
|
|
1072
|
+
name: "howaboua.pulses",
|
|
1073
|
+
tools: [tool],
|
|
1074
|
+
tasks: [Anchor, Run]
|
|
1075
|
+
}),
|
|
1076
|
+
tool,
|
|
1077
|
+
catalog,
|
|
1078
|
+
scan,
|
|
1079
|
+
explicitReady,
|
|
1080
|
+
async configuration(context) {
|
|
1081
|
+
return {
|
|
1082
|
+
concurrency: (await host().snapshot(Checkpoints, context))?.concurrency ?? initialConcurrency
|
|
1083
|
+
};
|
|
1084
|
+
},
|
|
1085
|
+
async setConcurrency(limit, context) {
|
|
1086
|
+
validateConcurrency(limit);
|
|
1087
|
+
return exclusive(async () => {
|
|
1088
|
+
await host().commit(async (tx) => {
|
|
1089
|
+
(await tx.doc(Checkpoints)).concurrency = limit;
|
|
1090
|
+
}, context);
|
|
1091
|
+
return { concurrency: limit };
|
|
1092
|
+
});
|
|
1093
|
+
},
|
|
1094
|
+
run(request, context) {
|
|
1095
|
+
return manualRun(request, context);
|
|
1096
|
+
},
|
|
1097
|
+
execution(request, context) {
|
|
1098
|
+
return host().commit((tx) => execution(tx, request), context);
|
|
1099
|
+
},
|
|
1100
|
+
async observe(context) {
|
|
1101
|
+
const references = (await host().snapshot(Checkpoints, context))?.pulses ?? {};
|
|
1102
|
+
return Promise.all(Object.entries(references).map(async ([key, checkpoint]) => ({
|
|
1103
|
+
key,
|
|
1104
|
+
...checkpoint,
|
|
1105
|
+
task: checkpoint.activeTask === undefined ? undefined : await host().getTask(checkpoint.activeTask, context)
|
|
1106
|
+
})));
|
|
1107
|
+
},
|
|
1108
|
+
async stop(request, context) {
|
|
1109
|
+
return exclusive(async () => {
|
|
1110
|
+
const checkpoint = (await host().snapshot(Checkpoints, context))?.pulses[pulseKey(request.bindingKey, request.pulseId)];
|
|
1111
|
+
if (checkpoint?.activeTask !== undefined) {
|
|
1112
|
+
const task = await host().getTask(checkpoint.activeTask, context);
|
|
1113
|
+
if (task && task.state.status !== "terminal") {
|
|
1114
|
+
await host().abortTask(checkpoint.activeTask, context);
|
|
1115
|
+
await host().waitForTask(checkpoint.activeTask, context);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
});
|
|
1119
|
+
},
|
|
1120
|
+
bind(value, context) {
|
|
1121
|
+
if (harness && harness !== value)
|
|
1122
|
+
throw new Error("Create one Pulses component per Harness");
|
|
1123
|
+
if (bindingFlight)
|
|
1124
|
+
return bindingFlight;
|
|
1125
|
+
harness = value;
|
|
1126
|
+
accepting = true;
|
|
1127
|
+
unsubscribeClose = value.subscribeClose(() => {
|
|
1128
|
+
accepting = false;
|
|
1129
|
+
if (timer)
|
|
1130
|
+
clearInterval(timer);
|
|
1131
|
+
timer = undefined;
|
|
1132
|
+
unsubscribeClose?.();
|
|
1133
|
+
unsubscribeClose = undefined;
|
|
1134
|
+
unsubscribeCommits?.();
|
|
1135
|
+
unsubscribeCommits = undefined;
|
|
1136
|
+
});
|
|
1137
|
+
unsubscribeCommits = value.subscribeCommits((publication) => {
|
|
1138
|
+
if (publication.changes.some((change) => change.type === "task" && change.value.kind === "howaboua.pulses.run" && change.value.state.status === "terminal"))
|
|
1139
|
+
releaseCapacity(context);
|
|
1140
|
+
});
|
|
1141
|
+
timer = setInterval(() => {
|
|
1142
|
+
scan(context).catch(options.onError);
|
|
1143
|
+
}, 300000);
|
|
1144
|
+
timer.unref?.();
|
|
1145
|
+
bindingFlight = exclusive(() => host().commit(async (tx) => {
|
|
1146
|
+
await restoreMissingReferences(tx);
|
|
1147
|
+
(await tx.doc(Checkpoints)).concurrency ??= initialConcurrency;
|
|
1148
|
+
}, context)).then(() => exclusive(async () => {
|
|
1149
|
+
const definitions = await catalog(context);
|
|
1150
|
+
await host().commit((tx) => reconcileSchedules(tx, definitions, Date.now()), context);
|
|
1151
|
+
})).then(() => {}).catch((error) => {
|
|
1152
|
+
accepting = false;
|
|
1153
|
+
if (timer)
|
|
1154
|
+
clearInterval(timer);
|
|
1155
|
+
timer = undefined;
|
|
1156
|
+
unsubscribeClose?.();
|
|
1157
|
+
unsubscribeClose = undefined;
|
|
1158
|
+
unsubscribeCommits?.();
|
|
1159
|
+
unsubscribeCommits = undefined;
|
|
1160
|
+
throw error;
|
|
1161
|
+
});
|
|
1162
|
+
bindingFlight.catch(options.onError);
|
|
1163
|
+
return bindingFlight;
|
|
1164
|
+
},
|
|
1165
|
+
async stopAdmission() {
|
|
1166
|
+
accepting = false;
|
|
1167
|
+
unsubscribeClose?.();
|
|
1168
|
+
unsubscribeClose = undefined;
|
|
1169
|
+
unsubscribeCommits?.();
|
|
1170
|
+
unsubscribeCommits = undefined;
|
|
1171
|
+
if (timer)
|
|
1172
|
+
clearInterval(timer);
|
|
1173
|
+
timer = undefined;
|
|
1174
|
+
await pending;
|
|
1175
|
+
if (bindingFlight)
|
|
1176
|
+
await bindingFlight.catch(() => {});
|
|
1177
|
+
},
|
|
1178
|
+
async unbind() {
|
|
1179
|
+
await component.stopAdmission();
|
|
1180
|
+
bindingFlight = undefined;
|
|
1181
|
+
harness = undefined;
|
|
1182
|
+
}
|
|
1183
|
+
};
|
|
1184
|
+
return component;
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
// packages/pulses/src/activation.ts
|
|
1188
|
+
function scheduledWork(definition) {
|
|
1189
|
+
const { pulseHome, status: _status, ...work } = definition;
|
|
1190
|
+
return { ...work, home: pulseHome };
|
|
1191
|
+
}
|
|
1192
|
+
function configuredOptions(request) {
|
|
1193
|
+
const grant = request.capabilities.get(schedulingCapability);
|
|
1194
|
+
const resolveToolBinding = grant.resolveToolBinding?.bind(grant);
|
|
1195
|
+
const withToolRunAuthorization = grant.withToolRunAuthorization?.bind(grant);
|
|
1196
|
+
const authorizeTransaction = grant.authorizeTransaction?.bind(grant);
|
|
1197
|
+
const submitInput = grant.submitInput?.bind(grant);
|
|
1198
|
+
const writeResult = grant.writeResult?.bind(grant);
|
|
1199
|
+
const concurrency = request.configuration["concurrency"];
|
|
1200
|
+
if (concurrency !== undefined && typeof concurrency !== "number")
|
|
1201
|
+
throw new Error("Pulses configuration.concurrency must be a number");
|
|
1202
|
+
return {
|
|
1203
|
+
...concurrency === undefined ? {} : { concurrency },
|
|
1204
|
+
getBindings: (context) => grant.bindings(context),
|
|
1205
|
+
readDefinitions: (binding, context) => grant.readDefinitions(binding, { directory: "pulses", fileName: "PULSE.md" }, context),
|
|
1206
|
+
admit: (binding, definition, trigger, context) => grant.authorize(binding, scheduledWork(definition), trigger, context),
|
|
1207
|
+
configure: (tx, conversationId, binding, definition, creation) => grant.configure(tx, conversationId, binding, scheduledWork(definition), creation),
|
|
1208
|
+
onError: (error) => grant.onError(error),
|
|
1209
|
+
...resolveToolBinding === undefined ? {} : { resolveToolBinding },
|
|
1210
|
+
...withToolRunAuthorization === undefined ? {} : {
|
|
1211
|
+
withToolRunAuthorization: (api, input, run, context) => withToolRunAuthorization(api, {
|
|
1212
|
+
bindingKey: input.bindingKey,
|
|
1213
|
+
workId: input.pulseId,
|
|
1214
|
+
requestId: input.requestId
|
|
1215
|
+
}, run, context)
|
|
1216
|
+
},
|
|
1217
|
+
...authorizeTransaction === undefined ? {} : {
|
|
1218
|
+
admitTransaction: (tx, admission, context) => {
|
|
1219
|
+
const { definition, ...rest } = admission;
|
|
1220
|
+
return authorizeTransaction(tx, { ...rest, work: scheduledWork(definition) }, context);
|
|
1221
|
+
}
|
|
1222
|
+
},
|
|
1223
|
+
...submitInput === undefined ? {} : { submitInput },
|
|
1224
|
+
...writeResult === undefined ? {} : { writeResult }
|
|
1225
|
+
};
|
|
1226
|
+
}
|
|
1227
|
+
var pulsesOptions = defineCapability("howaboua.pulses.options.v1", (value) => isCapabilityObject(value) && ["getBindings", "readDefinitions", "admit", "configure", "onError"].every((name) => typeof value[name] === "function") && [
|
|
1228
|
+
"resolveToolBinding",
|
|
1229
|
+
"withToolRunAuthorization",
|
|
1230
|
+
"admitTransaction",
|
|
1231
|
+
"submitInput",
|
|
1232
|
+
"writeResult"
|
|
1233
|
+
].every((name) => value[name] === undefined || typeof value[name] === "function") && (value["concurrency"] === undefined || typeof value["concurrency"] === "number"));
|
|
1234
|
+
function createComponent(request) {
|
|
1235
|
+
const api = createPulses(request.capabilities.has(pulsesOptions.id) ? request.capabilities.get(pulsesOptions) : configuredOptions(request));
|
|
1236
|
+
let stopped = false;
|
|
1237
|
+
const stopAdmission = async () => {
|
|
1238
|
+
stopped = true;
|
|
1239
|
+
await api.stopAdmission();
|
|
1240
|
+
};
|
|
1241
|
+
return {
|
|
1242
|
+
extensions: [api.extension],
|
|
1243
|
+
api,
|
|
1244
|
+
retention: "harness",
|
|
1245
|
+
bind: ({ harness }, context) => api.bind(harness, context),
|
|
1246
|
+
stopAdmission,
|
|
1247
|
+
beforeClose: stopAdmission,
|
|
1248
|
+
afterClose: () => api.unbind(),
|
|
1249
|
+
maintain: (context) => stopped ? undefined : api.scan(context)
|
|
1250
|
+
};
|
|
1251
|
+
}
|
|
1252
|
+
export {
|
|
1253
|
+
createComponent,
|
|
1254
|
+
pulsesOptions
|
|
1255
|
+
};
|