@capybara-hq/kernel 0.1.0-rc.79 → 0.1.0-rc.80

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.
@@ -40,7 +40,8 @@ export declare class BackgroundTaskFinisher {
40
40
  * task was no longer running, or, with `opts.unclaimed` (the poller), when a live stop claimed it:
41
41
  * the stop's finish is then the only one. `opts.stoppedBy` marks a stop that must never wake the
42
42
  * conversation: `"person"` (a person stopped it) or `"deletion"` (its conversation is being
43
- * deleted).
43
+ * deleted). `opts.keepOwed` keeps a managed task's record `cancel-pending` whatever its finish
44
+ * (a stop verified by operation only: a ref attached later still owes its exact stop).
44
45
  *
45
46
  * A managed task (permission runtime cutover phase 8.3) settles its durable launch state in the
46
47
  * same transaction: a verified end (an exit, a stop) is `terminal` and retires its start intent's
@@ -51,5 +52,6 @@ export declare class BackgroundTaskFinisher {
51
52
  finish(task: BackgroundTaskRow, to: BackgroundFinish, lastLines: string, reported: boolean, opts?: {
52
53
  unclaimed?: boolean;
53
54
  stoppedBy?: BackgroundStoppedBy;
55
+ keepOwed?: boolean;
54
56
  }): Promise<boolean>;
55
57
  }
@@ -55,7 +55,8 @@ let BackgroundTaskFinisher = class BackgroundTaskFinisher {
55
55
  * task was no longer running, or, with `opts.unclaimed` (the poller), when a live stop claimed it:
56
56
  * the stop's finish is then the only one. `opts.stoppedBy` marks a stop that must never wake the
57
57
  * conversation: `"person"` (a person stopped it) or `"deletion"` (its conversation is being
58
- * deleted).
58
+ * deleted). `opts.keepOwed` keeps a managed task's record `cancel-pending` whatever its finish
59
+ * (a stop verified by operation only: a ref attached later still owes its exact stop).
59
60
  *
60
61
  * A managed task (permission runtime cutover phase 8.3) settles its durable launch state in the
61
62
  * same transaction: a verified end (an exit, a stop) is `terminal` and retires its start intent's
