@capybara-hq/kernel 0.1.0-rc.47 → 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.
- package/dist/admin/admin.module.js +2 -0
- package/dist/admin/admin.schemas.d.ts +4 -0
- package/dist/admin/health.service.d.ts +2 -2
- package/dist/admin/health.service.js +8 -4
- package/dist/agents/agents.schemas.js +1 -1
- package/dist/agents/instruction-files.js +0 -3
- package/dist/background/launch.d.ts +4 -0
- package/dist/background/launch.js +6 -2
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/channels.module.js +3 -0
- package/dist/channels/connections.service.d.ts +18 -5
- package/dist/channels/connections.service.js +21 -5
- package/dist/channels/features.d.ts +2 -0
- package/dist/channels/features.js +9 -5
- package/dist/channels/file-delivery.d.ts +74 -0
- package/dist/channels/file-delivery.js +176 -0
- package/dist/channels/outbound.d.ts +6 -3
- package/dist/channels/outbound.js +156 -4
- package/dist/channels/phrases.d.ts +19 -0
- package/dist/channels/phrases.js +16 -0
- package/dist/config/schema.d.ts +2 -0
- package/dist/config/schema.js +18 -0
- package/dist/conversations/delivery-scope.d.ts +34 -0
- package/dist/conversations/delivery-scope.js +23 -0
- package/dist/conversations/event-log.d.ts +18 -0
- package/dist/conversations/event-log.js +54 -0
- package/dist/conversations/events.d.ts +2 -0
- package/dist/conversations/events.js +15 -2
- package/dist/conversations/prompt-suggestion-request.d.ts +95 -0
- package/dist/conversations/prompt-suggestion-request.js +213 -0
- package/dist/conversations/prompt-suggestion-store.d.ts +51 -0
- package/dist/conversations/prompt-suggestion-store.js +136 -0
- package/dist/conversations/prompt-suggestions.d.ts +153 -0
- package/dist/conversations/prompt-suggestions.js +563 -0
- package/dist/conversations/titles.js +11 -5
- package/dist/evals/reconstruct.d.ts +26 -1
- package/dist/evals/reconstruct.js +25 -6
- package/dist/identity/settings.d.ts +13 -0
- package/dist/identity/settings.js +37 -2
- package/dist/infra/queue/queue-names.d.ts +1 -1
- package/dist/infra/queue/queue-names.js +1 -0
- package/dist/kernel.module.js +4 -1
- package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
- package/dist/lifecycle/kernel-lifecycle.js +13 -7
- package/dist/models/image-usable.d.ts +30 -6
- package/dist/models/image-usable.js +38 -7
- package/dist/models/images.js +6 -4
- package/dist/models/purposes.d.ts +1 -1
- package/dist/models/purposes.js +10 -4
- package/dist/orgs/settings.service.d.ts +16 -0
- package/dist/orgs/settings.service.js +46 -5
- package/dist/overrides.d.ts +4 -0
- package/dist/overrides.js +2 -0
- package/dist/platform/availability.d.ts +5 -0
- package/dist/platform/availability.js +7 -3
- package/dist/platform/ops/accounts.ops.d.ts +1 -1
- package/dist/platform/ops/accounts.ops.js +1 -1
- package/dist/platform/ops/admin.ops.js +3 -2
- package/dist/platform/ops/agent-skills.ops.js +5 -5
- package/dist/platform/ops/agents.ops.js +3 -3
- package/dist/platform/ops/approvals.ops.d.ts +1 -1
- package/dist/platform/ops/approvals.ops.js +2 -2
- package/dist/platform/ops/background.ops.js +1 -1
- package/dist/platform/ops/catalog-admin.ops.js +3 -3
- package/dist/platform/ops/conversations.ops.js +2 -2
- package/dist/platform/ops/devices.ops.js +2 -2
- package/dist/platform/ops/extensions-admin.ops.js +2 -2
- package/dist/platform/ops/extensions.ops.js +3 -3
- package/dist/platform/ops/inbox.ops.js +4 -4
- package/dist/platform/ops/org-plugins.ops.js +4 -4
- package/dist/platform/ops/org-settings.ops.js +2 -2
- package/dist/platform/ops/orgs.ops.js +1 -0
- package/dist/platform/ops/plugins.ops.d.ts +1 -1
- package/dist/platform/ops/plugins.ops.js +3 -3
- package/dist/platform/ops/requests.ops.js +1 -1
- package/dist/platform/ops/schedules.ops.js +6 -6
- package/dist/roles/worker-role.d.ts +6 -3
- package/dist/roles/worker-role.js +21 -13
- package/dist/roles/worker.module.js +2 -0
- package/dist/runtime/compaction-settings.service.d.ts +8 -0
- package/dist/runtime/compaction-settings.service.js +12 -6
- package/dist/runtime/run-processors.d.ts +14 -6
- package/dist/runtime/run-processors.js +43 -8
- package/dist/runtime/run-worker.d.ts +5 -0
- package/dist/runtime/run-worker.js +24 -16
- package/dist/runtime/runtime.module.d.ts +1 -1
- package/dist/runtime/runtime.module.js +7 -1
- package/dist/runtime/stream.d.ts +7 -1
- package/dist/runtime/stream.js +54 -3
- package/dist/runtime/usage-report.d.ts +2 -1
- package/dist/runtime/usage-report.js +2 -1
- package/dist/sandbox/sandbox-file-reader.js +1 -1
- package/dist/storage/storage.service.d.ts +2 -0
- package/dist/storage/storage.service.js +3 -0
- package/dist/tools/builtin-names.js +2 -2
- package/dist/tools/builtins/agent.js +5 -5
- package/dist/tools/builtins/artifacts.d.ts +34 -8
- package/dist/tools/builtins/artifacts.js +95 -19
- package/dist/tools/builtins/image/generate.d.ts +4 -1
- package/dist/tools/builtins/image/generate.js +70 -14
- package/dist/tools/builtins/platform.d.ts +0 -2
- package/dist/tools/builtins/platform.js +3 -5
- package/dist/tools/builtins/sandbox/bash.js +15 -11
- package/dist/tools/builtins/sandbox/common.d.ts +3 -2
- package/dist/tools/builtins/sandbox/deliver.js +13 -7
- package/dist/tools/builtins/sandbox/glob.js +1 -1
- package/dist/tools/builtins/sandbox/grep.js +1 -1
- package/dist/tools/builtins/sandbox/read.js +3 -3
- package/dist/tools/builtins/sandbox/task-output.d.ts +1 -1
- package/dist/tools/builtins/sandbox/task-output.js +13 -11
- package/dist/tools/builtins/send-message.d.ts +1 -1
- package/dist/tools/builtins/send-message.js +3 -3
- package/dist/tools/builtins/skill-load.d.ts +1 -1
- package/dist/tools/builtins/tool-search.js +1 -1
- package/dist/tools/builtins/web/extract.js +1 -1
- package/dist/tools/builtins/web/search.js +2 -4
- package/dist/tools/connector-account-policies.js +1 -1
- package/dist/tools/info.d.ts +3 -1
- package/dist/tools/registry.d.ts +6 -0
- package/dist/tools/registry.js +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,563 @@
|
|
|
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 { isModelError, } from "@capybara-hq/plugin-sdk";
|
|
11
|
+
import { getQueueToken } from "@nestjs/bullmq";
|
|
12
|
+
import { Inject, Injectable, Module, Optional } from "@nestjs/common";
|
|
13
|
+
import { sql } from "kysely";
|
|
14
|
+
import { ApiError } from "../errors.js";
|
|
15
|
+
import { loadSnapshotMedia } from "../evals/reconstruct.js";
|
|
16
|
+
import { takeSnapshot, toEvents } from "../evals/snapshot.js";
|
|
17
|
+
import { ExtensionsModule } from "../extensions/extensions.module.js";
|
|
18
|
+
import { ExtensionHost } from "../extensions/host.js";
|
|
19
|
+
import { audit } from "../identity/audit.js";
|
|
20
|
+
import { IdentityModule } from "../identity/identity.module.js";
|
|
21
|
+
import { SettingsService } from "../identity/settings.js";
|
|
22
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
23
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
24
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
25
|
+
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
26
|
+
import { QueueModule } from "../infra/queue/queue.module.js";
|
|
27
|
+
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
28
|
+
import { OrgSettingsModule, OrgSettingsService } from "../orgs/settings.service.js";
|
|
29
|
+
import { resolveCompactionSettings } from "../runtime/compaction-settings.service.js";
|
|
30
|
+
import { fireObserve, hookDeniedAudit, hookDeniedEvent, hookRequestOf, } from "../runtime/hook-calls.js";
|
|
31
|
+
import { consumeModelStream } from "../runtime/model-call.js";
|
|
32
|
+
import { ProviderRegistry, ProvidersModule } from "../runtime/providers.js";
|
|
33
|
+
import { UsageReportJobs, UsageReportJobsModule } from "../runtime/usage-report-jobs.js";
|
|
34
|
+
import { AttachmentsModule } from "./attachments.module.js";
|
|
35
|
+
import { AttachmentsService } from "./attachments.service.js";
|
|
36
|
+
import { EventLog, EventLogModule } from "./event-log.js";
|
|
37
|
+
import { buildSuggestionRequest, cleanSuggestion, lastModelCallOf, PROMPT_SUGGESTION_TIMEOUT_MS, suggestionEligible, suggestionStale, } from "./prompt-suggestion-request.js";
|
|
38
|
+
import { PromptSuggestionStore } from "./prompt-suggestion-store.js";
|
|
39
|
+
/**
|
|
40
|
+
* Prompt suggestions (spec 2026-11-19 §2, §3, §7, §8): after a completed web run the run worker
|
|
41
|
+
* calls {@link PromptSuggestionQueue.maybeEnqueue} (a hint after the commit: a lost enqueue costs
|
|
42
|
+
* one suggestion, so no outbox row). The worker-role job ({@link PromptSuggestionGenerator.run})
|
|
43
|
+
* re-checks the run, rebuilds its last request through the eval zero-drift path, fires
|
|
44
|
+
* `model.request` (policy fail closed, then observe) with `purpose: "suggestion"`, calls the run's
|
|
45
|
+
* own model once (no retry, no fallback), fires `model.response`, logs a run-less `usage` event
|
|
46
|
+
* owing its `usage.report`, and stores the cleaned text ({@link PromptSuggestionStore}) while the
|
|
47
|
+
* run is still the conversation's newest exchange. No lock, no transaction around the call, no
|
|
48
|
+
* process state beyond the stop signal. Nothing model-visible: no `model_call`, no DriftReason.
|
|
49
|
+
*/
|
|
50
|
+
/** The suggestion queue (no `:` in the name). */
|
|
51
|
+
export const PROMPT_SUGGESTION_QUEUE = "cap-kernel-suggestions";
|
|
52
|
+
/** One job per run (no `:`: run ids are UUIDs); a second enqueue of the same run is a no-op. */
|
|
53
|
+
export const promptSuggestionJobId = (runId) => `suggest-${runId}`;
|
|
54
|
+
/** Worker concurrency per replica (the calls are short and mostly cached). */
|
|
55
|
+
export const PROMPT_SUGGESTION_CONCURRENCY = 4;
|
|
56
|
+
const JOB = "suggest";
|
|
57
|
+
/**
|
|
58
|
+
* Test seam (`KernelSeams`): the side call's time limit in ms, asked at every call; default
|
|
59
|
+
* {@link PROMPT_SUGGESTION_TIMEOUT_MS}.
|
|
60
|
+
*/
|
|
61
|
+
export const PROMPT_SUGGESTION_TIMEOUT = Symbol("PROMPT_SUGGESTION_TIMEOUT");
|
|
62
|
+
/**
|
|
63
|
+
* Model error kinds where the vendor refused the request before processing it: nothing is billed,
|
|
64
|
+
* so no estimated usage is logged.
|
|
65
|
+
*/
|
|
66
|
+
const UNBILLED_KINDS = new Set([
|
|
67
|
+
"rate_limited",
|
|
68
|
+
"overloaded",
|
|
69
|
+
"auth",
|
|
70
|
+
"invalid_request",
|
|
71
|
+
"context_overflow",
|
|
72
|
+
]);
|
|
73
|
+
/** The usage event's idempotency key: one suggestion usage per run. */
|
|
74
|
+
const usageIdemKey = (runId) => `usage_suggestion:${runId}`;
|
|
75
|
+
/** Whether the run's suggestion usage event exists (its call was made: a rerun is a no-op). */
|
|
76
|
+
async function suggestionUsageExists(db, conversationId, runId) {
|
|
77
|
+
const row = await db
|
|
78
|
+
.selectFrom("conversation_events")
|
|
79
|
+
.select(sql `1`.as("one"))
|
|
80
|
+
.where("conversation_id", "=", conversationId)
|
|
81
|
+
.where("idem_key", "=", usageIdemKey(runId))
|
|
82
|
+
.limit(1)
|
|
83
|
+
.executeTakeFirst();
|
|
84
|
+
return row !== undefined;
|
|
85
|
+
}
|
|
86
|
+
const textOf = (content) => content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
|
|
87
|
+
/** The failed call's error code; an abort of the call's own signal is its time limit. */
|
|
88
|
+
const errorCodeOf = (err, signal) => isModelError(err) ? `model.${err.kind}` : signal.aborted ? "model.timeout" : "model.unknown";
|
|
89
|
+
/**
|
|
90
|
+
* One suggestion job's work over the injected services, with its writes in transactions of their
|
|
91
|
+
* own: the call's usage event (owing its delivery) and a policy denial's audit row.
|
|
92
|
+
*/
|
|
93
|
+
let PromptSuggestionGenerator = class PromptSuggestionGenerator {
|
|
94
|
+
kdb;
|
|
95
|
+
eventLog;
|
|
96
|
+
registry;
|
|
97
|
+
host;
|
|
98
|
+
usage;
|
|
99
|
+
orgSettings;
|
|
100
|
+
settings;
|
|
101
|
+
attachments;
|
|
102
|
+
store;
|
|
103
|
+
config;
|
|
104
|
+
log;
|
|
105
|
+
txHost;
|
|
106
|
+
timeoutMs;
|
|
107
|
+
constructor(kdb, eventLog, registry,
|
|
108
|
+
/** The call fires the plugin hooks (`model.request`, `model.response`). */
|
|
109
|
+
host,
|
|
110
|
+
/** The call's `usage.report` delivery, owed with its usage event. */
|
|
111
|
+
usage, orgSettings,
|
|
112
|
+
/** The platform's compaction settings (the org's reserve for the fit guard). */
|
|
113
|
+
settings,
|
|
114
|
+
/** The run's media, as the run's steps load it. */
|
|
115
|
+
attachments, store, config, log, txHost, timeoutMs = () => PROMPT_SUGGESTION_TIMEOUT_MS) {
|
|
116
|
+
this.kdb = kdb;
|
|
117
|
+
this.eventLog = eventLog;
|
|
118
|
+
this.registry = registry;
|
|
119
|
+
this.host = host;
|
|
120
|
+
this.usage = usage;
|
|
121
|
+
this.orgSettings = orgSettings;
|
|
122
|
+
this.settings = settings;
|
|
123
|
+
this.attachments = attachments;
|
|
124
|
+
this.store = store;
|
|
125
|
+
this.config = config;
|
|
126
|
+
this.log = log;
|
|
127
|
+
this.txHost = txHost;
|
|
128
|
+
this.timeoutMs = timeoutMs;
|
|
129
|
+
}
|
|
130
|
+
get db() {
|
|
131
|
+
return this.kdb.db;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* One suggestion for the run (spec §1–§4); `shutdown` aborts the call (the worker stopping).
|
|
135
|
+
* Never throws: every skip and failure is logged and means no suggestion.
|
|
136
|
+
*/
|
|
137
|
+
async run(conversationId, runId, finishedAt, shutdown) {
|
|
138
|
+
const skip = (reason) => this.log.debug("prompt suggestion skipped", { conversationId, runId, reason });
|
|
139
|
+
try {
|
|
140
|
+
if (suggestionStale(finishedAt, Date.now()))
|
|
141
|
+
return skip("stale");
|
|
142
|
+
if (shutdown.aborted)
|
|
143
|
+
return skip("shutdown");
|
|
144
|
+
const facts = await this.runFacts(conversationId, runId);
|
|
145
|
+
if (typeof facts === "string")
|
|
146
|
+
return skip(facts);
|
|
147
|
+
// a rerun job (a stalled job's retry, an enqueue after the job was removed): the call was
|
|
148
|
+
// made and billed already
|
|
149
|
+
if (await suggestionUsageExists(this.db, conversationId, runId))
|
|
150
|
+
return skip("done");
|
|
151
|
+
if (!(await this.orgSettings.promptSuggestionsEnabled(facts.orgId)))
|
|
152
|
+
return skip("off");
|
|
153
|
+
if (!(await this.store.isFresh(conversationId, { runId, afterSeq: facts.afterSeq }))) {
|
|
154
|
+
return skip("not_fresh");
|
|
155
|
+
}
|
|
156
|
+
let snapshot;
|
|
157
|
+
try {
|
|
158
|
+
snapshot = await takeSnapshot(this.db, facts.orgId, conversationId, runId, this.config.get().evals.maxCaseBytes);
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
if (err instanceof ApiError)
|
|
162
|
+
return skip(err.code);
|
|
163
|
+
throw err;
|
|
164
|
+
}
|
|
165
|
+
const last = lastModelCallOf(toEvents(snapshot), runId);
|
|
166
|
+
if (last === undefined)
|
|
167
|
+
return skip("no_model_call");
|
|
168
|
+
const ref = { provider: last.payload.provider, model: last.payload.model };
|
|
169
|
+
let provider;
|
|
170
|
+
let info;
|
|
171
|
+
try {
|
|
172
|
+
({ provider, info } = await this.registry.resolve(facts.orgId, ref));
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
return skip("model_unavailable");
|
|
176
|
+
}
|
|
177
|
+
let media;
|
|
178
|
+
try {
|
|
179
|
+
media = await loadSnapshotMedia(snapshot, last.seq, info, {
|
|
180
|
+
info: (orgId, convId, ids) => this.attachments.mediaInfo(orgId, convId, ids),
|
|
181
|
+
fetch: (orgId, convId, ids, caps) => this.attachments.fetchMedia(orgId, convId, ids, caps),
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return skip("media_unavailable");
|
|
186
|
+
}
|
|
187
|
+
const { reserveTokens } = await resolveCompactionSettings(this.settings, this.db, facts.orgId);
|
|
188
|
+
const built = buildSuggestionRequest({
|
|
189
|
+
snapshot,
|
|
190
|
+
model: info,
|
|
191
|
+
mediaInfo: media.mediaInfo,
|
|
192
|
+
media: media.media,
|
|
193
|
+
reserveTokens,
|
|
194
|
+
});
|
|
195
|
+
if ("skip" in built)
|
|
196
|
+
return skip(built.skip);
|
|
197
|
+
const { request, estimate, finalText } = built;
|
|
198
|
+
const scope = {
|
|
199
|
+
orgId: facts.orgId,
|
|
200
|
+
accountId: facts.accountId,
|
|
201
|
+
agentId: facts.agentId,
|
|
202
|
+
agentVersion: facts.agentVersion,
|
|
203
|
+
conversationId,
|
|
204
|
+
runId,
|
|
205
|
+
};
|
|
206
|
+
const signal = AbortSignal.any([AbortSignal.timeout(this.timeoutMs()), shutdown]);
|
|
207
|
+
if (!(await this.allowed(scope, ref, request, signal)))
|
|
208
|
+
return;
|
|
209
|
+
if (signal.aborted)
|
|
210
|
+
return skip("shutdown");
|
|
211
|
+
const sentAt = Date.now();
|
|
212
|
+
let streamedChars = 0;
|
|
213
|
+
let out;
|
|
214
|
+
try {
|
|
215
|
+
out = await consumeModelStream(provider, request, info.streamIdleTimeoutMs ?? this.config.get().runtime.streamIdleMs, signal, (ev) => {
|
|
216
|
+
streamedChars += ev.text.length;
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
catch (err) {
|
|
220
|
+
if (shutdown.aborted) {
|
|
221
|
+
// cut by the replica stopping: no model.response (spec §7), the job is dropped
|
|
222
|
+
skip("aborted");
|
|
223
|
+
}
|
|
224
|
+
else {
|
|
225
|
+
// the observe hooks run on the lifecycle signal: the call's own signal is aborted after
|
|
226
|
+
// its time limit and would skip them
|
|
227
|
+
this.observe(scope, ref, sentAt, null, err, signal, shutdown);
|
|
228
|
+
this.log.warn("prompt suggestion call failed", {
|
|
229
|
+
conversationId,
|
|
230
|
+
runId,
|
|
231
|
+
provider: ref.provider,
|
|
232
|
+
model: ref.model,
|
|
233
|
+
errorCode: errorCodeOf(err, signal),
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
// a vendor refusal before processing bills nothing; any other sent call (a shutdown abort
|
|
237
|
+
// included) is billed: log its estimated input plus the output streamed so far
|
|
238
|
+
if (!isModelError(err) || !UNBILLED_KINDS.has(err.kind)) {
|
|
239
|
+
await this.logUsage(conversationId, runId, {
|
|
240
|
+
...ref,
|
|
241
|
+
usage: {
|
|
242
|
+
inputTokens: estimate,
|
|
243
|
+
outputTokens: Math.ceil(streamedChars / 4),
|
|
244
|
+
cacheReadTokens: 0,
|
|
245
|
+
cacheWriteTokens: 0,
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
this.observe(scope, ref, sentAt, out, null, signal, shutdown);
|
|
252
|
+
await this.logUsage(conversationId, runId, { ...ref, usage: out.usage });
|
|
253
|
+
const outcome = await this.result(conversationId, runId, facts.afterSeq, out, finalText);
|
|
254
|
+
this.log.debug("prompt suggestion call", {
|
|
255
|
+
conversationId,
|
|
256
|
+
runId,
|
|
257
|
+
provider: ref.provider,
|
|
258
|
+
model: ref.model,
|
|
259
|
+
inputTokens: out.usage.inputTokens,
|
|
260
|
+
cacheReadTokens: out.usage.cacheReadTokens,
|
|
261
|
+
cacheWriteTokens: out.usage.cacheWriteTokens,
|
|
262
|
+
outputTokens: out.usage.outputTokens,
|
|
263
|
+
outcome,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
catch (err) {
|
|
267
|
+
this.log.warn("prompt suggestion job failed", { conversationId, runId, err });
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* The run's facts by spec §2 (outcome, conversation kind and source, trigger) and its hook scope,
|
|
272
|
+
* or why it gets no suggestion.
|
|
273
|
+
*/
|
|
274
|
+
async runFacts(conversationId, runId) {
|
|
275
|
+
const conv = await this.db
|
|
276
|
+
.selectFrom("conversations")
|
|
277
|
+
.select(["org_id", "agent_id", "kind", "source"])
|
|
278
|
+
.where("id", "=", conversationId)
|
|
279
|
+
.executeTakeFirst();
|
|
280
|
+
if (!conv)
|
|
281
|
+
return "no_conversation";
|
|
282
|
+
const rows = await this.db
|
|
283
|
+
.selectFrom("conversation_events")
|
|
284
|
+
.select(["seq", "type", "payload"])
|
|
285
|
+
.where("conversation_id", "=", conversationId)
|
|
286
|
+
.where("run_id", "=", runId)
|
|
287
|
+
.where("type", "in", ["run_started", "run_finished"])
|
|
288
|
+
.orderBy("seq")
|
|
289
|
+
.execute();
|
|
290
|
+
const started = rows.find((r) => r.type === "run_started");
|
|
291
|
+
const finished = rows.find((r) => r.type === "run_finished");
|
|
292
|
+
if (!started || !finished)
|
|
293
|
+
return "not_finished";
|
|
294
|
+
const s = started.payload;
|
|
295
|
+
const f = finished.payload;
|
|
296
|
+
const eligible = suggestionEligible({
|
|
297
|
+
outcome: f.reason,
|
|
298
|
+
kind: conv.kind,
|
|
299
|
+
source: conv.source,
|
|
300
|
+
trigger: s.trigger,
|
|
301
|
+
});
|
|
302
|
+
if (!eligible)
|
|
303
|
+
return "not_eligible";
|
|
304
|
+
return {
|
|
305
|
+
orgId: conv.org_id,
|
|
306
|
+
agentId: conv.agent_id,
|
|
307
|
+
accountId: s.triggerAccountId,
|
|
308
|
+
agentVersion: s.agentVersion,
|
|
309
|
+
afterSeq: Number(finished.seq),
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* `model.request` (`purpose: "suggestion"`, the run's id, step 0, attempt 1): policy hooks first,
|
|
314
|
+
* failing closed (a policy extension not loaded on this replica denies), then observe. A denial
|
|
315
|
+
* writes the `hook.denied` audit row (`detail.purpose: "suggestion"`) and no `hook_denied`
|
|
316
|
+
* event (the call is not a step of the run).
|
|
317
|
+
*/
|
|
318
|
+
async allowed(scope, ref, request, signal) {
|
|
319
|
+
const hooks = this.host?.hooks;
|
|
320
|
+
if (!hooks?.has("model.request"))
|
|
321
|
+
return true;
|
|
322
|
+
const verdict = await hooks.run("model.request", {
|
|
323
|
+
...scope,
|
|
324
|
+
purpose: "suggestion",
|
|
325
|
+
step: 0,
|
|
326
|
+
attempt: 1,
|
|
327
|
+
provider: ref.provider,
|
|
328
|
+
model: ref.model,
|
|
329
|
+
request: hookRequestOf(request, this.log),
|
|
330
|
+
}, signal);
|
|
331
|
+
if (verdict.allowed)
|
|
332
|
+
return true;
|
|
333
|
+
const site = {
|
|
334
|
+
orgId: scope.orgId,
|
|
335
|
+
conversationId: scope.conversationId,
|
|
336
|
+
runId: scope.runId,
|
|
337
|
+
accountId: scope.accountId,
|
|
338
|
+
agentId: scope.agentId,
|
|
339
|
+
idemKey: "",
|
|
340
|
+
};
|
|
341
|
+
const entry = hookDeniedAudit(site, hookDeniedEvent(site, "model.request", verdict, { step: 0, attempt: 1 }).payload, verdict);
|
|
342
|
+
entry.detail = { ...entry.detail, purpose: "suggestion" };
|
|
343
|
+
await this.auditDenied(entry);
|
|
344
|
+
this.log.warn("prompt suggestion blocked by a policy hook", {
|
|
345
|
+
conversationId: scope.conversationId,
|
|
346
|
+
runId: scope.runId,
|
|
347
|
+
plugin: verdict.plugin,
|
|
348
|
+
cause: verdict.cause,
|
|
349
|
+
});
|
|
350
|
+
return false;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* `model.response` for a sent call (observe only, not awaited). The hooks run on `lifecycle`
|
|
354
|
+
* (the worker stopping), never on the call's own signal: a timed-out call still reports.
|
|
355
|
+
*/
|
|
356
|
+
observe(scope, ref, sentAt, out, err, callSignal, lifecycle) {
|
|
357
|
+
const hooks = this.host?.hooks;
|
|
358
|
+
if (!hooks)
|
|
359
|
+
return;
|
|
360
|
+
fireObserve(hooks, "model.response", {
|
|
361
|
+
...scope,
|
|
362
|
+
purpose: "suggestion",
|
|
363
|
+
step: 0,
|
|
364
|
+
attempt: 1,
|
|
365
|
+
provider: ref.provider,
|
|
366
|
+
model: ref.model,
|
|
367
|
+
outcome: out ? "ok" : "failed",
|
|
368
|
+
content: out?.content ?? [],
|
|
369
|
+
stopReason: out?.stopReason ?? null,
|
|
370
|
+
usage: out?.usage ?? null,
|
|
371
|
+
latencyMs: Date.now() - sentAt,
|
|
372
|
+
...(out === null && { errorCode: errorCodeOf(err, callSignal) }),
|
|
373
|
+
}, lifecycle, this.log);
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* The reply's outcome (spec §1.4, §1.7, §4): a tool call or a stop reason other than `end_turn`
|
|
377
|
+
* is discarded, as is a reply that cleans to nothing; the text is stored only while the run is
|
|
378
|
+
* still fresh. A failed write is logged (the usage stands).
|
|
379
|
+
*/
|
|
380
|
+
async result(conversationId, runId, afterSeq, out, finalText) {
|
|
381
|
+
if (out.content.some((b) => b.type === "tool_call"))
|
|
382
|
+
return "tool_call";
|
|
383
|
+
if (out.stopReason !== "end_turn")
|
|
384
|
+
return `stop_${out.stopReason}`;
|
|
385
|
+
const text = cleanSuggestion(textOf(out.content), finalText);
|
|
386
|
+
if (text === null)
|
|
387
|
+
return "none";
|
|
388
|
+
if (!(await this.store.isFresh(conversationId, { runId, afterSeq })))
|
|
389
|
+
return "not_fresh";
|
|
390
|
+
try {
|
|
391
|
+
await this.store.put(conversationId, { runId, afterSeq, text, createdAt: Date.now() });
|
|
392
|
+
}
|
|
393
|
+
catch (err) {
|
|
394
|
+
this.log.warn("prompt suggestion write failed", { conversationId, runId, err });
|
|
395
|
+
return "write_failed";
|
|
396
|
+
}
|
|
397
|
+
return "stored";
|
|
398
|
+
}
|
|
399
|
+
async logUsage(conversationId, runId, u) {
|
|
400
|
+
const ev = await this.writeUsage(conversationId, runId, u);
|
|
401
|
+
if (ev)
|
|
402
|
+
await this.eventLog.notify(conversationId, ev.seq);
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Appends the call's `usage` event (`purpose: "suggestion"`, step 0, no run, one per run) and
|
|
406
|
+
* owes its `usage.report` delivery, in one transaction of its own.
|
|
407
|
+
*/
|
|
408
|
+
async writeUsage(conversationId, runId, u) {
|
|
409
|
+
const event = {
|
|
410
|
+
type: "usage",
|
|
411
|
+
idemKey: usageIdemKey(runId),
|
|
412
|
+
payload: {
|
|
413
|
+
step: 0,
|
|
414
|
+
provider: u.provider,
|
|
415
|
+
model: u.model,
|
|
416
|
+
inputTokens: u.usage.inputTokens,
|
|
417
|
+
outputTokens: u.usage.outputTokens,
|
|
418
|
+
cacheReadTokens: u.usage.cacheReadTokens,
|
|
419
|
+
cacheWriteTokens: u.usage.cacheWriteTokens,
|
|
420
|
+
purpose: "suggestion",
|
|
421
|
+
},
|
|
422
|
+
};
|
|
423
|
+
const { events, fresh } = await this.eventLog.appendInReport(conversationId, [event]);
|
|
424
|
+
// only when this call wrote it (a replayed job's hit owes nothing new)
|
|
425
|
+
if (fresh[0])
|
|
426
|
+
await this.usage.oweEvents(conversationId, events);
|
|
427
|
+
return fresh[0] ? events[0] : undefined;
|
|
428
|
+
}
|
|
429
|
+
/** The `hook.denied` audit row of a denied suggestion call. */
|
|
430
|
+
async auditDenied(entry) {
|
|
431
|
+
await audit(this.db, entry);
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
__decorate([
|
|
435
|
+
Transactional({ propagation: "requires_new" })
|
|
436
|
+
], PromptSuggestionGenerator.prototype, "writeUsage", null);
|
|
437
|
+
__decorate([
|
|
438
|
+
Transactional({ propagation: "requires_new" })
|
|
439
|
+
], PromptSuggestionGenerator.prototype, "auditDenied", null);
|
|
440
|
+
PromptSuggestionGenerator = __decorate([
|
|
441
|
+
Injectable(),
|
|
442
|
+
__param(0, Inject(KernelDb)),
|
|
443
|
+
__param(1, Inject(EventLog)),
|
|
444
|
+
__param(2, Inject(ProviderRegistry)),
|
|
445
|
+
__param(3, Inject(ExtensionHost)),
|
|
446
|
+
__param(4, Inject(UsageReportJobs)),
|
|
447
|
+
__param(5, Inject(OrgSettingsService)),
|
|
448
|
+
__param(6, Inject(SettingsService)),
|
|
449
|
+
__param(7, Inject(AttachmentsService)),
|
|
450
|
+
__param(8, Inject(PromptSuggestionStore)),
|
|
451
|
+
__param(9, Inject(KernelConfigService)),
|
|
452
|
+
__param(10, Inject(KERNEL_LOGGER)),
|
|
453
|
+
__param(11, Inject(TransactionHost)),
|
|
454
|
+
__param(12, Optional()),
|
|
455
|
+
__param(12, Inject(PROMPT_SUGGESTION_TIMEOUT))
|
|
456
|
+
], PromptSuggestionGenerator);
|
|
457
|
+
export { PromptSuggestionGenerator };
|
|
458
|
+
/**
|
|
459
|
+
* The suggestion queue: `maybeEnqueue` on any role (the run worker after a completed run), consumed
|
|
460
|
+
* on the `worker` role by its `@Processor`. One attempt per job (no BullMQ retries); the stop
|
|
461
|
+
* aborts the call in flight and the job is dropped.
|
|
462
|
+
*/
|
|
463
|
+
let PromptSuggestionQueue = class PromptSuggestionQueue {
|
|
464
|
+
kdb;
|
|
465
|
+
queue;
|
|
466
|
+
generator;
|
|
467
|
+
log;
|
|
468
|
+
worker;
|
|
469
|
+
closed = false;
|
|
470
|
+
/** Lifecycle only: aborts the calls in flight when this process stops. */
|
|
471
|
+
stopping = new AbortController();
|
|
472
|
+
constructor(kdb, queue, generator, log) {
|
|
473
|
+
this.kdb = kdb;
|
|
474
|
+
this.queue = queue;
|
|
475
|
+
this.generator = generator;
|
|
476
|
+
this.log = log;
|
|
477
|
+
queue.on("error", (err) => this.log.error("prompt suggestion queue error", { err }));
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Enqueues the run's suggestion job when the outcome is `completed` or `max_steps` (never
|
|
481
|
+
* `max_duration` or `budget`), the conversation is a web chat and the run has no suggestion
|
|
482
|
+
* usage yet. A hint after the commit: never throws (logs instead).
|
|
483
|
+
*/
|
|
484
|
+
async maybeEnqueue(conversationId, runId, kind) {
|
|
485
|
+
if (this.closed)
|
|
486
|
+
return;
|
|
487
|
+
if (kind !== "completed" && kind !== "max_steps")
|
|
488
|
+
return;
|
|
489
|
+
try {
|
|
490
|
+
const due = await this.kdb.db
|
|
491
|
+
.selectFrom("conversations as c")
|
|
492
|
+
.select("c.id")
|
|
493
|
+
.where("c.id", "=", conversationId)
|
|
494
|
+
.where("c.kind", "=", "chat")
|
|
495
|
+
.where("c.source", "=", "web")
|
|
496
|
+
.executeTakeFirst();
|
|
497
|
+
if (!due || (await suggestionUsageExists(this.kdb.db, conversationId, runId)))
|
|
498
|
+
return;
|
|
499
|
+
await this.queue.add(JOB, { conversationId, runId, finishedAt: Date.now() }, {
|
|
500
|
+
jobId: promptSuggestionJobId(runId),
|
|
501
|
+
attempts: 1,
|
|
502
|
+
removeOnComplete: true,
|
|
503
|
+
removeOnFail: true,
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
catch (err) {
|
|
507
|
+
this.log.warn("cannot enqueue prompt suggestion", { conversationId, runId, err });
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
/** Starts consuming (worker role only): `worker` is the `@Processor` worker of the queue. */
|
|
511
|
+
startWorker(worker) {
|
|
512
|
+
if (this.worker || this.closed)
|
|
513
|
+
return;
|
|
514
|
+
this.worker = worker;
|
|
515
|
+
void worker.run().catch((err) => this.log.error("prompt suggestion worker error", { err }));
|
|
516
|
+
}
|
|
517
|
+
/** The worker's `error` event. */
|
|
518
|
+
onError(err) {
|
|
519
|
+
this.log.error("prompt suggestion worker error", { err });
|
|
520
|
+
}
|
|
521
|
+
/** One suggestion job (the `@Processor` calls it). */
|
|
522
|
+
async process(j) {
|
|
523
|
+
await this.generator.run(j.data.conversationId, j.data.runId, j.data.finishedAt, this.stopping.signal);
|
|
524
|
+
}
|
|
525
|
+
/** Stops: no more enqueues, the call in flight is aborted (its job dropped), the worker closes. */
|
|
526
|
+
async stop() {
|
|
527
|
+
this.closed = true;
|
|
528
|
+
this.stopping.abort();
|
|
529
|
+
const w = this.worker;
|
|
530
|
+
this.worker = undefined;
|
|
531
|
+
await w?.close().catch(() => { });
|
|
532
|
+
}
|
|
533
|
+
};
|
|
534
|
+
PromptSuggestionQueue = __decorate([
|
|
535
|
+
Injectable(),
|
|
536
|
+
__param(0, Inject(KernelDb)),
|
|
537
|
+
__param(1, Inject(getQueueToken(PROMPT_SUGGESTION_QUEUE))),
|
|
538
|
+
__param(2, Inject(PromptSuggestionGenerator)),
|
|
539
|
+
__param(3, Inject(KERNEL_LOGGER))
|
|
540
|
+
], PromptSuggestionQueue);
|
|
541
|
+
export { PromptSuggestionQueue };
|
|
542
|
+
/** The suggestion queue's registration (re-exported: the admin health reads its counts). */
|
|
543
|
+
const PROMPT_SUGGESTION_QUEUE_MODULE = QueueModule.registerQueue(PROMPT_SUGGESTION_QUEUE);
|
|
544
|
+
/** Prompt suggestions: the store, the queue and the job (consumed on the worker role). */
|
|
545
|
+
let PromptSuggestionsModule = class PromptSuggestionsModule {
|
|
546
|
+
};
|
|
547
|
+
PromptSuggestionsModule = __decorate([
|
|
548
|
+
Module({
|
|
549
|
+
imports: [
|
|
550
|
+
EventLogModule,
|
|
551
|
+
ProvidersModule,
|
|
552
|
+
ExtensionsModule,
|
|
553
|
+
UsageReportJobsModule,
|
|
554
|
+
OrgSettingsModule,
|
|
555
|
+
IdentityModule,
|
|
556
|
+
AttachmentsModule,
|
|
557
|
+
PROMPT_SUGGESTION_QUEUE_MODULE,
|
|
558
|
+
],
|
|
559
|
+
providers: [PromptSuggestionStore, PromptSuggestionGenerator, PromptSuggestionQueue],
|
|
560
|
+
exports: [PromptSuggestionStore, PromptSuggestionQueue, PROMPT_SUGGESTION_QUEUE_MODULE],
|
|
561
|
+
})
|
|
562
|
+
], PromptSuggestionsModule);
|
|
563
|
+
export { PromptSuggestionsModule };
|
|
@@ -241,7 +241,7 @@ export async function runTitleJob(d, conversationId, attempt) {
|
|
|
241
241
|
return;
|
|
242
242
|
}
|
|
243
243
|
if (sent && d.hooks)
|
|
244
|
-
observeTitle(d, scope, sent, null, err,
|
|
244
|
+
observeTitle(d, scope, sent, null, err, lifecycleOf(d));
|
|
245
245
|
// the replica is shutting down: give the attempt back unless something else took over
|
|
246
246
|
if (d.signal?.aborted && !(err instanceof PurposeAttemptError)) {
|
|
247
247
|
await giveBack(d.db, conversationId, attempt);
|
|
@@ -264,7 +264,7 @@ export async function runTitleJob(d, conversationId, attempt) {
|
|
|
264
264
|
return;
|
|
265
265
|
}
|
|
266
266
|
if (sent && d.hooks)
|
|
267
|
-
observeTitle(d, scope, sent, out, null,
|
|
267
|
+
observeTitle(d, scope, sent, out, null, lifecycleOf(d));
|
|
268
268
|
const title = cleanTitle(textOf(out.content));
|
|
269
269
|
if (title === null) {
|
|
270
270
|
d.log.warn("conversation title call returned no title", {
|
|
@@ -353,8 +353,14 @@ const errorCodeOf = (err) => {
|
|
|
353
353
|
const cause = err instanceof PurposeAttemptError ? err.cause : err;
|
|
354
354
|
return isModelError(cause) ? `model.${cause.kind}` : "model.unknown";
|
|
355
355
|
};
|
|
356
|
-
/**
|
|
357
|
-
|
|
356
|
+
/** The signal the observe hooks run on: the worker stopping, or one that never aborts. */
|
|
357
|
+
const lifecycleOf = (d) => d.signal ?? new AbortController().signal;
|
|
358
|
+
/**
|
|
359
|
+
* `model.response` for a sent title call (observe only, not awaited). The hooks run on
|
|
360
|
+
* `lifecycle` (the worker stopping), never on the call's own signal: after the call's time limit
|
|
361
|
+
* that signal is aborted and the hooks would be skipped.
|
|
362
|
+
*/
|
|
363
|
+
function observeTitle(d, scope, sent, out, err, lifecycle) {
|
|
358
364
|
if (!d.hooks)
|
|
359
365
|
return;
|
|
360
366
|
fireObserve(d.hooks, "model.response", {
|
|
@@ -370,7 +376,7 @@ function observeTitle(d, scope, sent, out, err, signal) {
|
|
|
370
376
|
usage: out?.usage ?? null,
|
|
371
377
|
latencyMs: Date.now() - sent.at,
|
|
372
378
|
...(out === null && { errorCode: errorCodeOf(err) }),
|
|
373
|
-
},
|
|
379
|
+
}, lifecycle, d.log);
|
|
374
380
|
}
|
|
375
381
|
/**
|
|
376
382
|
* One title attempt's work ({@link runTitleJob}) over the injected services, with its writes in
|
|
@@ -2,7 +2,7 @@ import { type ModelInfo, type ModelRequest, type ParamValue } from "@capybara-hq
|
|
|
2
2
|
import { type AgentDefinition, type ModelRef } from "../agents/definition.js";
|
|
3
3
|
import { type ConversationEvent, type EventPayload } from "../conversations/events.js";
|
|
4
4
|
import { type MediaBytes, type MediaInfo, type ModelCallMeta } from "../runtime/context/build.js";
|
|
5
|
-
import { type MediaSourceDeps } from "../runtime/model-call.js";
|
|
5
|
+
import { type AssembleModelRequestInput, type MediaSourceDeps } from "../runtime/model-call.js";
|
|
6
6
|
import { type CaseSnapshot } from "./snapshot.js";
|
|
7
7
|
/**
|
|
8
8
|
* 由用例快照还原某次模型请求(单步回放的基础,D2 / C5)。与运行时共用 {@link assembleModelRequest},
|
|
@@ -103,7 +103,32 @@ export declare function assertSnapshotPermissionEvents(events: readonly Conversa
|
|
|
103
103
|
* (inside or outside the range, covered by a summary or not) fails its strict schema.
|
|
104
104
|
*/
|
|
105
105
|
export declare function recordedPermissionContextDrift(events: readonly ConversationEvent[], call: ModelCallEvent): DriftReason[];
|
|
106
|
+
/** What {@link reconstructInputs} gathered for one recorded call. */
|
|
107
|
+
export interface ReconstructInputs {
|
|
108
|
+
/** The {@link assembleModelRequest} input that rebuilds the call (its own input events). */
|
|
109
|
+
input: AssembleModelRequestInput;
|
|
110
|
+
/** Drift found while gathering the inputs; the rest is judged after assembling. */
|
|
111
|
+
drift: Set<DriftReason>;
|
|
112
|
+
/** No candidate definition, params, version or template: a zero-drift baseline. */
|
|
113
|
+
baseline: boolean;
|
|
114
|
+
/** The recorded call. */
|
|
115
|
+
call: ModelCallEvent;
|
|
116
|
+
/** The snapshot's events. */
|
|
117
|
+
events: ConversationEvent[];
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* The inputs {@link reconstructRequest} hands {@link assembleModelRequest} for the `model_call` at
|
|
121
|
+
* `modelCallSeq`, with the drift found on the way. One path: `reconstructRequest` builds from it,
|
|
122
|
+
* and the prompt suggestion side request extends the same input with later events.
|
|
123
|
+
*/
|
|
124
|
+
export declare function reconstructInputs(s: CaseSnapshot, modelCallSeq: number, opts: ReconstructOptions): ReconstructInputs;
|
|
106
125
|
export declare function reconstructRequest(s: CaseSnapshot, modelCallSeq: number, opts: ReconstructOptions): ReconstructResult;
|
|
126
|
+
/**
|
|
127
|
+
* {@link reconstructRequest} from inputs {@link reconstructInputs} already gathered (with the same
|
|
128
|
+
* `s` and `opts`): assembles the request and judges the remaining drift. Leaves `gathered.input`
|
|
129
|
+
* as it was, so a caller may assemble from it again.
|
|
130
|
+
*/
|
|
131
|
+
export declare function reconstructFromInputs(s: CaseSnapshot, gathered: ReconstructInputs, opts: ReconstructOptions): ReconstructResult;
|
|
107
132
|
type SubagentStarted = EventPayload<"subagent_started">;
|
|
108
133
|
/** The `subagent_started` of a sub-agent's (child) log, or undefined for any other conversation. */
|
|
109
134
|
export declare function subagentStartedOf(events: readonly ConversationEvent[]): SubagentStarted | undefined;
|