@capybara-hq/kernel 0.1.0-rc.113 → 0.1.0-rc.115
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/bootstrap.json +7 -7
- package/dist/admin/admin.schemas.d.ts +1 -0
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/actions.js +2 -0
- package/dist/channels/cards.d.ts +4 -3
- package/dist/channels/cards.js +18 -3
- package/dist/channels/phrases.d.ts +15 -0
- package/dist/channels/phrases.js +9 -0
- package/dist/conversations/conversations.service.js +7 -0
- package/dist/conversations/events.d.ts +21 -0
- package/dist/conversations/events.js +35 -3
- package/dist/ctx/create-ctx.d.ts +1 -1
- package/dist/ctx/create-ctx.js +6 -1
- package/dist/db/kernel-schema.d.ts +29 -0
- package/dist/device-access/device-access.service.d.ts +74 -3
- package/dist/device-access/device-access.service.js +221 -7
- package/dist/devices/devices.service.js +3 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +6 -0
- package/dist/extensions/permission-set.d.ts +11 -1
- package/dist/extensions/permission-set.js +15 -1
- package/dist/extensions/permission-view.d.ts +3 -2
- package/dist/extensions/permission-view.js +15 -2
- package/dist/identity/settings.d.ts +5 -0
- package/dist/identity/settings.js +4 -0
- package/dist/infra/outbox/registry.d.ts +14 -0
- package/dist/infra/outbox/registry.js +14 -0
- package/dist/models/purposes.js +5 -0
- package/dist/orgs/offboarding.js +5 -1
- package/dist/orgs/settings.service.d.ts +2 -0
- package/dist/platform/ops/org-settings.ops.js +1 -1
- package/dist/roles/worker.module.js +3 -0
- package/dist/runtime/compaction-model.d.ts +57 -0
- package/dist/runtime/compaction-model.js +87 -0
- package/dist/runtime/compaction.service.d.ts +23 -8
- package/dist/runtime/compaction.service.js +15 -10
- package/dist/runtime/context/compaction.d.ts +19 -2
- package/dist/runtime/context/compaction.js +23 -2
- package/dist/runtime/context/idle-compaction-rules.d.ts +17 -2
- package/dist/runtime/context/idle-compaction-rules.js +20 -5
- package/dist/runtime/idle-arm.d.ts +12 -2
- package/dist/runtime/idle-arm.js +66 -18
- package/dist/runtime/idle-compaction-jobs.d.ts +24 -3
- package/dist/runtime/idle-compaction.d.ts +11 -3
- package/dist/runtime/idle-compaction.js +61 -30
- package/dist/runtime/maintenance.d.ts +4 -2
- package/dist/runtime/maintenance.js +14 -4
- package/dist/runtime/model-call.d.ts +52 -16
- package/dist/runtime/model-call.js +71 -24
- package/dist/runtime/run-finish.d.ts +12 -3
- package/dist/runtime/run-finish.js +14 -7
- package/dist/runtime/run-queue.d.ts +5 -2
- package/dist/runtime/run-queue.js +7 -4
- package/dist/runtime/run-steps.d.ts +4 -1
- package/dist/runtime/run-steps.js +9 -2
- package/dist/runtime/run-worker.js +4 -2
- package/dist/runtime/runtime.module.js +3 -0
- package/dist/sandbox/device-sandbox.d.ts +12 -0
- package/dist/sandbox/device-sandbox.js +2 -0
- package/dist/sandbox/device-services.d.ts +42 -2
- package/dist/sandbox/device-services.js +74 -14
- package/dist/sandbox/loopback-expiry.job.d.ts +21 -0
- package/dist/sandbox/loopback-expiry.job.js +50 -0
- package/dist/sandbox/loopback-grant-records.d.ts +143 -0
- package/dist/sandbox/loopback-grant-records.js +239 -0
- package/dist/sandbox/loopback-grants.d.ts +119 -0
- package/dist/sandbox/loopback-grants.js +454 -0
- package/dist/sandbox/loopback-live-ports.d.ts +12 -0
- package/dist/sandbox/loopback-live-ports.js +43 -0
- package/dist/sandbox/permission-call-types.d.ts +3 -2
- package/dist/sandbox/permission-ceiling-writes.js +13 -1
- package/dist/sandbox/permission-facts.d.ts +4 -0
- package/dist/sandbox/permission-facts.js +4 -0
- package/dist/sandbox/review/classifier.d.ts +26 -4
- package/dist/sandbox/review/classifier.js +31 -4
- package/dist/sandbox/review/index.d.ts +3 -3
- package/dist/sandbox/review/index.js +2 -2
- package/dist/sandbox/review/permission-candidate.d.ts +5 -4
- package/dist/sandbox/review/permission-candidate.js +6 -5
- package/dist/sandbox/review/review.service.d.ts +69 -0
- package/dist/sandbox/review/review.service.js +117 -0
- package/dist/sandbox/sandbox.module.d.ts +1 -1
- package/dist/sandbox/sandbox.module.js +13 -2
- package/dist/tools/approvals.service.d.ts +82 -6
- package/dist/tools/approvals.service.js +233 -11
- package/dist/tools/call-scope.d.ts +9 -1
- package/dist/tools/loopback-asks.d.ts +52 -0
- package/dist/tools/loopback-asks.js +70 -0
- package/dist/tools/network-asks.d.ts +2 -1
- package/dist/tools/network-asks.js +10 -5
- package/dist/tools/pipeline.d.ts +59 -3
- package/dist/tools/pipeline.js +403 -40
- package/dist/tools/tools.module.js +3 -0
- package/package.json +2 -2
- package/src/migrations/0199_device_loopback_grants.sql +59 -0
- package/src/migrations/0200_runs_idle_mode.sql +4 -0
package/dist/runtime/idle-arm.js
CHANGED
|
@@ -12,9 +12,11 @@ import { AccountsService } from "../identity/accounts.js";
|
|
|
12
12
|
import { COMPACTION_SETTINGS } from "../identity/settings.js";
|
|
13
13
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
14
14
|
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
15
|
+
import { ModelPurposesService } from "../models/purposes.js";
|
|
16
|
+
import { chooseSummarizer, compactionModelPort, } from "./compaction-model.js";
|
|
15
17
|
import { CompactionSettingsService } from "./compaction-settings.service.js";
|
|
16
18
|
import { deriveCacheExpiry } from "./context/cache-expiry.js";
|
|
17
|
-
import { idleArmDecision, } from "./context/idle-compaction-rules.js";
|
|
19
|
+
import { idleArmDecision, idleMinTokens, } from "./context/idle-compaction-rules.js";
|
|
18
20
|
import { inContextSummaryAllowed, unansweredAfterReply } from "./context/in-context-compaction.js";
|
|
19
21
|
import { ProviderRegistry } from "./providers.js";
|
|
20
22
|
/**
|
|
@@ -28,6 +30,8 @@ const PASSING = {
|
|
|
28
30
|
automationRunId: null,
|
|
29
31
|
outcome: "completed",
|
|
30
32
|
settings: COMPACTION_SETTINGS.parse({}),
|
|
33
|
+
mode: "cache",
|
|
34
|
+
now: 0,
|
|
31
35
|
personalOff: false,
|
|
32
36
|
expiry: {
|
|
33
37
|
callSeq: 0,
|
|
@@ -71,7 +75,12 @@ const modelKey = (provider, model) => `${provider}\u0000${model}`;
|
|
|
71
75
|
* The arm decision of idle compaction at a chat run's finish (idle compaction spec §4.2, S4–S7):
|
|
72
76
|
* gathers {@link IdleArmFacts} and asks {@link idleArmDecision} whether the run's terminal
|
|
73
77
|
* transaction owes an `idle-compaction` job. The run worker calls it before `RunFinish.finish`,
|
|
74
|
-
* outside any transaction (the model registry may list a provider's
|
|
78
|
+
* outside any transaction (the model registry and the `compaction` purpose may list a provider's
|
|
79
|
+
* models over the network).
|
|
80
|
+
*
|
|
81
|
+
* The job's mode (compaction model spec §6.1, §6.2): `compaction_model` when the summarizer a
|
|
82
|
+
* compaction would choose now against the last step call's model is the compaction model (usable
|
|
83
|
+
* and eligible, the same `chooseSummarizer` the compaction runs), else `cache`.
|
|
75
84
|
*/
|
|
76
85
|
let IdleArm = class IdleArm {
|
|
77
86
|
kdb;
|
|
@@ -79,12 +88,15 @@ let IdleArm = class IdleArm {
|
|
|
79
88
|
accounts;
|
|
80
89
|
models;
|
|
81
90
|
log;
|
|
82
|
-
|
|
91
|
+
/** The org's `compaction` purpose, read from PG on every decision (nothing cached). */
|
|
92
|
+
compactionModel;
|
|
93
|
+
constructor(kdb, compaction, accounts, models, purposes, log) {
|
|
83
94
|
this.kdb = kdb;
|
|
84
95
|
this.compaction = compaction;
|
|
85
96
|
this.accounts = accounts;
|
|
86
97
|
this.models = models;
|
|
87
98
|
this.log = log;
|
|
99
|
+
this.compactionModel = compactionModelPort(purposes);
|
|
88
100
|
}
|
|
89
101
|
/**
|
|
90
102
|
* The intent `RunFinish.finishIn` owes the job from, or undefined when the run does not arm.
|
|
@@ -144,7 +156,8 @@ let IdleArm = class IdleArm {
|
|
|
144
156
|
reason = failing();
|
|
145
157
|
if (reason !== undefined)
|
|
146
158
|
return skip(reason);
|
|
147
|
-
|
|
159
|
+
const settings = await this.compaction.resolve(conv.org_id);
|
|
160
|
+
known.settings = settings;
|
|
148
161
|
reason = failing();
|
|
149
162
|
if (reason !== undefined)
|
|
150
163
|
return skip(reason);
|
|
@@ -162,23 +175,44 @@ let IdleArm = class IdleArm {
|
|
|
162
175
|
.where("type", "in", ["model_call", "usage"])
|
|
163
176
|
.orderBy("seq")
|
|
164
177
|
.execute()).map(toEvent);
|
|
165
|
-
const
|
|
178
|
+
const resolved = new Map();
|
|
166
179
|
for (const e of calls) {
|
|
167
180
|
if (e.type !== "model_call")
|
|
168
181
|
continue;
|
|
169
182
|
const key = modelKey(e.payload.provider, e.payload.model);
|
|
170
|
-
if (
|
|
183
|
+
if (resolved.has(key))
|
|
171
184
|
continue;
|
|
172
|
-
|
|
185
|
+
resolved.set(key, await this.models.resolve(conv.org_id, {
|
|
173
186
|
provider: e.payload.provider,
|
|
174
187
|
model: e.payload.model,
|
|
175
|
-
});
|
|
176
|
-
infos.set(key, info);
|
|
188
|
+
}));
|
|
177
189
|
}
|
|
178
|
-
const infoOf = (provider, model) =>
|
|
179
|
-
known.expiry = deriveCacheExpiry(calls, (p, m) => infoOf(p, m)?.cache);
|
|
190
|
+
const infoOf = (provider, model) => resolved.get(modelKey(provider, model))?.info;
|
|
180
191
|
const last = lastStepCall(calls);
|
|
181
|
-
const
|
|
192
|
+
const lastModel = last && resolved.get(modelKey(last.call.payload.provider, last.call.payload.model));
|
|
193
|
+
const lastInfo = lastModel?.info;
|
|
194
|
+
// a context under the size floor arms in neither mode: skip before the purpose read (and the
|
|
195
|
+
// summarizer choice's fallback warnings) a small finish would otherwise pay every time
|
|
196
|
+
if (last !== undefined && lastInfo !== undefined) {
|
|
197
|
+
const u = last.usage.payload;
|
|
198
|
+
const total = u.inputTokens + u.cacheReadTokens + u.cacheWriteTokens + u.outputTokens;
|
|
199
|
+
if (total < idleMinTokens(lastInfo.contextWindow, settings))
|
|
200
|
+
return skip("small");
|
|
201
|
+
}
|
|
202
|
+
// compaction model spec §6.1, C2: the mode is the summarizer a compaction would choose now,
|
|
203
|
+
// V = the last step call's model under the effective settings; a failed purpose read throws
|
|
204
|
+
// (no job, logged by `decide`)
|
|
205
|
+
if (last !== undefined && lastModel !== undefined) {
|
|
206
|
+
const { summarizer } = await chooseSummarizer({ compactionModel: this.compactionModel, registry: this.models, log: this.log }, conv.org_id, {
|
|
207
|
+
ref: { provider: last.call.payload.provider, model: last.call.payload.model },
|
|
208
|
+
provider: lastModel.provider,
|
|
209
|
+
info: lastModel.info,
|
|
210
|
+
}, settings);
|
|
211
|
+
known.mode = summarizer.source === "compaction_model" ? "compaction_model" : "cache";
|
|
212
|
+
}
|
|
213
|
+
// C4: the run's end is not written yet; the terminal transaction follows within milliseconds
|
|
214
|
+
known.now = Date.now();
|
|
215
|
+
known.expiry = deriveCacheExpiry(calls, (p, m) => infoOf(p, m)?.cache);
|
|
182
216
|
known.lastCall =
|
|
183
217
|
last && lastInfo
|
|
184
218
|
? {
|
|
@@ -195,6 +229,8 @@ let IdleArm = class IdleArm {
|
|
|
195
229
|
if (reason !== undefined || last === undefined || lastInfo === undefined) {
|
|
196
230
|
return skip(reason ?? "no_cache");
|
|
197
231
|
}
|
|
232
|
+
if (known.mode === "compaction_model")
|
|
233
|
+
return this.armed(runId, conv, known);
|
|
198
234
|
// S7: the in-context quality gate (ruling R8) and the settled point (ruling R9)
|
|
199
235
|
known.inContextAllowed = inContextSummaryAllowed(last.call.payload.provider, lastInfo.id);
|
|
200
236
|
// a fit plan reshaped the last request's prefix: the fire-time in-context build skips it
|
|
@@ -217,18 +253,29 @@ let IdleArm = class IdleArm {
|
|
|
217
253
|
absorbedUpToSeq: Number.POSITIVE_INFINITY,
|
|
218
254
|
openers: [],
|
|
219
255
|
});
|
|
256
|
+
return this.armed(runId, conv, known);
|
|
257
|
+
}
|
|
258
|
+
/** The final decision over every fact gathered: the intent, or undefined with the skip logged. */
|
|
259
|
+
armed(runId, conv, known) {
|
|
220
260
|
const d = idleArmDecision({ ...PASSING, ...known });
|
|
221
|
-
|
|
222
|
-
|
|
261
|
+
const fields = { context: "IdleCompaction", conversationId: conv.id, runId };
|
|
262
|
+
if (!d.arm) {
|
|
263
|
+
this.log.debug("idle compaction not armed", { ...fields, reason: d.reason });
|
|
264
|
+
return undefined;
|
|
265
|
+
}
|
|
266
|
+
if (d.mode === "compaction_model") {
|
|
267
|
+
this.log.debug("idle compaction armed", { ...fields, mode: d.mode, runAt: d.runAt });
|
|
268
|
+
return { orgId: conv.org_id, mode: "compaction_model", runAt: d.runAt };
|
|
269
|
+
}
|
|
223
270
|
this.log.debug("idle compaction armed", {
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
runId,
|
|
271
|
+
...fields,
|
|
272
|
+
mode: d.mode,
|
|
227
273
|
runAt: d.runAt,
|
|
228
274
|
expiresAt: d.expiresAt,
|
|
229
275
|
});
|
|
230
276
|
return {
|
|
231
277
|
orgId: conv.org_id,
|
|
278
|
+
mode: "cache",
|
|
232
279
|
cacheCallSeq: d.cacheCallSeq,
|
|
233
280
|
expiresAt: d.expiresAt,
|
|
234
281
|
runAt: d.runAt,
|
|
@@ -241,7 +288,8 @@ IdleArm = __decorate([
|
|
|
241
288
|
__param(1, Inject(CompactionSettingsService)),
|
|
242
289
|
__param(2, Inject(AccountsService)),
|
|
243
290
|
__param(3, Inject(ProviderRegistry)),
|
|
244
|
-
__param(4, Inject(
|
|
291
|
+
__param(4, Inject(ModelPurposesService)),
|
|
292
|
+
__param(5, Inject(KERNEL_LOGGER))
|
|
245
293
|
], IdleArm);
|
|
246
294
|
export { IdleArm };
|
|
247
295
|
/**
|
|
@@ -8,18 +8,39 @@ import type { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
|
8
8
|
export declare const IDLE_COMPACTION_JOB = "idle-compaction";
|
|
9
9
|
/** One job per arming run (no `:`): a duplicate owe of the same run is a no-op. */
|
|
10
10
|
export declare const idleCompactionJobId: (runId: string) => string;
|
|
11
|
-
/**
|
|
12
|
-
|
|
11
|
+
/** What every `idle-compaction` job carries. */
|
|
12
|
+
interface IdleCompactionJobBase {
|
|
13
13
|
orgId: string;
|
|
14
14
|
conversationId: string;
|
|
15
15
|
/** The run that armed the job. */
|
|
16
16
|
runId: string;
|
|
17
17
|
/** The seq of that run's terminal `run_finished` event (S4). */
|
|
18
18
|
armedSeq: number;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The `idle-compaction` job's data, by how the job compacts (compaction model spec §6.2): in the
|
|
22
|
+
* armed prompt cache (`cache`, with the call the expiry was derived from and the expiry), or on the
|
|
23
|
+
* compaction model (`compaction_model`, due `idleDelayMinutes` after the run, no expiry). A row
|
|
24
|
+
* owed by the previous release has no `mode`: readers take `data.mode ?? "cache"` (C5).
|
|
25
|
+
*/
|
|
26
|
+
export type IdleCompactionJobData = (IdleCompactionJobBase & {
|
|
27
|
+
mode: "cache";
|
|
19
28
|
/** The seq of the `model_call` the cache expiry was derived from (`CacheExpiry.callSeq`). */
|
|
20
29
|
cacheCallSeq: number;
|
|
21
30
|
/** When the prompt cache entry expires, epoch ms. */
|
|
22
31
|
expiresAt: number;
|
|
23
|
-
}
|
|
32
|
+
}) | (IdleCompactionJobBase & {
|
|
33
|
+
mode: "compaction_model";
|
|
34
|
+
});
|
|
35
|
+
/**
|
|
36
|
+
* A delivered job's data: {@link IdleCompactionJobData}, or a cache-mode row owed before `mode`
|
|
37
|
+
* existed (still in the outbox or the queue across the deploy, C5).
|
|
38
|
+
*/
|
|
39
|
+
export type IdleCompactionJobInput = IdleCompactionJobData | (Omit<Extract<IdleCompactionJobData, {
|
|
40
|
+
mode: "cache";
|
|
41
|
+
}>, "mode"> & {
|
|
42
|
+
mode?: undefined;
|
|
43
|
+
});
|
|
24
44
|
/** Owes the idle compaction job in the caller's transaction (throws outside one), due at `runAt`. */
|
|
25
45
|
export declare function oweIdleCompaction(outbox: Pick<OutboxService, "add">, data: IdleCompactionJobData, runAt: number): Promise<boolean>;
|
|
46
|
+
export {};
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { AccountsService } from "../identity/accounts.js";
|
|
2
2
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
3
3
|
import type { KernelLogger } from "../log.js";
|
|
4
|
+
import { ModelPurposesService } from "../models/purposes.js";
|
|
4
5
|
import { CompactionService } from "./compaction.service.js";
|
|
5
6
|
import { CompactionSettingsService } from "./compaction-settings.service.js";
|
|
6
7
|
import { type IdleFireOutcome } from "./context/idle-compaction-rules.js";
|
|
7
|
-
import type {
|
|
8
|
+
import type { IdleCompactionJobInput } from "./idle-compaction-jobs.js";
|
|
8
9
|
import { ProviderRegistry } from "./providers.js";
|
|
9
10
|
import { RunQueue } from "./run-queue.js";
|
|
10
11
|
/**
|
|
@@ -15,6 +16,11 @@ import { RunQueue } from "./run-queue.js";
|
|
|
15
16
|
* inside `runJob` with the job's org scope. Holds no state between deliveries: every fact comes
|
|
16
17
|
* from the database and the event log, so a duplicate delivery on another replica sees the first
|
|
17
18
|
* delivery's run (an event after `armedSeq`, or an active run) and ends `obsolete` or `busy`.
|
|
19
|
+
*
|
|
20
|
+
* The job's mode (compaction model spec §6.3): a `compaction_model` job has no expiry (a late
|
|
21
|
+
* delivery still runs), requires the compaction model at fire time (`chooseSummarizer` against the
|
|
22
|
+
* effective definition's model, read from PG on every delivery) and never falls back to the
|
|
23
|
+
* conversation model or to cache mode; the run it starts carries the mode (`runs.idle_mode`).
|
|
18
24
|
*/
|
|
19
25
|
export declare class IdleCompactionJob {
|
|
20
26
|
private readonly kdb;
|
|
@@ -24,13 +30,15 @@ export declare class IdleCompactionJob {
|
|
|
24
30
|
private readonly compactions;
|
|
25
31
|
private readonly runs;
|
|
26
32
|
private readonly log;
|
|
27
|
-
|
|
33
|
+
/** The org's `compaction` purpose, read from PG on every delivery (nothing cached). */
|
|
34
|
+
private readonly compactionModel;
|
|
35
|
+
constructor(kdb: KernelDb, compaction: Pick<CompactionSettingsService, "resolve">, accounts: Pick<AccountsService, "idleCompactionOff">, models: Pick<ProviderRegistry, "resolve">, purposes: Pick<ModelPurposesService, "resolve">, compactions: Pick<CompactionService, "probeIdle">, runs: Pick<RunQueue, "startIdleCompaction">, log: Pick<KernelLogger, "info" | "warn" | "error" | "debug">);
|
|
28
36
|
/**
|
|
29
37
|
* One delivery of `idle-compact-<runId>` (spec §4.3): gathers {@link IdleFireFacts} cheapest
|
|
30
38
|
* first, stopping at the first failing check, decides, and starts the run. Logs one `info` line,
|
|
31
39
|
* context=IdleCompaction. A database failure throws (BullMQ retries the job within its attempts).
|
|
32
40
|
*/
|
|
33
|
-
fire(data:
|
|
41
|
+
fire(data: IdleCompactionJobInput, now?: number): Promise<IdleFireOutcome | "started">;
|
|
34
42
|
private decide;
|
|
35
43
|
/**
|
|
36
44
|
* Check 1's reads: the conversation (live, chat, owned), and its agent when the org is live, the
|
|
@@ -15,7 +15,9 @@ import { AccountsService } from "../identity/accounts.js";
|
|
|
15
15
|
import { COMPACTION_SETTINGS } from "../identity/settings.js";
|
|
16
16
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
17
17
|
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
18
|
+
import { ModelPurposesService } from "../models/purposes.js";
|
|
18
19
|
import { CompactionService } from "./compaction.service.js";
|
|
20
|
+
import { chooseSummarizer, compactionModelPort, } from "./compaction-model.js";
|
|
19
21
|
import { CompactionSettingsService } from "./compaction-settings.service.js";
|
|
20
22
|
import { CACHE_EXPIRY_MARGIN_MS, CACHE_FIRE_RATIO } from "./context/cache-expiry.js";
|
|
21
23
|
import { idleFireDecision, } from "./context/idle-compaction-rules.js";
|
|
@@ -38,7 +40,8 @@ const PASSING = {
|
|
|
38
40
|
now: 0,
|
|
39
41
|
expiresAt: Number.POSITIVE_INFINITY,
|
|
40
42
|
backoff: false,
|
|
41
|
-
|
|
43
|
+
mode: "cache",
|
|
44
|
+
modelReady: true,
|
|
42
45
|
probe: {
|
|
43
46
|
estimate: Number.POSITIVE_INFINITY,
|
|
44
47
|
window: 0,
|
|
@@ -56,6 +59,11 @@ const PASSING = {
|
|
|
56
59
|
* inside `runJob` with the job's org scope. Holds no state between deliveries: every fact comes
|
|
57
60
|
* from the database and the event log, so a duplicate delivery on another replica sees the first
|
|
58
61
|
* delivery's run (an event after `armedSeq`, or an active run) and ends `obsolete` or `busy`.
|
|
62
|
+
*
|
|
63
|
+
* The job's mode (compaction model spec §6.3): a `compaction_model` job has no expiry (a late
|
|
64
|
+
* delivery still runs), requires the compaction model at fire time (`chooseSummarizer` against the
|
|
65
|
+
* effective definition's model, read from PG on every delivery) and never falls back to the
|
|
66
|
+
* conversation model or to cache mode; the run it starts carries the mode (`runs.idle_mode`).
|
|
59
67
|
*/
|
|
60
68
|
let IdleCompactionJob = class IdleCompactionJob {
|
|
61
69
|
kdb;
|
|
@@ -65,7 +73,9 @@ let IdleCompactionJob = class IdleCompactionJob {
|
|
|
65
73
|
compactions;
|
|
66
74
|
runs;
|
|
67
75
|
log;
|
|
68
|
-
|
|
76
|
+
/** The org's `compaction` purpose, read from PG on every delivery (nothing cached). */
|
|
77
|
+
compactionModel;
|
|
78
|
+
constructor(kdb, compaction, accounts, models, purposes, compactions, runs, log) {
|
|
69
79
|
this.kdb = kdb;
|
|
70
80
|
this.compaction = compaction;
|
|
71
81
|
this.accounts = accounts;
|
|
@@ -73,6 +83,7 @@ let IdleCompactionJob = class IdleCompactionJob {
|
|
|
73
83
|
this.compactions = compactions;
|
|
74
84
|
this.runs = runs;
|
|
75
85
|
this.log = log;
|
|
86
|
+
this.compactionModel = compactionModelPort(purposes);
|
|
76
87
|
}
|
|
77
88
|
/**
|
|
78
89
|
* One delivery of `idle-compact-<runId>` (spec §4.3): gathers {@link IdleFireFacts} cheapest
|
|
@@ -80,7 +91,8 @@ let IdleCompactionJob = class IdleCompactionJob {
|
|
|
80
91
|
* context=IdleCompaction. A database failure throws (BullMQ retries the job within its attempts).
|
|
81
92
|
*/
|
|
82
93
|
async fire(data, now = Date.now()) {
|
|
83
|
-
|
|
94
|
+
// a row owed before `mode` existed is a cache-mode job (compaction model spec §6.3, C5)
|
|
95
|
+
const extra = { mode: data.mode ?? "cache" };
|
|
84
96
|
const outcome = await this.decide(data, now, extra);
|
|
85
97
|
this.log.info("idle compaction job", {
|
|
86
98
|
context: "IdleCompaction",
|
|
@@ -96,27 +108,31 @@ let IdleCompactionJob = class IdleCompactionJob {
|
|
|
96
108
|
async decide(data, now, extra) {
|
|
97
109
|
const t = this.kdb.db;
|
|
98
110
|
const { orgId, conversationId, armedSeq } = data;
|
|
99
|
-
|
|
111
|
+
// a row owed before `mode` existed is a cache-mode job (compaction model spec §6.3, C5)
|
|
112
|
+
const cache = data.mode === "compaction_model" ? undefined : data;
|
|
113
|
+
const mode = cache === undefined ? "compaction_model" : "cache";
|
|
114
|
+
const known = { mode };
|
|
100
115
|
const failing = () => {
|
|
101
116
|
const d = idleFireDecision({ ...PASSING, ...known });
|
|
102
117
|
return d.fire ? undefined : d.outcome;
|
|
103
118
|
};
|
|
104
|
-
// the armed call
|
|
105
|
-
const call =
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
119
|
+
// cache mode: the armed call, its lifetime (for the log) and its model (check 7)
|
|
120
|
+
const call = cache &&
|
|
121
|
+
(await t
|
|
122
|
+
.selectFrom("conversation_events")
|
|
123
|
+
.select("payload")
|
|
124
|
+
.where("conversation_id", "=", conversationId)
|
|
125
|
+
.where("seq", "=", String(cache.cacheCallSeq))
|
|
126
|
+
.where("type", "=", "model_call")
|
|
127
|
+
.executeTakeFirst());
|
|
112
128
|
const armed = call?.payload;
|
|
113
129
|
const lifetime = (ttl) => {
|
|
114
|
-
if (ttl === undefined || extra.ttl !== undefined)
|
|
130
|
+
if (cache === undefined || ttl === undefined || extra.ttl !== undefined)
|
|
115
131
|
return;
|
|
116
132
|
extra.ttl = ttl;
|
|
117
133
|
// the arm decision's fire time, `min(t0 + 0.9 L, expiresAt - 30 s)` with t0 = expiresAt - L
|
|
118
|
-
const t0 =
|
|
119
|
-
const runAt = Math.min(t0 + CACHE_FIRE_RATIO * ttl * 1000,
|
|
134
|
+
const t0 = cache.expiresAt - ttl * 1000;
|
|
135
|
+
const runAt = Math.min(t0 + CACHE_FIRE_RATIO * ttl * 1000, cache.expiresAt - CACHE_EXPIRY_MARGIN_MS);
|
|
120
136
|
extra.lateMs = now - runAt;
|
|
121
137
|
};
|
|
122
138
|
lifetime(armed?.request?.cacheTtl);
|
|
@@ -171,9 +187,10 @@ let IdleCompactionJob = class IdleCompactionJob {
|
|
|
171
187
|
outcome = failing();
|
|
172
188
|
if (outcome !== undefined)
|
|
173
189
|
return outcome;
|
|
174
|
-
// check 5 needs no read: the job's time against the armed call's expiry
|
|
190
|
+
// check 5 (cache mode only) needs no read: the job's time against the armed call's expiry
|
|
175
191
|
known.now = now;
|
|
176
|
-
|
|
192
|
+
if (cache)
|
|
193
|
+
known.expiresAt = cache.expiresAt;
|
|
177
194
|
outcome = failing();
|
|
178
195
|
if (outcome !== undefined)
|
|
179
196
|
return outcome;
|
|
@@ -191,7 +208,9 @@ let IdleCompactionJob = class IdleCompactionJob {
|
|
|
191
208
|
if (outcome !== undefined)
|
|
192
209
|
return outcome;
|
|
193
210
|
// check 7: the effective definition (the agent's current version under the conversation's
|
|
194
|
-
// model selection, what the idle run will use) resolves
|
|
211
|
+
// model selection, what the idle run will use) resolves and is enabled; in cache mode it is the
|
|
212
|
+
// armed call's model, in compaction-model mode the compaction model summarizes for it (C6: a
|
|
213
|
+
// model switch since arming does not end the job, the probe sizes against the new model)
|
|
195
214
|
const version = await t
|
|
196
215
|
.selectFrom("agent_versions")
|
|
197
216
|
.select("definition")
|
|
@@ -200,12 +219,11 @@ let IdleCompactionJob = class IdleCompactionJob {
|
|
|
200
219
|
.executeTakeFirst();
|
|
201
220
|
const definition = version &&
|
|
202
221
|
effectiveDefinition(normalizeStoredDefinition(version.definition), await readSelection(t, conversationId));
|
|
203
|
-
let
|
|
204
|
-
if (definition && armed && sameModel(definition.model, armed)) {
|
|
222
|
+
let ready = false;
|
|
223
|
+
if (definition && (cache === undefined || (armed && sameModel(definition.model, armed)))) {
|
|
224
|
+
let model;
|
|
205
225
|
try {
|
|
206
|
-
|
|
207
|
-
lifetime(info.cache?.defaultTtl);
|
|
208
|
-
resolved = true;
|
|
226
|
+
model = await this.models.resolve(orgId, definition.model);
|
|
209
227
|
}
|
|
210
228
|
catch (err) {
|
|
211
229
|
// unknown, disabled, or a provider list that failed: no model to compact with now
|
|
@@ -216,12 +234,24 @@ let IdleCompactionJob = class IdleCompactionJob {
|
|
|
216
234
|
err,
|
|
217
235
|
});
|
|
218
236
|
}
|
|
237
|
+
if (model && cache) {
|
|
238
|
+
lifetime(model.info.cache?.defaultTtl);
|
|
239
|
+
ready = true;
|
|
240
|
+
}
|
|
241
|
+
else if (model) {
|
|
242
|
+
// the same choice the idle run makes; a cleared, disabled, unavailable or too small
|
|
243
|
+
// compaction model ends the job (never V, never cache mode); a failed purpose read throws
|
|
244
|
+
const { summarizer } = await chooseSummarizer({ compactionModel: this.compactionModel, registry: this.models, log: this.log }, orgId, { ref: definition.model, provider: model.provider, info: model.info }, settings);
|
|
245
|
+
ready = summarizer.source === "compaction_model";
|
|
246
|
+
}
|
|
219
247
|
}
|
|
220
|
-
known.
|
|
248
|
+
known.modelReady = ready;
|
|
221
249
|
outcome = failing();
|
|
222
250
|
if (outcome !== undefined || !definition)
|
|
223
251
|
return outcome ?? "no_model";
|
|
224
|
-
// checks 8 and 9 (S13): the compaction's dry run (reads every event and the
|
|
252
|
+
// checks 8 and 9 (S13): the compaction's dry run in the job's mode (reads every event and the
|
|
253
|
+
// media: last); in compaction-model mode a null probe (C gone since check 7) is `small`, and
|
|
254
|
+
// in cache mode a compaction model mapped since arming reports no in-context build (C3)
|
|
225
255
|
const probe = await this.compactions.probeIdle({
|
|
226
256
|
orgId,
|
|
227
257
|
conversationId,
|
|
@@ -231,7 +261,7 @@ let IdleCompactionJob = class IdleCompactionJob {
|
|
|
231
261
|
source: conv.source,
|
|
232
262
|
conversationKind: "chat",
|
|
233
263
|
absorbedUpToSeq: Number(conv.consumed_seq),
|
|
234
|
-
});
|
|
264
|
+
}, mode);
|
|
235
265
|
// an unavailable model or storage during the dry run: nothing to compact with now
|
|
236
266
|
known.probe = probe;
|
|
237
267
|
known.inContext = probe?.inContext ?? false;
|
|
@@ -242,7 +272,7 @@ let IdleCompactionJob = class IdleCompactionJob {
|
|
|
242
272
|
return outcome;
|
|
243
273
|
// §5.1: the run, under the conversation row lock (checks 1-3 again); a refusal is a message,
|
|
244
274
|
// a run or a queued message that arrived in between
|
|
245
|
-
const idleRunId = await this.runs.startIdleCompaction(conversationId, armedSeq);
|
|
275
|
+
const idleRunId = await this.runs.startIdleCompaction(conversationId, armedSeq, mode);
|
|
246
276
|
if (idleRunId === null) {
|
|
247
277
|
// label the refusal by the first check it now fails (the order of checks 1-3)
|
|
248
278
|
if ((await this.readLive(orgId, conversationId)).agent === undefined)
|
|
@@ -309,8 +339,9 @@ IdleCompactionJob = __decorate([
|
|
|
309
339
|
__param(1, Inject(CompactionSettingsService)),
|
|
310
340
|
__param(2, Inject(AccountsService)),
|
|
311
341
|
__param(3, Inject(ProviderRegistry)),
|
|
312
|
-
__param(4, Inject(
|
|
313
|
-
__param(5, Inject(
|
|
314
|
-
__param(6, Inject(
|
|
342
|
+
__param(4, Inject(ModelPurposesService)),
|
|
343
|
+
__param(5, Inject(CompactionService)),
|
|
344
|
+
__param(6, Inject(RunQueue)),
|
|
345
|
+
__param(7, Inject(KERNEL_LOGGER))
|
|
315
346
|
], IdleCompactionJob);
|
|
316
347
|
export { IdleCompactionJob };
|
|
@@ -13,6 +13,7 @@ import type { KernelLogger } from "../log.js";
|
|
|
13
13
|
import { DirectorySync } from "../orgs/directory-sync.js";
|
|
14
14
|
import { Offboarding } from "../orgs/offboarding.js";
|
|
15
15
|
import { CloudPermissionSnapshots } from "../sandbox/cloud-permission-snapshot.js";
|
|
16
|
+
import { LoopbackGrants } from "../sandbox/loopback-grants.js";
|
|
16
17
|
import { SandboxOperationReconcileJob } from "../sandbox/operation-reconcile.job.js";
|
|
17
18
|
import { SandboxService } from "../sandbox/sandbox.service.js";
|
|
18
19
|
import { ShareObjects } from "../shares/share-objects.js";
|
|
@@ -37,7 +38,7 @@ export declare const MAINTENANCE_CONCURRENCY = 5;
|
|
|
37
38
|
* {@link BlobObjects}, `file-library-hash`, `file-library-hash-org` → {@link FileLibraryHashJob},
|
|
38
39
|
* `file-library-backfill` → {@link FileLibraryBackfill}, `platform-icon-delete` →
|
|
39
40
|
* {@link PlatformIconObjects}, `device-conversation-notice` → {@link ConversationNoticeDelivery},
|
|
40
|
-
* `idle-compaction` → {@link IdleCompactionJob}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
|
|
41
|
+
* `idle-compaction` → {@link IdleCompactionJob}, `device-loopback-refresh` → {@link LoopbackGrants}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
|
|
41
42
|
* such as `sandbox-suspend-idle`) runs that job's body once ({@link ScheduledRuns.runNow}), as the
|
|
42
43
|
* maintenance handlers did when those jobs were schedulers on this queue: an operator's or a
|
|
43
44
|
* test's one-off run, not a second schedule (decision R23 of the Nest kernel spec). Any other
|
|
@@ -66,8 +67,9 @@ export declare class MaintenanceProcessor extends WorkerHost<Worker> {
|
|
|
66
67
|
private readonly triggers;
|
|
67
68
|
private readonly coalescer;
|
|
68
69
|
private readonly idleCompaction;
|
|
70
|
+
private readonly loopback;
|
|
69
71
|
private readonly snapshots?;
|
|
70
|
-
constructor(permissionApprovals: Pick<PermissionApprovalJobs, "recheck">, waits: Pick<Waits, "processTimeout" | "childFinished" | "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, sandbox: Pick<SandboxService, "destroyDevice" | "resetFileSystem" | "revokeDeadHolder">, drift: Pick<ToolDrift, "check">, directory: Pick<DirectorySync, "runSyncJob">, deletion: Pick<RunDeletion, "stopOrg" | "stopTree">, offboarding: Pick<Offboarding, "stopRun">, runs: Pick<RunQueue, "ensureRun">, ownedCleanup: Pick<OwnedPluginCleanup, "run">, automations: Pick<AutomationFirer, "fire" | "settle">, scheduled: Pick<ScheduledRuns, "runNow">, log: Pick<KernelLogger, "error" | "warn">, operations: Pick<SandboxOperationReconcileJob, "reconcile" | "revoke">, shareObjects: Pick<ShareObjects, "deleteObject">, blobObjects: Pick<BlobObjects, "deleteBlob" | "deleteStaging" | "releaseFile">, hashing: Pick<FileLibraryHashJob, "dispatch" | "runOrgBatch">, backfill: Pick<FileLibraryBackfill, "run">, platformIcons: Pick<PlatformIconObjects, "deleteObject">, notices: Pick<ConversationNoticeDelivery, "attempt">, triggers: Pick<TriggerDispatcher, "dispatch">, coalescer: Pick<EventCoalescer, "flush">, idleCompaction: Pick<IdleCompactionJob, "fire">, snapshots?: Pick<CloudPermissionSnapshots, "reconcileDevice"> | undefined);
|
|
72
|
+
constructor(permissionApprovals: Pick<PermissionApprovalJobs, "recheck">, waits: Pick<Waits, "processTimeout" | "childFinished" | "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, sandbox: Pick<SandboxService, "destroyDevice" | "resetFileSystem" | "revokeDeadHolder">, drift: Pick<ToolDrift, "check">, directory: Pick<DirectorySync, "runSyncJob">, deletion: Pick<RunDeletion, "stopOrg" | "stopTree">, offboarding: Pick<Offboarding, "stopRun">, runs: Pick<RunQueue, "ensureRun">, ownedCleanup: Pick<OwnedPluginCleanup, "run">, automations: Pick<AutomationFirer, "fire" | "settle">, scheduled: Pick<ScheduledRuns, "runNow">, log: Pick<KernelLogger, "error" | "warn">, operations: Pick<SandboxOperationReconcileJob, "reconcile" | "revoke">, shareObjects: Pick<ShareObjects, "deleteObject">, blobObjects: Pick<BlobObjects, "deleteBlob" | "deleteStaging" | "releaseFile">, hashing: Pick<FileLibraryHashJob, "dispatch" | "runOrgBatch">, backfill: Pick<FileLibraryBackfill, "run">, platformIcons: Pick<PlatformIconObjects, "deleteObject">, notices: Pick<ConversationNoticeDelivery, "attempt">, triggers: Pick<TriggerDispatcher, "dispatch">, coalescer: Pick<EventCoalescer, "flush">, idleCompaction: Pick<IdleCompactionJob, "fire">, loopback: Pick<LoopbackGrants, "refresh">, snapshots?: Pick<CloudPermissionSnapshots, "reconcileDevice"> | undefined);
|
|
71
73
|
process(job: Job, token?: string): Promise<void>;
|
|
72
74
|
/** Starts consuming (worker role, after the extensions loaded; built with `autorun: false`). */
|
|
73
75
|
start(): void;
|
|
@@ -35,6 +35,8 @@ import { Offboarding, RUN_STOP_JOB } from "../orgs/offboarding.js";
|
|
|
35
35
|
import { OrgsModule } from "../orgs/orgs.module.js";
|
|
36
36
|
import { CloudPermissionSnapshots } from "../sandbox/cloud-permission-snapshot.js";
|
|
37
37
|
import { runSandboxDestroyFor, runSandboxResetFiles, SANDBOX_DESTROY_FOR_JOB, SANDBOX_RESET_FILES_JOB, } from "../sandbox/jobs.js";
|
|
38
|
+
import { LOOPBACK_REFRESH_JOB, LOOPBACK_REFRESH_TIMEOUT_MS, } from "../sandbox/loopback-grant-records.js";
|
|
39
|
+
import { LoopbackGrants } from "../sandbox/loopback-grants.js";
|
|
38
40
|
import { HOLDER_REVOKE, OPERATION_RECONCILE, OPERATION_REVOKE, } from "../sandbox/operation-intents.js";
|
|
39
41
|
import { SandboxOperationReconcileJob } from "../sandbox/operation-reconcile.job.js";
|
|
40
42
|
import { PERMISSION_APPROVAL_RECHECK } from "../sandbox/permission-transitions.js";
|
|
@@ -68,7 +70,7 @@ export const MAINTENANCE_CONCURRENCY = 5;
|
|
|
68
70
|
* {@link BlobObjects}, `file-library-hash`, `file-library-hash-org` → {@link FileLibraryHashJob},
|
|
69
71
|
* `file-library-backfill` → {@link FileLibraryBackfill}, `platform-icon-delete` →
|
|
70
72
|
* {@link PlatformIconObjects}, `device-conversation-notice` → {@link ConversationNoticeDelivery},
|
|
71
|
-
* `idle-compaction` → {@link IdleCompactionJob}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
|
|
73
|
+
* `idle-compaction` → {@link IdleCompactionJob}, `device-loopback-refresh` → {@link LoopbackGrants}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
|
|
72
74
|
* such as `sandbox-suspend-idle`) runs that job's body once ({@link ScheduledRuns.runNow}), as the
|
|
73
75
|
* maintenance handlers did when those jobs were schedulers on this queue: an operator's or a
|
|
74
76
|
* test's one-off run, not a second schedule (decision R23 of the Nest kernel spec). Any other
|
|
@@ -97,8 +99,9 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
97
99
|
triggers;
|
|
98
100
|
coalescer;
|
|
99
101
|
idleCompaction;
|
|
102
|
+
loopback;
|
|
100
103
|
snapshots;
|
|
101
|
-
constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, ownedCleanup, automations, scheduled, log, operations, shareObjects, blobObjects, hashing, backfill, platformIcons, notices, triggers, coalescer, idleCompaction, snapshots) {
|
|
104
|
+
constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, ownedCleanup, automations, scheduled, log, operations, shareObjects, blobObjects, hashing, backfill, platformIcons, notices, triggers, coalescer, idleCompaction, loopback, snapshots) {
|
|
102
105
|
super();
|
|
103
106
|
this.permissionApprovals = permissionApprovals;
|
|
104
107
|
this.waits = waits;
|
|
@@ -122,6 +125,7 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
122
125
|
this.triggers = triggers;
|
|
123
126
|
this.coalescer = coalescer;
|
|
124
127
|
this.idleCompaction = idleCompaction;
|
|
128
|
+
this.loopback = loopback;
|
|
125
129
|
this.snapshots = snapshots;
|
|
126
130
|
}
|
|
127
131
|
process(job, token) {
|
|
@@ -265,6 +269,11 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
265
269
|
await this.notices.attempt(orgId, noticeId, { timeoutMs: NOTICE_PROMPT_TIMEOUT_MS });
|
|
266
270
|
return;
|
|
267
271
|
}
|
|
272
|
+
// a service's live loopback port set sent to it, after revoking what the device now
|
|
273
|
+
// refuses (browser loopback port grants design §4)
|
|
274
|
+
case LOOPBACK_REFRESH_JOB:
|
|
275
|
+
await this.loopback.refresh(job.data, AbortSignal.timeout(LOOPBACK_REFRESH_TIMEOUT_MS));
|
|
276
|
+
return;
|
|
268
277
|
// a large idle conversation's compaction before its prompt cache expires (idle compaction §4.3)
|
|
269
278
|
case IDLE_COMPACTION_JOB:
|
|
270
279
|
await this.idleCompaction.fire(job.data);
|
|
@@ -315,8 +324,9 @@ MaintenanceProcessor = __decorate([
|
|
|
315
324
|
__param(19, Inject(TriggerDispatcher)),
|
|
316
325
|
__param(20, Inject(EventCoalescer)),
|
|
317
326
|
__param(21, Inject(IdleCompactionJob)),
|
|
318
|
-
__param(22,
|
|
319
|
-
__param(
|
|
327
|
+
__param(22, Inject(LoopbackGrants)),
|
|
328
|
+
__param(23, Optional()),
|
|
329
|
+
__param(23, Inject(CloudPermissionSnapshots))
|
|
320
330
|
], MaintenanceProcessor);
|
|
321
331
|
export { MaintenanceProcessor };
|
|
322
332
|
/**
|