@@ -65,7 +66,7 @@ let BackgroundTaskFinisher = class BackgroundTaskFinisher {
65
66
  */
66
67
  async finish(task, to, lastLines, reported, opts = {}) {
67
68
  const managed = isManagedTask(task)
68
- ? to.status === "lost"
69
+ ? to.status === "lost" || opts.keepOwed
69
70
  ? "cancel-pending"
70
71
  : "terminal"
71
72
  : undefined;
@@ -15,7 +15,11 @@ export declare class ManagedInstanceMismatchError extends Error {
15
15
  export declare const MANAGED_STOP_GRACE_MS = 5000;
16
16
  /** The most bytes a summary's tail asks for (the summary keeps 20 lines, 4,000 characters). */
17
17
  export declare const MANAGED_TAIL_BYTES = 12000;
18
- /** The task's exact ref and instance generation, validated against its own recorded identity. */
18
+ /**
19
+ * The task's exact ref and instance generation, validated against its own recorded identity. The
20
+ * generation is the kernel's (the task's recorded instance); the ref's own `instanceGeneration` is
21
+ * the provider's locator (device-local's machine names its bound generation) and is not compared.
22
+ */
19
23
  export declare function exactRefOf(task: BackgroundTaskRow): {
20
24
  ref: SandboxExecutionRef;
21
25
  deviceId: string;
@@ -24,7 +24,11 @@ export class ManagedInstanceMismatchError extends Error {
24
24
  export const MANAGED_STOP_GRACE_MS = 5000;
25
25
  /** The most bytes a summary's tail asks for (the summary keeps 20 lines, 4,000 characters). */
26
26
  export const MANAGED_TAIL_BYTES = 12_000;
27
- /** The task's exact ref and instance generation, validated against its own recorded identity. */
27
+ /**
28
+ * The task's exact ref and instance generation, validated against its own recorded identity. The
29
+ * generation is the kernel's (the task's recorded instance); the ref's own `instanceGeneration` is
30
+ * the provider's locator (device-local's machine names its bound generation) and is not compared.
31
+ */
28
32
  export function exactRefOf(task) {
29
33
  const bad = () => new ManagedRefError(task.id);
30
34
  if (task.executionRef === null ||
@@ -45,7 +49,6 @@ export function exactRefOf(task) {
45
49
  if (!Number.isSafeInteger(generation) ||
46
50
  ref.operationId !== task.operationId ||
47
51
  ref.instanceId !== task.instanceId ||
48
- ref.instanceGeneration !== task.instanceGeneration ||
49
52
  (task.sandboxCreatedAt !== null && task.sandboxCreatedAt.getTime() !== generation))
50
53
  throw bad();
51
54
  return { ref, deviceId: task.deviceId, generation };
@@ -57,6 +57,15 @@ export declare class BackgroundTaskStopper {
57
57
  * conversation, a sub-agent's root) or its org is deleted or gone, else null.
58
58
  */
59
59
  private deletedConversationStop;
60
+ /**
61
+ * A managed task whose start was never confirmed (no ref) and whose exact operation revoke the
62
+ * provider acknowledged: the operation is tombstoned and any execution it owned cancelled
63
+ * (`revokeOperation`), a verified end. The task finishes `stopped` with its asker's wake rule,
64
+ * instead of running until its retention expires (#765). Its record stays `cancel-pending`: a
65
+ * ref attached later still owes the exact stop by that ref, and the retention expiry settles a
66
+ * record that never gets one.
67
+ */
68
+ settleRevokedUnconfirmed(task: BackgroundTaskRow): Promise<void>;
60
69
  private stopManaged;
61
70
  /**
62
71
  * A legacy task's own instance, never signalled: a running one refuses with the retirement
@@ -28,6 +28,17 @@ export const RECREATED = {
28
28
  lostReason: "sandbox_recreated",
29
29
  killPending: false,
30
30
  };
31
+ /** The finish options of a stop asked for by `by`: who stopped it decides whether it may wake. */
32
+ function stoppedByOpts(by) {
33
+ const stoppedBy = by === "person"
34
+ ? "person"
35
+ : by === "conversation_deleted"
36
+ ? "deletion"
37
+ : by === "subagent_end"
38
+ ? "subagent_end"
39
+ : undefined;
40
+ return stoppedBy === undefined ? {} : { stoppedBy };
41
+ }
31
42
  /**
32
43
  * Stops background tasks (spec 2026-11-05-background-bash-design §2.3, §4.3, permission runtime
33
44
  * cutover phase 8.3): a managed task by its exact ref on its exact instance only, through
@@ -135,6 +146,26 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
135
146
  ? "conversation_deleted"
136
147
  : null;
137
148
  }
149
+ /**
150
+ * A managed task whose start was never confirmed (no ref) and whose exact operation revoke the
151
+ * provider acknowledged: the operation is tombstoned and any execution it owned cancelled
152
+ * (`revokeOperation`), a verified end. The task finishes `stopped` with its asker's wake rule,
153
+ * instead of running until its retention expires (#765). Its record stays `cancel-pending`: a
154
+ * ref attached later still owes the exact stop by that ref, and the retention expiry settles a
155
+ * record that never gets one.
156
+ */
157
+ async settleRevokedUnconfirmed(task) {
158
+ const cur = (await this.store.get(task.id)) ?? task;
159
+ if (cur.status !== "running" || cur.executionRef !== null || !isManagedTask(cur))
160
+ return;
161
+ if (cur.launchState !== "dispatched" && cur.launchState !== "cancel-pending")
162
+ return;
163
+ const by = cur.cancelRequestedBy ?? (await this.deletedConversationStop(cur));
164
+ await this.finisher.finish(cur, { status: "stopped" }, "", false, {
165
+ ...stoppedByOpts(by),
166
+ keepOwed: true,
167
+ });
168
+ }
138
169
  async stopManaged(cur, why, signal, reportedHere) {
139
170
  if (cur.status !== "running")
140
171
  return cur;
@@ -150,14 +181,7 @@ let BackgroundTaskStopper = class BackgroundTaskStopper {
150
181
  }
151
182
  // `reportedHere`: the caller's own result tells the model this finish (a TaskOutput read)
152
183
  const reported = reportedHere ?? (by === "tool" && why === "tool");
153
- const stoppedBy = by === "person"
154
- ? "person"
155
- : by === "conversation_deleted"
156
- ? "deletion"
157
- : by === "subagent_end"
158
- ? "subagent_end"
159
- : undefined;
160
- const opts = stoppedBy === undefined ? {} : { stoppedBy };
184
+ const opts = stoppedByOpts(by);
161
185
  const pending = async () => {
162
186
  await this.store.requestCancel(cur.id, asker, true);
163
187
  return (await this.store.get(cur.id)) ?? cur;
@@ -211,6 +211,26 @@ export declare const templateIdOfPath: (path: string) => string;
211
211
  * version's file (an update's target) ships it off, in place of the platform row's.
212
212
  */
213
213
  export declare function connectorTemplatesOn(db: KernelSchemaDb, orgId: string, itemId: string, ids: readonly string[], defaultOff?: ReadonlyMap<string, boolean>): Promise<Set<string>>;
214
+ /** A component switch an install writes for the templates the org chose (or left out). */
215
+ export interface TemplateSwitch {
216
+ componentId: string;
217
+ name: string;
218
+ plugin: string | null;
219
+ from: boolean | null;
220
+ to: boolean;
221
+ }
222
+ /**
223
+ * The org's choice of a plugin's connector templates at install (the wizard's choose step), read
224
+ * with the plugin installed: `on` the chosen template ids, `switches` the org switches that make
225
+ * exactly those on (a chosen one off now -> on, a left-out one on now -> off), `refused` chosen ids
226
+ * that cannot come on in the org (disabled, not offered) and left-out ids of a builtin plugin
227
+ * (locked on). Template ids without a component row are left to the caller.
228
+ */
229
+ export declare function connectorTemplateChoice(db: KernelSchemaDb, orgId: string, itemId: string, chosen: ReadonlySet<string>): Promise<{
230
+ on: Set<string>;
231
+ switches: TemplateSwitch[];
232
+ refused: string[];
233
+ }>;
214
234
  /** The org's live connectors made from platform connector template `id` (they stay its own). */
215
235
  export declare function connectorsMadeFrom(db: KernelSchemaDb, orgId: string, id: string): Promise<number>;
216
236
  /**
@@ -465,6 +465,43 @@ export async function connectorTemplatesOn(db, orgId, itemId, ids, defaultOff) {
465
465
  .map((c) => c.name));
466
466
  return new Set(ids.filter((id) => !off.has(id)));
467
467
  }
468
+ /**
469
+ * The org's choice of a plugin's connector templates at install (the wizard's choose step), read
470
+ * with the plugin installed: `on` the chosen template ids, `switches` the org switches that make
471
+ * exactly those on (a chosen one off now -> on, a left-out one on now -> off), `refused` chosen ids
472
+ * that cannot come on in the org (disabled, not offered) and left-out ids of a builtin plugin
473
+ * (locked on). Template ids without a component row are left to the caller.
474
+ */
475
+ export async function connectorTemplateChoice(db, orgId, itemId, chosen) {
476
+ const comps = await loadComponents(db, "connector_template", { itemId });
477
+ const st = await loadScopeState(db, "connector_template", comps);
478
+ const on = new Set();
479
+ const switches = [];
480
+ const refused = [];
481
+ for (const c of comps) {
482
+ const p = pluginFactsOf(st, c.itemId, orgId);
483
+ const installed = p && { ...p, installed: true };
484
+ const listed = listedIn(st, c.id, orgId);
485
+ const sw = switchOf(st, c.id, orgId);
486
+ const now = componentOn(c, installed, listed, sw);
487
+ const want = chosen.has(c.name);
488
+ if (want) {
489
+ if (!componentOn(c, installed, listed, true)) {
490
+ refused.push(c.name);
491
+ continue;
492
+ }
493
+ on.add(c.name);
494
+ }
495
+ else if (now && componentLocked(c, p)) {
496
+ refused.push(c.name);
497
+ continue;
498
+ }
499
+ if (now !== want) {
500
+ switches.push({ componentId: c.id, name: c.name, plugin: c.plugin, from: sw, to: want });
501
+ }
502
+ }
503
+ return { on, switches, refused };
504
+ }
468
505
  /** The org's live connectors made from platform connector template `id` (they stay its own). */
469
506
  export async function connectorsMadeFrom(db, orgId, id) {
470
507
  const r = await db
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.65";
211
+ readonly sdk: "0.1.0-rc.66";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -43,7 +43,10 @@ export declare const CatalogConnectorInput: z.ZodObject<{
43
43
  }, z.core.$strict>>;
44
44
  }, z.core.$strict>;
45
45
  /**
46
- * The org install body: template input. No version: an org installs the platform version (one per
46
+ * The org install body: template input, and the connector templates the org chose to switch on
47
+ * (`templatesOn`: exactly these are on after the install and make connectors, the plugin's other
48
+ * templates are switched off in the org and stay available on the connectors page; absent: the
49
+ * templates on in the org now). No version: an org installs the platform version (one per
47
50
  * deployment, ruling P2-17).
48
51
  */
49
52
  export declare const OrgPluginInstallBody: z.ZodObject<{
@@ -57,6 +60,7 @@ export declare const OrgPluginInstallBody: z.ZodObject<{
57
60
  clientSecret: z.ZodOptional<z.ZodString>;
58
61
  }, z.core.$strict>>;
59
62
  }, z.core.$strict>>>;
63
+ templatesOn: z.ZodOptional<z.ZodArray<z.ZodString>>;
60
64
  }, z.core.$strict>;
61
65
  /**
62
66
  * `POST …/catalog/:itemId/connectors` (ruling P2-10): the input of missing connectors, by template
@@ -110,6 +114,7 @@ export declare const OrgPluginSwitchBody: z.ZodObject<{
110
114
  clientSecret: z.ZodOptional<z.ZodString>;
111
115
  }, z.core.$strict>>;
112
116
  }, z.core.$strict>>>;
117
+ templatesOn: z.ZodOptional<z.ZodArray<z.ZodString>>;
113
118
  }, z.core.$strict>>;
114
119
  confirm: z.ZodOptional<z.ZodString>;
115
120
  }, z.core.$strict>;
@@ -70,12 +70,16 @@ export const CatalogConnectorInput = z
70
70
  })
71
71
  .strict();
72
72
  /**
73
- * The org install body: template input. No version: an org installs the platform version (one per
73
+ * The org install body: template input, and the connector templates the org chose to switch on
74
+ * (`templatesOn`: exactly these are on after the install and make connectors, the plugin's other
75
+ * templates are switched off in the org and stay available on the connectors page; absent: the
76
+ * templates on in the org now). No version: an org installs the platform version (one per
74
77
  * deployment, ruling P2-17).
75
78
  */
76
79
  export const OrgPluginInstallBody = z
77
80
  .object({
78
81
  connectors: z.record(z.string(), CatalogConnectorInput).optional(),
82
+ templatesOn: z.array(z.string().min(1).max(100)).max(50).optional(),
79
83
  })
80
84
  .strict();
81
85
  /**
@@ -15,7 +15,7 @@ import { type ThemePreview } from "../themes/theme-usage.js";
15
15
  import type { ConnectorDetail, CreateConnectorInput, ToolIssue } from "../tools/connectors.service.js";
16
16
  import { ConnectorsService } from "../tools/connectors.service.js";
17
17
  import { type CatalogVersionFiles, type TemplateDeps } from "./catalog-content.js";
18
- import { type DefinitionRefs } from "./component-state.js";
18
+ import { type DefinitionRefs, type TemplateSwitch } from "./component-state.js";
19
19
  /** What an org fills in for one connector template at install (C30). */
20
20
  export interface ConnectorInstallInput {
21
21
  name?: string;
@@ -35,6 +35,12 @@ export interface ConnectorInstallInput {
35
35
  */
36
36
  export interface PluginInstallInput {
37
37
  connectors?: Record<string, ConnectorInstallInput>;
38
+ /**
39
+ * The connector templates the org chose to switch on with the install (the install wizard's choose step):
40
+ * exactly these are on afterwards, the others switched off in the org. Absent: the templates on
41
+ * in the org now. Root installs only (dependencies get no input).
42
+ */
43
+ templatesOn?: string[];
38
44
  }
39
45
  /**
40
46
  * `plugin` is a dependency install (ref = its plugin install id); `agent_template` (phase C) an
@@ -168,6 +174,11 @@ export interface InstallPlan {
168
174
  id: string;
169
175
  file: ConnectorTemplateFile;
170
176
  }[];
177
+ /**
178
+ * The org switches of the plugin's connector templates the install writes with its completion
179
+ * (the org's `templatesOn` choice); empty without a choice.
180
+ */
181
+ templateSwitches: TemplateSwitch[];
171
182
  /** The connector inputs built from the templates (empty for a preflight without input). */
172
183
  connectors: Map<string, CreateConnectorInput>;
173
184
  /** The names of the plugin's skills (from each SKILL.md). */
@@ -322,6 +333,12 @@ export declare class PluginInstaller {
322
333
  * `approvedBy` is the root item for a dependency.
323
334
  */
324
335
  plan(orgId: string, actor: string | null, itemId: string, version: string, input: PluginInstallInput | null, at: string, approvedBy: string | undefined): Promise<InstallPlan>;
336
+ /**
337
+ * Checks the org's choice of connector templates (`templatesOn`): every id is one of the
338
+ * plugin's templates and can come on in the org, and no template of a builtin plugin is left
339
+ * out (`validation_failed` at `templatesOn`). Returns the chosen ids and the switches to write.
340
+ */
341
+ private templateChoice;
325
342
  /**
326
343
  * The providers of the templates' connector kinds as implied dependencies: a template whose
327
344
  * `plugin` is neither this plugin, a declared dependency nor already enabled in the org makes that
@@ -32,7 +32,7 @@ import { assertNotPlatformDefault, themesPreview, } from "../themes/theme-usage.
32
32
  import { ConnectorsService } from "../tools/connectors.service.js";
33
33
  import { findConnectorIn, lockOrgForActions, readCatalogAgentTemplates, readCatalogFiles, readCatalogTemplates, requiredActions, templateConnectorInput, templatePluginProblem, } from "./catalog-content.js";
34
34
  import { versionUsable } from "./catalog-items.js";
35
- import { agentDefinitionRefs, componentOn, connectorTemplateState, connectorTemplatesOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, referenceIds, switchOf, themeIdClashes, } from "./component-state.js";
35
+ import { agentDefinitionRefs, componentOn, connectorTemplateChoice, connectorTemplateState, connectorTemplatesOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, referenceIds, switchOf, themeIdClashes, } from "./component-state.js";
36
36
  import { LIVE_INSTALL_STATUSES } from "./install-status.js";
37
37
  import { assertItemInstallable, disabledPluginItems, pluginItemDisabled, resolveRequestsByInstall, } from "./request-rules.js";
38
38
  import { visibleTo } from "./scope.js";
@@ -465,7 +465,17 @@ let PluginInstaller = class PluginInstaller {
465
465
  const allTemplates = await readCatalogTemplates(this.storage, v);
466
466
  // Only the connector templates on in the org make connectors (ruling P2-6): one switched off
467
467
  // there, outside its own scope or disabled is skipped (input given for it is ignored)
468
- const on = await connectorTemplatesOn(this.db, orgId, itemId, allTemplates.map((t) => t.id));
468
+ // The org's choice (`templatesOn`), else the templates on in the org now
469
+ let on;
470
+ let templateSwitches = [];
471
+ if (input?.templatesOn !== undefined) {
472
+ const choice = await this.templateChoice(orgId, itemId, allTemplates, input.templatesOn, at);
473
+ on = choice.on;
474
+ templateSwitches = choice.switches;
475
+ }
476
+ else {
477
+ on = await connectorTemplatesOn(this.db, orgId, itemId, allTemplates.map((t) => t.id));
478
+ }
469
479
  const templates = allTemplates.filter((t) => on.has(t.id));
470
480
  const deps = [
471
481
  ...declared,
@@ -514,12 +524,30 @@ let PluginInstaller = class PluginInstaller {
514
524
  sourceFormat: v.source_format,
515
525
  extension,
516
526
  templates,
527
+ templateSwitches,
517
528
  connectors,
518
529
  skillNames,
519
530
  agentTemplates,
520
531
  dependencies,
521
532
  };
522
533
  }
534
+ /**
535
+ * Checks the org's choice of connector templates (`templatesOn`): every id is one of the
536
+ * plugin's templates and can come on in the org, and no template of a builtin plugin is left
537
+ * out (`validation_failed` at `templatesOn`). Returns the chosen ids and the switches to write.
538
+ */
539
+ async templateChoice(orgId, itemId, allTemplates, chosen, at) {
540
+ const ids = new Set(allTemplates.map((t) => t.id));
541
+ for (const id of chosen) {
542
+ if (!ids.has(id))
543
+ throw fail(`${at}templatesOn`, `No such connector template in this plugin: ${id}`);
544
+ }
545
+ const choice = await connectorTemplateChoice(this.db, orgId, itemId, new Set(chosen));
546
+ if (choice.refused.length > 0) {
547
+ throw fail(`${at}templatesOn`, `These connector templates cannot be chosen in this organization (disabled, not offered, or built in): ${choice.refused.join(", ")}`);
548
+ }
549
+ return { on: choice.on, switches: choice.switches };
550
+ }
523
551
  /**
524
552
  * The providers of the templates' connector kinds as implied dependencies: a template whose
525
553
  * `plugin` is neither this plugin, a declared dependency nor already enabled in the org makes that
@@ -898,6 +926,41 @@ let PluginInstaller = class PluginInstaller {
898
926
  if (ctx.switchOn === true && ctx.parent === undefined) {
899
927
  await upsertOrgSwitch(t, orgId, itemId, true, actor);
900
928
  }
929
+ // The org's choice of connector templates is written with the install too: the chosen ones on,
930
+ // the ones left out off (they stay available on the connectors page)
931
+ for (const sw of plan.templateSwitches) {
932
+ await t
933
+ .insertInto("component_org_switches")
934
+ .values({
935
+ kind: "connector_template",
936
+ component_id: sw.componentId,
937
+ org_id: orgId,
938
+ enabled: sw.to,
939
+ updated_by: actor,
940
+ })
941
+ .onConflict((oc) => oc.columns(["kind", "component_id", "org_id"]).doUpdateSet({
942
+ enabled: sw.to,
943
+ updated_by: actor,
944
+ updated_at: sql `now()`,
945
+ }))
946
+ .execute();
947
+ await audit(t, {
948
+ actorAccountId: actor,
949
+ ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
950
+ orgId,
951
+ action: "component.org_switched",
952
+ target: sw.componentId,
953
+ detail: {
954
+ kind: "connector_template",
955
+ name: sw.name,
956
+ plugin: sw.plugin,
957
+ from: sw.from,
958
+ to: sw.to,
959
+ viaInstall: installId,
960
+ ...opts.auditDetail,
961
+ },
962
+ });
963
+ }
901
964
  await audit(t, {
902
965
  actorAccountId: actor,
903
966
  ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
@@ -11,7 +11,7 @@ import { Inject, Injectable } from "@nestjs/common";
11
11
  import { z } from "zod";
12
12
  import { AppearanceService } from "../../catalog/appearance.service.js";
13
13
  import { CatalogScopeService } from "../../catalog/catalog-scope.service.js";
14
- import { CatalogConnectorInput, CatalogItemPathParams, PluginInstallPathParams, } from "../../catalog/org-catalog.schemas.js";
14
+ import { CatalogConnectorInput, CatalogItemPathParams, OrgPluginInstallBody, PluginInstallPathParams, } from "../../catalog/org-catalog.schemas.js";
15
15
  import { OrgCatalogService } from "../../catalog/org-catalog.service.js";
16
16
  import { OrgExtensionParams } from "../../catalog/org-extension.schemas.js";
17
17
  import { OrgPluginUploads } from "../../catalog/org-plugin-uploads.js";
@@ -57,6 +57,7 @@ const InstallInput = z
57
57
  .object({
58
58
  itemId: ItemId,
59
59
  templates: Templates.optional().describe("Per connector template id (plugins.get lists them), the connector's name, slug, endpoint fields and OAuth client id; never a credential."),
60
+ templatesOn: OrgPluginInstallBody.shape.templatesOn.describe("The connector template ids to switch on with the install (the web wizard's choose step): exactly these make connectors, the plugin's other templates are switched off in the org and stay available on the connectors page. Omit to take the templates on in the org now (default-on ones, and default-off ones an admin switched on)."),
60
61
  askPerson: personFieldParams.askPerson,
61
62
  })
62
63
  .strict();
@@ -181,9 +182,12 @@ let OrgPluginsOperations = class OrgPluginsOperations {
181
182
  * switch-off, as the install wizard asks). The extension's config for the org is its copy of the
182
183
  * overridable fields, saved apart (`extensions.save-org-config`).
183
184
  */
184
- async installTargets(ctx, itemId) {
185
+ async installTargets(ctx, itemId, templatesOn) {
185
186
  const d = await this.orgCatalog.detail(ctx.orgId, ctx.actorAccountId, itemId);
186
- const templates = d.templates.filter((t) => t.on && !t.connected).map(targetOf);
187
+ const templates = d.templates
188
+ .filter((t) => (templatesOn === undefined ? t.on : templatesOn.includes(t.id)))
189
+ .filter((t) => !t.connected)
190
+ .map(targetOf);
187
191
  return {
188
192
  item: d.item,
189
193
  templates,
@@ -621,7 +625,7 @@ let OrgPluginsOperations = class OrgPluginsOperations {
621
625
  precheck: async (i, ctx) => {
622
626
  let r;
623
627
  const read = await precheckBy(async () => {
624
- r = await this.installTargets(ctx, i.itemId);
628
+ r = await this.installTargets(ctx, i.itemId, i.templatesOn);
625
629
  });
626
630
  if (!read.ok || r === undefined)
627
631
  return read;
@@ -634,9 +638,9 @@ let OrgPluginsOperations = class OrgPluginsOperations {
634
638
  }
635
639
  return templatesRefusal(r.templates, i.templates);
636
640
  },
637
- personFields: async (i, ctx) => (await this.installTargets(ctx, i.itemId)).target,
641
+ personFields: async (i, ctx) => (await this.installTargets(ctx, i.itemId, i.templatesOn)).target,
638
642
  summary: async (i, ctx) => {
639
- const { item, templates } = await this.installTargets(ctx, i.itemId);
643
+ const { item, templates } = await this.installTargets(ctx, i.itemId, i.templatesOn);
640
644
  const n = localized(item.displayName, item.name);
641
645
  const e = entersText(ctx);
642
646
  return {
@@ -645,13 +649,16 @@ let OrgPluginsOperations = class OrgPluginsOperations {
645
649
  };
646
650
  },
647
651
  run: async (input, ctx) => {
648
- const { templates } = await this.installTargets(ctx, input.itemId);
652
+ const { templates } = await this.installTargets(ctx, input.itemId, input.templatesOn);
649
653
  // the install runs steps in transactions of their own under the org row lock, so the
650
654
  // values are taken first (takePersonInputs)
651
655
  const { entered, auditDetail } = await takePersonInputs("plugins.install", ctx);
652
656
  const connectors = connectorInputs(templates, input.templates, entered);
653
657
  const r = await this.orgCatalog
654
- .install(ctx.orgId, ctx.actorAccountId, input.itemId, (connectors !== undefined ? { connectors } : {}), undefined, auditDetail)
658
+ .install(ctx.orgId, ctx.actorAccountId, input.itemId, {
659
+ ...(connectors !== undefined && { connectors }),
660
+ ...(input.templatesOn !== undefined && { templatesOn: input.templatesOn }),
661
+ }, undefined, auditDetail)
655
662
  .catch((e) => {
656
663
  throw afterTaken(e, entered);
657
664
  });
@@ -186,7 +186,8 @@ export declare class SandboxOperationIntents {
186
186
  * Gives up on an unknown start (its retention ended, or the kernel would not send it again): the
187
187
  * task becomes terminal `lost` (`launch_unknown`), freeing its slot of `maxTasks`, while the
188
188
  * intent is revoked with an unknown outcome so the exact revoke (the operation tombstone) stays
189
- * owed. A reservation that never dispatched settles as a pre-effect failure instead.
189
+ * owed. A reservation that never dispatched settles as a pre-effect failure instead, and a task
190
+ * already stopped by an acknowledged operation revoke has its record settled.
190
191
  */
191
192
  abandonBackgroundLaunch(id: string, why: string): Promise<void>;
192
193
  /** The recorded input of an operation (for a same-identity retry only). */
@@ -672,9 +672,10 @@ let SandboxOperationIntents = class SandboxOperationIntents {
672
672
  .forUpdate()
673
673
  .executeTakeFirstOrThrow();
674
674
  const ref = parseSandboxExecutionRef(result);
675
+ // the ref's generation is the provider's own (device-local's machine names its bound
676
+ // generation, #765): the exact instance is the intent's generation and the held handle's id
675
677
  if (r.method !== "backgroundStart" ||
676
678
  ref.operationId !== r.operation_id ||
677
- ref.instanceGeneration !== r.instance_generation ||
678
679
  ref.instanceId !== instanceId)
679
680
  throw new SandboxOperationOutcomeUnknownError("The start result does not name this operation's exact instance; reconcile the same identity");
680
681
  if (r.execution_ref && permissionScopeHash(r.execution_ref) !== permissionScopeHash(ref))
@@ -912,7 +913,8 @@ let SandboxOperationIntents = class SandboxOperationIntents {
912
913
  * Gives up on an unknown start (its retention ended, or the kernel would not send it again): the
913
914
  * task becomes terminal `lost` (`launch_unknown`), freeing its slot of `maxTasks`, while the
914
915
  * intent is revoked with an unknown outcome so the exact revoke (the operation tombstone) stays
915
- * owed. A reservation that never dispatched settles as a pre-effect failure instead.
916
+ * owed. A reservation that never dispatched settles as a pre-effect failure instead, and a task
917
+ * already stopped by an acknowledged operation revoke has its record settled.
916
918
  */
917
919
  async abandonBackgroundLaunch(id, why) {
918
920
  const initial = await this.read(id);
@@ -983,6 +985,22 @@ let SandboxOperationIntents = class SandboxOperationIntents {
983
985
  .where("id", "=", task.id)
984
986
  .where("org_id", "=", r.org_id)
985
987
  .execute();
988
+ // a finished task whose stop was verified by its acknowledged operation revoke only (no ref
989
+ // ever attached): nothing is owed any more once its start can no longer be acknowledged
990
+ if (task &&
991
+ task.status !== "running" &&
992
+ task.execution_ref === null &&
993
+ task.launch_state === "cancel-pending" &&
994
+ r.state === "revoked" &&
995
+ r.revoke_acknowledged)
996
+ await this.db
997
+ .updateTable("background_tasks")
998
+ .set({ launch_state: "terminal" })
999
+ .where("id", "=", task.id)
1000
+ .where("org_id", "=", r.org_id)
1001
+ .where("launch_state", "=", "cancel-pending")
1002
+ .where("execution_ref", "is", null)
1003
+ .execute();
986
1004
  }
987
1005
  /** The recorded input of an operation (for a same-identity retry only). */
988
1006
  async input(row) {
@@ -17,7 +17,7 @@ export declare class SandboxOperationReconcileJob {
17
17
  private readonly config;
18
18
  /** Where a recovered start's refusal keeps the provider's own message (never the task's). */
19
19
  private readonly log?;
20
- constructor(intents: SandboxOperationIntents, db: KernelDb, providers: Pick<DeviceProviders, "forDevice">, sandbox: Pick<SandboxService, "ifRunning">, tasks: Pick<BackgroundTaskStore, "byOperation" | "settleOwedCancel">, stopper: Pick<BackgroundTaskStopper, "stop">, config: Pick<KernelConfigService, "get">,
20
+ constructor(intents: SandboxOperationIntents, db: KernelDb, providers: Pick<DeviceProviders, "forDevice">, sandbox: Pick<SandboxService, "ifRunning">, tasks: Pick<BackgroundTaskStore, "byOperation" | "settleOwedCancel">, stopper: Pick<BackgroundTaskStopper, "stop" | "settleRevokedUnconfirmed">, config: Pick<KernelConfigService, "get">,
21
21
  /** Where a recovered start's refusal keeps the provider's own message (never the task's). */
22
22
  log?: Pick<KernelLogger, "warn"> | undefined);
23
23
  reconcile(operationId: string): Promise<void>;
@@ -205,6 +205,13 @@ let SandboxOperationReconcileJob = class SandboxOperationReconcileJob {
205
205
  if (!provider?.revokeOperation)
206
206
  throw new SandboxOperationOutcomeUnknownError("The operation's provider is unavailable; revocation remains owed");
207
207
  await provider.revokeOperation(instance.handle, { operationId: row.operation_id, admitBeforeMs: row.deadline.getTime() }, AbortSignal.timeout(30_000));
208
+ // a start revoked before its ref was known: the tombstone cancelled whatever it launched, so
209
+ // its task ends now rather than at its retention expiry
210
+ if (row.method === "backgroundStart") {
211
+ const task = await this.tasks.byOperation(row.operation_id);
212
+ if (task)
213
+ await this.stopper.settleRevokedUnconfirmed(task);
214
+ }
208
215
  await this.intents.acknowledgeRevocation(operationId);
209
216
  }
210
217
  /**
@@ -257,9 +264,8 @@ let SandboxOperationReconcileJob = class SandboxOperationReconcileJob {
257
264
  return;
258
265
  }
259
266
  const generation = Number(row.instance_generation);
260
- if (!Number.isSafeInteger(generation) ||
261
- ref.operationId !== row.operation_id ||
262
- ref.instanceGeneration !== row.instance_generation)
267
+ // the ref's own generation is the provider's; the incarnation is the intent's generation
268
+ if (!Number.isSafeInteger(generation) || ref.operationId !== row.operation_id)
263
269
  throw owed("The recorded execution reference does not match its start");
264
270
  const r = await this.sandbox.ifRunning(row.device_id,
265
271
  // the exact stop of a revoked start: an exact-ref drain (8.5)
@@ -2350,9 +2350,8 @@ let SandboxService = class SandboxService {
2350
2350
  catch {
2351
2351
  return { failed: `revoked start ${m.refId} has no valid execution reference` };
2352
2352
  }
2353
- if (ref.operationId !== m.refId ||
2354
- ref.instanceGeneration !== o.instanceGeneration ||
2355
- ref.instanceId !== live.handle.id)
2353
+ // the intent named the incarnation above; the ref's generation is the provider's own
2354
+ if (ref.operationId !== m.refId || ref.instanceId !== live.handle.id)
2356
2355
  return { failed: `revoked start ${m.refId} names another instance` };
2357
2356
  owed.push(ref);
2358
2357
  }
@@ -261,9 +261,12 @@ export async function runInBackgroundManaged(deps, ctx, input) {
261
261
  if (launch.kind === "unknown") {
262
262
  throw new ToolError(`Background task ${task.id} ("${description}") may have started, but its start was not confirmed; it is being reconciled under its original identity and will not be started again. Check TaskList before starting it again.`, { kind: "unavailable" });
263
263
  }
264
- // a retry of a call whose acknowledged task has since ended reports the start it made
264
+ // a retry of a call whose acknowledged task has since ended reports the start it made; a ref
265
+ // attached to an owed cancellation (a task stopped by its operation revoke before the ref was
266
+ // known) is a stop still being applied, not a start
265
267
  const started = task.executionRef !== null &&
266
- (task.launchState === "acknowledged" || task.status !== "running");
268
+ (task.launchState === "acknowledged" ||
269
+ (task.status !== "running" && task.launchState !== "cancel-pending"));
267
270
  if (!started && launch.kind !== "refused" && task.status === "lost") {
268
271
  // revoked or given up before its start was confirmed: the process may have started, and its
269
272
  // exact revoke (owed with the revocation) stops it; never claim that nothing ran
@@ -324,6 +324,10 @@ async function managedTaskOutput(deps, env, ctx, first, block, timeout) {
324
324
  else if (task.lostReason === "launch_unknown") {
325
325
  why = "[No output: whether the command started could not be confirmed.]";
326
326
  }
327
+ else if (task.status === "stopped" && task.instanceGeneration !== null) {
328
+ // dispatched (its instance recorded), then stopped by its operation revoke unconfirmed
329
+ why = "[No output: the task was stopped before its start was confirmed.]";
330
+ }
327
331
  return result(task, [statusLine(task), why]);
328
332
  }
329
333
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.79",
3
+ "version": "0.1.0-rc.80",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  "yaml": "^2.9.1",
67
67
  "yauzl": "3.4.0",
68
68
  "zod": "^4.6.7",
69
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.65"
69
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.66"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",