@deepagents/experimental 4.2.0 → 4.3.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.
Files changed (34) hide show
  1. package/README.md +9 -0
  2. package/dist/coding-agent-reminders/context.d.ts +15 -0
  3. package/dist/coding-agent-reminders/context.d.ts.map +1 -0
  4. package/dist/coding-agent-reminders/evaluate.d.ts +3 -0
  5. package/dist/coding-agent-reminders/evaluate.d.ts.map +1 -0
  6. package/dist/coding-agent-reminders/index.d.ts +5 -0
  7. package/dist/coding-agent-reminders/index.d.ts.map +1 -0
  8. package/dist/coding-agent-reminders/index.js +310 -0
  9. package/dist/coding-agent-reminders/index.js.map +7 -0
  10. package/dist/coding-agent-reminders/io.d.ts +4 -0
  11. package/dist/coding-agent-reminders/io.d.ts.map +1 -0
  12. package/dist/coding-agent-reminders/predicates/classifier.d.ts +10 -0
  13. package/dist/coding-agent-reminders/predicates/classifier.d.ts.map +1 -0
  14. package/dist/coding-agent-reminders/predicates/combinators.d.ts +6 -0
  15. package/dist/coding-agent-reminders/predicates/combinators.d.ts.map +1 -0
  16. package/dist/coding-agent-reminders/predicates/content.d.ts +7 -0
  17. package/dist/coding-agent-reminders/predicates/content.d.ts.map +1 -0
  18. package/dist/coding-agent-reminders/predicates/count.d.ts +4 -0
  19. package/dist/coding-agent-reminders/predicates/count.d.ts.map +1 -0
  20. package/dist/coding-agent-reminders/predicates/environment.d.ts +3 -0
  21. package/dist/coding-agent-reminders/predicates/environment.d.ts.map +1 -0
  22. package/dist/coding-agent-reminders/predicates/event.d.ts +3 -0
  23. package/dist/coding-agent-reminders/predicates/event.d.ts.map +1 -0
  24. package/dist/coding-agent-reminders/predicates/index.d.ts +8 -0
  25. package/dist/coding-agent-reminders/predicates/index.d.ts.map +1 -0
  26. package/dist/coding-agent-reminders/predicates/tool.d.ts +11 -0
  27. package/dist/coding-agent-reminders/predicates/tool.d.ts.map +1 -0
  28. package/dist/coding-agent-reminders/types.d.ts +86 -0
  29. package/dist/coding-agent-reminders/types.d.ts.map +1 -0
  30. package/dist/index.d.ts +1 -0
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +314 -0
  33. package/dist/index.js.map +3 -3
  34. package/package.json +9 -3
package/README.md CHANGED
@@ -3,6 +3,15 @@
3
3
  A home for unstable, in-progress building blocks that are not yet part of the
4
4
  stable `@deepagents/*` surface. APIs here may change without notice.
5
5
 
6
+ ## `@deepagents/experimental/coding-agent-reminders`
7
+
8
+ `coding-agent-reminders` is an experimental event-aware reminder and guard
9
+ framework for coding agents. It provides Claude Code hook types, predicates,
10
+ context normalization, command I/O, and rule evaluation without prescribing a
11
+ reminder catalog. See
12
+ [`src/coding-agent-reminders/README.md`](./src/coding-agent-reminders/README.md)
13
+ for the public API and lifecycle mapping.
14
+
6
15
  ## `@deepagents/experimental/zukhruf`
7
16
 
8
17
  `zukhruf` is an internal DSL for **declaring** an agent, plus a **runtime** that
