@capybara-hq/kernel 0.1.0-rc.34 → 0.1.0-rc.35
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/outbox-dead.service.d.ts +2 -0
- package/dist/admin/outbox-dead.service.js +34 -0
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/conversations/conversations.service.d.ts +3 -3
- package/dist/conversations/conversations.service.js +58 -29
- package/dist/db/kernel-schema.d.ts +8 -0
- package/dist/infra/database/transaction-host.d.ts +1 -0
- package/dist/infra/database/transaction-host.js +13 -2
- package/dist/infra/outbox/registry.d.ts +17 -0
- package/dist/infra/outbox/registry.js +11 -0
- package/dist/local-devices/local-device-gateway.d.ts +1 -1
- package/dist/local-devices/local-device-gateway.js +1 -1
- package/dist/local-devices/local-device-provider.d.ts +2 -2
- package/dist/local-devices/local-device-provider.js +7 -5
- package/dist/orgs/offboarding.d.ts +2 -0
- package/dist/orgs/offboarding.js +4 -0
- package/dist/orgs/orgs.service.d.ts +3 -1
- package/dist/orgs/orgs.service.js +23 -10
- package/dist/runtime/checkpointer.js +3 -0
- package/dist/runtime/context/compaction.js +5 -5
- package/dist/runtime/conversation-lock.d.ts +4 -11
- package/dist/runtime/conversation-lock.js +14 -18
- package/dist/runtime/maintenance.d.ts +3 -1
- package/dist/runtime/maintenance.js +17 -10
- package/dist/runtime/project/knowledge.service.js +2 -2
- package/dist/runtime/run-deletion.d.ts +23 -0
- package/dist/runtime/run-deletion.js +130 -0
- package/dist/runtime/run-execution.d.ts +23 -0
- package/dist/runtime/run-execution.js +105 -0
- package/dist/runtime/run-finish.js +17 -4
- package/dist/runtime/run-jobs.js +11 -0
- package/dist/runtime/run-orphan-check.job.d.ts +12 -12
- package/dist/runtime/run-orphan-check.job.js +94 -26
- package/dist/runtime/run-queue.js +14 -0
- package/dist/runtime/run-worker.d.ts +9 -5
- package/dist/runtime/run-worker.js +90 -44
- package/dist/runtime/runtime.module.js +6 -0
- package/dist/runtime/stream.js +8 -2
- package/dist/runtime/subagents/tree-jobs.d.ts +4 -3
- package/dist/runtime/subagents/tree-jobs.js +4 -4
- package/dist/tools/pipeline.js +7 -1
- package/package.json +3 -3
- package/src/migrations/0135_run_execution_claim.sql +2 -0
- package/src/migrations/0136_run_recovery_cursor.sql +6 -0
|
@@ -58,6 +58,8 @@ export declare class OutboxDeadService {
|
|
|
58
58
|
outcome: OutboxRetryOutcome;
|
|
59
59
|
}>;
|
|
60
60
|
private retryOnce;
|
|
61
|
+
/** A run-job retry is a new delivery generation, serialized with its terminal transition. */
|
|
62
|
+
private lockRunRetryIn;
|
|
61
63
|
/** Deletes a dead row: its job is never delivered. `outbox.not_found` (404) when none. */
|
|
62
64
|
discard(id: string, actor: WriteActor, detail?: Record<string, unknown>): Promise<void>;
|
|
63
65
|
/** The dead row `id`, locked for the transaction; `outbox.not_found` when it is not dead. */
|
|
@@ -111,6 +111,7 @@ let OutboxDeadService = class OutboxDeadService {
|
|
|
111
111
|
}
|
|
112
112
|
}
|
|
113
113
|
async retryOnce(id, actor, detail) {
|
|
114
|
+
await this.lockRunRetryIn(id);
|
|
114
115
|
const row = await this.lockDead(id);
|
|
115
116
|
const owed = await this.db.db
|
|
116
117
|
.selectFrom("outbox")
|
|
@@ -136,6 +137,36 @@ let OutboxDeadService = class OutboxDeadService {
|
|
|
136
137
|
await this.audit("outbox.retried", id, row, actor, { ...detail, outcome });
|
|
137
138
|
return { outcome };
|
|
138
139
|
}
|
|
140
|
+
/** A run-job retry is a new delivery generation, serialized with its terminal transition. */
|
|
141
|
+
async lockRunRetryIn(id) {
|
|
142
|
+
// Read before taking any outbox lock: the lock order is conversation, then outbox. The
|
|
143
|
+
// subsequent lockDead rechecks this row, so a concurrent discard/retry rolls this back.
|
|
144
|
+
const row = await this.db
|
|
145
|
+
.selectFrom("outbox")
|
|
146
|
+
.select(["job_name", "job_id", "data"])
|
|
147
|
+
.where("id", "=", id)
|
|
148
|
+
.where("dead_at", "is not", null)
|
|
149
|
+
.executeTakeFirst();
|
|
150
|
+
if (row?.job_name !== "run" || row.data === null || typeof row.data !== "object")
|
|
151
|
+
return;
|
|
152
|
+
const data = row.data;
|
|
153
|
+
if (typeof data.conversationId !== "string" || typeof data.runId !== "string")
|
|
154
|
+
return;
|
|
155
|
+
await this.db
|
|
156
|
+
.selectFrom("conversations")
|
|
157
|
+
.select("id")
|
|
158
|
+
.where("id", "=", data.conversationId)
|
|
159
|
+
.forUpdate()
|
|
160
|
+
.execute();
|
|
161
|
+
await this.db
|
|
162
|
+
.updateTable("runs")
|
|
163
|
+
.set({ queued_at: sql `clock_timestamp()` })
|
|
164
|
+
.where("id", "=", data.runId)
|
|
165
|
+
.where("conversation_id", "=", data.conversationId)
|
|
166
|
+
.where("status", "=", "queued")
|
|
167
|
+
.where(sql `COALESCE(job_id, 'run-' || conversation_id || '-' || trigger_seq::text) = ${row.job_id}`)
|
|
168
|
+
.execute();
|
|
169
|
+
}
|
|
139
170
|
/** Deletes a dead row: its job is never delivered. `outbox.not_found` (404) when none. */
|
|
140
171
|
async discard(id, actor, detail = {}) {
|
|
141
172
|
const row = await this.lockDead(id);
|
|
@@ -178,6 +209,9 @@ let OutboxDeadService = class OutboxDeadService {
|
|
|
178
209
|
__decorate([
|
|
179
210
|
Transactional()
|
|
180
211
|
], OutboxDeadService.prototype, "retryOnce", null);
|
|
212
|
+
__decorate([
|
|
213
|
+
Transactional({ propagation: "mandatory" })
|
|
214
|
+
], OutboxDeadService.prototype, "lockRunRetryIn", null);
|
|
181
215
|
__decorate([
|
|
182
216
|
Transactional()
|
|
183
217
|
], OutboxDeadService.prototype, "discard", null);
|
|
@@ -188,7 +188,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
|
|
|
188
188
|
/** The host versions (an entry's `minKernel` is judged against them). */
|
|
189
189
|
export declare const HOST_VERSIONS: {
|
|
190
190
|
readonly kernel: string;
|
|
191
|
-
readonly sdk: "0.1.0-rc.
|
|
191
|
+
readonly sdk: "0.1.0-rc.25";
|
|
192
192
|
};
|
|
193
193
|
/** Whether this deployment satisfies the entry's `minKernel`. */
|
|
194
194
|
export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
|
|
@@ -2,7 +2,6 @@ import type { ConversationSource } from "@capybara-hq/plugin-sdk";
|
|
|
2
2
|
import { AgentLookup } from "../agents/agent-lookup.js";
|
|
3
3
|
import type { ModelRef } from "../agents/definition.js";
|
|
4
4
|
import type { AgentAvatar } from "../agents/profile.js";
|
|
5
|
-
import { BackgroundTaskStopper } from "../background/stop.js";
|
|
6
5
|
import type { TitleSource } from "../db/kernel-schema.js";
|
|
7
6
|
import { ConversationDevices, type NewConversationDevice } from "../devices/conversation-devices.js";
|
|
8
7
|
import { DeviceProjectsService } from "../devices/device-projects.service.js";
|
|
@@ -10,6 +9,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
|
|
|
10
9
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
11
10
|
import { KernelEvents } from "../infra/events/kernel-events.js";
|
|
12
11
|
import { ProviderRegistry } from "../runtime/providers.js";
|
|
12
|
+
import { RunDeletion } from "../runtime/run-deletion.js";
|
|
13
13
|
import type { ScheduleMarker } from "../schedules/types.js";
|
|
14
14
|
import { type RenderedInvocation, SkillInvoker } from "../skills/invoke.js";
|
|
15
15
|
import { type ApprovalRecord, ApprovalsService } from "../tools/approvals.service.js";
|
|
@@ -288,7 +288,7 @@ export declare class ConversationsService {
|
|
|
288
288
|
/** Renders a person's skill invocation (phase D). */
|
|
289
289
|
private readonly invoker;
|
|
290
290
|
/** Stops a deleted conversation's background tasks. */
|
|
291
|
-
private readonly
|
|
291
|
+
private readonly deletion;
|
|
292
292
|
/** The device a new conversation is bound to (environments spec §4.1 item 1). */
|
|
293
293
|
private readonly devices;
|
|
294
294
|
/** The project of that device a new conversation is bound to (project root design §4.3). */
|
|
@@ -311,7 +311,7 @@ export declare class ConversationsService {
|
|
|
311
311
|
/** Renders a person's skill invocation (phase D). */
|
|
312
312
|
invoker: Pick<SkillInvoker, "prepare">,
|
|
313
313
|
/** Stops a deleted conversation's background tasks. */
|
|
314
|
-
|
|
314
|
+
deletion: Pick<RunDeletion, "stopTree">,
|
|
315
315
|
/** The device a new conversation is bound to (environments spec §4.1 item 1). */
|
|
316
316
|
devices: Pick<ConversationDevices, "forNew">,
|
|
317
317
|
/** The project of that device a new conversation is bound to (project root design §4.3). */
|
|
@@ -11,7 +11,6 @@ import { randomUUID } from "node:crypto";
|
|
|
11
11
|
import { Inject, Injectable } from "@nestjs/common";
|
|
12
12
|
import { sql } from "kysely";
|
|
13
13
|
import { AgentLookup, visibleTo } from "../agents/agent-lookup.js";
|
|
14
|
-
import { BackgroundTaskStopper } from "../background/stop.js";
|
|
15
14
|
import { unbindConversation } from "../channels/threads.js";
|
|
16
15
|
import { ConversationDevices, } from "../devices/conversation-devices.js";
|
|
17
16
|
import { DeviceProjectsService } from "../devices/device-projects.service.js";
|
|
@@ -22,6 +21,7 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
|
22
21
|
import { KernelEvents } from "../infra/events/kernel-events.js";
|
|
23
22
|
import { ProviderRegistry } from "../runtime/providers.js";
|
|
24
23
|
import { RunControl as RunControlService } from "../runtime/run-control.js";
|
|
24
|
+
import { RunDeletion } from "../runtime/run-deletion.js";
|
|
25
25
|
import { rootConversationOf } from "../runtime/subagents/child.js";
|
|
26
26
|
import { SkillInvoker } from "../skills/invoke.js";
|
|
27
27
|
import { ApprovalsService } from "../tools/approvals.service.js";
|
|
@@ -33,7 +33,7 @@ import { AttachmentsService } from "./attachments.service.js";
|
|
|
33
33
|
import { EventLog } from "./event-log.js";
|
|
34
34
|
import { userMessageIdemKey } from "./idem-keys.js";
|
|
35
35
|
import { readMessageContext, } from "./message-context.js";
|
|
36
|
-
import { NO_SELECTION, planSelection, readSelection } from "./selection.js";
|
|
36
|
+
import { NO_SELECTION, planSelection, readSelection, sameSelection, } from "./selection.js";
|
|
37
37
|
import { conversationTree } from "./tree.js";
|
|
38
38
|
/**
|
|
39
39
|
* SQL for the {@link ProjectState} of the conversation row aliased/named `ref` (a correlated
|
|
@@ -157,7 +157,7 @@ let ConversationsService = class ConversationsService {
|
|
|
157
157
|
content;
|
|
158
158
|
attachments;
|
|
159
159
|
invoker;
|
|
160
|
-
|
|
160
|
+
deletion;
|
|
161
161
|
devices;
|
|
162
162
|
projects;
|
|
163
163
|
questions;
|
|
@@ -176,7 +176,7 @@ let ConversationsService = class ConversationsService {
|
|
|
176
176
|
/** Renders a person's skill invocation (phase D). */
|
|
177
177
|
invoker,
|
|
178
178
|
/** Stops a deleted conversation's background tasks. */
|
|
179
|
-
|
|
179
|
+
deletion,
|
|
180
180
|
/** The device a new conversation is bound to (environments spec §4.1 item 1). */
|
|
181
181
|
devices,
|
|
182
182
|
/** The project of that device a new conversation is bound to (project root design §4.3). */
|
|
@@ -194,7 +194,7 @@ let ConversationsService = class ConversationsService {
|
|
|
194
194
|
this.content = content;
|
|
195
195
|
this.attachments = attachments;
|
|
196
196
|
this.invoker = invoker;
|
|
197
|
-
this.
|
|
197
|
+
this.deletion = deletion;
|
|
198
198
|
this.devices = devices;
|
|
199
199
|
this.projects = projects;
|
|
200
200
|
this.questions = questions;
|
|
@@ -409,25 +409,26 @@ let ConversationsService = class ConversationsService {
|
|
|
409
409
|
* log, runs and trajectory stay (super admins still see them).
|
|
410
410
|
*/
|
|
411
411
|
async remove(orgId, conversationId, accountId) {
|
|
412
|
-
|
|
413
|
-
//
|
|
414
|
-
// is read-only, so `writable` refused it)
|
|
415
|
-
if (conv.parentConversationId === null) {
|
|
416
|
-
await this.abortRootRun(conversationId, accountId);
|
|
417
|
-
}
|
|
412
|
+
await this.writable(orgId, conversationId, accountId);
|
|
413
|
+
// Close entrances before the direct stop. The outbox owes the same claim-revoking cleanup.
|
|
418
414
|
await this.markDeleted(orgId, conversationId, accountId);
|
|
419
|
-
|
|
420
|
-
// root (`ensureRun` refuses it). The sandbox's tasks stop first, so the sub-agents' tasks end
|
|
421
|
-
// as a deletion; the tree stop then only stops a task a sub-agent started in between
|
|
422
|
-
// (`stoppedBy: "subagent_end"`, which never wakes either)
|
|
423
|
-
await this.background.stopForDeletedConversation(conversationId);
|
|
424
|
-
// the whole tree stops (agent map spec §10)
|
|
425
|
-
await this.runs.stopTree(conversationId, accountId, { includeSelf: false });
|
|
415
|
+
await this.deletion.stopTree(conversationId, accountId);
|
|
426
416
|
await this.eventLog.publishChanged(conversationId, "deleted");
|
|
427
417
|
}
|
|
428
418
|
// the publish happens after the commit, in the caller; the tree stop after it is owed here
|
|
429
419
|
// (transactional outbox spec §6), so a process that dies before it still stops the tree
|
|
430
420
|
async markDeleted(orgId, conversationId, accountId) {
|
|
421
|
+
const row = await this.db
|
|
422
|
+
.selectFrom("conversations")
|
|
423
|
+
.select("id")
|
|
424
|
+
.where("id", "=", conversationId)
|
|
425
|
+
.where("org_id", "=", orgId)
|
|
426
|
+
.where("account_id", "=", accountId)
|
|
427
|
+
.where("deleted_at", "is", null)
|
|
428
|
+
.forUpdate()
|
|
429
|
+
.executeTakeFirst();
|
|
430
|
+
if (!row)
|
|
431
|
+
throw notFound();
|
|
431
432
|
await this.db
|
|
432
433
|
.updateTable("conversations")
|
|
433
434
|
.set({ deleted_at: sql `now()` })
|
|
@@ -781,11 +782,8 @@ let ConversationsService = class ConversationsService {
|
|
|
781
782
|
*/
|
|
782
783
|
async postUserMessage(orgId, conversationId, accountId, input) {
|
|
783
784
|
const conv = await this.writable(orgId, conversationId, accountId);
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
// A retry returns the written event (no resource read, no file check, no skill resolution)
|
|
787
|
-
if ((refs.length > 0 || files.length > 0 || input.skill !== undefined) &&
|
|
788
|
-
input.clientMessageId !== undefined) {
|
|
785
|
+
// A retry returns the written event before resolving today's model or resources.
|
|
786
|
+
if (input.clientMessageId !== undefined) {
|
|
789
787
|
const existing = await this.eventLog.findByIdem(conversationId, userMessageIdemKey(input.clientMessageId));
|
|
790
788
|
if (existing) {
|
|
791
789
|
await this.startRun(conversationId);
|
|
@@ -796,16 +794,29 @@ let ConversationsService = class ConversationsService {
|
|
|
796
794
|
const agent = needsAgent
|
|
797
795
|
? (await this.agents.get(orgId, conv.agentId, accountId)).definition
|
|
798
796
|
: undefined;
|
|
799
|
-
const next = agent === undefined || (input.model === undefined && input.effort === undefined)
|
|
800
|
-
? null
|
|
801
|
-
: await this.planSwitch(orgId, agent, conv.selection, input);
|
|
802
797
|
const extra = await this.resolveExtra(orgId, accountId, input);
|
|
803
798
|
const invoked = agent === undefined
|
|
804
799
|
? undefined
|
|
805
800
|
: await this.prepareSkill(orgId, accountId, conv.agentId, conversationId, agent, input);
|
|
806
801
|
// one transaction: the sender, time zone and language are read with the message's write
|
|
807
802
|
// (run context spec §3.2)
|
|
808
|
-
|
|
803
|
+
let current = conv.selection;
|
|
804
|
+
let posted;
|
|
805
|
+
let next = null;
|
|
806
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
807
|
+
next = agent === undefined ? null : await this.planSwitch(orgId, agent, current, input);
|
|
808
|
+
const result = await this.postIn(orgId, conversationId, accountId, input, next, extra, invoked, input.model !== undefined || input.effort !== undefined ? current : undefined);
|
|
809
|
+
if ("selection" in result) {
|
|
810
|
+
current = result.selection;
|
|
811
|
+
continue;
|
|
812
|
+
}
|
|
813
|
+
posted = result;
|
|
814
|
+
break;
|
|
815
|
+
}
|
|
816
|
+
if (posted === undefined) {
|
|
817
|
+
throw new ApiError("conflict", "The conversation selection changed; send the message again");
|
|
818
|
+
}
|
|
819
|
+
const { event, skipped, toSeq } = posted;
|
|
809
820
|
await this.eventLog.notify(conversationId, toSeq);
|
|
810
821
|
await this.announceSkipped(skipped);
|
|
811
822
|
if (next !== null)
|
|
@@ -827,7 +838,25 @@ let ConversationsService = class ConversationsService {
|
|
|
827
838
|
* (after its `model_switched` when it switches).
|
|
828
839
|
*/
|
|
829
840
|
// its own transaction: the caller notifies and publishes after the commit
|
|
830
|
-
async postIn(orgId, conversationId, accountId, input, next, extra, invoked) {
|
|
841
|
+
async postIn(orgId, conversationId, accountId, input, next, extra, invoked, expectedSelection) {
|
|
842
|
+
// Serialize the partial pick with the append. Provider resolution runs outside this
|
|
843
|
+
// transaction; if another send changed the selection, revalidate its model before retrying.
|
|
844
|
+
const row = await this.db
|
|
845
|
+
.selectFrom("conversations")
|
|
846
|
+
.select("id")
|
|
847
|
+
.where("id", "=", conversationId)
|
|
848
|
+
.where("org_id", "=", orgId)
|
|
849
|
+
.where("account_id", "=", accountId)
|
|
850
|
+
.where("deleted_at", "is", null)
|
|
851
|
+
.forUpdate()
|
|
852
|
+
.executeTakeFirst();
|
|
853
|
+
if (!row)
|
|
854
|
+
throw notFound();
|
|
855
|
+
if (expectedSelection !== undefined) {
|
|
856
|
+
const selection = await readSelection(this.db.db, conversationId);
|
|
857
|
+
if (!sameSelection(expectedSelection, selection))
|
|
858
|
+
return { selection };
|
|
859
|
+
}
|
|
831
860
|
const blocks = await this.bindIn(orgId, conversationId, accountId, input.files ?? []);
|
|
832
861
|
const written = await this.writeMessage(orgId, conversationId, accountId, input, next, extra, blocks, invoked);
|
|
833
862
|
const event = written.events.at(-1);
|
|
@@ -1204,7 +1233,7 @@ ConversationsService = __decorate([
|
|
|
1204
1233
|
__param(6, Inject(ConnectorContent)),
|
|
1205
1234
|
__param(7, Inject(AttachmentsService)),
|
|
1206
1235
|
__param(8, Inject(SkillInvoker)),
|
|
1207
|
-
__param(9, Inject(
|
|
1236
|
+
__param(9, Inject(RunDeletion)),
|
|
1208
1237
|
__param(10, Inject(ConversationDevices)),
|
|
1209
1238
|
__param(11, Inject(DeviceProjectsService)),
|
|
1210
1239
|
__param(12, Inject(QuestionsService)),
|
|
@@ -342,7 +342,14 @@ export interface ConversationEventsTable {
|
|
|
342
342
|
created_at: Ts;
|
|
343
343
|
}
|
|
344
344
|
/** 0006_conversations.sql:一次 agent 运行。 */
|
|
345
|
+
export interface RunRecoveryCursorsTable {
|
|
346
|
+
name: string;
|
|
347
|
+
since: TsNullable;
|
|
348
|
+
run_id: string | null;
|
|
349
|
+
}
|
|
345
350
|
export interface RunsTable {
|
|
351
|
+
/** 0135: the worker acquisition currently authorized to mutate this run. */
|
|
352
|
+
execution_id: string | null;
|
|
346
353
|
id: string;
|
|
347
354
|
conversation_id: string;
|
|
348
355
|
status: "queued" | "running" | "waiting" | "completed" | "failed" | "aborted";
|
|
@@ -1312,6 +1319,7 @@ export interface KernelDatabase {
|
|
|
1312
1319
|
file_previewers: FilePreviewersTable;
|
|
1313
1320
|
org_extension_point_defaults: OrgExtensionPointDefaultsTable;
|
|
1314
1321
|
runs: RunsTable;
|
|
1322
|
+
run_recovery_cursors: RunRecoveryCursorsTable;
|
|
1315
1323
|
subagent_dispatches: SubagentDispatchesTable;
|
|
1316
1324
|
agent_templates: AgentTemplatesTable;
|
|
1317
1325
|
agent_template_versions: AgentTemplateVersionsTable;
|
|
@@ -9,6 +9,7 @@ interface TransactionStore {
|
|
|
9
9
|
/** Set once the transaction settled: continuations that outlive it must not use it. */
|
|
10
10
|
done: boolean;
|
|
11
11
|
}
|
|
12
|
+
export declare function withTransactionFence<T>(fence: () => Promise<void>, fn: () => Promise<T>): Promise<T>;
|
|
12
13
|
export type Propagation = "required" | "requires_new" | "mandatory";
|
|
13
14
|
export interface TransactionOptions {
|
|
14
15
|
/**
|
|
@@ -14,6 +14,11 @@ import { Inject, Injectable } from "@nestjs/common";
|
|
|
14
14
|
import { KERNEL_LOGGER, KERNEL_POOL } from "../tokens.js";
|
|
15
15
|
/** One store for the process: `afterCommit` (a free function) reads it without a host instance. */
|
|
16
16
|
const storage = new AsyncLocalStorage();
|
|
17
|
+
/** A caller's execution authority, checked inside every new transaction before domain writes. */
|
|
18
|
+
const fences = new AsyncLocalStorage();
|
|
19
|
+
export function withTransactionFence(fence, fn) {
|
|
20
|
+
return fences.run(fence, fn);
|
|
21
|
+
}
|
|
17
22
|
/** Logger for hook failures outside a transaction; set by `TransactionHost`, console until then. */
|
|
18
23
|
let hookLog = {
|
|
19
24
|
error: (msg, fields) => console.error(`[afterCommit] ${msg}`, fields ?? ""),
|
|
@@ -51,7 +56,7 @@ export function currentStore() {
|
|
|
51
56
|
* join (or write through) a transaction that may already be committed or rolled back.
|
|
52
57
|
*/
|
|
53
58
|
export function runOutsideTransaction(fn) {
|
|
54
|
-
return storage.exit(fn);
|
|
59
|
+
return fences.exit(() => storage.exit(fn));
|
|
55
60
|
}
|
|
56
61
|
let TransactionHost = class TransactionHost {
|
|
57
62
|
pool;
|
|
@@ -97,7 +102,13 @@ let TransactionHost = class TransactionHost {
|
|
|
97
102
|
builder = builder.setAccessMode(opts.accessMode);
|
|
98
103
|
result = await builder.execute((trx) => {
|
|
99
104
|
store = { pool: this.pool, trx, hooks, done: false };
|
|
100
|
-
return storage.run(store,
|
|
105
|
+
return storage.run(store, async () => {
|
|
106
|
+
// PostgreSQL forbids row locks in a read-only snapshot and enforces that it cannot
|
|
107
|
+
// mutate. Every later mutation or external dispatch still enters a writable fence.
|
|
108
|
+
if (opts.accessMode !== "read only")
|
|
109
|
+
await fences.getStore()?.();
|
|
110
|
+
return fn();
|
|
111
|
+
});
|
|
101
112
|
});
|
|
102
113
|
}
|
|
103
114
|
finally {
|
|
@@ -66,6 +66,23 @@ export declare const OUTBOX_JOBS: {
|
|
|
66
66
|
readonly removeOnFail: true;
|
|
67
67
|
};
|
|
68
68
|
};
|
|
69
|
+
readonly "stop-deleted-org": {
|
|
70
|
+
readonly queue: "cap-kernel-maintenance";
|
|
71
|
+
readonly idempotent: "only active runs are settled and only running background tasks are stopped";
|
|
72
|
+
readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
|
|
73
|
+
readonly opts: {
|
|
74
|
+
readonly attempts: 5;
|
|
75
|
+
readonly backoff: {
|
|
76
|
+
readonly type: "exponential";
|
|
77
|
+
readonly delay: 5000;
|
|
78
|
+
};
|
|
79
|
+
readonly removeOnComplete: true;
|
|
80
|
+
readonly removeOnFail: {
|
|
81
|
+
readonly age: number;
|
|
82
|
+
readonly count: 1000;
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
};
|
|
69
86
|
readonly "run-stop": {
|
|
70
87
|
readonly queue: "cap-kernel-maintenance";
|
|
71
88
|
readonly idempotent: "stopping a finished run is a no-op";
|
|
@@ -56,6 +56,17 @@ export const OUTBOX_JOBS = {
|
|
|
56
56
|
},
|
|
57
57
|
// `orgs/offboarding.ts` RUN_STOP_JOB: owed by the offboard transaction for each of the departed
|
|
58
58
|
// member's active runs in the org, under `runStopJobId` (spec §8.1)
|
|
59
|
+
"stop-deleted-org": {
|
|
60
|
+
queue: "cap-kernel-maintenance",
|
|
61
|
+
idempotent: "only active runs are settled and only running background tasks are stopped",
|
|
62
|
+
processedIn: "packages/kernel/src/runtime/maintenance.ts",
|
|
63
|
+
opts: {
|
|
64
|
+
attempts: 5,
|
|
65
|
+
backoff: { type: "exponential", delay: 5_000 },
|
|
66
|
+
removeOnComplete: true,
|
|
67
|
+
removeOnFail: { age: 7 * 86_400, count: 1_000 },
|
|
68
|
+
},
|
|
69
|
+
},
|
|
59
70
|
"run-stop": {
|
|
60
71
|
queue: "cap-kernel-maintenance",
|
|
61
72
|
idempotent: "stopping a finished run is a no-op",
|
|
@@ -19,7 +19,7 @@ export declare const DEVICE_CLOSE: {
|
|
|
19
19
|
readonly replaced: 4002;
|
|
20
20
|
/** The machine's credential was revoked: the program exits. */
|
|
21
21
|
readonly revoked: 4003;
|
|
22
|
-
/** No valid `hello` first, or a frame that is not protocol
|
|
22
|
+
/** No valid `hello` first, or a frame that is not the current protocol from a device. */
|
|
23
23
|
readonly protocol: 4400;
|
|
24
24
|
/** The lease could not be claimed in time: reconnect. */
|
|
25
25
|
readonly claimTimeout: 4409;
|
|
@@ -30,7 +30,7 @@ export const DEVICE_CLOSE = {
|
|
|
30
30
|
replaced: 4002,
|
|
31
31
|
/** The machine's credential was revoked: the program exits. */
|
|
32
32
|
revoked: 4003,
|
|
33
|
-
/** No valid `hello` first, or a frame that is not protocol
|
|
33
|
+
/** No valid `hello` first, or a frame that is not the current protocol from a device. */
|
|
34
34
|
protocol: 4400,
|
|
35
35
|
/** The lease could not be claimed in time: reconnect. */
|
|
36
36
|
claimTimeout: 4409,
|
|
@@ -143,10 +143,10 @@ export declare class LocalDeviceProvider implements SandboxProvider {
|
|
|
143
143
|
/** The kernel never sends `list` or `scan` to a machine that did not announce `projects`. */
|
|
144
144
|
private requireProjects;
|
|
145
145
|
/**
|
|
146
|
-
* The device's org and
|
|
146
|
+
* The device's org and current limits for an exec or file read (ruling R27): the effective policy's
|
|
147
147
|
* `allowedMode` and the sandbox-mode allowlist. A deleted device is not found. A machine whose
|
|
148
148
|
* local policy is auto mode while the organization allows only sandbox mode is refused here, at
|
|
149
|
-
* every
|
|
149
|
+
* every such operation, so a machine switched locally is not used until it is switched back.
|
|
150
150
|
*/
|
|
151
151
|
private currentLimits;
|
|
152
152
|
}
|
|
@@ -162,9 +162,10 @@ let LocalDeviceProvider = class LocalDeviceProvider {
|
|
|
162
162
|
return { ...result, network: { blocked: relayer(result.network.blocked, limits) } };
|
|
163
163
|
}
|
|
164
164
|
async readFile(h, path, opts) {
|
|
165
|
+
const { limits } = await this.currentLimits(h.id);
|
|
165
166
|
// the answer must fit one frame: a larger file comes back truncated (Deliver: too large)
|
|
166
167
|
const maxBytes = Math.min(opts.maxBytes, maxReadBytes(this.config.get().devices.local.maxFrameBytes));
|
|
167
|
-
const r = await this.relay.call(h.id, "readFile", { path, maxBytes }, { deadlineMs: OP_DEADLINE_MS, signal: opts.signal });
|
|
168
|
+
const r = await this.relay.call(h.id, "readFile", { path, maxBytes, limits: { mode: limits.mode } }, { deadlineMs: OP_DEADLINE_MS, signal: opts.signal });
|
|
168
169
|
return r === null ? null : { data: bytesOf(r.dataB64), truncated: r.truncated };
|
|
169
170
|
}
|
|
170
171
|
async writeFile(h, path, data, signal) {
|
|
@@ -172,7 +173,8 @@ let LocalDeviceProvider = class LocalDeviceProvider {
|
|
|
172
173
|
await this.relay.call(h.id, "writeFile", { path, dataB64 }, { deadlineMs: OP_DEADLINE_MS, signal });
|
|
173
174
|
}
|
|
174
175
|
async stat(h, path, signal) {
|
|
175
|
-
|
|
176
|
+
const { limits } = await this.currentLimits(h.id);
|
|
177
|
+
return this.relay.call(h.id, "stat", { path, limits: { mode: limits.mode } }, { deadlineMs: OP_DEADLINE_MS, signal });
|
|
176
178
|
}
|
|
177
179
|
/**
|
|
178
180
|
* Lists one directory on the machine (the `list` op, project root §4.1), read in the mode the
|
|
@@ -201,10 +203,10 @@ let LocalDeviceProvider = class LocalDeviceProvider {
|
|
|
201
203
|
}
|
|
202
204
|
}
|
|
203
205
|
/**
|
|
204
|
-
* The device's org and
|
|
206
|
+
* The device's org and current limits for an exec or file read (ruling R27): the effective policy's
|
|
205
207
|
* `allowedMode` and the sandbox-mode allowlist. A deleted device is not found. A machine whose
|
|
206
208
|
* local policy is auto mode while the organization allows only sandbox mode is refused here, at
|
|
207
|
-
* every
|
|
209
|
+
* every such operation, so a machine switched locally is not used until it is switched back.
|
|
208
210
|
*/
|
|
209
211
|
async currentLimits(deviceId) {
|
|
210
212
|
const orgId = await this.targets.orgOf(deviceId);
|
|
@@ -215,7 +217,7 @@ let LocalDeviceProvider = class LocalDeviceProvider {
|
|
|
215
217
|
this.grants.reportedMode(deviceId),
|
|
216
218
|
]);
|
|
217
219
|
if (policy.allowedMode === "sandbox" && reported === "auto") {
|
|
218
|
-
this.log.warn("
|
|
220
|
+
this.log.warn("device operation refused on a machine that reports auto mode", { deviceId });
|
|
219
221
|
throw new ApiError("device.auto_mode_not_allowed", AUTO_MODE_NOT_ALLOWED_TEXT);
|
|
220
222
|
}
|
|
221
223
|
return {
|
|
@@ -49,6 +49,8 @@ export interface OffboardingRunControl {
|
|
|
49
49
|
export declare const RUN_STOP_JOB = "run-stop";
|
|
50
50
|
/** The `run-stop` job's data. */
|
|
51
51
|
export interface RunStopJobData {
|
|
52
|
+
/** A deletion already settled PG; cancellation still needs delivery to its old worker. */
|
|
53
|
+
deleted?: true;
|
|
52
54
|
conversationId: string;
|
|
53
55
|
runId: string;
|
|
54
56
|
}
|
package/dist/orgs/offboarding.js
CHANGED
|
@@ -406,6 +406,10 @@ let Offboarding = class Offboarding {
|
|
|
406
406
|
* A failure throws (the job is retried).
|
|
407
407
|
*/
|
|
408
408
|
async stopRun(data) {
|
|
409
|
+
if (data.deleted) {
|
|
410
|
+
await this.runs.requestAbort(data.runId, null);
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
409
413
|
const run = await this.db
|
|
410
414
|
.selectFrom("runs")
|
|
411
415
|
.select("status")
|
|
@@ -8,6 +8,7 @@ import { SettingsService } from "../identity/settings.js";
|
|
|
8
8
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
9
9
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
10
10
|
import { KernelEvents } from "../infra/events/kernel-events.js";
|
|
11
|
+
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
11
12
|
import { OrgLock } from "./org-lock.js";
|
|
12
13
|
import type { OrgRole } from "./roles.js";
|
|
13
14
|
export type Org = {
|
|
@@ -26,6 +27,7 @@ export declare function slugFromName(name: string): string;
|
|
|
26
27
|
*/
|
|
27
28
|
export declare class OrgsService {
|
|
28
29
|
private readonly db;
|
|
30
|
+
private readonly outbox;
|
|
29
31
|
readonly txHost: TransactionHost;
|
|
30
32
|
private readonly settings;
|
|
31
33
|
private readonly apiTokens;
|
|
@@ -39,7 +41,7 @@ export declare class OrgsService {
|
|
|
39
41
|
private readonly ownedItems;
|
|
40
42
|
/** Records `org.deleted` for the subscribing plugins in the delete's transaction. */
|
|
41
43
|
private readonly lifecycle;
|
|
42
|
-
constructor(db: KernelDb, txHost: TransactionHost, settings: SettingsService, apiTokens: ApiTokenService, orgLock: OrgLock, events: KernelEvents,
|
|
44
|
+
constructor(db: KernelDb, outbox: Pick<OutboxService, "add">, txHost: TransactionHost, settings: SettingsService, apiTokens: ApiTokenService, orgLock: OrgLock, events: KernelEvents,
|
|
43
45
|
/** Cancels the deleted org's running eval runs (in the delete's transaction). */
|
|
44
46
|
evalBudget: Pick<EvalBudget, "cancelRuns">,
|
|
45
47
|
/** A new org gets the plugins its scope offers it (the scope sync, owed with the org). */
|
|
@@ -24,6 +24,9 @@ import { KernelDb } from "../infra/database/kernel-db.js";
|
|
|
24
24
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
25
25
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
26
26
|
import { KernelEvents } from "../infra/events/kernel-events.js";
|
|
27
|
+
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
28
|
+
import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
|
|
29
|
+
import { STOP_DELETED_ORG_JOB } from "../runtime/run-deletion.js";
|
|
27
30
|
import { USAGE_REPORT_QUEUE } from "../runtime/usage-report-jobs.js";
|
|
28
31
|
import { OrgLock } from "./org-lock.js";
|
|
29
32
|
/** 组织 slug:小写字母数字与 `-`,首尾不能是 `-`,1–40 个字符。 */
|
|
@@ -79,6 +82,7 @@ async function slugGuard(p) {
|
|
|
79
82
|
*/
|
|
80
83
|
let OrgsService = class OrgsService {
|
|
81
84
|
db;
|
|
85
|
+
outbox;
|
|
82
86
|
txHost;
|
|
83
87
|
settings;
|
|
84
88
|
apiTokens;
|
|
@@ -88,7 +92,7 @@ let OrgsService = class OrgsService {
|
|
|
88
92
|
scopeSync;
|
|
89
93
|
ownedItems;
|
|
90
94
|
lifecycle;
|
|
91
|
-
constructor(db, txHost, settings, apiTokens, orgLock, events,
|
|
95
|
+
constructor(db, outbox, txHost, settings, apiTokens, orgLock, events,
|
|
92
96
|
/** Cancels the deleted org's running eval runs (in the delete's transaction). */
|
|
93
97
|
evalBudget,
|
|
94
98
|
/** A new org gets the plugins its scope offers it (the scope sync, owed with the org). */
|
|
@@ -98,6 +102,7 @@ let OrgsService = class OrgsService {
|
|
|
98
102
|
/** Records `org.deleted` for the subscribing plugins in the delete's transaction. */
|
|
99
103
|
lifecycle) {
|
|
100
104
|
this.db = db;
|
|
105
|
+
this.outbox = outbox;
|
|
101
106
|
this.txHost = txHost;
|
|
102
107
|
this.settings = settings;
|
|
103
108
|
this.apiTokens = apiTokens;
|
|
@@ -236,6 +241,7 @@ let OrgsService = class OrgsService {
|
|
|
236
241
|
await this.softDeleteIn(orgId, actor, actorTokenId);
|
|
237
242
|
}
|
|
238
243
|
async softDeleteIn(orgId, actor, actorTokenId) {
|
|
244
|
+
// The same org authorization lock admits fenced worker writes before conversation locks.
|
|
239
245
|
await this.orgLock.lockAndAuthorize(orgId, actor.id, "org.delete");
|
|
240
246
|
await this.db
|
|
241
247
|
.updateTable("orgs")
|
|
@@ -251,6 +257,12 @@ let OrgsService = class OrgsService {
|
|
|
251
257
|
.where("dead_at", "is", null)
|
|
252
258
|
.where("queue", "<>", USAGE_REPORT_QUEUE)
|
|
253
259
|
.execute();
|
|
260
|
+
await this.outbox.add({
|
|
261
|
+
queue: MAINTENANCE_QUEUE_NAME,
|
|
262
|
+
name: STOP_DELETED_ORG_JOB,
|
|
263
|
+
jobId: `stop-deleted-org-${orgId}`,
|
|
264
|
+
data: { orgId, byAccountId: actor.id },
|
|
265
|
+
});
|
|
254
266
|
// after the org is marked deleted, so it counts as no user of what it shared (P3-18)
|
|
255
267
|
await this.ownedItems.onOrgDeleted(orgId, actor.id, {
|
|
256
268
|
...(actorTokenId !== undefined && { actorTokenId }),
|
|
@@ -290,14 +302,15 @@ __decorate([
|
|
|
290
302
|
OrgsService = __decorate([
|
|
291
303
|
Injectable(),
|
|
292
304
|
__param(0, Inject(KernelDb)),
|
|
293
|
-
__param(1, Inject(
|
|
294
|
-
__param(2, Inject(
|
|
295
|
-
__param(3, Inject(
|
|
296
|
-
__param(4, Inject(
|
|
297
|
-
__param(5, Inject(
|
|
298
|
-
__param(6, Inject(
|
|
299
|
-
__param(7, Inject(
|
|
300
|
-
__param(8, Inject(
|
|
301
|
-
__param(9, Inject(
|
|
305
|
+
__param(1, Inject(OutboxService)),
|
|
306
|
+
__param(2, Inject(TransactionHost)),
|
|
307
|
+
__param(3, Inject(SettingsService)),
|
|
308
|
+
__param(4, Inject(ApiTokenService)),
|
|
309
|
+
__param(5, Inject(OrgLock)),
|
|
310
|
+
__param(6, Inject(KernelEvents)),
|
|
311
|
+
__param(7, Inject(EvalBudget)),
|
|
312
|
+
__param(8, Inject(PluginScopeSync)),
|
|
313
|
+
__param(9, Inject(OwnedItems)),
|
|
314
|
+
__param(10, Inject(LifecycleHooks))
|
|
302
315
|
], OrgsService);
|
|
303
316
|
export { OrgsService };
|
|
@@ -258,6 +258,9 @@ let KyselyCheckpointSaver = class KyselyCheckpointSaver extends BaseCheckpointSa
|
|
|
258
258
|
versions.length > 0 ? maxChannelVersion(...versions) : this.getNextVersion(undefined);
|
|
259
259
|
}
|
|
260
260
|
};
|
|
261
|
+
__decorate([
|
|
262
|
+
Transactional({ propagation: "requires_new" })
|
|
263
|
+
], KyselyCheckpointSaver.prototype, "put", null);
|
|
261
264
|
__decorate([
|
|
262
265
|
Transactional({ propagation: "requires_new" })
|
|
263
266
|
], KyselyCheckpointSaver.prototype, "insertWrites", null);
|
|
@@ -369,13 +369,13 @@ function renderBlocks(blocks) {
|
|
|
369
369
|
* result fails the attempt.
|
|
370
370
|
*/
|
|
371
371
|
export function extractSummary(text) {
|
|
372
|
-
|
|
372
|
+
// Strip scratchpads before looking for a summary: a truncated analysis can itself contain
|
|
373
|
+
// summary-shaped draft text. An unclosed analysis consumes the rest of the response.
|
|
374
|
+
const answer = text.replace(/<analysis>[\s\S]*?(?:<\/analysis>|$)/gi, "");
|
|
375
|
+
const block = /<summary>([\s\S]*?)<\/summary>/i.exec(answer);
|
|
373
376
|
if (block)
|
|
374
377
|
return (block[1] ?? "").trim();
|
|
375
|
-
return
|
|
376
|
-
.replace(/<analysis>[\s\S]*?<\/analysis>/gi, "")
|
|
377
|
-
.replace(/<\/?summary>/gi, "")
|
|
378
|
-
.trim();
|
|
378
|
+
return answer.replace(/<\/?summary>/gi, "").trim();
|
|
379
379
|
}
|
|
380
380
|
/** The marker a hard-split line carries where it was cut (context compaction spec §4.5). */
|
|
381
381
|
const CHUNK_SPLIT_MARKER = "\n[chunk split]\n";
|