@capybara-hq/kernel 0.1.0-rc.48 → 0.1.0-rc.49

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 (104) hide show
  1. package/dist/admin/admin.module.js +2 -0
  2. package/dist/admin/admin.schemas.d.ts +4 -0
  3. package/dist/admin/health.service.d.ts +2 -2
  4. package/dist/admin/health.service.js +8 -4
  5. package/dist/agents/agents.schemas.js +1 -1
  6. package/dist/agents/instruction-files.js +0 -3
  7. package/dist/background/launch.d.ts +4 -0
  8. package/dist/background/launch.js +6 -2
  9. package/dist/catalog/marketplaces.service.d.ts +1 -1
  10. package/dist/conversations/delivery-scope.d.ts +34 -0
  11. package/dist/conversations/delivery-scope.js +23 -0
  12. package/dist/conversations/event-log.d.ts +18 -0
  13. package/dist/conversations/event-log.js +54 -0
  14. package/dist/conversations/events.d.ts +2 -0
  15. package/dist/conversations/events.js +15 -2
  16. package/dist/conversations/prompt-suggestion-request.d.ts +95 -0
  17. package/dist/conversations/prompt-suggestion-request.js +213 -0
  18. package/dist/conversations/prompt-suggestion-store.d.ts +51 -0
  19. package/dist/conversations/prompt-suggestion-store.js +136 -0
  20. package/dist/conversations/prompt-suggestions.d.ts +153 -0
  21. package/dist/conversations/prompt-suggestions.js +563 -0
  22. package/dist/conversations/titles.js +11 -5
  23. package/dist/evals/reconstruct.d.ts +26 -1
  24. package/dist/evals/reconstruct.js +25 -6
  25. package/dist/identity/settings.d.ts +13 -0
  26. package/dist/identity/settings.js +37 -2
  27. package/dist/infra/queue/queue-names.d.ts +1 -1
  28. package/dist/infra/queue/queue-names.js +1 -0
  29. package/dist/kernel.module.js +4 -1
  30. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  31. package/dist/lifecycle/kernel-lifecycle.js +13 -7
  32. package/dist/models/image-usable.d.ts +30 -6
  33. package/dist/models/image-usable.js +38 -7
  34. package/dist/models/images.js +6 -4
  35. package/dist/models/purposes.d.ts +1 -1
  36. package/dist/models/purposes.js +10 -4
  37. package/dist/orgs/settings.service.d.ts +16 -0
  38. package/dist/orgs/settings.service.js +46 -5
  39. package/dist/overrides.d.ts +4 -0
  40. package/dist/overrides.js +2 -0
  41. package/dist/platform/availability.d.ts +5 -0
  42. package/dist/platform/availability.js +7 -3
  43. package/dist/platform/ops/accounts.ops.d.ts +1 -1
  44. package/dist/platform/ops/accounts.ops.js +1 -1
  45. package/dist/platform/ops/admin.ops.js +3 -2
  46. package/dist/platform/ops/agent-skills.ops.js +5 -5
  47. package/dist/platform/ops/agents.ops.js +3 -3
  48. package/dist/platform/ops/approvals.ops.d.ts +1 -1
  49. package/dist/platform/ops/approvals.ops.js +2 -2
  50. package/dist/platform/ops/background.ops.js +1 -1
  51. package/dist/platform/ops/catalog-admin.ops.js +3 -3
  52. package/dist/platform/ops/conversations.ops.js +2 -2
  53. package/dist/platform/ops/devices.ops.js +2 -2
  54. package/dist/platform/ops/extensions-admin.ops.js +2 -2
  55. package/dist/platform/ops/extensions.ops.js +3 -3
  56. package/dist/platform/ops/inbox.ops.js +4 -4
  57. package/dist/platform/ops/org-plugins.ops.js +4 -4
  58. package/dist/platform/ops/org-settings.ops.js +2 -2
  59. package/dist/platform/ops/orgs.ops.js +1 -0
  60. package/dist/platform/ops/plugins.ops.d.ts +1 -1
  61. package/dist/platform/ops/plugins.ops.js +3 -3
  62. package/dist/platform/ops/requests.ops.js +1 -1
  63. package/dist/platform/ops/schedules.ops.js +6 -6
  64. package/dist/roles/worker-role.d.ts +6 -3
  65. package/dist/roles/worker-role.js +21 -13
  66. package/dist/roles/worker.module.js +2 -0
  67. package/dist/runtime/compaction-settings.service.d.ts +8 -0
  68. package/dist/runtime/compaction-settings.service.js +12 -6
  69. package/dist/runtime/run-processors.d.ts +14 -6
  70. package/dist/runtime/run-processors.js +43 -8
  71. package/dist/runtime/run-worker.d.ts +5 -0
  72. package/dist/runtime/run-worker.js +24 -16
  73. package/dist/runtime/runtime.module.d.ts +1 -1
  74. package/dist/runtime/runtime.module.js +7 -1
  75. package/dist/runtime/stream.d.ts +7 -1
  76. package/dist/runtime/stream.js +54 -3
  77. package/dist/runtime/usage-report.d.ts +2 -1
  78. package/dist/runtime/usage-report.js +2 -1
  79. package/dist/sandbox/sandbox-file-reader.js +1 -1
  80. package/dist/tools/builtins/agent.js +5 -5
  81. package/dist/tools/builtins/artifacts.d.ts +33 -7
  82. package/dist/tools/builtins/artifacts.js +92 -14
  83. package/dist/tools/builtins/image/generate.d.ts +4 -1
  84. package/dist/tools/builtins/image/generate.js +70 -14
  85. package/dist/tools/builtins/platform.d.ts +0 -2
  86. package/dist/tools/builtins/platform.js +3 -5
  87. package/dist/tools/builtins/sandbox/bash.js +15 -11
  88. package/dist/tools/builtins/sandbox/common.d.ts +3 -2
  89. package/dist/tools/builtins/sandbox/deliver.js +13 -7
  90. package/dist/tools/builtins/sandbox/glob.js +1 -1
  91. package/dist/tools/builtins/sandbox/grep.js +1 -1
  92. package/dist/tools/builtins/sandbox/read.js +3 -3
  93. package/dist/tools/builtins/sandbox/task-output.d.ts +1 -1
  94. package/dist/tools/builtins/sandbox/task-output.js +13 -11
  95. package/dist/tools/builtins/send-message.d.ts +1 -1
  96. package/dist/tools/builtins/send-message.js +3 -3
  97. package/dist/tools/builtins/skill-load.d.ts +1 -1
  98. package/dist/tools/builtins/tool-search.js +1 -1
  99. package/dist/tools/builtins/web/extract.js +1 -1
  100. package/dist/tools/builtins/web/search.js +2 -4
  101. package/dist/tools/connector-account-policies.js +1 -1
  102. package/dist/tools/registry.d.ts +6 -0
  103. package/dist/tools/registry.js +1 -1
  104. package/package.json +2 -2