@@ -0,0 +1,15 @@
1
+ import type { ClaudeHookInput, ToolCallState, ToolNameSpec } from './types.ts';
2
+ export type NormalizedToolCall = {
3
+ name: string;
4
+ state: ToolCallState;
5
+ input?: unknown;
6
+ output?: unknown;
7
+ errorText?: string;
8
+ };
9
+ export declare function contentText(ctx: ClaudeHookInput): string;
10
+ export declare function bashCommand(ctx: ClaudeHookInput): string;
11
+ export declare function outputText(ctx: ClaudeHookInput): string;
12
+ export declare function textOf(value: unknown): string;
13
+ export declare function toolCallsOf(ctx: ClaudeHookInput): NormalizedToolCall[];
14
+ export declare function matchesName(spec: ToolNameSpec, name: string): boolean;
15
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/coding-agent-reminders/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/E,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,aAAa,CAAC;IACrB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,wBAAgB,WAAW,CAAC,GAAG,EAAE,eAAe,GAAG,MAAM,CAIxD;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,eAAe,GAAG,MAAM,CAIxD;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,eAAe,GAAG,MAAM,CASvD;AAED,wBAAgB,MAAM,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAQ7C;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,eAAe,GAAG,kBAAkB,EAAE,CAsBtE;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAErE"}
@@ -0,0 +1,3 @@
1
+ import type { ClaudeHookInput, ClaudeHookOutput, ReminderHookConfig } from './types.ts';
2
+ export declare function evaluateReminderHook(input: ClaudeHookInput, config: ReminderHookConfig): Promise<ClaudeHookOutput | undefined>;
3
+ //# sourceMappingURL=evaluate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"evaluate.d.ts","sourceRoot":"","sources":["../../src/coding-agent-reminders/evaluate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,gBAAgB,EAGhB,kBAAkB,EAEnB,MAAM,YAAY,CAAC;AAEpB,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,eAAe,EACtB,MAAM,EAAE,kBAAkB,GACzB,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAiCvC"}
@@ -0,0 +1,5 @@
1
+ export * from './evaluate.ts';
2
+ export * from './io.ts';
3
+ export * from './predicates/index.ts';
4
+ export * from './types.ts';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/coding-agent-reminders/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,SAAS,CAAC;AACxB,cAAc,uBAAuB,CAAC;AACtC,cAAc,YAAY,CAAC"}
@@ -0,0 +1,310 @@
1
+ // packages/experimental/src/coding-agent-reminders/evaluate.ts
2
+ async function evaluateReminderHook(input, config) {
3
+ const guardMatch = input.hook_event_name === "PreToolUse" ? await firstMatchingGuard(input, config.guards) : void 0;
4
+ if (guardMatch) {
5
+ return {
6
+ hookSpecificOutput: {
7
+ hookEventName: input.hook_event_name,
8
+ permissionDecision: "deny",
9
+ permissionDecisionReason: guardMatch.errorReason ?? resolveGuardReason(guardMatch.rule, input)
10
+ }
11
+ };
12
+ }
13
+ if (input.stop_hook_active === true && (input.hook_event_name === "Stop" || input.hook_event_name === "SubagentStop")) {
14
+ return void 0;
15
+ }
16
+ const reminders = await matchingReminders(input, config.reminders);
17
+ if (reminders.length === 0) return void 0;
18
+ return {
19
+ hookSpecificOutput: {
20
+ hookEventName: input.hook_event_name,
21
+ additionalContext: reminders.join("\n\n")
22
+ }
23
+ };
24
+ }
25
+ async function firstMatchingGuard(input, guards) {
26
+ for (const rule of guards) {
27
+ try {
28
+ if (await rule.when(input)) return { rule };
29
+ } catch (error) {
30
+ console.error(`Guard "${rule.id}" predicate failed`, error);
31
+ return {
32
+ rule,
33
+ errorReason: `Guard "${rule.id}" failed to evaluate; denying by default.`
34
+ };
35
+ }
36
+ }
37
+ return void 0;
38
+ }
39
+ async function matchingReminders(input, reminders) {
40
+ const matched = [];
41
+ for (const rule of reminders) {
42
+ if (!rule.events.includes(input.hook_event_name)) continue;
43
+ try {
44
+ if (!await rule.when(input)) continue;
45
+ matched.push(
46
+ `[${rule.target}:${rule.id}]
47
+ ${resolveText(rule.message, input)}`
48
+ );
49
+ } catch (error) {
50
+ console.error(`Reminder "${rule.id}" evaluation failed`, error);
51
+ }
52
+ }
53
+ return matched;
54
+ }
55
+ function resolveText(value, input) {
56
+ return typeof value === "function" ? value(input) : value;
57
+ }
58
+ function resolveGuardReason(rule, input) {
59
+ try {
60
+ return resolveText(rule.deny, input);
61
+ } catch (error) {
62
+ console.error(`Guard "${rule.id}" denial message failed`, error);
63
+ return `Guard "${rule.id}" matched but its denial message failed; denying by default.`;
64
+ }
65
+ }
66
+
67
+ // packages/experimental/src/coding-agent-reminders/io.ts
68
+ async function readStdin() {
69
+ const chunks = [];
70
+ for await (const chunk of process.stdin) {
71
+ chunks.push(Buffer.from(chunk));
72
+ }
73
+ return Buffer.concat(chunks).toString("utf8");
74
+ }
75
+ function writeOutput(output) {
76
+ process.stdout.write(`${JSON.stringify(output)}
77
+ `);
78
+ }
79
+
80
+ // packages/experimental/src/coding-agent-reminders/predicates/classifier.ts
81
+ import { Corpus } from "tiny-tfidf";
82
+ var BM25Classifier = class {
83
+ #corpus;
84
+ #itemsByName;
85
+ constructor(items) {
86
+ const names = items.map((item) => item.name);
87
+ const texts = items.map((item) => `${item.name} ${item.description}`);
88
+ this.#corpus = new Corpus(names, texts);
89
+ this.#itemsByName = new Map(items.map((item) => [item.name, item]));
90
+ }
91
+ match(query, options) {
92
+ const topN = options?.topN ?? 5;
93
+ const threshold = options?.threshold ?? 0;
94
+ return this.#corpus.getResultsForQuery(query).filter(([, score]) => score > threshold).slice(0, topN).map(([name, score]) => {
95
+ const item = this.#itemsByName.get(name);
96
+ if (!item) return null;
97
+ return { item, score };
98
+ }).filter((match) => match !== null);
99
+ }
100
+ };
101
+
102
+ // packages/experimental/src/coding-agent-reminders/predicates/combinators.ts
103
+ var always = () => true;
104
+ var and = (...predicates) => async (ctx) => {
105
+ for (const predicate of predicates) {
106
+ if (!await predicate(ctx)) return false;
107
+ }
108
+ return true;
109
+ };
110
+ var or = (...predicates) => async (ctx) => {
111
+ for (const predicate of predicates) {
112
+ if (await predicate(ctx)) return true;
113
+ }
114
+ return false;
115
+ };
116
+ var not = (predicate) => async (ctx) => !await predicate(ctx);
117
+
118
+ // packages/experimental/src/coding-agent-reminders/context.ts
119
+ function contentText(ctx) {
120
+ return [ctx.prompt, ctx.command_name, ctx.command_args].filter((value) => typeof value === "string").join(" ");
121
+ }
122
+ function bashCommand(ctx) {
123
+ if (ctx.tool_name !== "Bash") return "";
124
+ const command = ctx.tool_input?.command;
125
+ return typeof command === "string" ? command : "";
126
+ }
127
+ function outputText(ctx) {
128
+ if (ctx.hook_event_name === "PostToolBatch" && ctx.tool_calls) {
129
+ return ctx.tool_calls.map((call) => textOf(call.tool_response)).filter(Boolean).join("\n");
130
+ }
131
+ const output = ctx.tool_output ?? ctx.tool_response;
132
+ return textOf(output);
133
+ }
134
+ function textOf(value) {
135
+ if (typeof value === "string") return value;
136
+ if (value === void 0) return "";
137
+ try {
138
+ return JSON.stringify(value);
139
+ } catch {
140
+ return String(value);
141
+ }
142
+ }
143
+ function toolCallsOf(ctx) {
144
+ if (ctx.hook_event_name === "PostToolBatch" && ctx.tool_calls) {
145
+ return ctx.tool_calls.map((call) => ({
146
+ name: call.tool_name,
147
+ state: "output-available",
148
+ input: call.tool_input,
149
+ output: call.tool_response
150
+ }));
151
+ }
152
+ const calls = [];
153
+ const toolName = ctx.tool_name;
154
+ if (typeof toolName === "string") {
155
+ calls.push({
156
+ name: toolName,
157
+ state: stateOf(ctx.hook_event_name),
158
+ input: ctx.tool_input,
159
+ output: ctx.tool_output ?? ctx.tool_response,
160
+ errorText: errorTextOf(ctx)
161
+ });
162
+ }
163
+ return calls;
164
+ }
165
+ function matchesName(spec, name) {
166
+ return typeof spec === "function" ? spec(name) : spec === name;
167
+ }
168
+ function stateOf(eventName) {
169
+ if (eventName === "PostToolUseFailure") return "output-error";
170
+ if (eventName === "PostToolUse") return "output-available";
171
+ return "input-available";
172
+ }
173
+ function errorTextOf(ctx) {
174
+ const error = ctx.tool_error ?? ctx.error ?? ctx.reason ?? ctx.tool_output ?? ctx.tool_response;
175
+ return textOf(error);
176
+ }
177
+
178
+ // packages/experimental/src/coding-agent-reminders/predicates/content.ts
179
+ function contentMatches(topics, options) {
180
+ const classifier = new BM25Classifier(
181
+ topics.map((topic, index) => ({
182
+ name: `t${index}`,
183
+ description: topic
184
+ }))
185
+ );
186
+ return (ctx) => classifier.match(contentText(ctx), {
187
+ threshold: options?.threshold
188
+ }).length > 0;
189
+ }
190
+ function classifies(classifier, options) {
191
+ return (ctx) => classifier.match(contentText(ctx), options).length > 0;
192
+ }
193
+ function contentIncludes(keywords) {
194
+ const lower = keywords.map((keyword) => keyword.toLowerCase());
195
+ return (ctx) => {
196
+ const text = contentText(ctx).toLowerCase();
197
+ return lower.some((keyword) => text.includes(keyword));
198
+ };
199
+ }
200
+ var contentPattern = (pattern) => (ctx) => {
201
+ pattern.lastIndex = 0;
202
+ return pattern.test(contentText(ctx));
203
+ };
204
+ var promptMatches = contentPattern;
205
+
206
+ // packages/experimental/src/coding-agent-reminders/predicates/count.ts
207
+ function assertCountSpec(spec) {
208
+ const hasEq = spec.eq !== void 0;
209
+ const hasRange = spec.gte !== void 0 || spec.lte !== void 0;
210
+ if (!hasEq && !hasRange) {
211
+ throw new Error("CountSpec must include at least one of gte/lte/eq");
212
+ }
213
+ if (hasEq && hasRange) {
214
+ throw new Error("CountSpec.eq cannot be combined with gte/lte");
215
+ }
216
+ }
217
+ function checkCount(count, spec) {
218
+ if (spec.eq !== void 0) return count === spec.eq;
219
+ if (spec.gte !== void 0 && count < spec.gte) return false;
220
+ if (spec.lte !== void 0 && count > spec.lte) return false;
221
+ return true;
222
+ }
223
+
224
+ // packages/experimental/src/coding-agent-reminders/predicates/environment.ts
225
+ var envFlag = (name) => () => process.env[name] === "1" || process.env[name] === "true";
226
+
227
+ // packages/experimental/src/coding-agent-reminders/predicates/event.ts
228
+ var eventIs = (...events) => (ctx) => events.includes(ctx.hook_event_name);
229
+
230
+ // packages/experimental/src/coding-agent-reminders/predicates/tool.ts
231
+ var toolIs = (name) => (ctx) => ctx.tool_name === name;
232
+ var bashCommandMatches = (pattern) => (ctx) => {
233
+ pattern.lastIndex = 0;
234
+ return pattern.test(bashCommand(ctx));
235
+ };
236
+ function toolCall(options) {
237
+ return (ctx) => {
238
+ return toolCallsOf(ctx).some((call) => {
239
+ if (options.state && call.state !== options.state) return false;
240
+ if (options.name !== void 0 && !matchesName(options.name, call.name)) {
241
+ return false;
242
+ }
243
+ if (options.input && !options.input(call.input)) return false;
244
+ if (options.output) {
245
+ if (call.state !== "output-available") return false;
246
+ if (!options.output(call.output)) return false;
247
+ }
248
+ if (options.errorText) {
249
+ if (call.state !== "output-error") return false;
250
+ if (!options.errorText(call.errorText ?? "")) return false;
251
+ }
252
+ return true;
253
+ });
254
+ };
255
+ }
256
+ function toolCalled(name) {
257
+ return toolCall({ name });
258
+ }
259
+ function toolFailed(name) {
260
+ return toolCall({ name, state: "output-error" });
261
+ }
262
+ function anyToolCalled() {
263
+ return (ctx) => toolCallsOf(ctx).length > 0;
264
+ }
265
+ function toolCallCount(name, spec) {
266
+ assertCountSpec(spec);
267
+ return (ctx) => checkCount(
268
+ toolCallsOf(ctx).filter((call) => matchesName(name, call.name)).length,
269
+ spec
270
+ );
271
+ }
272
+ var outputMatches = (pattern) => (ctx) => {
273
+ pattern.lastIndex = 0;
274
+ return pattern.test(outputText(ctx));
275
+ };
276
+ var toolOutputMatches = (pattern) => toolCall({
277
+ output: (output) => {
278
+ pattern.lastIndex = 0;
279
+ return pattern.test(textOf(output));
280
+ }
281
+ });
282
+ export {
283
+ BM25Classifier,
284
+ always,
285
+ and,
286
+ anyToolCalled,
287
+ assertCountSpec,
288
+ bashCommandMatches,
289
+ checkCount,
290
+ classifies,
291
+ contentIncludes,
292
+ contentMatches,
293
+ contentPattern,
294
+ envFlag,
295
+ evaluateReminderHook,
296
+ eventIs,
297
+ not,
298
+ or,
299
+ outputMatches,
300
+ promptMatches,
301
+ readStdin,
302
+ toolCall,
303
+ toolCallCount,
304
+ toolCalled,
305
+ toolFailed,
306
+ toolIs,
307
+ toolOutputMatches,
308
+ writeOutput
309
+ };
310
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/coding-agent-reminders/evaluate.ts", "../../src/coding-agent-reminders/io.ts", "../../src/coding-agent-reminders/predicates/classifier.ts", "../../src/coding-agent-reminders/predicates/combinators.ts", "../../src/coding-agent-reminders/context.ts", "../../src/coding-agent-reminders/predicates/content.ts", "../../src/coding-agent-reminders/predicates/count.ts", "../../src/coding-agent-reminders/predicates/environment.ts", "../../src/coding-agent-reminders/predicates/event.ts", "../../src/coding-agent-reminders/predicates/tool.ts"],
4
+ "sourcesContent": ["import type {\n ClaudeHookInput,\n ClaudeHookOutput,\n GuardRule,\n HookEventName,\n ReminderHookConfig,\n ReminderRule,\n} from './types.ts';\n\nexport async function evaluateReminderHook(\n input: ClaudeHookInput,\n config: ReminderHookConfig,\n): Promise<ClaudeHookOutput | undefined> {\n const guardMatch =\n input.hook_event_name === 'PreToolUse'\n ? await firstMatchingGuard(input, config.guards)\n : undefined;\n if (guardMatch) {\n return {\n hookSpecificOutput: {\n hookEventName: input.hook_event_name,\n permissionDecision: 'deny',\n permissionDecisionReason:\n guardMatch.errorReason ?? resolveGuardReason(guardMatch.rule, input),\n },\n };\n }\n\n if (\n input.stop_hook_active === true &&\n (input.hook_event_name === 'Stop' ||\n input.hook_event_name === 'SubagentStop')\n ) {\n return undefined;\n }\n\n const reminders = await matchingReminders(input, config.reminders);\n if (reminders.length === 0) return undefined;\n\n return {\n hookSpecificOutput: {\n hookEventName: input.hook_event_name,\n additionalContext: reminders.join('\\n\\n'),\n },\n };\n}\n\nasync function firstMatchingGuard(\n input: ClaudeHookInput,\n guards: GuardRule[],\n): Promise<{ rule: GuardRule; errorReason?: string } | undefined> {\n for (const rule of guards) {\n try {\n if (await rule.when(input)) return { rule };\n } catch (error) {\n console.error(`Guard \"${rule.id}\" predicate failed`, error);\n return {\n rule,\n errorReason: `Guard \"${rule.id}\" failed to evaluate; denying by default.`,\n };\n }\n }\n return undefined;\n}\n\nasync function matchingReminders(\n input: ClaudeHookInput,\n reminders: ReminderRule[],\n): Promise<string[]> {\n const matched: string[] = [];\n for (const rule of reminders) {\n if (!rule.events.includes(input.hook_event_name as HookEventName)) continue;\n try {\n if (!(await rule.when(input))) continue;\n matched.push(\n `[${rule.target}:${rule.id}]\\n${resolveText(rule.message, input)}`,\n );\n } catch (error) {\n console.error(`Reminder \"${rule.id}\" evaluation failed`, error);\n }\n }\n return matched;\n}\n\nfunction resolveText(\n value: string | ((ctx: ClaudeHookInput) => string),\n input: ClaudeHookInput,\n): string {\n return typeof value === 'function' ? value(input) : value;\n}\n\nfunction resolveGuardReason(rule: GuardRule, input: ClaudeHookInput): string {\n try {\n return resolveText(rule.deny, input);\n } catch (error) {\n console.error(`Guard \"${rule.id}\" denial message failed`, error);\n return `Guard \"${rule.id}\" matched but its denial message failed; denying by default.`;\n }\n}\n", "import type { ClaudeHookOutput } from './types.ts';\n\nexport async function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n\nexport function writeOutput(output: ClaudeHookOutput): void {\n process.stdout.write(`${JSON.stringify(output)}\\n`);\n}\n", "import { Corpus } from 'tiny-tfidf';\n\nimport type {\n ClassifierMatch,\n ClassifierOptions,\n IClassifier,\n} from '../types.ts';\n\nexport class BM25Classifier<\n T extends { name: string; description: string },\n> implements IClassifier<T> {\n #corpus: Corpus;\n #itemsByName: Map<string, T>;\n\n constructor(items: T[]) {\n const names = items.map((item) => item.name);\n const texts = items.map((item) => `${item.name} ${item.description}`);\n this.#corpus = new Corpus(names, texts);\n this.#itemsByName = new Map(items.map((item) => [item.name, item]));\n }\n\n match(query: string, options?: ClassifierOptions): ClassifierMatch<T>[] {\n const topN = options?.topN ?? 5;\n const threshold = options?.threshold ?? 0;\n\n return this.#corpus\n .getResultsForQuery(query)\n .filter(([, score]: [string, number]) => score > threshold)\n .slice(0, topN)\n .map(([name, score]: [string, number]) => {\n const item = this.#itemsByName.get(name);\n if (!item) return null;\n return { item, score };\n })\n .filter((match): match is ClassifierMatch<T> => match !== null);\n }\n}\n", "import type { AsyncHookPredicate, HookPredicate } from '../types.ts';\n\nexport const always: HookPredicate = () => true;\n\nexport const and =\n (...predicates: HookPredicate[]): AsyncHookPredicate =>\n async (ctx) => {\n for (const predicate of predicates) {\n if (!(await predicate(ctx))) return false;\n }\n return true;\n };\n\nexport const or =\n (...predicates: HookPredicate[]): AsyncHookPredicate =>\n async (ctx) => {\n for (const predicate of predicates) {\n if (await predicate(ctx)) return true;\n }\n return false;\n };\n\nexport const not =\n (predicate: HookPredicate): AsyncHookPredicate =>\n async (ctx) =>\n !(await predicate(ctx));\n", "import type { ClaudeHookInput, ToolCallState, ToolNameSpec } from './types.ts';\n\nexport type NormalizedToolCall = {\n name: string;\n state: ToolCallState;\n input?: unknown;\n output?: unknown;\n errorText?: string;\n};\n\nexport function contentText(ctx: ClaudeHookInput): string {\n return [ctx.prompt, ctx.command_name, ctx.command_args]\n .filter((value): value is string => typeof value === 'string')\n .join(' ');\n}\n\nexport function bashCommand(ctx: ClaudeHookInput): string {\n if (ctx.tool_name !== 'Bash') return '';\n const command = ctx.tool_input?.command;\n return typeof command === 'string' ? command : '';\n}\n\nexport function outputText(ctx: ClaudeHookInput): string {\n if (ctx.hook_event_name === 'PostToolBatch' && ctx.tool_calls) {\n return ctx.tool_calls\n .map((call) => textOf(call.tool_response))\n .filter(Boolean)\n .join('\\n');\n }\n const output = ctx.tool_output ?? ctx.tool_response;\n return textOf(output);\n}\n\nexport function textOf(value: unknown): string {\n if (typeof value === 'string') return value;\n if (value === undefined) return '';\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nexport function toolCallsOf(ctx: ClaudeHookInput): NormalizedToolCall[] {\n if (ctx.hook_event_name === 'PostToolBatch' && ctx.tool_calls) {\n return ctx.tool_calls.map((call) => ({\n name: call.tool_name,\n state: 'output-available',\n input: call.tool_input,\n output: call.tool_response,\n }));\n }\n\n const calls: NormalizedToolCall[] = [];\n const toolName = ctx.tool_name;\n if (typeof toolName === 'string') {\n calls.push({\n name: toolName,\n state: stateOf(ctx.hook_event_name),\n input: ctx.tool_input,\n output: ctx.tool_output ?? ctx.tool_response,\n errorText: errorTextOf(ctx),\n });\n }\n return calls;\n}\n\nexport function matchesName(spec: ToolNameSpec, name: string): boolean {\n return typeof spec === 'function' ? spec(name) : spec === name;\n}\n\nfunction stateOf(eventName: string): ToolCallState {\n if (eventName === 'PostToolUseFailure') return 'output-error';\n if (eventName === 'PostToolUse') return 'output-available';\n return 'input-available';\n}\n\nfunction errorTextOf(ctx: ClaudeHookInput): string {\n const error =\n ctx.tool_error ??\n ctx.error ??\n ctx.reason ??\n ctx.tool_output ??\n ctx.tool_response;\n return textOf(error);\n}\n", "import { contentText } from '../context.ts';\nimport type {\n ClassifierOptions,\n ContentMatchesOptions,\n HookPredicate,\n IClassifier,\n} from '../types.ts';\nimport { BM25Classifier } from './classifier.ts';\n\nexport function contentMatches(\n topics: string[],\n options?: ContentMatchesOptions,\n): HookPredicate {\n const classifier = new BM25Classifier(\n topics.map((topic, index) => ({\n name: `t${index}`,\n description: topic,\n })),\n );\n return (ctx) =>\n classifier.match(contentText(ctx), {\n threshold: options?.threshold,\n }).length > 0;\n}\n\nexport function classifies<T>(\n classifier: IClassifier<T>,\n options?: ClassifierOptions,\n): HookPredicate {\n return (ctx) => classifier.match(contentText(ctx), options).length > 0;\n}\n\nexport function contentIncludes(keywords: string[]): HookPredicate {\n const lower = keywords.map((keyword) => keyword.toLowerCase());\n return (ctx) => {\n const text = contentText(ctx).toLowerCase();\n return lower.some((keyword) => text.includes(keyword));\n };\n}\n\nexport const contentPattern =\n (pattern: RegExp): HookPredicate =>\n (ctx) => {\n pattern.lastIndex = 0;\n return pattern.test(contentText(ctx));\n };\n\nexport const promptMatches = contentPattern;\n", "import type { CountSpec } from '../types.ts';\n\nexport function assertCountSpec(spec: CountSpec): void {\n const hasEq = spec.eq !== undefined;\n const hasRange = spec.gte !== undefined || spec.lte !== undefined;\n if (!hasEq && !hasRange) {\n throw new Error('CountSpec must include at least one of gte/lte/eq');\n }\n if (hasEq && hasRange) {\n throw new Error('CountSpec.eq cannot be combined with gte/lte');\n }\n}\n\nexport function checkCount(count: number, spec: CountSpec): boolean {\n if (spec.eq !== undefined) return count === spec.eq;\n if (spec.gte !== undefined && count < spec.gte) return false;\n if (spec.lte !== undefined && count > spec.lte) return false;\n return true;\n}\n", "import type { HookPredicate } from '../types.ts';\n\nexport const envFlag =\n (name: string): HookPredicate =>\n () =>\n process.env[name] === '1' || process.env[name] === 'true';\n", "import type { HookEventName, HookPredicate } from '../types.ts';\n\nexport const eventIs =\n (...events: HookEventName[]): HookPredicate =>\n (ctx) =>\n events.includes(ctx.hook_event_name as HookEventName);\n", "import {\n bashCommand,\n matchesName,\n outputText,\n textOf,\n toolCallsOf,\n} from '../context.ts';\nimport type {\n CountSpec,\n HookPredicate,\n ToolCallOptions,\n ToolNameSpec,\n} from '../types.ts';\nimport { assertCountSpec, checkCount } from './count.ts';\n\nexport const toolIs =\n (name: string): HookPredicate =>\n (ctx) =>\n ctx.tool_name === name;\n\nexport const bashCommandMatches =\n (pattern: RegExp): HookPredicate =>\n (ctx) => {\n pattern.lastIndex = 0;\n return pattern.test(bashCommand(ctx));\n };\n\nexport function toolCall(options: ToolCallOptions): HookPredicate {\n return (ctx) => {\n return toolCallsOf(ctx).some((call) => {\n if (options.state && call.state !== options.state) return false;\n if (options.name !== undefined && !matchesName(options.name, call.name)) {\n return false;\n }\n if (options.input && !options.input(call.input)) return false;\n if (options.output) {\n if (call.state !== 'output-available') return false;\n if (!options.output(call.output)) return false;\n }\n if (options.errorText) {\n if (call.state !== 'output-error') return false;\n if (!options.errorText(call.errorText ?? '')) return false;\n }\n return true;\n });\n };\n}\n\nexport function toolCalled(name: ToolNameSpec): HookPredicate {\n return toolCall({ name });\n}\n\nexport function toolFailed(name: ToolNameSpec): HookPredicate {\n return toolCall({ name, state: 'output-error' });\n}\n\nexport function anyToolCalled(): HookPredicate {\n return (ctx) => toolCallsOf(ctx).length > 0;\n}\n\nexport function toolCallCount(\n name: ToolNameSpec,\n spec: CountSpec,\n): HookPredicate {\n assertCountSpec(spec);\n return (ctx) =>\n checkCount(\n toolCallsOf(ctx).filter((call) => matchesName(name, call.name)).length,\n spec,\n );\n}\n\nexport const outputMatches =\n (pattern: RegExp): HookPredicate =>\n (ctx) => {\n pattern.lastIndex = 0;\n return pattern.test(outputText(ctx));\n };\n\nexport const toolOutputMatches = (pattern: RegExp): HookPredicate =>\n toolCall({\n output: (output) => {\n pattern.lastIndex = 0;\n return pattern.test(textOf(output));\n },\n });\n"],
5
+ "mappings": ";AASA,eAAsB,qBACpB,OACA,QACuC;AACvC,QAAM,aACJ,MAAM,oBAAoB,eACtB,MAAM,mBAAmB,OAAO,OAAO,MAAM,IAC7C;AACN,MAAI,YAAY;AACd,WAAO;AAAA,MACL,oBAAoB;AAAA,QAClB,eAAe,MAAM;AAAA,QACrB,oBAAoB;AAAA,QACpB,0BACE,WAAW,eAAe,mBAAmB,WAAW,MAAM,KAAK;AAAA,MACvE;AAAA,IACF;AAAA,EACF;AAEA,MACE,MAAM,qBAAqB,SAC1B,MAAM,oBAAoB,UACzB,MAAM,oBAAoB,iBAC5B;AACA,WAAO;AAAA,EACT;AAEA,QAAM,YAAY,MAAM,kBAAkB,OAAO,OAAO,SAAS;AACjE,MAAI,UAAU,WAAW,EAAG,QAAO;AAEnC,SAAO;AAAA,IACL,oBAAoB;AAAA,MAClB,eAAe,MAAM;AAAA,MACrB,mBAAmB,UAAU,KAAK,MAAM;AAAA,IAC1C;AAAA,EACF;AACF;AAEA,eAAe,mBACb,OACA,QACgE;AAChE,aAAW,QAAQ,QAAQ;AACzB,QAAI;AACF,UAAI,MAAM,KAAK,KAAK,KAAK,EAAG,QAAO,EAAE,KAAK;AAAA,IAC5C,SA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AAE,KAAK,CAAC;AAC1B;AAEO,SAAS,WAAW,MAAmC;AAC5D,SAAO,SAAS,EAAE,MAAM,OAAO,eAAe,CAAC;AACjD;AAEO,SAAS,gBAA+B;AAC7C,SAAO,CAAC,QAAQ,YAAY,GAAG,EAAE,SAAS;AAC5C;AAEO,SAAS,cACd,MACA,MACe;AACf,kBAAgB,IAAI;AACpB,SAAO,CAAC,QACN;AAAA,IACE,YAAY,GAAG,EAAE,OAAO,CAAC,SAAS,YAAY,MAAM,KAAK,IAAI,CAAC,EAAE;AAAA,IAChE;AAAA,EACF;AACJ;AAEO,IAAM,gBACX,CAAC,YACD,CAAC,QAAQ;AACP,UAAQ,YAAY;AACpB,SAAO,QAAQ,KAAK,WAAW,GAAG,CAAC;AACrC;AAEK,IAAM,oBAAoB,CAAC,YAChC,SAAS;AAAA,EACP,QAAQ,CAAC,WAAW;AAClB,YAAQ,YAAY;AACpB,WAAO,QAAQ,KAAK,OAAO,MAAM,CAAC;AAAA,EACpC;AACF,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,4 @@
1
+ import type { ClaudeHookOutput } from './types.ts';
2
+ export declare function readStdin(): Promise<string>;
3
+ export declare function writeOutput(output: ClaudeHookOutput): void;
4
+ //# sourceMappingURL=io.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"io.d.ts","sourceRoot":"","sources":["../../src/coding-agent-reminders/io.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,wBAAsB,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAMjD;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,gBAAgB,GAAG,IAAI,CAE1D"}
@@ -0,0 +1,10 @@
1
+ import type { ClassifierMatch, ClassifierOptions, IClassifier } from '../types.ts';
2
+ export declare class BM25Classifier<T extends {
3
+ name: string;
4
+ description: string;
5
+ }> implements IClassifier<T> {
6
+ #private;
7
+ constructor(items: T[]);
8
+ match(query: string, options?: ClassifierOptions): ClassifierMatch<T>[];
9
+ }
10
+ //# sourceMappingURL=classifier.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"classifier.d.ts","sourceRoot":"","sources":["../../../src/coding-agent-reminders/predicates/classifier.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,eAAe,EACf,iBAAiB,EACjB,WAAW,EACZ,MAAM,aAAa,CAAC;AAErB,qBAAa,cAAc,CACzB,CAAC,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,CAC/C,YAAW,WAAW,CAAC,CAAC,CAAC;;gBAIb,KAAK,EAAE,CAAC,EAAE;IAOtB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,eAAe,CAAC,CAAC,CAAC,EAAE;CAexE"}
@@ -0,0 +1,6 @@
1
+ import type { AsyncHookPredicate, HookPredicate } from '../types.ts';
2
+ export declare const always: HookPredicate;
3
+ export declare const and: (...predicates: HookPredicate[]) => AsyncHookPredicate;
4
+ export declare const or: (...predicates: HookPredicate[]) => AsyncHookPredicate;
5
+ export declare const not: (predicate: HookPredicate) => AsyncHookPredicate;
6
+ //# sourceMappingURL=combinators.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"combinators.d.ts","sourceRoot":"","sources":["../../../src/coding-agent-reminders/predicates/combinators.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAErE,eAAO,MAAM,MAAM,EAAE,aAA0B,CAAC;AAEhD,eAAO,MAAM,GAAG,GACb,GAAG,YAAY,aAAa,EAAE,KAAG,kBAMjC,CAAC;AAEJ,eAAO,MAAM,EAAE,GACZ,GAAG,YAAY,aAAa,EAAE,KAAG,kBAMjC,CAAC;AAEJ,eAAO,MAAM,GAAG,GACb,WAAW,aAAa,KAAG,kBAEH,CAAC"}
@@ -0,0 +1,7 @@
1
+ import type { ClassifierOptions, ContentMatchesOptions, HookPredicate, IClassifier } from '../types.ts';
2
+ export declare function contentMatches(topics: string[], options?: ContentMatchesOptions): HookPredicate;
3
+ export declare function classifies<T>(classifier: IClassifier<T>, options?: ClassifierOptions): HookPredicate;
4
+ export declare function contentIncludes(keywords: string[]): HookPredicate;
5
+ export declare const contentPattern: (pattern: RegExp) => HookPredicate;
6
+ export declare const promptMatches: (pattern: RegExp) => HookPredicate;
7
+ //# sourceMappingURL=content.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"content.d.ts","sourceRoot":"","sources":["../../../src/coding-agent-reminders/predicates/content.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,iBAAiB,EACjB,qBAAqB,EACrB,aAAa,EACb,WAAW,EACZ,MAAM,aAAa,CAAC;AAGrB,wBAAgB,cAAc,CAC5B,MAAM,EAAE,MAAM,EAAE,EAChB,OAAO,CAAC,EAAE,qBAAqB,GAC9B,aAAa,CAWf;AAED,wBAAgB,UAAU,CAAC,CAAC,EAC1B,UAAU,EAAE,WAAW,CAAC,CAAC,CAAC,EAC1B,OAAO,CAAC,EAAE,iBAAiB,GAC1B,aAAa,CAEf;AAED,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,aAAa,CAMjE;AAED,eAAO,MAAM,cAAc,GACxB,SAAS,MAAM,KAAG,aAIlB,CAAC;AAEJ,eAAO,MAAM,aAAa,YANd,MAAM,KAAG,aAMsB,CAAC"}
@@ -0,0 +1,4 @@
1
+ import type { CountSpec } from '../types.ts';
2
+ export declare function assertCountSpec(spec: CountSpec): void;
3
+ export declare function checkCount(count: number, spec: CountSpec): boolean;
4
+ //# sourceMappingURL=count.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"count.d.ts","sourceRoot":"","sources":["../../../src/coding-agent-reminders/predicates/count.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE7C,wBAAgB,eAAe,CAAC,IAAI,EAAE,SAAS,GAAG,IAAI,CASrD;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,GAAG,OAAO,CAKlE"}
@@ -0,0 +1,3 @@
1
+ import type { HookPredicate } from '../types.ts';
2
+ export declare const envFlag: (name: string) => HookPredicate;
3
+ //# sourceMappingURL=environment.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"environment.d.ts","sourceRoot":"","sources":["../../../src/coding-agent-reminders/predicates/environment.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD,eAAO,MAAM,OAAO,GACjB,MAAM,MAAM,KAAG,aAE2C,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { HookEventName, HookPredicate } from '../types.ts';
2
+ export declare const eventIs: (...events: HookEventName[]) => HookPredicate;
3
+ //# sourceMappingURL=event.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event.d.ts","sourceRoot":"","sources":["../../../src/coding-agent-reminders/predicates/event.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEhE,eAAO,MAAM,OAAO,GACjB,GAAG,QAAQ,aAAa,EAAE,KAAG,aAEyB,CAAC"}
@@ -0,0 +1,8 @@
1
+ export * from './classifier.ts';
2
+ export * from './combinators.ts';
3
+ export * from './content.ts';
4
+ export * from './count.ts';
5
+ export * from './environment.ts';
6
+ export * from './event.ts';
7
+ export * from './tool.ts';
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/coding-agent-reminders/predicates/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC;AACjC,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,kBAAkB,CAAC;AACjC,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC"}
@@ -0,0 +1,11 @@
1
+ import type { CountSpec, HookPredicate, ToolCallOptions, ToolNameSpec } from '../types.ts';
2
+ export declare const toolIs: (name: string) => HookPredicate;
3
+ export declare const bashCommandMatches: (pattern: RegExp) => HookPredicate;
4
+ export declare function toolCall(options: ToolCallOptions): HookPredicate;
5
+ export declare function toolCalled(name: ToolNameSpec): HookPredicate;
6
+ export declare function toolFailed(name: ToolNameSpec): HookPredicate;
7
+ export declare function anyToolCalled(): HookPredicate;
8
+ export declare function toolCallCount(name: ToolNameSpec, spec: CountSpec): HookPredicate;
9
+ export declare const outputMatches: (pattern: RegExp) => HookPredicate;
10
+ export declare const toolOutputMatches: (pattern: RegExp) => HookPredicate;
11
+ //# sourceMappingURL=tool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../src/coding-agent-reminders/predicates/tool.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,SAAS,EACT,aAAa,EACb,eAAe,EACf,YAAY,EACb,MAAM,aAAa,CAAC;AAGrB,eAAO,MAAM,MAAM,GAChB,MAAM,MAAM,KAAG,aAEQ,CAAC;AAE3B,eAAO,MAAM,kBAAkB,GAC5B,SAAS,MAAM,KAAG,aAIlB,CAAC;AAEJ,wBAAgB,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,aAAa,CAmBhE;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,YAAY,GAAG,aAAa,CAE5D;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,YAAY,GAAG,aAAa,CAE5D;AAED,wBAAgB,aAAa,IAAI,aAAa,CAE7C;AAED,wBAAgB,aAAa,CAC3B,IAAI,EAAE,YAAY,EAClB,IAAI,EAAE,SAAS,GACd,aAAa,CAOf;AAED,eAAO,MAAM,aAAa,GACvB,SAAS,MAAM,KAAG,aAIlB,CAAC;AAEJ,eAAO,MAAM,iBAAiB,GAAI,SAAS,MAAM,KAAG,aAMhD,CAAC"}
@@ -0,0 +1,86 @@
1
+ export type HookEventName = 'SessionStart' | 'Setup' | 'SubagentStart' | 'UserPromptSubmit' | 'UserPromptExpansion' | 'PreToolUse' | 'PostToolUse' | 'PostToolUseFailure' | 'PostToolBatch' | 'Stop' | 'SubagentStop';
2
+ export type ClaudeBatchToolCall = {
3
+ tool_name: string;
4
+ tool_input?: Record<string, unknown>;
5
+ tool_use_id?: string;
6
+ tool_response?: unknown;
7
+ };
8
+ export type ClaudeHookInput = {
9
+ hook_event_name: HookEventName | string;
10
+ session_id?: string;
11
+ prompt_id?: string;
12
+ transcript_path?: string;
13
+ cwd?: string;
14
+ permission_mode?: string;
15
+ prompt?: string;
16
+ command_name?: string;
17
+ command_args?: string;
18
+ tool_name?: string;
19
+ tool_input?: Record<string, unknown>;
20
+ tool_output?: unknown;
21
+ tool_response?: unknown;
22
+ tool_calls?: ClaudeBatchToolCall[];
23
+ source?: string;
24
+ trigger?: string;
25
+ agent_type?: string;
26
+ stop_hook_active?: boolean;
27
+ [key: string]: unknown;
28
+ };
29
+ export type HookPredicate = (ctx: ClaudeHookInput) => boolean | Promise<boolean>;
30
+ export type AsyncHookPredicate = (ctx: ClaudeHookInput) => Promise<boolean>;
31
+ export type ReminderTarget = 'session' | 'prompt' | 'tool-result' | 'tool-batch' | 'stop-feedback';
32
+ export type ReminderRule = {
33
+ id: string;
34
+ target: ReminderTarget;
35
+ events: HookEventName[];
36
+ when: HookPredicate;
37
+ message: string | ((ctx: ClaudeHookInput) => string);
38
+ };
39
+ export type GuardRule = {
40
+ id: string;
41
+ when: HookPredicate;
42
+ deny: string | ((ctx: ClaudeHookInput) => string);
43
+ };
44
+ export type ClaudeHookOutput = {
45
+ decision?: 'block';
46
+ reason?: string;
47
+ hookSpecificOutput?: {
48
+ hookEventName: string;
49
+ additionalContext?: string;
50
+ permissionDecision?: 'allow' | 'deny' | 'ask' | 'defer';
51
+ permissionDecisionReason?: string;
52
+ };
53
+ };
54
+ export type ReminderHookConfig = {
55
+ reminders: ReminderRule[];
56
+ guards: GuardRule[];
57
+ };
58
+ export type CountSpec = {
59
+ gte?: number;
60
+ lte?: number;
61
+ eq?: number;
62
+ };
63
+ export type ToolNameSpec = string | ((name: string) => boolean);
64
+ export type ToolCallState = 'input-available' | 'output-available' | 'output-error';
65
+ export type ToolCallOptions = {
66
+ name?: ToolNameSpec;
67
+ state?: ToolCallState;
68
+ input?: (input: unknown) => boolean;
69
+ output?: (output: unknown) => boolean;
70
+ errorText?: (text: string) => boolean;
71
+ };
72
+ export interface ClassifierMatch<T> {
73
+ item: T;
74
+ score: number;
75
+ }
76
+ export interface ClassifierOptions {
77
+ topN?: number;
78
+ threshold?: number;
79
+ }
80
+ export interface IClassifier<T> {
81
+ match(query: string, options?: ClassifierOptions): ClassifierMatch<T>[];
82
+ }
83
+ export interface ContentMatchesOptions {
84
+ threshold?: number;
85
+ }
86
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/coding-agent-reminders/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,aAAa,GACrB,cAAc,GACd,OAAO,GACP,eAAe,GACf,kBAAkB,GAClB,qBAAqB,GACrB,YAAY,GACZ,aAAa,GACb,oBAAoB,GACpB,eAAe,GACf,MAAM,GACN,cAAc,CAAC;AAEnB,MAAM,MAAM,mBAAmB,GAAG;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,eAAe,EAAE,aAAa,GAAG,MAAM,CAAC;IACxC,UAAU,CAAC,EAAE,MAAM,CAAC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AM,KAAK,OAAO,CAAC;CACvC,CAAC;AAEF,MAAM,WAAW,eAAe,CAAC,CAAC;IAChC,IAAI,EAAE,CAAC,CAAC;IACR,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,WAAW,CAAC,CAAC;IAC5B,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,eAAe,CAAC,CAAC,CAAC,EAAE,CAAC;CACzE;AAED,MAAM,WAAW,qBAAqB;IACpC,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB"}
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
+ export * as codingAgentReminders from './coding-agent-reminders/index.ts';
1
2
  export * as zukhruf from './zukhruf/index.ts';
