@capybara-hq/kernel 0.1.0-rc.34 → 0.1.0-rc.36
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/agents/agents.module.js +3 -0
- package/dist/agents/readiness.controller.d.ts +8 -11
- package/dist/agents/readiness.controller.js +11 -17
- package/dist/agents/readiness.service.d.ts +30 -0
- package/dist/agents/readiness.service.js +61 -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/platform/ops/agents.ops.d.ts +3 -3
- package/dist/platform/ops/agents.ops.js +7 -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);
|
|
@@ -22,6 +22,7 @@ import { AgentsFromTemplate } from "./from-template.service.js";
|
|
|
22
22
|
import { OrgAgentTemplates } from "./org-templates.js";
|
|
23
23
|
import { PendingConnectorRequests } from "./pending-connector-requests.js";
|
|
24
24
|
import { PendingConnectorsService } from "./pending-connectors.service.js";
|
|
25
|
+
import { ReadinessService } from "./readiness.service.js";
|
|
25
26
|
import { AgentTemplatesService } from "./templates.js";
|
|
26
27
|
/**
|
|
27
28
|
* Agents: the one {@link AgentsService} (definitions, versions, visibility; writes under the org
|
|
@@ -61,6 +62,7 @@ AgentsModule = __decorate([
|
|
|
61
62
|
AgentsFromTemplate,
|
|
62
63
|
PendingConnectorRequests,
|
|
63
64
|
PendingConnectorsService,
|
|
65
|
+
ReadinessService,
|
|
64
66
|
],
|
|
65
67
|
exports: [
|
|
66
68
|
AgentLookupModule,
|
|
@@ -72,6 +74,7 @@ AgentsModule = __decorate([
|
|
|
72
74
|
AgentsFromTemplate,
|
|
73
75
|
PendingConnectorRequests,
|
|
74
76
|
PendingConnectorsService,
|
|
77
|
+
ReadinessService,
|
|
75
78
|
],
|
|
76
79
|
})
|
|
77
80
|
], AgentsModule);
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { type Principal } from "../identity/principal.js";
|
|
2
2
|
import { type OrgContext } from "../orgs/org.guard.js";
|
|
3
|
-
import {
|
|
4
|
-
import { AgentsService } from "./agents.service.js";
|
|
3
|
+
import { type OrgReadiness, ReadinessService } from "./readiness.service.js";
|
|
5
4
|
/**
|
|
6
5
|
* Whether the org can run (`/api/v1/orgs/:orgId/readiness`, web-order spec §3.8): the web app
|
|
7
6
|
* decides between the shell and the setup layout with it. `modelProvider` is `ready` when a
|
|
8
7
|
* model-provider extension is loaded (enabled and configured), from extension state only, never
|
|
9
|
-
* a vendor call; `
|
|
10
|
-
*
|
|
8
|
+
* a vendor call; `orgCanAddModel` says whether an org admin can make one usable from the org's
|
|
9
|
+
* 扩展 page (switch on a provider the platform offers, or fill its org config) or only the super
|
|
10
|
+
* admin can; `agents` is the number of agents the caller can see (the agent list's visibility).
|
|
11
|
+
* Humans and service tokens (`org.read`).
|
|
11
12
|
*
|
|
12
13
|
* `modelProvider` counts the deployment's providers whose effective config is valid in this org
|
|
13
14
|
* (spec B §5.5: a provider the platform installed without a key needs each org's own). It is read
|
|
@@ -16,11 +17,7 @@ import { AgentsService } from "./agents.service.js";
|
|
|
16
17
|
* a moment.
|
|
17
18
|
*/
|
|
18
19
|
export declare class ReadinessController {
|
|
19
|
-
private readonly
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
get(principal: Principal, org: OrgContext): Promise<{
|
|
23
|
-
modelProvider: "ready" | "none";
|
|
24
|
-
agents: number;
|
|
25
|
-
}>;
|
|
20
|
+
private readonly readiness;
|
|
21
|
+
constructor(readiness: ReadinessService);
|
|
22
|
+
get(principal: Principal, org: OrgContext): Promise<OrgReadiness>;
|
|
26
23
|
}
|
|
@@ -10,16 +10,17 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
10
10
|
import { Controller, Get, Inject } from "@nestjs/common";
|
|
11
11
|
import { CurrentPrincipal } from "../identity/principal.js";
|
|
12
12
|
import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
|
|
13
|
-
import {
|
|
14
|
-
import { AgentsService } from "./agents.service.js";
|
|
13
|
+
import { ReadinessService } from "./readiness.service.js";
|
|
15
14
|
/** Service tokens have no account: they see `visibility='org'` agents only (as the agent list). */
|
|
16
15
|
const viewerOf = (p) => (p.kind === "user" ? p.account.id : null);
|
|
17
16
|
/**
|
|
18
17
|
* Whether the org can run (`/api/v1/orgs/:orgId/readiness`, web-order spec §3.8): the web app
|
|
19
18
|
* decides between the shell and the setup layout with it. `modelProvider` is `ready` when a
|
|
20
19
|
* model-provider extension is loaded (enabled and configured), from extension state only, never
|
|
21
|
-
* a vendor call; `
|
|
22
|
-
*
|
|
20
|
+
* a vendor call; `orgCanAddModel` says whether an org admin can make one usable from the org's
|
|
21
|
+
* 扩展 page (switch on a provider the platform offers, or fill its org config) or only the super
|
|
22
|
+
* admin can; `agents` is the number of agents the caller can see (the agent list's visibility).
|
|
23
|
+
* Humans and service tokens (`org.read`).
|
|
23
24
|
*
|
|
24
25
|
* `modelProvider` counts the deployment's providers whose effective config is valid in this org
|
|
25
26
|
* (spec B §5.5: a provider the platform installed without a key needs each org's own). It is read
|
|
@@ -28,18 +29,12 @@ const viewerOf = (p) => (p.kind === "user" ? p.account.id : null);
|
|
|
28
29
|
* a moment.
|
|
29
30
|
*/
|
|
30
31
|
let ReadinessController = class ReadinessController {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
this.registry = registry;
|
|
35
|
-
this.agents = agents;
|
|
32
|
+
readiness;
|
|
33
|
+
constructor(readiness) {
|
|
34
|
+
this.readiness = readiness;
|
|
36
35
|
}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
return {
|
|
40
|
-
modelProvider: (await this.registry.hasProvider(org.orgId)) ? "ready" : "none",
|
|
41
|
-
agents: visible.length,
|
|
42
|
-
};
|
|
36
|
+
get(principal, org) {
|
|
37
|
+
return this.readiness.get(org.orgId, viewerOf(principal));
|
|
43
38
|
}
|
|
44
39
|
};
|
|
45
40
|
__decorate([
|
|
@@ -50,7 +45,6 @@ __decorate([
|
|
|
50
45
|
], ReadinessController.prototype, "get", null);
|
|
51
46
|
ReadinessController = __decorate([
|
|
52
47
|
Controller("api/v1/orgs/:orgId/readiness"),
|
|
53
|
-
__param(0, Inject(
|
|
54
|
-
__param(1, Inject(AgentsService))
|
|
48
|
+
__param(0, Inject(ReadinessService))
|
|
55
49
|
], ReadinessController);
|
|
56
50
|
export { ReadinessController };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { OrgExtensionConfigs } from "../extensions/org-config.js";
|
|
2
|
+
import { ProviderRegistry } from "../runtime/providers.js";
|
|
3
|
+
import { AgentsService } from "./agents.service.js";
|
|
4
|
+
/** What `GET /orgs/:orgId/readiness` and the `agents.readiness` operation answer. */
|
|
5
|
+
export interface OrgReadiness {
|
|
6
|
+
/** `ready` when a model provider is usable in the org (extension state only, no vendor call). */
|
|
7
|
+
modelProvider: "ready" | "none";
|
|
8
|
+
/**
|
|
9
|
+
* Whether an org admin can make a model provider usable from the org's 扩展 page: a provider
|
|
10
|
+
* loaded on the deployment that is off in this org (and the org may switch it), or on but
|
|
11
|
+
* waiting for the org's own config. False when only the super admin can help (no provider is
|
|
12
|
+
* loaded on the deployment). Meaningful while `modelProvider` is `none`.
|
|
13
|
+
*/
|
|
14
|
+
orgCanAddModel: boolean;
|
|
15
|
+
/** The agents the caller can see (the agent list's visibility). */
|
|
16
|
+
agents: number;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Whether the org can run (web-order spec §3.8): the web app decides between the shell and the
|
|
20
|
+
* setup layout with it, and the setup checklist sends the viewer to the org's 扩展 page or to the
|
|
21
|
+
* admin console by `orgCanAddModel`.
|
|
22
|
+
*/
|
|
23
|
+
export declare class ReadinessService {
|
|
24
|
+
private readonly registry;
|
|
25
|
+
private readonly configs;
|
|
26
|
+
private readonly agents;
|
|
27
|
+
constructor(registry: ProviderRegistry, configs: OrgExtensionConfigs, agents: AgentsService);
|
|
28
|
+
get(orgId: string, viewer: string | null): Promise<OrgReadiness>;
|
|
29
|
+
private orgCanAddModel;
|
|
30
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
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 { MODEL_PROVIDER_EXTENSION_POINT_V2, parseExtensionPoint } from "@capybara-hq/plugin-sdk";
|
|
11
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
12
|
+
import { OrgExtensionConfigs, providesOf, } from "../extensions/org-config.js";
|
|
13
|
+
import { ProviderRegistry } from "../runtime/providers.js";
|
|
14
|
+
import { AgentsService } from "./agents.service.js";
|
|
15
|
+
const MODEL_PROVIDER = parseExtensionPoint(MODEL_PROVIDER_EXTENSION_POINT_V2).name;
|
|
16
|
+
const isModelProvider = (v) => providesOf(v).some((ref) => parseExtensionPoint(ref).name === MODEL_PROVIDER);
|
|
17
|
+
/**
|
|
18
|
+
* Whether the org admin can turn `v` into a usable provider here: it is loaded on the deployment
|
|
19
|
+
* and either switchable while off, or on and waiting for the org's config (an org-level field or
|
|
20
|
+
* an overridable platform field).
|
|
21
|
+
*/
|
|
22
|
+
const orgCanFix = (v) => v.available &&
|
|
23
|
+
((!v.enabled && v.switchable) ||
|
|
24
|
+
(v.enabled && v.needsConfig && (v.configurable || v.overrideState !== "none")));
|
|
25
|
+
/**
|
|
26
|
+
* Whether the org can run (web-order spec §3.8): the web app decides between the shell and the
|
|
27
|
+
* setup layout with it, and the setup checklist sends the viewer to the org's 扩展 page or to the
|
|
28
|
+
* admin console by `orgCanAddModel`.
|
|
29
|
+
*/
|
|
30
|
+
let ReadinessService = class ReadinessService {
|
|
31
|
+
registry;
|
|
32
|
+
configs;
|
|
33
|
+
agents;
|
|
34
|
+
constructor(registry, configs, agents) {
|
|
35
|
+
this.registry = registry;
|
|
36
|
+
this.configs = configs;
|
|
37
|
+
this.agents = agents;
|
|
38
|
+
}
|
|
39
|
+
async get(orgId, viewer) {
|
|
40
|
+
const [ready, visible] = await Promise.all([
|
|
41
|
+
this.registry.hasProvider(orgId),
|
|
42
|
+
this.agents.listVisible(orgId, viewer),
|
|
43
|
+
]);
|
|
44
|
+
return {
|
|
45
|
+
modelProvider: ready ? "ready" : "none",
|
|
46
|
+
orgCanAddModel: ready ? false : await this.orgCanAddModel(orgId),
|
|
47
|
+
agents: visible.length,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
async orgCanAddModel(orgId) {
|
|
51
|
+
const views = await this.configs.list(orgId);
|
|
52
|
+
return views.some((v) => isModelProvider(v) && orgCanFix(v));
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
ReadinessService = __decorate([
|
|
56
|
+
Injectable(),
|
|
57
|
+
__param(0, Inject(ProviderRegistry)),
|
|
58
|
+
__param(1, Inject(OrgExtensionConfigs)),
|
|
59
|
+
__param(2, Inject(AgentsService))
|
|
60
|
+
], ReadinessService);
|
|
61
|
+
export { ReadinessService };
|
|
@@ -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
|
}
|