@@ -0,0 +1,213 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { ApiError } from "../errors.js";
3
+ import { reconstructFromInputs, reconstructInputs } from "../evals/reconstruct.js";
4
+ import { toEvents } from "../evals/snapshot.js";
5
+ import { estimateTokens } from "../runtime/context/tokens.js";
6
+ import { assembleModelRequest } from "../runtime/model-call.js";
7
+ import { HIDDEN_FORMAT_RE } from "../text.js";
8
+ /**
9
+ * Prompt suggestions (spec 2026-11-19 §1, §2): the pure part of the side request sent after a
10
+ * completed web run. The request is the run's last request rebuilt through the eval zero-drift
11
+ * path, plus the final reply and {@link PROMPT_SUGGESTION_INSTRUCTION}; only the output cap and
12
+ * `purpose` change besides, so the provider's prompt cache serves the prefix.
13
+ */
14
+ /** The appended instruction (model-facing, English; spec §1.3). */
15
+ export const PROMPT_SUGGESTION_INSTRUCTION = "The user has not replied yet. Write the message the user is most likely to send next in this " +
16
+ "conversation, as the user would type it, in the language the user writes in. Keep it short " +
17
+ "(at most 12 words, or about 25 CJK characters) and specific to what just happened: a natural " +
18
+ "follow-up request, a choice between options you offered, or a go-ahead to continue. Do not " +
19
+ "answer it, do not call tools and do not explain. Reply with the message text only, or with " +
20
+ "exactly NONE when no next message is clear.";
21
+ /** The side request's output cap ceiling (a cost ceiling, not a target; spec §1.4). */
22
+ export const PROMPT_SUGGESTION_MAX_OUTPUT_TOKENS = 2048;
23
+ /** Above this many input tokens with no cache activity on the last step, skip (spec §1.5). */
24
+ export const PROMPT_SUGGESTION_UNCACHED_INPUT_MAX = 8000;
25
+ /** A job that starts later than this after the run finished is stale (spec §1.5). */
26
+ export const PROMPT_SUGGESTION_MAX_DELAY_MS = 60_000;
27
+ /** The side call's time limit (spec §1.6). */
28
+ export const PROMPT_SUGGESTION_TIMEOUT_MS = 60_000;
29
+ /** The longest suggestion kept, in characters (code points; spec §1.7). */
30
+ export const PROMPT_SUGGESTION_MAX_CHARS = 200;
31
+ /** The run's last `model_call` (the highest seq with the run's id), or undefined. */
32
+ export function lastModelCallOf(events, runId) {
33
+ let last;
34
+ for (const e of events) {
35
+ if (e.type === "model_call" && e.runId === runId && (last === undefined || e.seq > last.seq)) {
36
+ last = e;
37
+ }
38
+ }
39
+ return last;
40
+ }
41
+ function lastOfRun(events, runId, pick) {
42
+ let last;
43
+ for (const e of events) {
44
+ if (e.runId === runId && pick(e) && (last === undefined || e.seq > last.seq))
45
+ last = e;
46
+ }
47
+ return last;
48
+ }
49
+ /**
50
+ * The side request, or why there is none (spec §1). `model` is the current info of the last
51
+ * call's provider and model as the caller resolved it for the org; `mediaInfo` / `media` come from
52
+ * `loadSnapshotMedia` for that call; `reserveTokens` is the org's compaction reserve.
53
+ *
54
+ * Checks, in order: the run has a `model_call` (`no_model_call`); `model` is that call's model
55
+ * (`model_mismatch`); the call carries no fit plan (`fit`); a final `assistant_message` follows
56
+ * the call (`no_final_reply`) without a `tool_call` block (`final_reply_has_tool_call`) and with
57
+ * text (`no_final_reply`); the run's last step usage shows cache activity or at most
58
+ * {@link PROMPT_SUGGESTION_UNCACHED_INPUT_MAX} input tokens (`uncached`); the baseline
59
+ * reconstruction of the call has no drift and the snapshot is valid (`drift`); the extension, the
60
+ * same inputs with every snapshot event up to the run's terminal event, keeps `model`, `system`,
61
+ * `tools`, `toolChoice`, `params` and the messages as a prefix, followed by exactly one assistant
62
+ * message, so only usage and the terminal event follow the final reply (`prefix_mismatch`); the
63
+ * estimate plus the cap fits `contextWindow - reserveTokens` (`too_large`). Never throws for a
64
+ * snapshot's content.
65
+ */
66
+ export function buildSuggestionRequest(input) {
67
+ const { snapshot, model } = input;
68
+ const runId = snapshot.runId;
69
+ const events = toEvents(snapshot);
70
+ const call = lastModelCallOf(events, runId);
71
+ if (call === undefined)
72
+ return { skip: "no_model_call" };
73
+ if (model.id !== call.payload.model)
74
+ return { skip: "model_mismatch" };
75
+ if (call.payload.request.fit !== undefined)
76
+ return { skip: "fit" };
77
+ const final = lastOfRun(events, runId, (e) => e.type === "assistant_message");
78
+ if (final === undefined || final.seq < call.seq)
79
+ return { skip: "no_final_reply" };
80
+ if (final.payload.content.some((b) => b.type === "tool_call")) {
81
+ return { skip: "final_reply_has_tool_call" };
82
+ }
83
+ const finalText = final.payload.content
84
+ .flatMap((b) => (b.type === "text" ? [b.text] : []))
85
+ .join("\n")
86
+ .trim();
87
+ if (finalText === "")
88
+ return { skip: "no_final_reply" };
89
+ const usage = lastOfRun(events, runId, (e) => e.type === "usage" && e.payload.purpose === undefined);
90
+ if (usage !== undefined &&
91
+ usage.payload.cacheReadTokens + usage.payload.cacheWriteTokens === 0 &&
92
+ usage.payload.inputTokens > PROMPT_SUGGESTION_UNCACHED_INPUT_MAX) {
93
+ return { skip: "uncached" };
94
+ }
95
+ const opts = {
96
+ model,
97
+ ...(input.mediaInfo !== undefined && { mediaInfo: input.mediaInfo }),
98
+ ...(input.media !== undefined && { media: input.media }),
99
+ };
100
+ let reference;
101
+ let extended;
102
+ try {
103
+ const gathered = reconstructInputs(snapshot, call.seq, opts);
104
+ const ref = reconstructFromInputs(snapshot, gathered, opts);
105
+ if (ref.drift.length > 0)
106
+ return { skip: "drift" };
107
+ reference = ref.request;
108
+ // every event of the snapshot (it ends at the run's terminal event): absorbable events past
109
+ // the recorded absorbedUpToSeq stay out, anything else model-visible after the final reply
110
+ // breaks the check below
111
+ extended = assembleModelRequest({ ...gathered.input, events });
112
+ }
113
+ catch (err) {
114
+ // a corrupt recorded permission context (`eval.snapshot_invalid`)
115
+ if (err instanceof ApiError)
116
+ return { skip: "drift" };
117
+ throw err;
118
+ }
119
+ const { request, mediaTokens } = extended;
120
+ const n = reference.messages.length;
121
+ if (request.model !== reference.model ||
122
+ !isDeepStrictEqual(request.system, reference.system) ||
123
+ !isDeepStrictEqual(request.tools, reference.tools) ||
124
+ !isDeepStrictEqual(request.toolChoice, reference.toolChoice) ||
125
+ !isDeepStrictEqual(request.params, reference.params) ||
126
+ request.messages.length !== n + 1 ||
127
+ request.messages[n]?.role !== "assistant" ||
128
+ !isDeepStrictEqual(request.messages.slice(0, n), reference.messages)) {
129
+ return { skip: "prefix_mismatch" };
130
+ }
131
+ request.messages.push({
132
+ role: "user",
133
+ content: [{ type: "text", text: PROMPT_SUGGESTION_INSTRUCTION }],
134
+ });
135
+ request.maxOutputTokens = Math.min(reference.maxOutputTokens, PROMPT_SUGGESTION_MAX_OUTPUT_TOKENS);
136
+ request.purpose = "suggestion";
137
+ const estimate = estimateTokens(request.messages, request.system, request.tools, mediaTokens);
138
+ if (estimate + request.maxOutputTokens > model.contextWindow - input.reserveTokens) {
139
+ return { skip: "too_large" };
140
+ }
141
+ return {
142
+ request,
143
+ lastCall: { seq: call.seq, provider: call.payload.provider, model: call.payload.model },
144
+ finalText,
145
+ estimate,
146
+ };
147
+ }
148
+ /**
149
+ * Whether a finished run may get a suggestion by its outcome, conversation and trigger (spec §2):
150
+ * `completed` or `max_steps`, a `chat` conversation from `web`, not a scheduled or compact run.
151
+ * The final reply, freshness and the switches are checked elsewhere.
152
+ */
153
+ export function suggestionEligible(i) {
154
+ return ((i.outcome === "completed" || i.outcome === "max_steps") &&
155
+ i.kind === "chat" &&
156
+ i.source === "web" &&
157
+ i.trigger !== "schedule" &&
158
+ i.trigger !== "compact");
159
+ }
160
+ // C0 and C1 controls (newlines are split on first; a tab becomes a space)
161
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it removes
162
+ const CONTROL_RE = /[\u0000-\u0008\u000a-\u001f\u007f-\u009f]/g;
163
+ const LINE_RE = /\r\n|[\n\r\u0085\u2028\u2029]/;
164
+ const LABEL_RE = /^(?:user|用户)\s*[::]\s*/i;
165
+ const QUOTES = [
166
+ ['"', '"'],
167
+ ["'", "'"],
168
+ ["`", "`"],
169
+ ["“", "”"],
170
+ ["‘", "’"],
171
+ ["「", "」"],
172
+ ["『", "』"],
173
+ ["«", "»"],
174
+ ];
175
+ const NONE_RE = /^none[.!。!]?$/i;
176
+ function unquote(s) {
177
+ let out = s;
178
+ for (;;) {
179
+ const pair = QUOTES.find(([open, close]) => out.length >= 2 && out.startsWith(open) && out.endsWith(close));
180
+ if (pair === undefined)
181
+ return out;
182
+ const inner = out.slice(pair[0].length, out.length - pair[1].length);
183
+ // only one balanced pair wraps the text: `"a" and "b"` is two quotations, kept as is
184
+ if (inner.includes(pair[0]) || inner.includes(pair[1]))
185
+ return out;
186
+ out = inner.trim();
187
+ }
188
+ }
189
+ /**
190
+ * The suggestion from the model's reply text (spec §1.7), or null for none: the first non-empty
191
+ * line with control and hidden format characters removed, a leading user label (`User:`, or the
192
+ * Chinese word for user with a full-width colon, `LABEL_RE`) and balanced wrapping quotes
193
+ * stripped, trimmed, cut to {@link PROMPT_SUGGESTION_MAX_CHARS} code points.
194
+ * `NONE` (any case), an empty result or an echo of the final reply (`finalText`) is null.
195
+ */
196
+ export function cleanSuggestion(reply, finalText) {
197
+ const line = reply
198
+ .split(LINE_RE)
199
+ .map((l) => l.replace(/\t/g, " ").replace(CONTROL_RE, "").replace(HIDDEN_FORMAT_RE, "").trim())
200
+ .find((l) => l !== "") ?? "";
201
+ let text = unquote(line.replace(LABEL_RE, "").trim());
202
+ text = unquote(text.replace(LABEL_RE, "").trim());
203
+ text = Array.from(text).slice(0, PROMPT_SUGGESTION_MAX_CHARS).join("").trim();
204
+ if (text === "" || NONE_RE.test(text))
205
+ return null;
206
+ if (text === finalText.trim())
207
+ return null;
208
+ return text;
209
+ }
210
+ /** Whether the job is too late (`now - finishedAt > PROMPT_SUGGESTION_MAX_DELAY_MS`). */
211
+ export function suggestionStale(finishedAt, now) {
212
+ return now - finishedAt > PROMPT_SUGGESTION_MAX_DELAY_MS;
213
+ }
@@ -0,0 +1,51 @@
1
+ import type { ExtensionContext } from "@capybara-hq/plugin-sdk";
2
+ import type { Redis } from "ioredis";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ /**
5
+ * Prompt suggestions (spec 2026-11-19 §4): the conversation's latest suggestion is a Redis key
6
+ * with a TTL plus a bus message on the conversation's topic, never an event in the log. One key
7
+ * per conversation (a newer suggestion replaces an older one); the TTL is the backstop, and the
8
+ * readers apply the freshness rule ({@link PromptSuggestionStore.isFresh}) instead of deleting the
9
+ * key on every message. The key is the only shared state: any replica reads it.
10
+ */
11
+ /** How long a suggestion key lives (24 h). */
12
+ export declare const PROMPT_SUGGESTION_TTL_SECONDS = 86400;
13
+ /** The conversation's suggestion key. */
14
+ export declare const promptSuggestionKey: (conversationId: string) => string;
15
+ /** The bus message kind the SSE forwards as `event: suggestion`. */
16
+ export declare const PROMPT_SUGGESTION_BUS_KIND = "prompt_suggestion";
17
+ /** A stored suggestion: the run it follows, that run's `run_finished` seq, the text, when. */
18
+ export interface StoredSuggestion {
19
+ runId: string;
20
+ /** The seq of the run's `run_finished`: a `user_message` / `run_started` after it is newer. */
21
+ afterSeq: number;
22
+ text: string;
23
+ /** Epoch milliseconds. */
24
+ createdAt: number;
25
+ }
26
+ /** The conversation's prompt suggestion key and its freshness rule (spec §4). */
27
+ export declare class PromptSuggestionStore {
28
+ private readonly redis;
29
+ private readonly bus;
30
+ private readonly kdb;
31
+ constructor(redis: Pick<Redis, "set" | "get" | "eval">, bus: Pick<ExtensionContext["bus"], "publish">, kdb: KernelDb);
32
+ /**
33
+ * Writes the key (`SET … EX` {@link PROMPT_SUGGESTION_TTL_SECONDS}), then publishes
34
+ * `{ kind: "prompt_suggestion", conversationId, runId, afterSeq, text }` on the conversation's
35
+ * topic. Throws when Redis or the bus fails (the caller logs).
36
+ */
37
+ put(conversationId: string, s: StoredSuggestion): Promise<void>;
38
+ /** The stored suggestion, or null (none, expired or unreadable). Not checked for freshness. */
39
+ get(conversationId: string): Promise<StoredSuggestion | null>;
40
+ /**
41
+ * Deletes the key only while it still holds `s` (a reader found `s` stale): a newer suggestion
42
+ * written since the read is kept (compare and delete in one script).
43
+ */
44
+ delete(conversationId: string, s: StoredSuggestion): Promise<void>;
45
+ /**
46
+ * The freshness rule (spec §4), read from PG with plain queries (no lock): `runId` is the
47
+ * conversation's latest run and it is terminal, the log has no `user_message` and no
48
+ * `run_started` with a seq above `afterSeq`, and the conversation's message queue is empty.
49
+ */
50
+ isFresh(conversationId: string, s: Pick<StoredSuggestion, "runId" | "afterSeq">): Promise<boolean>;
51
+ }
@@ -0,0 +1,136 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { KERNEL_BUS, REDIS } from "../infra/tokens.js";
14
+ import { conversationTopic } from "./event-log.js";
15
+ /**
16
+ * Prompt suggestions (spec 2026-11-19 §4): the conversation's latest suggestion is a Redis key
17
+ * with a TTL plus a bus message on the conversation's topic, never an event in the log. One key
18
+ * per conversation (a newer suggestion replaces an older one); the TTL is the backstop, and the
19
+ * readers apply the freshness rule ({@link PromptSuggestionStore.isFresh}) instead of deleting the
20
+ * key on every message. The key is the only shared state: any replica reads it.
21
+ */
22
+ /** How long a suggestion key lives (24 h). */
23
+ export const PROMPT_SUGGESTION_TTL_SECONDS = 86_400;
24
+ /** The conversation's suggestion key. */
25
+ export const promptSuggestionKey = (conversationId) => `capk:prompt-suggestion:${conversationId}`;
26
+ /** The bus message kind the SSE forwards as `event: suggestion`. */
27
+ export const PROMPT_SUGGESTION_BUS_KIND = "prompt_suggestion";
28
+ const parse = (raw) => {
29
+ if (raw === null)
30
+ return null;
31
+ let v;
32
+ try {
33
+ v = JSON.parse(raw);
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ if (typeof v !== "object" || v === null)
39
+ return null;
40
+ const s = v;
41
+ if (typeof s.runId !== "string" ||
42
+ typeof s.afterSeq !== "number" ||
43
+ typeof s.text !== "string" ||
44
+ typeof s.createdAt !== "number") {
45
+ return null;
46
+ }
47
+ return { runId: s.runId, afterSeq: s.afterSeq, text: s.text, createdAt: s.createdAt };
48
+ };
49
+ /** The stored form of a suggestion (`put` writes it; `delete` compares against it). */
50
+ const serialize = (s) => JSON.stringify({ runId: s.runId, afterSeq: s.afterSeq, text: s.text, createdAt: s.createdAt });
51
+ const DELETE_IF_UNCHANGED = `if redis.call("GET", KEYS[1]) == ARGV[1] then
52
+ return redis.call("DEL", KEYS[1])
53
+ end
54
+ return 0`;
55
+ /** The conversation's prompt suggestion key and its freshness rule (spec §4). */
56
+ let PromptSuggestionStore = class PromptSuggestionStore {
57
+ redis;
58
+ bus;
59
+ kdb;
60
+ constructor(redis, bus, kdb) {
61
+ this.redis = redis;
62
+ this.bus = bus;
63
+ this.kdb = kdb;
64
+ }
65
+ /**
66
+ * Writes the key (`SET … EX` {@link PROMPT_SUGGESTION_TTL_SECONDS}), then publishes
67
+ * `{ kind: "prompt_suggestion", conversationId, runId, afterSeq, text }` on the conversation's
68
+ * topic. Throws when Redis or the bus fails (the caller logs).
69
+ */
70
+ async put(conversationId, s) {
71
+ await this.redis.set(promptSuggestionKey(conversationId), serialize(s), "EX", PROMPT_SUGGESTION_TTL_SECONDS);
72
+ const msg = {
73
+ kind: PROMPT_SUGGESTION_BUS_KIND,
74
+ conversationId,
75
+ runId: s.runId,
76
+ afterSeq: s.afterSeq,
77
+ text: s.text,
78
+ };
79
+ await this.bus.publish(conversationTopic(conversationId), msg);
80
+ }
81
+ /** The stored suggestion, or null (none, expired or unreadable). Not checked for freshness. */
82
+ async get(conversationId) {
83
+ return parse(await this.redis.get(promptSuggestionKey(conversationId)));
84
+ }
85
+ /**
86
+ * Deletes the key only while it still holds `s` (a reader found `s` stale): a newer suggestion
87
+ * written since the read is kept (compare and delete in one script).
88
+ */
89
+ async delete(conversationId, s) {
90
+ await this.redis.eval(DELETE_IF_UNCHANGED, 1, promptSuggestionKey(conversationId), serialize(s));
91
+ }
92
+ /**
93
+ * The freshness rule (spec §4), read from PG with plain queries (no lock): `runId` is the
94
+ * conversation's latest run and it is terminal, the log has no `user_message` and no
95
+ * `run_started` with a seq above `afterSeq`, and the conversation's message queue is empty.
96
+ */
97
+ async isFresh(conversationId, s) {
98
+ const db = this.kdb.db;
99
+ const latest = await db
100
+ .selectFrom("runs")
101
+ .select(["id", "status"])
102
+ .where("conversation_id", "=", conversationId)
103
+ .orderBy("created_at", "desc")
104
+ .orderBy("id", "desc")
105
+ .limit(1)
106
+ .executeTakeFirst();
107
+ if (latest?.id !== s.runId)
108
+ return false;
109
+ if (latest.status !== "completed")
110
+ return false;
111
+ const newer = await db
112
+ .selectFrom("conversation_events")
113
+ .select(sql `1`.as("one"))
114
+ .where("conversation_id", "=", conversationId)
115
+ .where("seq", ">", String(s.afterSeq))
116
+ .where("type", "in", ["user_message", "run_started"])
117
+ .limit(1)
118
+ .executeTakeFirst();
119
+ if (newer !== undefined)
120
+ return false;
121
+ const queued = await db
122
+ .selectFrom("conversation_queue")
123
+ .select(sql `1`.as("one"))
124
+ .where("conversation_id", "=", conversationId)
125
+ .limit(1)
126
+ .executeTakeFirst();
127
+ return queued === undefined;
128
+ }
129
+ };
130
+ PromptSuggestionStore = __decorate([
131
+ Injectable(),
132
+ __param(0, Inject(REDIS)),
133
+ __param(1, Inject(KERNEL_BUS)),
134
+ __param(2, Inject(KernelDb))
135
+ ], PromptSuggestionStore);
136
+ export { PromptSuggestionStore };
@@ -0,0 +1,153 @@
1
+ import { type ModelUsage } from "@capybara-hq/plugin-sdk";
2
+ import type { Job, Queue, Worker } from "bullmq";
3
+ import { SettingsService } from "../identity/settings.js";
4
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
+ import { KernelDb } from "../infra/database/kernel-db.js";
6
+ import { TransactionHost } from "../infra/database/transaction-host.js";
7
+ import type { KernelLogger } from "../log.js";
8
+ import { OrgSettingsService } from "../orgs/settings.service.js";
9
+ import { type AuditEntry, type HookRunner } from "../runtime/hook-calls.js";
10
+ import { ProviderRegistry } from "../runtime/providers.js";
11
+ import { UsageReportJobs } from "../runtime/usage-report-jobs.js";
12
+ import { AttachmentsService } from "./attachments.service.js";
13
+ import { EventLog } from "./event-log.js";
14
+ import type { ConversationEvent, EventPayload } from "./events.js";
15
+ import { PromptSuggestionStore } from "./prompt-suggestion-store.js";
16
+ /**
17
+ * Prompt suggestions (spec 2026-11-19 §2, §3, §7, §8): after a completed web run the run worker
18
+ * calls {@link PromptSuggestionQueue.maybeEnqueue} (a hint after the commit: a lost enqueue costs
19
+ * one suggestion, so no outbox row). The worker-role job ({@link PromptSuggestionGenerator.run})
20
+ * re-checks the run, rebuilds its last request through the eval zero-drift path, fires
21
+ * `model.request` (policy fail closed, then observe) with `purpose: "suggestion"`, calls the run's
22
+ * own model once (no retry, no fallback), fires `model.response`, logs a run-less `usage` event
23
+ * owing its `usage.report`, and stores the cleaned text ({@link PromptSuggestionStore}) while the
24
+ * run is still the conversation's newest exchange. No lock, no transaction around the call, no
25
+ * process state beyond the stop signal. Nothing model-visible: no `model_call`, no DriftReason.
26
+ */
27
+ /** The suggestion queue (no `:` in the name). */
28
+ export declare const PROMPT_SUGGESTION_QUEUE = "cap-kernel-suggestions";
29
+ /** One job per run (no `:`: run ids are UUIDs); a second enqueue of the same run is a no-op. */
30
+ export declare const promptSuggestionJobId: (runId: string) => string;
31
+ /** Worker concurrency per replica (the calls are short and mostly cached). */
32
+ export declare const PROMPT_SUGGESTION_CONCURRENCY = 4;
33
+ /**
34
+ * Test seam (`KernelSeams`): the side call's time limit in ms, asked at every call; default
35
+ * {@link PROMPT_SUGGESTION_TIMEOUT_MS}.
36
+ */
37
+ export declare const PROMPT_SUGGESTION_TIMEOUT: unique symbol;
38
+ /** The job's data. `finishedAt`: when the run finished (epoch ms), for the staleness guard. */
39
+ export interface PromptSuggestionJob {
40
+ conversationId: string;
41
+ runId: string;
42
+ finishedAt: number;
43
+ }
44
+ type RunOutcome = EventPayload<"run_finished">["reason"];
45
+ /**
46
+ * One suggestion job's work over the injected services, with its writes in transactions of their
47
+ * own: the call's usage event (owing its delivery) and a policy denial's audit row.
48
+ */
49
+ export declare class PromptSuggestionGenerator {
50
+ private readonly kdb;
51
+ private readonly eventLog;
52
+ private readonly registry;
53
+ /** The call fires the plugin hooks (`model.request`, `model.response`). */
54
+ private readonly host;
55
+ /** The call's `usage.report` delivery, owed with its usage event. */
56
+ private readonly usage;
57
+ private readonly orgSettings;
58
+ /** The platform's compaction settings (the org's reserve for the fit guard). */
59
+ private readonly settings;
60
+ /** The run's media, as the run's steps load it. */
61
+ private readonly attachments;
62
+ private readonly store;
63
+ private readonly config;
64
+ private readonly log;
65
+ readonly txHost: TransactionHost;
66
+ private readonly timeoutMs;
67
+ constructor(kdb: KernelDb, eventLog: Pick<EventLog, "appendInReport" | "notify">, registry: Pick<ProviderRegistry, "resolve">,
68
+ /** The call fires the plugin hooks (`model.request`, `model.response`). */
69
+ host: {
70
+ readonly hooks?: HookRunner;
71
+ } | undefined,
72
+ /** The call's `usage.report` delivery, owed with its usage event. */
73
+ usage: Pick<UsageReportJobs, "oweEvents">, orgSettings: Pick<OrgSettingsService, "promptSuggestionsEnabled">,
74
+ /** The platform's compaction settings (the org's reserve for the fit guard). */
75
+ settings: Pick<SettingsService, "get">,
76
+ /** The run's media, as the run's steps load it. */
77
+ attachments: Pick<AttachmentsService, "mediaInfo" | "fetchMedia">, store: Pick<PromptSuggestionStore, "isFresh" | "put">, config: KernelConfigService, log: Pick<KernelLogger, "debug" | "warn">, txHost: TransactionHost, timeoutMs?: () => number);
78
+ private get db();
79
+ /**
80
+ * One suggestion for the run (spec §1–§4); `shutdown` aborts the call (the worker stopping).
81
+ * Never throws: every skip and failure is logged and means no suggestion.
82
+ */
83
+ run(conversationId: string, runId: string, finishedAt: number, shutdown: AbortSignal): Promise<void>;
84
+ /**
85
+ * The run's facts by spec §2 (outcome, conversation kind and source, trigger) and its hook scope,
86
+ * or why it gets no suggestion.
87
+ */
88
+ private runFacts;
89
+ /**
90
+ * `model.request` (`purpose: "suggestion"`, the run's id, step 0, attempt 1): policy hooks first,
91
+ * failing closed (a policy extension not loaded on this replica denies), then observe. A denial
92
+ * writes the `hook.denied` audit row (`detail.purpose: "suggestion"`) and no `hook_denied`
93
+ * event (the call is not a step of the run).
94
+ */
95
+ private allowed;
96
+ /**
97
+ * `model.response` for a sent call (observe only, not awaited). The hooks run on `lifecycle`
98
+ * (the worker stopping), never on the call's own signal: a timed-out call still reports.
99
+ */
100
+ private observe;
101
+ /**
102
+ * The reply's outcome (spec §1.4, §1.7, §4): a tool call or a stop reason other than `end_turn`
103
+ * is discarded, as is a reply that cleans to nothing; the text is stored only while the run is
104
+ * still fresh. A failed write is logged (the usage stands).
105
+ */
106
+ private result;
107
+ private logUsage;
108
+ /**
109
+ * Appends the call's `usage` event (`purpose: "suggestion"`, step 0, no run, one per run) and
110
+ * owes its `usage.report` delivery, in one transaction of its own.
111
+ */
112
+ writeUsage(conversationId: string, runId: string, u: {
113
+ provider: string;
114
+ model: string;
115
+ usage: ModelUsage;
116
+ }): Promise<ConversationEvent | undefined>;
117
+ /** The `hook.denied` audit row of a denied suggestion call. */
118
+ auditDenied(entry: AuditEntry): Promise<void>;
119
+ }
120
+ /**
121
+ * The suggestion queue: `maybeEnqueue` on any role (the run worker after a completed run), consumed
122
+ * on the `worker` role by its `@Processor`. One attempt per job (no BullMQ retries); the stop
123
+ * aborts the call in flight and the job is dropped.
124
+ */
125
+ export declare class PromptSuggestionQueue {
126
+ private readonly kdb;
127
+ private readonly queue;
128
+ private readonly generator;
129
+ private readonly log;
130
+ private worker;
131
+ private closed;
132
+ /** Lifecycle only: aborts the calls in flight when this process stops. */
133
+ private readonly stopping;
134
+ constructor(kdb: KernelDb, queue: Queue<PromptSuggestionJob>, generator: Pick<PromptSuggestionGenerator, "run">, log: Pick<KernelLogger, "warn" | "error">);
135
+ /**
136
+ * Enqueues the run's suggestion job when the outcome is `completed` or `max_steps` (never
137
+ * `max_duration` or `budget`), the conversation is a web chat and the run has no suggestion
138
+ * usage yet. A hint after the commit: never throws (logs instead).
139
+ */
140
+ maybeEnqueue(conversationId: string, runId: string, kind: RunOutcome): Promise<void>;
141
+ /** Starts consuming (worker role only): `worker` is the `@Processor` worker of the queue. */
142
+ startWorker(worker: Worker<PromptSuggestionJob>): void;
143
+ /** The worker's `error` event. */
144
+ onError(err: Error): void;
145
+ /** One suggestion job (the `@Processor` calls it). */
146
+ process(j: Job<PromptSuggestionJob>): Promise<void>;
147
+ /** Stops: no more enqueues, the call in flight is aborted (its job dropped), the worker closes. */
148
+ stop(): Promise<void>;
149
+ }
150
+ /** Prompt suggestions: the store, the queue and the job (consumed on the worker role). */
151
+ export declare class PromptSuggestionsModule {
152
+ }
153
+ export {};