2
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,oBAAoB,MAAM,mCAAmC,CAAC;AAC1E,OAAO,KAAK,OAAO,MAAM,oBAAoB,CAAC"}
package/dist/index.js CHANGED
@@ -4,6 +4,319 @@ var __export = (target, all) => {
4
4
  __defProp(target, name, { get: all[name], enumerable: true });
5
5
  };
6
6
 
7
+ // packages/experimental/src/coding-agent-reminders/index.ts
8
+ var coding_agent_reminders_exports = {};
9
+ __export(coding_agent_reminders_exports, {
10
+ BM25Classifier: () => BM25Classifier,
11
+ always: () => always,
12
+ and: () => and,
13
+ anyToolCalled: () => anyToolCalled,
14
+ assertCountSpec: () => assertCountSpec,
15
+ bashCommandMatches: () => bashCommandMatches,
16
+ checkCount: () => checkCount,
17
+ classifies: () => classifies,
18
+ contentIncludes: () => contentIncludes,
19
+ contentMatches: () => contentMatches,
20
+ contentPattern: () => contentPattern,
21
+ envFlag: () => envFlag,
22
+ evaluateReminderHook: () => evaluateReminderHook,
23
+ eventIs: () => eventIs,
24
+ not: () => not,
25
+ or: () => or,
26
+ outputMatches: () => outputMatches,
27
+ promptMatches: () => promptMatches,
28
+ readStdin: () => readStdin,
29
+ toolCall: () => toolCall,
30
+ toolCallCount: () => toolCallCount,
31
+ toolCalled: () => toolCalled,
32
+ toolFailed: () => toolFailed,
33
+ toolIs: () => toolIs,
34
+ toolOutputMatches: () => toolOutputMatches,
35
+ writeOutput: () => writeOutput
36
+ });
37
+
38
+ // packages/experimental/src/coding-agent-reminders/evaluate.ts
39
+ async function evaluateReminderHook(input, config) {
40
+ const guardMatch = input.hook_event_name === "PreToolUse" ? await firstMatchingGuard(input, config.guards) : void 0;
41
+ if (guardMatch) {
42
+ return {
43
+ hookSpecificOutput: {
44
+ hookEventName: input.hook_event_name,
45
+ permissionDecision: "deny",
46
+ permissionDecisionReason: guardMatch.errorReason ?? resolveGuardReason(guardMatch.rule, input)
47
+ }
48
+ };
49
+ }
50
+ if (input.stop_hook_active === true && (input.hook_event_name === "Stop" || input.hook_event_name === "SubagentStop")) {
51
+ return void 0;
52
+ }
53
+ const reminders = await matchingReminders(input, config.reminders);
54
+ if (reminders.length === 0) return void 0;
55
+ return {
56
+ hookSpecificOutput: {
57
+ hookEventName: input.hook_event_name,
58
+ additionalContext: reminders.join("\n\n")
59
+ }
60
+ };
61
+ }
62
+ async function firstMatchingGuard(input, guards) {
63
+ for (const rule of guards) {
64
+ try {
65
+ if (await rule.when(input)) return { rule };
66
+ } catch (error) {
67
+ console.error(`Guard "${rule.id}" predicate failed`, error);
68
+ return {
69
+ rule,
70
+ errorReason: `Guard "${rule.id}" failed to evaluate; denying by default.`
71
+ };
72
+ }
73
+ }
74
+ return void 0;
75
+ }
76
+ async function matchingReminders(input, reminders) {
77
+ const matched = [];
78
+ for (const rule of reminders) {
79
+ if (!rule.events.includes(input.hook_event_name)) continue;
80
+ try {
81
+ if (!await rule.when(input)) continue;
82
+ matched.push(
83
+ `[${rule.target}:${rule.id}]
84
+ ${resolveText(rule.message, input)}`
85
+ );
86
+ } catch (error) {
87
+ console.error(`Reminder "${rule.id}" evaluation failed`, error);
88
+ }
89
+ }
90
+ return matched;
91
+ }
92
+ function resolveText(value, input) {
93
+ return typeof value === "function" ? value(input) : value;
94
+ }
95
+ function resolveGuardReason(rule, input) {
96
+ try {
97
+ return resolveText(rule.deny, input);
98
+ } catch (error) {
99
+ console.error(`Guard "${rule.id}" denial message failed`, error);
100
+ return `Guard "${rule.id}" matched but its denial message failed; denying by default.`;
101
+ }
102
+ }
103
+
104
+ // packages/experimental/src/coding-agent-reminders/io.ts
105
+ async function readStdin() {
106
+ const chunks = [];
107
+ for await (const chunk of process.stdin) {
108
+ chunks.push(Buffer.from(chunk));
109
+ }
110
+ return Buffer.concat(chunks).toString("utf8");
111
+ }
112
+ function writeOutput(output) {
113
+ process.stdout.write(`${JSON.stringify(output)}
114
+ `);
115
+ }
116
+
117
+ // packages/experimental/src/coding-agent-reminders/predicates/classifier.ts
118
+ import { Corpus } from "tiny-tfidf";
119
+ var BM25Classifier = class {
120
+ #corpus;
121
+ #itemsByName;
122
+ constructor(items) {
123
+ const names = items.map((item) => item.name);
124
+ const texts = items.map((item) => `${item.name} ${item.description}`);
125
+ this.#corpus = new Corpus(names, texts);
126
+ this.#itemsByName = new Map(items.map((item) => [item.name, item]));
127
+ }
128
+ match(query, options) {
129
+ const topN = options?.topN ?? 5;
130
+ const threshold = options?.threshold ?? 0;
131
+ return this.#corpus.getResultsForQuery(query).filter(([, score]) => score > threshold).slice(0, topN).map(([name, score]) => {
132
+ const item = this.#itemsByName.get(name);
133
+ if (!item) return null;
134
+ return { item, score };
135
+ }).filter((match) => match !== null);
136
+ }
137
+ };
138
+
139
+ // packages/experimental/src/coding-agent-reminders/predicates/combinators.ts
140
+ var always = () => true;
141
+ var and = (...predicates) => async (ctx) => {
142
+ for (const predicate of predicates) {
143
+ if (!await predicate(ctx)) return false;
144
+ }
145
+ return true;
146
+ };
147
+ var or = (...predicates) => async (ctx) => {
148
+ for (const predicate of predicates) {
149
+ if (await predicate(ctx)) return true;
150
+ }
151
+ return false;
152
+ };
153
+ var not = (predicate) => async (ctx) => !await predicate(ctx);
154
+
155
+ // packages/experimental/src/coding-agent-reminders/context.ts
156
+ function contentText(ctx) {
157
+ return [ctx.prompt, ctx.command_name, ctx.command_args].filter((value) => typeof value === "string").join(" ");
158
+ }
159
+ function bashCommand(ctx) {
160
+ if (ctx.tool_name !== "Bash") return "";
161
+ const command = ctx.tool_input?.command;
162
+ return typeof command === "string" ? command : "";
163
+ }
164
+ function outputText(ctx) {
165
+ if (ctx.hook_event_name === "PostToolBatch" && ctx.tool_calls) {
166
+ return ctx.tool_calls.map((call) => textOf(call.tool_response)).filter(Boolean).join("\n");
167
+ }
168
+ const output = ctx.tool_output ?? ctx.tool_response;
169
+ return textOf(output);
170
+ }
171
+ function textOf(value) {
172
+ if (typeof value === "string") return value;
173
+ if (value === void 0) return "";
174
+ try {
175
+ return JSON.stringify(value);
176
+ } catch {
177
+ return String(value);
178
+ }
179
+ }
180
+ function toolCallsOf(ctx) {
181
+ if (ctx.hook_event_name === "PostToolBatch" && ctx.tool_calls) {
182
+ return ctx.tool_calls.map((call) => ({
183
+ name: call.tool_name,
184
+ state: "output-available",
185
+ input: call.tool_input,
186
+ output: call.tool_response
187
+ }));
188
+ }
189
+ const calls = [];
190
+ const toolName = ctx.tool_name;
191
+ if (typeof toolName === "string") {
192
+ calls.push({
193
+ name: toolName,
194
+ state: stateOf(ctx.hook_event_name),
195
+ input: ctx.tool_input,
196
+ output: ctx.tool_output ?? ctx.tool_response,
197
+ errorText: errorTextOf(ctx)
198
+ });
199
+ }
200
+ return calls;
201
+ }
202
+ function matchesName(spec, name) {
203
+ return typeof spec === "function" ? spec(name) : spec === name;
204
+ }
205
+ function stateOf(eventName) {
206
+ if (eventName === "PostToolUseFailure") return "output-error";
207
+ if (eventName === "PostToolUse") return "output-available";
208
+ return "input-available";
209
+ }
210
+ function errorTextOf(ctx) {
211
+ const error = ctx.tool_error ?? ctx.error ?? ctx.reason ?? ctx.tool_output ?? ctx.tool_response;
212
+ return textOf(error);
213
+ }
214
+
215
+ // packages/experimental/src/coding-agent-reminders/predicates/content.ts
216
+ function contentMatches(topics, options) {
217
+ const classifier = new BM25Classifier(
218
+ topics.map((topic, index) => ({
219
+ name: `t${index}`,
220
+ description: topic
221
+ }))
222
+ );
223
+ return (ctx) => classifier.match(contentText(ctx), {
224
+ threshold: options?.threshold
225
+ }).length > 0;
226
+ }
227
+ function classifies(classifier, options) {
228
+ return (ctx) => classifier.match(contentText(ctx), options).length > 0;
229
+ }
230
+ function contentIncludes(keywords) {
231
+ const lower = keywords.map((keyword) => keyword.toLowerCase());
232
+ return (ctx) => {
233
+ const text = contentText(ctx).toLowerCase();
234
+ return lower.some((keyword) => text.includes(keyword));
235
+ };
236
+ }
237
+ var contentPattern = (pattern) => (ctx) => {
238
+ pattern.lastIndex = 0;
239
+ return pattern.test(contentText(ctx));
240
+ };
241
+ var promptMatches = contentPattern;
242
+
243
+ // packages/experimental/src/coding-agent-reminders/predicates/count.ts
244
+ function assertCountSpec(spec) {
245
+ const hasEq = spec.eq !== void 0;
246
+ const hasRange = spec.gte !== void 0 || spec.lte !== void 0;
247
+ if (!hasEq && !hasRange) {
248
+ throw new Error("CountSpec must include at least one of gte/lte/eq");
249
+ }
250
+ if (hasEq && hasRange) {
251
+ throw new Error("CountSpec.eq cannot be combined with gte/lte");
252
+ }
253
+ }
254
+ function checkCount(count, spec) {
255
+ if (spec.eq !== void 0) return count === spec.eq;
256
+ if (spec.gte !== void 0 && count < spec.gte) return false;
257
+ if (spec.lte !== void 0 && count > spec.lte) return false;
258
+ return true;
259
+ }
260
+
261
+ // packages/experimental/src/coding-agent-reminders/predicates/environment.ts
262
+ var envFlag = (name) => () => process.env[name] === "1" || process.env[name] === "true";
263
+
264
+ // packages/experimental/src/coding-agent-reminders/predicates/event.ts
265
+ var eventIs = (...events) => (ctx) => events.includes(ctx.hook_event_name);
266
+
267
+ // packages/experimental/src/coding-agent-reminders/predicates/tool.ts
268
+ var toolIs = (name) => (ctx) => ctx.tool_name === name;
269
+ var bashCommandMatches = (pattern) => (ctx) => {
270
+ pattern.lastIndex = 0;
271
+ return pattern.test(bashCommand(ctx));
272
+ };
273
+ function toolCall(options) {
274
+ return (ctx) => {
275
+ return toolCallsOf(ctx).some((call) => {
276
+ if (options.state && call.state !== options.state) return false;
277
+ if (options.name !== void 0 && !matchesName(options.name, call.name)) {
278
+ return false;
279
+ }
280
+ if (options.input && !options.input(call.input)) return false;
281
+ if (options.output) {
282
+ if (call.state !== "output-available") return false;
283
+ if (!options.output(call.output)) return false;
284
+ }
285
+ if (options.errorText) {
286
+ if (call.state !== "output-error") return false;
287
+ if (!options.errorText(call.errorText ?? "")) return false;
288
+ }
289
+ return true;
290
+ });
291
+ };
292
+ }
293
+ function toolCalled(name) {
294
+ return toolCall({ name });
295
+ }
296
+ function toolFailed(name) {
297
+ return toolCall({ name, state: "output-error" });
298
+ }
299
+ function anyToolCalled() {
300
+ return (ctx) => toolCallsOf(ctx).length > 0;
301
+ }
302
+ function toolCallCount(name, spec) {
303
+ assertCountSpec(spec);
304
+ return (ctx) => checkCount(
305
+ toolCallsOf(ctx).filter((call) => matchesName(name, call.name)).length,
306
+ spec
307
+ );
308
+ }
309
+ var outputMatches = (pattern) => (ctx) => {
310
+ pattern.lastIndex = 0;
311
+ return pattern.test(outputText(ctx));
312
+ };
313
+ var toolOutputMatches = (pattern) => toolCall({
314
+ output: (output) => {
315
+ pattern.lastIndex = 0;
316
+ return pattern.test(textOf(output));
317
+ }
318
+ });
319
+
7
320
  // packages/experimental/src/zukhruf/index.ts
8
321
  var zukhruf_exports = {};
9
322
  __export(zukhruf_exports, {
@@ -331,6 +644,7 @@ function orphanError(output) {
331
644
  return output ? JSON.stringify(output) : "turn orphaned";
332
645
  }
333
646
  export {
647
+ coding_agent_reminders_exports as codingAgentReminders,
334
648
  zukhruf_exports as zukhruf
335
649
  };
336
650
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/zukhruf/index.ts", "../src/zukhruf/agent.ts", "../src/zukhruf/instructions.ts", "../src/zukhruf/tool.ts", "../src/zukhruf/sandbox/define.ts", "../src/zukhruf/runtime.ts", "../src/zukhruf/queue/turn-queue.ts", "../src/zukhruf/queue/pg-boss.turn-queue.ts"],
4
- "sourcesContent": ["export { defineAgent } from './agent.ts';\nexport type { AgentDeclaration, SandboxContext } from './agent.ts';\nexport { defineInstructions } from './instructions.ts';\nexport { defineTool } from './tool.ts';\nexport { defineSandbox } from './sandbox/define.ts';\nexport { createRuntime } from './runtime.ts';\nexport type {\n ConversationId,\n RuntimeOptions,\n TurnInput,\n WorkOptions,\n} from './runtime.ts';\nexport { TurnQueue } from './queue/turn-queue.ts';\nexport type {\n ConsumeContext,\n ConsumeOptions,\n TurnRef,\n} from './queue/turn-queue.ts';\nexport { PgBossTurnQueue } from './queue/pg-boss.turn-queue.ts';\nexport type { PgBossTurnQueueOptions } from './queue/pg-boss.turn-queue.ts';\n", "import type { ToolSet } from 'ai';\n\nimport type {\n AgentModel,\n AgentSandbox,\n ContextFragment,\n} from '@deepagents/context';\n\n/**\n * Sandboxes are per-chat: the factory receives the conversation identity so\n * the backend can be named by `chatId` and re-attached across turns, workers,\n * and restarts (the container engine is the registry \u2014 no in-memory state).\n */\nexport interface SandboxContext {\n chatId: string;\n userId: string;\n}\n\nexport interface AgentDeclaration {\n name: string;\n model: AgentModel;\n sandbox: (context: SandboxContext) => Promise<AgentSandbox>;\n instructions: ContextFragment[];\n tools?: ToolSet;\n}\n\nexport function defineAgent(declaration: {\n model: AgentModel;\n sandbox: (context: SandboxContext) => Promise<AgentSandbox>;\n instructions: ContextFragment[];\n tools?: ToolSet;\n name?: string;\n}): AgentDeclaration {\n return {\n name: declaration.name ?? 'agent',\n model: declaration.model,\n sandbox: declaration.sandbox,\n instructions: declaration.instructions,\n tools: declaration.tools,\n };\n}\n", "import type { ContextFragment } from '@deepagents/context';\n\nexport function defineInstructions(...fragments: ContextFragment[]) {\n return fragments;\n}\n", "/**\n * Declaration-layer tool definition: a pure passthrough of the AI SDK's\n * `tool()` (full generics, zero side effects). Set `needsApproval: true` to\n * pause the turn on this tool's call until `runtime.approve()`/`deny()`.\n */\nexport { tool as defineTool } from 'ai';\n", "import {\n type AgentSandbox,\n type DisposableSandbox,\n createBashTool,\n} from '@deepagents/context';\n\nimport type { SandboxContext } from '../agent.ts';\n\ntype WrapOptions = Omit<Parameters<typeof createBashTool>[0], 'sandbox'>;\n\nexport function defineSandbox(\n createBackend: (context: SandboxContext) => Promise<DisposableSandbox>,\n options?: WrapOptions,\n): (context: SandboxContext) => Promise<AgentSandbox> {\n return async (context) =>\n createBashTool({ sandbox: await createBackend(context), ...options });\n}\n", "import { type UIMessage, isToolUIPart } from 'ai';\n\nimport {\n ContextEngine,\n type ContextStore,\n PollingChangeSource,\n StreamManager,\n type StreamStore,\n agent,\n assistant,\n chat,\n user,\n} from '@deepagents/context';\n\nimport type { AgentDeclaration } from './agent.ts';\nimport type { ConsumeContext, TurnQueue, TurnRef } from './queue/turn-queue.ts';\n\nexport interface RuntimeOptions {\n store: ContextStore;\n streamStore: StreamStore;\n queue: TurnQueue;\n}\n\nexport interface ConversationId {\n chatId: string;\n userId: string;\n}\n\nexport interface WorkOptions {\n concurrency?: number;\n}\n\nexport interface TurnInput {\n /**\n * The ask's identity, supplied by the caller: any unique string (a client's\n * message id, or `crypto.randomUUID()` when the caller has no natural key).\n * It doubles as the stream id and the assistant message id. Enqueueing the\n * same id again reattaches to the existing turn instead of running it\n * twice; the first call's `input` wins.\n */\n id: string;\n input: string;\n}\n\nconst SETTLED_TOOL_STATES = new Set([\n 'output-available',\n 'output-error',\n 'output-denied',\n]);\n\nfunction pendingToolPart(message: UIMessage) {\n return message.parts.find(\n (part) => isToolUIPart(part) && !SETTLED_TOOL_STATES.has(part.state),\n );\n}\n\n/**\n * Executes an AgentDeclaration as a background agent, split into three roles:\n *\n * - `enqueue` \u2014 durably queue a turn (the queue carries the user message\n * until execution); executes nothing. Safe from any short-lived process.\n * - `work` \u2014 start a worker that consumes queued turns; each turn runs\n * start-to-finish in this process, serialized per chat by the TurnQueue.\n * - `observe` \u2014 reconnect/cancel from anywhere; never spins a sandbox.\n *\n * Plus the approval verbs: a turn pauses when the model calls a\n * `needsApproval` tool (the pause is pure data \u2014 a dangling tool part on the\n * chain head + a terminal stream); `approve`/`deny` resolve it and re-run the\n * turn as a continuation. Turns enqueued while a chat awaits approval QUEUE\n * BEHIND it (parked, revived in order after the continuation).\n */\nexport function createRuntime(\n declaration: AgentDeclaration,\n options: RuntimeOptions,\n) {\n const { store, streamStore, queue } = options;\n const manager = new StreamManager({\n store: streamStore,\n changeSource: new PollingChangeSource({ reads: streamStore }),\n });\n\n function engineFor({ chatId, userId }: ConversationId) {\n return new ContextEngine({ store, chatId, userId });\n }\n\n async function executeTurn(\n turn: TurnRef,\n { signal, park }: ConsumeContext,\n ): Promise<void> {\n const status = await streamStore.getStreamStatus(turn.streamId);\n if (status !== 'queued' && status !== 'running') return;\n\n const engine = engineFor(turn).set(...declaration.instructions);\n\n if (turn.kind === 'ask') {\n const head = (await engine.getMessages()).at(-1);\n if (head?.role === 'assistant' && pendingToolPart(head)) {\n await park();\n return;\n }\n engine.set(\n user(turn.input),\n assistant({ id: turn.streamId, role: 'assistant', parts: [] }),\n );\n await engine.save({ branch: true });\n }\n\n const sandbox = await declaration.sandbox({\n chatId: turn.chatId,\n userId: turn.userId,\n });\n const ai = agent({\n name: declaration.name,\n model: declaration.model,\n sandbox,\n context: engine,\n tools: declaration.tools,\n });\n\n const abort = new AbortController();\n const onWorkerAbort = () => abort.abort();\n signal.addEventListener('abort', onWorkerAbort, { once: true });\n try {\n const stream = await chat(ai, { abortSignal: abort.signal });\n await manager.persist(stream, turn.streamId, {\n onCancelDetected: () => abort.abort(),\n });\n } finally {\n signal.removeEventListener('abort', onWorkerAbort);\n }\n }\n\n async function respondToApproval(\n conversation: ConversationId,\n toolCallId: string,\n approval: { approved: true } | { approved: false; reason?: string },\n ) {\n const engine = engineFor(conversation);\n const head = (await engine.getMessages()).at(-1);\n if (head?.role !== 'assistant') {\n throw new Error(\n 'approve: no paused turn \u2014 the chain head is not an assistant message',\n );\n }\n const part = head.parts.find(\n (p) => isToolUIPart(p) && p.toolCallId === toolCallId,\n );\n if (!part || !isToolUIPart(part)) {\n throw new Error(\n `approve: no tool call \"${toolCallId}\" on the paused turn`,\n );\n }\n if (part.state !== 'approval-requested') {\n // Already responded (or settled) \u2014 idempotent reattach.\n return { id: head.id, stream: manager.watch(head.id) };\n }\n\n const responded = {\n ...part,\n state: 'approval-responded',\n approval: { ...part.approval, ...approval },\n };\n const updated: UIMessage = {\n ...head,\n parts: head.parts.map((p) => (p === part ? responded : p)),\n } as UIMessage;\n await engine.continue(assistant(updated));\n\n try {\n await manager.reopen(head.id);\n } catch {\n // Lost the benign race: a concurrent approve already reopened (stream\n // no longer terminal) and pushed the continuation. Reattach.\n return { id: head.id, stream: manager.watch(head.id) };\n }\n await queue.push({\n kind: 'continuation',\n streamId: head.id,\n chatId: conversation.chatId,\n userId: conversation.userId,\n });\n // Revive turns that parked behind the approval; the continuation's\n // priority guarantees it runs before them.\n await queue.resumeParked(conversation.chatId);\n return { id: head.id, stream: manager.watch(head.id) };\n }\n\n return {\n async enqueue({ chatId, userId }: ConversationId, turn: TurnInput) {\n if (!turn.id) {\n throw new Error(\n 'enqueue: turn id is required \u2014 it names the ask, making retries idempotent',\n );\n }\n // register is an upsert (ON CONFLICT DO NOTHING) and the queue is\n // at-least-once, so a retried enqueue may create a duplicate job \u2014 the\n // queue serializes it behind the original and executeTurn's terminal\n // check turns it into a no-op. The stream row, not the queue, is the\n // durable dedup: it never expires with job retention.\n await manager.register(turn.id);\n await queue.push({\n kind: 'ask',\n streamId: turn.id,\n chatId,\n userId,\n input: turn.input,\n });\n return { id: turn.id, stream: manager.watch(turn.id) };\n },\n\n async approve(conversation: ConversationId, input: { toolCallId: string }) {\n return respondToApproval(conversation, input.toolCallId, {\n approved: true,\n });\n },\n\n async deny(\n conversation: ConversationId,\n input: { toolCallId: string; reason?: string },\n ) {\n return respondToApproval(conversation, input.toolCallId, {\n approved: false,\n reason: input.reason,\n });\n },\n\n observe({ chatId, userId }: ConversationId) {\n const engine = engineFor({ chatId, userId });\n\n async function headStreamId(): Promise<string | undefined> {\n const head = await engine.headMessage();\n return head?.name === 'assistant' ? head.id : undefined;\n }\n\n return {\n engine,\n async resume() {\n const id = await headStreamId();\n if (!id) return null;\n const status = await streamStore.getStreamStatus(id);\n return status ? manager.watch(id) : null;\n },\n async cancel(streamId?: string) {\n const id = streamId ?? (await headStreamId());\n if (!id) return;\n const status = await streamStore.getStreamStatus(id);\n if (status === 'queued' || status === 'running') {\n await manager.cancel(id);\n }\n },\n };\n },\n\n async work(options?: WorkOptions): Promise<AsyncDisposable> {\n return queue.consume(executeTurn, {\n concurrency: options?.concurrency,\n onOrphaned: async (turn, error) => {\n const status = await streamStore.getStreamStatus(turn.streamId);\n if (status === 'queued' || status === 'running') {\n await streamStore.updateStreamStatus(turn.streamId, 'failed', {\n error,\n });\n }\n },\n });\n },\n };\n}\n", "export type TurnRef = {\n streamId: string;\n chatId: string;\n userId: string;\n} & (\n | {\n kind: 'ask';\n /**\n * The user message, carried by the queue until the turn executes. It\n * enters the context chain only when the turn RUNS \u2014 enqueue-time\n * persistence would let a queued turn's message leak into the running\n * turn's prompt (and `chat()` streams into the chain head, which must\n * be THIS turn's placeholder).\n */\n input: string;\n }\n | {\n /**\n * Re-execution of an existing (reopened) stream after a tool approval\n * or denial. Carries no payload: the chain was already updated in\n * place by `approve()`/`deny()`.\n */\n kind: 'continuation';\n }\n);\n\nexport interface ConsumeContext {\n signal: AbortSignal;\n /**\n * Park the turn being handled: it settles WITHOUT executing and is not\n * delivered again until `resumeParked(chatId)`. Used by the queue-behind\n * gate \u2014 turns arriving while their chat awaits a tool approval.\n */\n park: () => Promise<void>;\n}\n\nexport interface ConsumeOptions {\n /** Max turns processed concurrently by this consumer (across chats). */\n concurrency?: number;\n /**\n * Fires for a turn whose handler crashed or whose worker died mid-turn.\n * After it resolves, the turn's chat is unblocked and its next queued\n * turn becomes eligible.\n */\n onOrphaned: (turn: TurnRef, error: string) => Promise<void>;\n}\n\n/**\n * Durable holding pen for pending turns.\n *\n * Contract every implementation must honor:\n * - `push` is durable: a pushed turn survives process death until consumed.\n * - Delivery is AT-LEAST-ONCE: a pushed turn is delivered until settled, and\n * duplicate pushes of the same `streamId` may each be delivered. Consumers\n * MUST be idempotent on `streamId` (the zukhruf runtime skips turns whose\n * stream row is terminal \u2014 a check that, unlike queue-side dedup, never\n * expires with job retention).\n * - Per chat, at most ONE handler invocation is active at a time, and turns\n * run in the order they were pushed (strict FIFO per `chatId`) \u2014 this\n * covers duplicates too: they can never run concurrently or out of order.\n * - Turns from different chats may run concurrently.\n * - A handler that throws (or a worker that dies mid-turn) does not retry:\n * the turn surfaces once through `onOrphaned`, then the chat unblocks.\n * - A parked turn (`context.park()`) is not delivered again until\n * `resumeParked(chatId)`; revived turns keep their original FIFO order,\n * and a `'continuation'` turn pushed for the chat outranks them.\n *\n * On platforms with native per-conversation serialization (e.g. Durable\n * Objects) this port is absorbed by the host rather than implemented.\n */\nexport abstract class TurnQueue {\n abstract push(turn: TurnRef): Promise<void>;\n\n abstract consume(\n handler: (turn: TurnRef, context: ConsumeContext) => Promise<void>,\n options: ConsumeOptions,\n ): Promise<AsyncDisposable>;\n\n abstract resumeParked(chatId: string): Promise<void>;\n}\n", "import type { JobWithMetadata, PgBoss } from 'pg-boss';\nimport { v7 as uuidv7 } from 'uuid';\n\nimport {\n type ConsumeContext,\n type ConsumeOptions,\n TurnQueue,\n type TurnRef,\n} from './turn-queue.ts';\n\nexport interface PgBossTurnQueueOptions {\n queue?: string;\n /** Hard cap on one turn attempt; the job fails past this. */\n expireInSeconds?: number;\n /** Dead-worker detection window; must be >= 10 (pg-boss constraint). */\n heartbeatSeconds?: number;\n pollingIntervalSeconds?: number;\n}\n\n/**\n * TurnQueue on pg-boss.\n *\n * - `key_strict_fifo` policy with `singletonKey = chatId` gives the per-chat\n * serialization contract structurally: one active turn per chat, strict\n * push order, cross-chat concurrency.\n * - `retryLimit: 0` \u2014 a crashed turn is never silently re-run (its bash\n * already executed). It dead-letters instead.\n * - A failed job blocks its chat's key until acknowledged; the dead-letter\n * consumer is that acknowledgement: it reports the orphan via\n * `onOrphaned`, then deletes the source job, unblocking the chat.\n * - `deleteAfterSeconds: 0` \u2014 pg-boss never deletes a terminal job on a\n * wall-clock timer. That is what makes a parked (cancelled) turn durable: it\n * awaits its approval for as long as it takes, with no retention deadline.\n * Cleanup is commit-driven instead \u2014 `consume` deletes a job the moment its\n * turn runs and commits to the chain \u2014 so completed jobs don't accumulate.\n * (`retentionSeconds`, which governs still-`created` jobs, can't be 0; its\n * default 14d is never approached because a queued turn only waits behind one\n * running turn.)\n *\n * The `PgBoss` instance is borrowed: the caller `start()`s and `stop()`s it.\n */\nexport class PgBossTurnQueue extends TurnQueue {\n #boss: PgBoss;\n #queue: string;\n #expireInSeconds: number;\n #heartbeatSeconds: number;\n #pollingIntervalSeconds: number;\n\n constructor(boss: PgBoss, options: PgBossTurnQueueOptions = {}) {\n super();\n this.#boss = boss;\n this.#queue = options.queue ?? 'zukhruf-turns';\n this.#expireInSeconds = options.expireInSeconds ?? 3600;\n this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;\n this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;\n }\n\n get queue(): string {\n return this.#queue;\n }\n\n get deadLetterQueue(): string {\n return `${this.#queue}-dead`;\n }\n\n async initialize(): Promise<void> {\n if (!(await this.#boss.getQueue(this.deadLetterQueue))) {\n await this.#boss.createQueue(this.deadLetterQueue);\n }\n if (!(await this.#boss.getQueue(this.#queue))) {\n await this.#boss.createQueue(this.#queue, {\n policy: 'key_strict_fifo',\n retryLimit: 0,\n expireInSeconds: this.#expireInSeconds,\n heartbeatSeconds: this.#heartbeatSeconds,\n deleteAfterSeconds: 0,\n deadLetter: this.deadLetterQueue,\n });\n }\n }\n\n async push(turn: TurnRef): Promise<void> {\n // pg-boss fetches `ORDER BY priority desc, created_on, id`. A monotonic\n // UUIDv7 job id makes the id tiebreak follow push order, so FIFO survives\n // created_on timestamp ties (millisecond-resolution clocks like PGlite).\n // Every push creates a job \u2014 delivery is at-least-once; turn-level dedup\n // lives in the consumer (the runtime skips terminal streams).\n // Continuations outrank waiting turns: revived parked jobs keep their\n // original (older) created_on, so priority is what puts the continuation\n // first.\n await this.#boss.send(this.#queue, turn, {\n id: uuidv7(),\n singletonKey: turn.chatId,\n priority: turn.kind === 'continuation' ? 1 : 0,\n });\n }\n\n async consume(\n handler: (turn: TurnRef, context: ConsumeContext) => Promise<void>,\n options: ConsumeOptions,\n ): Promise<AsyncDisposable> {\n const turnWorkerId = await this.#boss.work<TurnRef>(\n this.#queue,\n {\n localConcurrency: options.concurrency ?? 1,\n pollingIntervalSeconds: this.#pollingIntervalSeconds,\n },\n async ([job]) => {\n let parked = false;\n await handler(job.data, {\n signal: job.signal,\n // Parking = self-cancel: a cancelled job stops blocking the chat's\n // key and is revived (original created_on, so original order) by\n // resumeParked(). The worker's completion of a cancelled job is a\n // clean no-op (probe-verified).\n park: async () => {\n parked = true;\n await this.#boss.cancel(this.#queue, job.id);\n },\n });\n // Commit-driven GC. A handler that returns without parking has run its\n // turn to a terminal stream and committed to the chain (the permanent\n // record) \u2014 the job is spent, so delete it now instead of leaning on a\n // wall-clock timer (`deleteAfterSeconds: 0` disables that). Deleting an\n // active job from inside its own handler is safe: pg-boss's subsequent\n // completion finds no row and no-ops (probe-verified, zero errors). A\n // parked turn is skipped \u2014 it must stay `cancelled` for resumeParked to\n // revive it. A throwing handler is skipped too \u2014 the throw propagates to\n // pg-boss and the turn dead-letters.\n if (!parked) {\n await this.#boss.deleteJob(this.#queue, job.id);\n }\n },\n );\n\n const deadWorkerId = await this.#boss.work(\n this.deadLetterQueue,\n {\n includeMetadata: true,\n pollingIntervalSeconds: this.#pollingIntervalSeconds,\n },\n async ([job]: JobWithMetadata<TurnRef>[]) => {\n await options.onOrphaned(job.data, orphanError(job.output));\n if (job.sourceId) {\n await this.#boss.deleteJob(this.#queue, job.sourceId);\n }\n },\n );\n\n return {\n [Symbol.asyncDispose]: async () => {\n await this.#boss.offWork(this.#queue, { id: turnWorkerId });\n await this.#boss.offWork(this.deadLetterQueue, { id: deadWorkerId });\n },\n };\n }\n\n async resumeParked(chatId: string): Promise<void> {\n // Revives every cancelled job for the chat. A revived USER-cancelled\n // turn is harmless \u2014 the consumer's terminal-stream check skips it \u2014\n // so no parked-vs-cancelled bookkeeping is needed here.\n const jobs = await this.#boss.findJobs(this.#queue, { key: chatId });\n const parked = jobs\n .filter((job) => job.state === 'cancelled')\n .map((job) => job.id);\n if (parked.length > 0) {\n await this.#boss.resume(this.#queue, parked);\n }\n }\n}\n\nfunction orphanError(output: object | null | undefined): string {\n if (output && 'message' in output && typeof output.message === 'string') {\n return output.message;\n }\n return output ? JSON.stringify(output) : 'turn orphaned';\n}\n"],
5
- "mappings": ";;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC0BO,SAAS,YAAY,aAMP;AACnB,SAAO;AAAA,IACL,MAAM,YAAY,QAAQ;AAAA,IAC1B,OAAO,YAAY;AAAA,IACnB,SAAS,YAAY;AAAA,IACrB,cAAc,YAAY;AAAA,IAC1B,OAAO,YAAY;AAAA,EACrB;AACF;;;ACtCO,SAAS,sBAAsB,WAA8B;AAClE,SAAO;AACT;;;ACCA,SAAiB,YAAkB;;;ACLnC;AAA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AAQ,MAAM;AAAA,IAC7C;AAAA,EACF;AACF;AAEA,SAAS,YAAY,QAA2C;AAC9D,MAAI,UAAU,aAAa,UAAU,OAAO,OAAO,YAAY,UAAU;AACvE,WAAO,OAAO;AAAA,EAChB;AACA,SAAO,SAAS,KAAK,UAAU,MAAM,IAAI;AAC3C;",
3
+ "sources": ["../src/coding-agent-reminders/index.ts", "../src/coding-agent-reminders/evaluate.ts", "../src/coding-agent-reminders/io.ts", "../src/coding-agent-reminders/predicates/classifier.ts", "../src/coding-agent-reminders/predicates/combinators.ts", "../src/coding-agent-reminders/context.ts", "../src/coding-agent-reminders/predicates/content.ts", "../src/coding-agent-reminders/predicates/count.ts", "../src/coding-agent-reminders/predicates/environment.ts", "../src/coding-agent-reminders/predicates/event.ts", "../src/coding-agent-reminders/predicates/tool.ts", "../src/zukhruf/index.ts", "../src/zukhruf/agent.ts", "../src/zukhruf/instructions.ts", "../src/zukhruf/tool.ts", "../src/zukhruf/sandbox/define.ts", "../src/zukhruf/runtime.ts", "../src/zukhruf/queue/turn-queue.ts", "../src/zukhruf/queue/pg-boss.turn-queue.ts"],
4
+ "sourcesContent": ["export * from './evaluate.ts';\nexport * from './io.ts';\nexport * from './predicates/index.ts';\nexport * from './types.ts';\n", "import type {\n ClaudeHookInput,\n ClaudeHookOutput,\n GuardRule,\n HookEventName,\n ReminderHookConfig,\n ReminderRule,\n} from './types.ts';\n\nexport async function evaluateReminderHook(\n input: ClaudeHookInput,\n config: ReminderHookConfig,\n): Promise<ClaudeHookOutput | undefined> {\n const guardMatch =\n input.hook_event_name === 'PreToolUse'\n ? await firstMatchingGuard(input, config.guards)\n : undefined;\n if (guardMatch) {\n return {\n hookSpecificOutput: {\n hookEventName: input.hook_event_name,\n permissionDecision: 'deny',\n permissionDecisionReason:\n guardMatch.errorReason ?? resolveGuardReason(guardMatch.rule, input),\n },\n };\n }\n\n if (\n input.stop_hook_active === true &&\n (input.hook_event_name === 'Stop' ||\n input.hook_event_name === 'SubagentStop')\n ) {\n return undefined;\n }\n\n const reminders = await matchingReminders(input, config.reminders);\n if (reminders.length === 0) return undefined;\n\n return {\n hookSpecificOutput: {\n hookEventName: input.hook_event_name,\n additionalContext: reminders.join('\\n\\n'),\n },\n };\n}\n\nasync function firstMatchingGuard(\n input: ClaudeHookInput,\n guards: GuardRule[],\n): Promise<{ rule: GuardRule; errorReason?: string } | undefined> {\n for (const rule of guards) {\n try {\n if (await rule.when(input)) return { rule };\n } catch (error) {\n console.error(`Guard \"${rule.id}\" predicate failed`, error);\n return {\n rule,\n errorReason: `Guard \"${rule.id}\" failed to evaluate; denying by default.`,\n };\n }\n }\n return undefined;\n}\n\nasync function matchingReminders(\n input: ClaudeHookInput,\n reminders: ReminderRule[],\n): Promise<string[]> {\n const matched: string[] = [];\n for (const rule of reminders) {\n if (!rule.events.includes(input.hook_event_name as HookEventName)) continue;\n try {\n if (!(await rule.when(input))) continue;\n matched.push(\n `[${rule.target}:${rule.id}]\\n${resolveText(rule.message, input)}`,\n );\n } catch (error) {\n console.error(`Reminder \"${rule.id}\" evaluation failed`, error);\n }\n }\n return matched;\n}\n\nfunction resolveText(\n value: string | ((ctx: ClaudeHookInput) => string),\n input: ClaudeHookInput,\n): string {\n return typeof value === 'function' ? value(input) : value;\n}\n\nfunction resolveGuardReason(rule: GuardRule, input: ClaudeHookInput): string {\n try {\n return resolveText(rule.deny, input);\n } catch (error) {\n console.error(`Guard \"${rule.id}\" denial message failed`, error);\n return `Guard \"${rule.id}\" matched but its denial message failed; denying by default.`;\n }\n}\n", "import type { ClaudeHookOutput } from './types.ts';\n\nexport async function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n\nexport function writeOutput(output: ClaudeHookOutput): void {\n process.stdout.write(`${JSON.stringify(output)}\\n`);\n}\n", "import { Corpus } from 'tiny-tfidf';\n\nimport type {\n ClassifierMatch,\n ClassifierOptions,\n IClassifier,\n} from '../types.ts';\n\nexport class BM25Classifier<\n T extends { name: string; description: string },\n> implements IClassifier<T> {\n #corpus: Corpus;\n #itemsByName: Map<string, T>;\n\n constructor(items: T[]) {\n const names = items.map((item) => item.name);\n const texts = items.map((item) => `${item.name} ${item.description}`);\n this.#corpus = new Corpus(names, texts);\n this.#itemsByName = new Map(items.map((item) => [item.name, item]));\n }\n\n match(query: string, options?: ClassifierOptions): ClassifierMatch<T>[] {\n const topN = options?.topN ?? 5;\n const threshold = options?.threshold ?? 0;\n\n return this.#corpus\n .getResultsForQuery(query)\n .filter(([, score]: [string, number]) => score > threshold)\n .slice(0, topN)\n .map(([name, score]: [string, number]) => {\n const item = this.#itemsByName.get(name);\n if (!item) return null;\n return { item, score };\n })\n .filter((match): match is ClassifierMatch<T> => match !== null);\n }\n}\n", "import type { AsyncHookPredicate, HookPredicate } from '../types.ts';\n\nexport const always: HookPredicate = () => true;\n\nexport const and =\n (...predicates: HookPredicate[]): AsyncHookPredicate =>\n async (ctx) => {\n for (const predicate of predicates) {\n if (!(await predicate(ctx))) return false;\n }\n return true;\n };\n\nexport const or =\n (...predicates: HookPredicate[]): AsyncHookPredicate =>\n async (ctx) => {\n for (const predicate of predicates) {\n if (await predicate(ctx)) return true;\n }\n return false;\n };\n\nexport const not =\n (predicate: HookPredicate): AsyncHookPredicate =>\n async (ctx) =>\n !(await predicate(ctx));\n", "import type { ClaudeHookInput, ToolCallState, ToolNameSpec } from './types.ts';\n\nexport type NormalizedToolCall = {\n name: string;\n state: ToolCallState;\n input?: unknown;\n output?: unknown;\n errorText?: string;\n};\n\nexport function contentText(ctx: ClaudeHookInput): string {\n return [ctx.prompt, ctx.command_name, ctx.command_args]\n .filter((value): value is string => typeof value === 'string')\n .join(' ');\n}\n\nexport function bashCommand(ctx: ClaudeHookInput): string {\n if (ctx.tool_name !== 'Bash') return '';\n const command = ctx.tool_input?.command;\n return typeof command === 'string' ? command : '';\n}\n\nexport function outputText(ctx: ClaudeHookInput): string {\n if (ctx.hook_event_name === 'PostToolBatch' && ctx.tool_calls) {\n return ctx.tool_calls\n .map((call) => textOf(call.tool_response))\n .filter(Boolean)\n .join('\\n');\n }\n const output = ctx.tool_output ?? ctx.tool_response;\n return textOf(output);\n}\n\nexport function textOf(value: unknown): string {\n if (typeof value === 'string') return value;\n if (value === undefined) return '';\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nexport function toolCallsOf(ctx: ClaudeHookInput): NormalizedToolCall[] {\n if (ctx.hook_event_name === 'PostToolBatch' && ctx.tool_calls) {\n return ctx.tool_calls.map((call) => ({\n name: call.tool_name,\n state: 'output-available',\n input: call.tool_input,\n output: call.tool_response,\n }));\n }\n\n const calls: NormalizedToolCall[] = [];\n const toolName = ctx.tool_name;\n if (typeof toolName === 'string') {\n calls.push({\n name: toolName,\n state: stateOf(ctx.hook_event_name),\n input: ctx.tool_input,\n output: ctx.tool_output ?? ctx.tool_response,\n errorText: errorTextOf(ctx),\n });\n }\n return calls;\n}\n\nexport function matchesName(spec: ToolNameSpec, name: string): boolean {\n return typeof spec === 'function' ? spec(name) : spec === name;\n}\n\nfunction stateOf(eventName: string): ToolCallState {\n if (eventName === 'PostToolUseFailure') return 'output-error';\n if (eventName === 'PostToolUse') return 'output-available';\n return 'input-available';\n}\n\nfunction errorTextOf(ctx: ClaudeHookInput): string {\n const error =\n ctx.tool_error ??\n ctx.error ??\n ctx.reason ??\n ctx.tool_output ??\n ctx.tool_response;\n return textOf(error);\n}\n", "import { contentText } from '../context.ts';\nimport type {\n ClassifierOptions,\n ContentMatchesOptions,\n HookPredicate,\n IClassifier,\n} from '../types.ts';\nimport { BM25Classifier } from './classifier.ts';\n\nexport function contentMatches(\n topics: string[],\n options?: ContentMatchesOptions,\n): HookPredicate {\n const classifier = new BM25Classifier(\n topics.map((topic, index) => ({\n name: `t${index}`,\n description: topic,\n })),\n );\n return (ctx) =>\n classifier.match(contentText(ctx), {\n threshold: options?.threshold,\n }).length > 0;\n}\n\nexport function classifies<T>(\n classifier: IClassifier<T>,\n options?: ClassifierOptions,\n): HookPredicate {\n return (ctx) => classifier.match(contentText(ctx), options).length > 0;\n}\n\nexport function contentIncludes(keywords: string[]): HookPredicate {\n const lower = keywords.map((keyword) => keyword.toLowerCase());\n return (ctx) => {\n const text = contentText(ctx).toLowerCase();\n return lower.some((keyword) => text.includes(keyword));\n };\n}\n\nexport const contentPattern =\n (pattern: RegExp): HookPredicate =>\n (ctx) => {\n pattern.lastIndex = 0;\n return pattern.test(contentText(ctx));\n };\n\nexport const promptMatches = contentPattern;\n", "import type { CountSpec } from '../types.ts';\n\nexport function assertCountSpec(spec: CountSpec): void {\n const hasEq = spec.eq !== undefined;\n const hasRange = spec.gte !== undefined || spec.lte !== undefined;\n if (!hasEq && !hasRange) {\n throw new Error('CountSpec must include at least one of gte/lte/eq');\n }\n if (hasEq && hasRange) {\n throw new Error('CountSpec.eq cannot be combined with gte/lte');\n }\n}\n\nexport function checkCount(count: number, spec: CountSpec): boolean {\n if (spec.eq !== undefined) return count === spec.eq;\n if (spec.gte !== undefined && count < spec.gte) return false;\n if (spec.lte !== undefined && count > spec.lte) return false;\n return true;\n}\n", "import type { HookPredicate } from '../types.ts';\n\nexport const envFlag =\n (name: string): HookPredicate =>\n () =>\n process.env[name] === '1' || process.env[name] === 'true';\n", "import type { HookEventName, HookPredicate } from '../types.ts';\n\nexport const eventIs =\n (...events: HookEventName[]): HookPredicate =>\n (ctx) =>\n events.includes(ctx.hook_event_name as HookEventName);\n", "import {\n bashCommand,\n matchesName,\n outputText,\n textOf,\n toolCallsOf,\n} from '../context.ts';\nimport type {\n CountSpec,\n HookPredicate,\n ToolCallOptions,\n ToolNameSpec,\n} from '../types.ts';\nimport { assertCountSpec, checkCount } from './count.ts';\n\nexport const toolIs =\n (name: string): HookPredicate =>\n (ctx) =>\n ctx.tool_name === name;\n\nexport const bashCommandMatches =\n (pattern: RegExp): HookPredicate =>\n (ctx) => {\n pattern.lastIndex = 0;\n return pattern.test(bashCommand(ctx));\n };\n\nexport function toolCall(options: ToolCallOptions): HookPredicate {\n return (ctx) => {\n return toolCallsOf(ctx).some((call) => {\n if (options.state && call.state !== options.state) return false;\n if (options.name !== undefined && !matchesName(options.name, call.name)) {\n return false;\n }\n if (options.input && !options.input(call.input)) return false;\n if (options.output) {\n if (call.state !== 'output-available') return false;\n if (!options.output(call.output)) return false;\n }\n if (options.errorText) {\n if (call.state !== 'output-error') return false;\n if (!options.errorText(call.errorText ?? '')) return false;\n }\n return true;\n });\n };\n}\n\nexport function toolCalled(name: ToolNameSpec): HookPredicate {\n return toolCall({ name });\n}\n\nexport function toolFailed(name: ToolNameSpec): HookPredicate {\n return toolCall({ name, state: 'output-error' });\n}\n\nexport function anyToolCalled(): HookPredicate {\n return (ctx) => toolCallsOf(ctx).length > 0;\n}\n\nexport function toolCallCount(\n name: ToolNameSpec,\n spec: CountSpec,\n): HookPredicate {\n assertCountSpec(spec);\n return (ctx) =>\n checkCount(\n toolCallsOf(ctx).filter((call) => matchesName(name, call.name)).length,\n spec,\n );\n}\n\nexport const outputMatches =\n (pattern: RegExp): HookPredicate =>\n (ctx) => {\n pattern.lastIndex = 0;\n return pattern.test(outputText(ctx));\n };\n\nexport const toolOutputMatches = (pattern: RegExp): HookPredicate =>\n toolCall({\n output: (output) => {\n pattern.lastIndex = 0;\n return pattern.test(textOf(output));\n },\n });\n", "export { defineAgent } from './agent.ts';\nexport type { AgentDeclaration, SandboxContext } from './agent.ts';\nexport { defineInstructions } from './instructions.ts';\nexport { defineTool } from './tool.ts';\nexport { defineSandbox } from './sandbox/define.ts';\nexport { createRuntime } from './runtime.ts';\nexport type {\n ConversationId,\n RuntimeOptions,\n TurnInput,\n WorkOptions,\n} from './runtime.ts';\nexport { TurnQueue } from './queue/turn-queue.ts';\nexport type {\n ConsumeContext,\n ConsumeOptions,\n TurnRef,\n} from './queue/turn-queue.ts';\nexport { PgBossTurnQueue } from './queue/pg-boss.turn-queue.ts';\nexport type { PgBossTurnQueueOptions } from './queue/pg-boss.turn-queue.ts';\n", "import type { ToolSet } from 'ai';\n\nimport type {\n AgentModel,\n AgentSandbox,\n ContextFragment,\n} from '@deepagents/context';\n\n/**\n * Sandboxes are per-chat: the factory receives the conversation identity so\n * the backend can be named by `chatId` and re-attached across turns, workers,\n * and restarts (the container engine is the registry \u2014 no in-memory state).\n */\nexport interface SandboxContext {\n chatId: string;\n userId: string;\n}\n\nexport interface AgentDeclaration {\n name: string;\n model: AgentModel;\n sandbox: (context: SandboxContext) => Promise<AgentSandbox>;\n instructions: ContextFragment[];\n tools?: ToolSet;\n}\n\nexport function defineAgent(declaration: {\n model: AgentModel;\n sandbox: (context: SandboxContext) => Promise<AgentSandbox>;\n instructions: ContextFragment[];\n tools?: ToolSet;\n name?: string;\n}): AgentDeclaration {\n return {\n name: declaration.name ?? 'agent',\n model: declaration.model,\n sandbox: declaration.sandbox,\n instructions: declaration.instructions,\n tools: declaration.tools,\n };\n}\n", "import type { ContextFragment } from '@deepagents/context';\n\nexport function defineInstructions(...fragments: ContextFragment[]) {\n return fragments;\n}\n", "/**\n * Declaration-layer tool definition: a pure passthrough of the AI SDK's\n * `tool()` (full generics, zero side effects). Set `needsApproval: true` to\n * pause the turn on this tool's call until `runtime.approve()`/`deny()`.\n */\nexport { tool as defineTool } from 'ai';\n", "import {\n type AgentSandbox,\n type DisposableSandbox,\n createBashTool,\n} from '@deepagents/context';\n\nimport type { SandboxContext } from '../agent.ts';\n\ntype WrapOptions = Omit<Parameters<typeof createBashTool>[0], 'sandbox'>;\n\nexport function defineSandbox(\n createBackend: (context: SandboxContext) => Promise<DisposableSandbox>,\n options?: WrapOptions,\n): (context: SandboxContext) => Promise<AgentSandbox> {\n return async (context) =>\n createBashTool({ sandbox: await createBackend(context), ...options });\n}\n", "import { type UIMessage, isToolUIPart } from 'ai';\n\nimport {\n ContextEngine,\n type ContextStore,\n PollingChangeSource,\n StreamManager,\n type StreamStore,\n agent,\n assistant,\n chat,\n user,\n} from '@deepagents/context';\n\nimport type { AgentDeclaration } from './agent.ts';\nimport type { ConsumeContext, TurnQueue, TurnRef } from './queue/turn-queue.ts';\n\nexport interface RuntimeOptions {\n store: ContextStore;\n streamStore: StreamStore;\n queue: TurnQueue;\n}\n\nexport interface ConversationId {\n chatId: string;\n userId: string;\n}\n\nexport interface WorkOptions {\n concurrency?: number;\n}\n\nexport interface TurnInput {\n /**\n * The ask's identity, supplied by the caller: any unique string (a client's\n * message id, or `crypto.randomUUID()` when the caller has no natural key).\n * It doubles as the stream id and the assistant message id. Enqueueing the\n * same id again reattaches to the existing turn instead of running it\n * twice; the first call's `input` wins.\n */\n id: string;\n input: string;\n}\n\nconst SETTLED_TOOL_STATES = new Set([\n 'output-available',\n 'output-error',\n 'output-denied',\n]);\n\nfunction pendingToolPart(message: UIMessage) {\n return message.parts.find(\n (part) => isToolUIPart(part) && !SETTLED_TOOL_STATES.has(part.state),\n );\n}\n\n/**\n * Executes an AgentDeclaration as a background agent, split into three roles:\n *\n * - `enqueue` \u2014 durably queue a turn (the queue carries the user message\n * until execution); executes nothing. Safe from any short-lived process.\n * - `work` \u2014 start a worker that consumes queued turns; each turn runs\n * start-to-finish in this process, serialized per chat by the TurnQueue.\n * - `observe` \u2014 reconnect/cancel from anywhere; never spins a sandbox.\n *\n * Plus the approval verbs: a turn pauses when the model calls a\n * `needsApproval` tool (the pause is pure data \u2014 a dangling tool part on the\n * chain head + a terminal stream); `approve`/`deny` resolve it and re-run the\n * turn as a continuation. Turns enqueued while a chat awaits approval QUEUE\n * BEHIND it (parked, revived in order after the continuation).\n */\nexport function createRuntime(\n declaration: AgentDeclaration,\n options: RuntimeOptions,\n) {\n const { store, streamStore, queue } = options;\n const manager = new StreamManager({\n store: streamStore,\n changeSource: new PollingChangeSource({ reads: streamStore }),\n });\n\n function engineFor({ chatId, userId }: ConversationId) {\n return new ContextEngine({ store, chatId, userId });\n }\n\n async function executeTurn(\n turn: TurnRef,\n { signal, park }: ConsumeContext,\n ): Promise<void> {\n const status = await streamStore.getStreamStatus(turn.streamId);\n if (status !== 'queued' && status !== 'running') return;\n\n const engine = engineFor(turn).set(...declaration.instructions);\n\n if (turn.kind === 'ask') {\n const head = (await engine.getMessages()).at(-1);\n if (head?.role === 'assistant' && pendingToolPart(head)) {\n await park();\n return;\n }\n engine.set(\n user(turn.input),\n assistant({ id: turn.streamId, role: 'assistant', parts: [] }),\n );\n await engine.save({ branch: true });\n }\n\n const sandbox = await declaration.sandbox({\n chatId: turn.chatId,\n userId: turn.userId,\n });\n const ai = agent({\n name: declaration.name,\n model: declaration.model,\n sandbox,\n context: engine,\n tools: declaration.tools,\n });\n\n const abort = new AbortController();\n const onWorkerAbort = () => abort.abort();\n signal.addEventListener('abort', onWorkerAbort, { once: true });\n try {\n const stream = await chat(ai, { abortSignal: abort.signal });\n await manager.persist(stream, turn.streamId, {\n onCancelDetected: () => abort.abort(),\n });\n } finally {\n signal.removeEventListener('abort', onWorkerAbort);\n }\n }\n\n async function respondToApproval(\n conversation: ConversationId,\n toolCallId: string,\n approval: { approved: true } | { approved: false; reason?: string },\n ) {\n const engine = engineFor(conversation);\n const head = (await engine.getMessages()).at(-1);\n if (head?.role !== 'assistant') {\n throw new Error(\n 'approve: no paused turn \u2014 the chain head is not an assistant message',\n );\n }\n const part = head.parts.find(\n (p) => isToolUIPart(p) && p.toolCallId === toolCallId,\n );\n if (!part || !isToolUIPart(part)) {\n throw new Error(\n `approve: no tool call \"${toolCallId}\" on the paused turn`,\n );\n }\n if (part.state !== 'approval-requested') {\n // Already responded (or settled) \u2014 idempotent reattach.\n return { id: head.id, stream: manager.watch(head.id) };\n }\n\n const responded = {\n ...part,\n state: 'approval-responded',\n approval: { ...part.approval, ...approval },\n };\n const updated: UIMessage = {\n ...head,\n parts: head.parts.map((p) => (p === part ? responded : p)),\n } as UIMessage;\n await engine.continue(assistant(updated));\n\n try {\n await manager.reopen(head.id);\n } catch {\n // Lost the benign race: a concurrent approve already reopened (stream\n // no longer terminal) and pushed the continuation. Reattach.\n return { id: head.id, stream: manager.watch(head.id) };\n }\n await queue.push({\n kind: 'continuation',\n streamId: head.id,\n chatId: conversation.chatId,\n userId: conversation.userId,\n });\n // Revive turns that parked behind the approval; the continuation's\n // priority guarantees it runs before them.\n await queue.resumeParked(conversation.chatId);\n return { id: head.id, stream: manager.watch(head.id) };\n }\n\n return {\n async enqueue({ chatId, userId }: ConversationId, turn: TurnInput) {\n if (!turn.id) {\n throw new Error(\n 'enqueue: turn id is required \u2014 it names the ask, making retries idempotent',\n );\n }\n // register is an upsert (ON CONFLICT DO NOTHING) and the queue is\n // at-least-once, so a retried enqueue may create a duplicate job \u2014 the\n // queue serializes it behind the original and executeTurn's terminal\n // check turns it into a no-op. The stream row, not the queue, is the\n // durable dedup: it never expires with job retention.\n await manager.register(turn.id);\n await queue.push({\n kind: 'ask',\n streamId: turn.id,\n chatId,\n userId,\n input: turn.input,\n });\n return { id: turn.id, stream: manager.watch(turn.id) };\n },\n\n async approve(conversation: ConversationId, input: { toolCallId: string }) {\n return respondToApproval(conversation, input.toolCallId, {\n approved: true,\n });\n },\n\n async deny(\n conversation: ConversationId,\n input: { toolCallId: string; reason?: string },\n ) {\n return respondToApproval(conversation, input.toolCallId, {\n approved: false,\n reason: input.reason,\n });\n },\n\n observe({ chatId, userId }: ConversationId) {\n const engine = engineFor({ chatId, userId });\n\n async function headStreamId(): Promise<string | undefined> {\n const head = await engine.headMessage();\n return head?.name === 'assistant' ? head.id : undefined;\n }\n\n return {\n engine,\n async resume() {\n const id = await headStreamId();\n if (!id) return null;\n const status = await streamStore.getStreamStatus(id);\n return status ? manager.watch(id) : null;\n },\n async cancel(streamId?: string) {\n const id = streamId ?? (await headStreamId());\n if (!id) return;\n const status = await streamStore.getStreamStatus(id);\n if (status === 'queued' || status === 'running') {\n await manager.cancel(id);\n }\n },\n };\n },\n\n async work(options?: WorkOptions): Promise<AsyncDisposable> {\n return queue.consume(executeTurn, {\n concurrency: options?.concurrency,\n onOrphaned: async (turn, error) => {\n const status = await streamStore.getStreamStatus(turn.streamId);\n if (status === 'queued' || status === 'running') {\n await streamStore.updateStreamStatus(turn.streamId, 'failed', {\n error,\n });\n }\n },\n });\n },\n };\n}\n", "export type TurnRef = {\n streamId: string;\n chatId: string;\n userId: string;\n} & (\n | {\n kind: 'ask';\n /**\n * The user message, carried by the queue until the turn executes. It\n * enters the context chain only when the turn RUNS \u2014 enqueue-time\n * persistence would let a queued turn's message leak into the running\n * turn's prompt (and `chat()` streams into the chain head, which must\n * be THIS turn's placeholder).\n */\n input: string;\n }\n | {\n /**\n * Re-execution of an existing (reopened) stream after a tool approval\n * or denial. Carries no payload: the chain was already updated in\n * place by `approve()`/`deny()`.\n */\n kind: 'continuation';\n }\n);\n\nexport interface ConsumeContext {\n signal: AbortSignal;\n /**\n * Park the turn being handled: it settles WITHOUT executing and is not\n * delivered again until `resumeParked(chatId)`. Used by the queue-behind\n * gate \u2014 turns arriving while their chat awaits a tool approval.\n */\n park: () => Promise<void>;\n}\n\nexport interface ConsumeOptions {\n /** Max turns processed concurrently by this consumer (across chats). */\n concurrency?: number;\n /**\n * Fires for a turn whose handler crashed or whose worker died mid-turn.\n * After it resolves, the turn's chat is unblocked and its next queued\n * turn becomes eligible.\n */\n onOrphaned: (turn: TurnRef, error: string) => Promise<void>;\n}\n\n/**\n * Durable holding pen for pending turns.\n *\n * Contract every implementation must honor:\n * - `push` is durable: a pushed turn survives process death until consumed.\n * - Delivery is AT-LEAST-ONCE: a pushed turn is delivered until settled, and\n * duplicate pushes of the same `streamId` may each be delivered. Consumers\n * MUST be idempotent on `streamId` (the zukhruf runtime skips turns whose\n * stream row is terminal \u2014 a check that, unlike queue-side dedup, never\n * expires with job retention).\n * - Per chat, at most ONE handler invocation is active at a time, and turns\n * run in the order they were pushed (strict FIFO per `chatId`) \u2014 this\n * covers duplicates too: they can never run concurrently or out of order.\n * - Turns from different chats may run concurrently.\n * - A handler that throws (or a worker that dies mid-turn) does not retry:\n * the turn surfaces once through `onOrphaned`, then the chat unblocks.\n * - A parked turn (`context.park()`) is not delivered again until\n * `resumeParked(chatId)`; revived turns keep their original FIFO order,\n * and a `'continuation'` turn pushed for the chat outranks them.\n *\n * On platforms with native per-conversation serialization (e.g. Durable\n * Objects) this port is absorbed by the host rather than implemented.\n */\nexport abstract class TurnQueue {\n abstract push(turn: TurnRef): Promise<void>;\n\n abstract consume(\n handler: (turn: TurnRef, context: ConsumeContext) => Promise<void>,\n options: ConsumeOptions,\n ): Promise<AsyncDisposable>;\n\n abstract resumeParked(chatId: string): Promise<void>;\n}\n", "import type { JobWithMetadata, PgBoss } from 'pg-boss';\nimport { v7 as uuidv7 } from 'uuid';\n\nimport {\n type ConsumeContext,\n type ConsumeOptions,\n TurnQueue,\n type TurnRef,\n} from './turn-queue.ts';\n\nexport interface PgBossTurnQueueOptions {\n queue?: string;\n /** Hard cap on one turn attempt; the job fails past this. */\n expireInSeconds?: number;\n /** Dead-worker detection window; must be >= 10 (pg-boss constraint). */\n heartbeatSeconds?: number;\n pollingIntervalSeconds?: number;\n}\n\n/**\n * TurnQueue on pg-boss.\n *\n * - `key_strict_fifo` policy with `singletonKey = chatId` gives the per-chat\n * serialization contract structurally: one active turn per chat, strict\n * push order, cross-chat concurrency.\n * - `retryLimit: 0` \u2014 a crashed turn is never silently re-run (its bash\n * already executed). It dead-letters instead.\n * - A failed job blocks its chat's key until acknowledged; the dead-letter\n * consumer is that acknowledgement: it reports the orphan via\n * `onOrphaned`, then deletes the source job, unblocking the chat.\n * - `deleteAfterSeconds: 0` \u2014 pg-boss never deletes a terminal job on a\n * wall-clock timer. That is what makes a parked (cancelled) turn durable: it\n * awaits its approval for as long as it takes, with no retention deadline.\n * Cleanup is commit-driven instead \u2014 `consume` deletes a job the moment its\n * turn runs and commits to the chain \u2014 so completed jobs don't accumulate.\n * (`retentionSeconds`, which governs still-`created` jobs, can't be 0; its\n * default 14d is never approached because a queued turn only waits behind one\n * running turn.)\n *\n * The `PgBoss` instance is borrowed: the caller `start()`s and `stop()`s it.\n */\nexport class PgBossTurnQueue extends TurnQueue {\n #boss: PgBoss;\n #queue: string;\n #expireInSeconds: number;\n #heartbeatSeconds: number;\n #pollingIntervalSeconds: number;\n\n constructor(boss: PgBoss, options: PgBossTurnQueueOptions = {}) {\n super();\n this.#boss = boss;\n this.#queue = options.queue ?? 'zukhruf-turns';\n this.#expireInSeconds = options.expireInSeconds ?? 3600;\n this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;\n this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;\n }\n\n get queue(): string {\n return this.#queue;\n }\n\n get deadLetterQueue(): string {\n return `${this.#queue}-dead`;\n }\n\n async initialize(): Promise<void> {\n if (!(await this.#boss.getQueue(this.deadLetterQueue))) {\n await this.#boss.createQueue(this.deadLetterQueue);\n }\n if (!(await this.#boss.getQueue(this.#queue))) {\n await this.#boss.createQueue(this.#queue, {\n policy: 'key_strict_fifo',\n retryLimit: 0,\n expireInSeconds: this.#expireInSeconds,\n heartbeatSeconds: this.#heartbeatSeconds,\n deleteAfterSeconds: 0,\n deadLetter: this.deadLetterQueue,\n });\n }\n }\n\n async push(turn: TurnRef): Promise<void> {\n // pg-boss fetches `ORDER BY priority desc, created_on, id`. A monotonic\n // UUIDv7 job id makes the id tiebreak follow push order, so FIFO survives\n // created_on timestamp ties (millisecond-resolution clocks like PGlite).\n // Every push creates a job \u2014 delivery is at-least-once; turn-level dedup\n // lives in the consumer (the runtime skips terminal streams).\n // Continuations outrank waiting turns: revived parked jobs keep their\n // original (older) created_on, so priority is what puts the continuation\n // first.\n await this.#boss.send(this.#queue, turn, {\n id: uuidv7(),\n singletonKey: turn.chatId,\n priority: turn.kind === 'continuation' ? 1 : 0,\n });\n }\n\n async consume(\n handler: (turn: TurnRef, context: ConsumeContext) => Promise<void>,\n options: ConsumeOptions,\n ): Promise<AsyncDisposable> {\n const turnWorkerId = await this.#boss.work<TurnRef>(\n this.#queue,\n {\n localConcurrency: options.concurrency ?? 1,\n pollingIntervalSeconds: this.#pollingIntervalSeconds,\n },\n async ([job]) => {\n let parked = false;\n await handler(job.data, {\n signal: job.signal,\n // Parking = self-cancel: a cancelled job stops blocking the chat's\n // key and is revived (original created_on, so original order) by\n // resumeParked(). The worker's completion of a cancelled job is a\n // clean no-op (probe-verified).\n park: async () => {\n parked = true;\n await this.#boss.cancel(this.#queue, job.id);\n },\n });\n // Commit-driven GC. A handler that returns without parking has run its\n // turn to a terminal stream and committed to the chain (the permanent\n // record) \u2014 the job is spent, so delete it now instead of leaning on a\n // wall-clock timer (`deleteAfterSeconds: 0` disables that). Deleting an\n // active job from inside its own handler is safe: pg-boss's subsequent\n // completion finds no row and no-ops (probe-verified, zero errors). A\n // parked turn is skipped \u2014 it must stay `cancelled` for resumeParked to\n // revive it. A throwing handler is skipped too \u2014 the throw propagates to\n // pg-boss and the turn dead-letters.\n if (!parked) {\n await this.#boss.deleteJob(this.#queue, job.id);\n }\n },\n );\n\n const deadWorkerId = await this.#boss.work(\n this.deadLetterQueue,\n {\n includeMetadata: true,\n pollingIntervalSeconds: this.#pollingIntervalSeconds,\n },\n async ([job]: JobWithMetadata<TurnRef>[]) => {\n await options.onOrphaned(job.data, orphanError(job.output));\n if (job.sourceId) {\n await this.#boss.deleteJob(this.#queue, job.sourceId);\n }\n },\n );\n\n return {\n [Symbol.asyncDispose]: async () => {\n await this.#boss.offWork(this.#queue, { id: turnWorkerId });\n await this.#boss.offWork(this.deadLetterQueue, { id: deadWorkerId });\n },\n };\n }\n\n async resumeParked(chatId: string): Promise<void> {\n // Revives every cancelled job for the chat. A revived USER-cancelled\n // turn is harmless \u2014 the consumer's terminal-stream check skips it \u2014\n // so no parked-vs-cancelled bookkeeping is needed here.\n const jobs = await this.#boss.findJobs(this.#queue, { key: chatId });\n const parked = jobs\n .filter((job) => job.state === 'cancelled')\n .map((job) => job.id);\n if (parked.length > 0) {\n await this.#boss.resume(this.#queue, parked);\n }\n }\n}\n\nfunction orphanError(output: object | null | undefined): string {\n if (output && 'message' in output && typeof output.message === 'string') {\n return output.message;\n }\n return output ? JSON.stringify(output) : 'turn orphaned';\n}\n"],
5
+ "mappings": ";;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSA,eAAsB,qBACpB,OACA,QACuC;AACvC,QAAM,aACJ,MAAM,oBAAoB,eACtB,MAAM,mBAAmB,OAAO,OAAO,MAAM,IAC7C;AACN,MAAI,YAAY;AACd,WAAO;AAAA,MACL,oBAAoB;AAAA,QAClB,eAAe,MAAM;AAAA,QACrB,oBAAoB;AAAA,QACpB,0BACE,WAAW,eAAe,mBAAmB,WAAW,MAAM,KAAK;AAAA,MACvE;AAAA,IACF;AAAA,EACF;AAEA,MACE,MAAM,qBAAqB,SAC1B,MAAM,oBAAoB,UACzB,MAAM,oBAAoB,iBAC5B;AACA,WAAO;AAAA,EACT;AAEA,QAAM,YAAY,MAAM,kBAAkB,OAAO,OAAO,SAAS;AACjE,MAAI,UAAU,WAAW,EAAG,QAAO;AAEnC,SAAO;AAAA,IACL,oBAAoB;AAAA,MAClB,eAAe,MAAM;AAAA,MACrB,mBAAmB,UAAU,KAAK,MAAM;AAAA,IAC1C;AAAA,EACF;AACF;AAEA,eAAe,mBACb,OACA,QACgE;AAChE,aAAW,QAAQ,QAAQ;AACzB,QAAI;AACF,UAAI,MAAM,KAAK,KAAK,KAAK,EAAG,QAAO,EAAE,KAAK;AAAA,IAC5C,SAAS,OAAO;AACd,cAAQ,MAAM,UAAU,KAAK,EAAE,sBAAsB,KAAK;AAC1D,aAAO;AAAA,QACL;AAAA,QACA,aAAa,UAAU,KAAK,EAAE;AAAA,MAChC;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,eAAe,kBACb,OACA,WACmB;AACnB,QAAM,UA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,wBAAwB,KAAK;AAAA,MAC/B;AAAA,MACA,OAAO,CAAC,GAAG,MAAkC;AAC3C,cAAM,QAAQ,WAAW,IAAI,MAAM,YAAY,IAAI,MAAM,CAAC;AAC1D,YAAI,IAAI,UAAU;AAChB,gBAAM,KAAK,MAAM,UAAU,KAAK,QAAQ,IAAI,QAAQ;AAAA,QACtD;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,MACL,CAAC,OAAO,YAAY,GAAG,YAAY;AACjC,cAAM,KAAK,MAAM,QAAQ,KAAK,QAAQ,EAAE,IAAI,aAAa,CAAC;AAC1D,cAAM,KAAK,MAAM,QAAQ,KAAK,iBAAiB,EAAE,IAAI,aAAa,CAAC;AAAA,MACrE;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,aAAa,QAA+B;AAIhD,UAAM,OAAO,MAAM,KAAK,MAAM,SAAS,KAAK,QAAQ,EAAE,KAAK,OAAO,CAAC;AACnE,UAAM,SAAS,KACZ,OAAO,CAAC,QAAQ,IAAI,UAAU,WAAW,EACzC,IAAI,CAAC,QAAQ,IAAI,EAAE;AACtB,QAAI,OAAO,SAAS,GAAG;AACrB,YAAM,KAAK,MAAM,OAAO,KAAK,QAAQ,MAAM;AAAA,IAC7C;AAAA,EACF;AACF;AAEA,SAAS,YAAY,QAA2C;AAC9D,MAAI,UAAU,aAAa,UAAU,OAAO,OAAO,YAAY,UAAU;AACvE,WAAO,OAAO;AAAA,EAChB;AACA,SAAO,SAAS,KAAK,UAAU,MAAM,IAAI;AAC3C;",
6
6
  "names": ["options"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepagents/experimental",
3
- "version": "4.2.0",
3
+ "version": "4.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -22,6 +22,11 @@
22
22
  "import": "./dist/index.js",
23
23
  "default": "./dist/index.js"
24
24
  },
25
+ "./coding-agent-reminders": {
26
+ "types": "./dist/coding-agent-reminders/index.d.ts",
27
+ "import": "./dist/coding-agent-reminders/index.js",
28
+ "default": "./dist/coding-agent-reminders/index.js"
29
+ },
25
30
  "./zukhruf": {
26
31
  "types": "./dist/zukhruf/index.d.ts",
27
32
  "import": "./dist/zukhruf/index.js",
@@ -37,14 +42,15 @@
37
42
  "access": "public"
38
43
  },
39
44
  "dependencies": {
40
- "@deepagents/context": "4.2.0",
45
+ "@deepagents/context": "4.3.0",
41
46
  "ai": "^6.0.218",
47
+ "just-bash": "^3.0.1",
42
48
  "pg-boss": "^12.24.1",
49
+ "tiny-tfidf": "^1.0.0",
43
50
  "uuid": "^13.0.2"
44
51
  },
45
52
  "devDependencies": {
46
53
  "@ai-sdk/provider": "^3.0.13",
47
- "@deepagents/test": "0.15.0",
48
54
  "@electric-sql/pglite": "^0.5.3",
49
55
  "just-bash": "^3.0.1",
50
56
  "zod": "^3.25.76 || ^4.0.0"