@capybara-hq/kernel 0.1.0-rc.74 → 0.1.0-rc.76

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.
Files changed (94) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/agents/readiness.controller.d.ts +4 -3
  3. package/dist/agents/readiness.controller.js +4 -3
  4. package/dist/agents/readiness.service.d.ts +44 -11
  5. package/dist/agents/readiness.service.js +59 -16
  6. package/dist/catalog/catalog-import.module.d.ts +1 -1
  7. package/dist/catalog/catalog-import.module.js +1 -1
  8. package/dist/catalog/cli.d.ts +9 -2
  9. package/dist/catalog/cli.js +10 -4
  10. package/dist/catalog/marketplaces.service.d.ts +1 -1
  11. package/dist/catalog/plugin-upgrade.d.ts +4 -2
  12. package/dist/catalog/plugin-upgrade.js +9 -3
  13. package/dist/db/kernel-schema.d.ts +5 -0
  14. package/dist/devices/device-projects.service.d.ts +3 -12
  15. package/dist/devices/device-projects.service.js +20 -63
  16. package/dist/devices/devices.service.d.ts +15 -12
  17. package/dist/devices/devices.service.js +25 -19
  18. package/dist/dial-in/machines.d.ts +3 -15
  19. package/dist/dial-in/machines.js +4 -60
  20. package/dist/extensions/bootstrap.d.ts +17 -3
  21. package/dist/extensions/bootstrap.js +56 -14
  22. package/dist/http/meta.controller.d.ts +0 -1
  23. package/dist/http/meta.controller.js +2 -6
  24. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  25. package/dist/lifecycle/kernel-lifecycle.js +16 -11
  26. package/dist/overrides.d.ts +0 -5
  27. package/dist/overrides.js +0 -2
  28. package/dist/platform/file-ref.d.ts +6 -5
  29. package/dist/platform/ops/agent-skills.ops.js +1 -1
  30. package/dist/platform/ops/agents.ops.js +1 -1
  31. package/dist/runtime/model-call.d.ts +2 -2
  32. package/dist/runtime/project/knowledge.d.ts +1 -1
  33. package/dist/runtime/project/knowledge.js +1 -1
  34. package/dist/runtime/project/knowledge.service.d.ts +5 -11
  35. package/dist/runtime/project/knowledge.service.js +12 -23
  36. package/dist/runtime/providers.d.ts +34 -1
  37. package/dist/runtime/providers.js +56 -7
  38. package/dist/runtime/run-steps.d.ts +4 -6
  39. package/dist/runtime/run-steps.js +7 -15
  40. package/dist/runtime/runtime.module.js +1 -1
  41. package/dist/sandbox/device-sandbox.d.ts +16 -2
  42. package/dist/sandbox/device-sandbox.js +13 -5
  43. package/dist/sandbox/held-operations.d.ts +2 -5
  44. package/dist/sandbox/held-operations.js +0 -14
  45. package/dist/sandbox/managed-device-context.d.ts +1 -1
  46. package/dist/sandbox/managed-device-context.js +1 -1
  47. package/dist/sandbox/operation-authority.js +3 -1
  48. package/dist/sandbox/permission-authority-lock.d.ts +6 -0
  49. package/dist/sandbox/permission-authority-lock.js +14 -0
  50. package/dist/sandbox/permission-context-types.d.ts +0 -11
  51. package/dist/sandbox/permission-context-types.js +0 -13
  52. package/dist/sandbox/permission-facts.d.ts +4 -0
  53. package/dist/sandbox/permission-facts.js +6 -1
  54. package/dist/sandbox/providers.d.ts +5 -0
  55. package/dist/sandbox/providers.js +1 -1
  56. package/dist/sandbox/review/permission-candidate.d.ts +12 -7
  57. package/dist/sandbox/review/permission-candidate.js +28 -7
  58. package/dist/sandbox/sandbox-file-reader.d.ts +7 -12
  59. package/dist/sandbox/sandbox-file-reader.js +12 -29
  60. package/dist/sandbox/sandbox.service.d.ts +53 -32
  61. package/dist/sandbox/sandbox.service.js +217 -141
  62. package/dist/sandbox/use-context.d.ts +4 -1
  63. package/dist/setup/setup-guides.service.d.ts +1 -2
  64. package/dist/setup/setup-guides.service.js +1 -4
  65. package/dist/shares/sweep.job.d.ts +2 -0
  66. package/dist/shares/sweep.job.js +3 -1
  67. package/dist/skills/invoke.d.ts +13 -35
  68. package/dist/skills/invoke.js +23 -162
  69. package/dist/tools/builtins/builtin-tools.d.ts +2 -11
  70. package/dist/tools/builtins/builtin-tools.js +5 -23
  71. package/dist/tools/builtins/image/generate.js +2 -2
  72. package/dist/tools/builtins/sandbox/common.d.ts +32 -80
  73. package/dist/tools/builtins/sandbox/common.js +61 -173
  74. package/dist/tools/builtins/sandbox/deliver.js +2 -2
  75. package/dist/tools/builtins/sandbox/device-owner.d.ts +4 -5
  76. package/dist/tools/builtins/sandbox/device-owner.js +5 -6
  77. package/dist/tools/builtins/sandbox/fetch-attachment.js +2 -2
  78. package/dist/tools/builtins/sandbox/glob.js +1 -1
  79. package/dist/tools/builtins/sandbox/grep.js +1 -1
  80. package/dist/tools/builtins/sandbox/index.d.ts +2 -2
  81. package/dist/tools/builtins/sandbox/index.js +2 -2
  82. package/dist/tools/builtins/sandbox/read.js +1 -1
  83. package/dist/tools/builtins/sandbox/task-output.d.ts +3 -3
  84. package/dist/tools/builtins/sandbox/task-output.js +4 -4
  85. package/dist/tools/builtins/sandbox/task-stop.js +1 -1
  86. package/dist/tools/builtins/skill-load.js +2 -2
  87. package/dist/tools/connectors.service.d.ts +4 -2
  88. package/dist/tools/connectors.service.js +15 -3
  89. package/dist/tools/pipeline.d.ts +0 -2
  90. package/dist/tools/pipeline.js +7 -14
  91. package/dist/tools/tools.module.js +1 -1
  92. package/package.json +2 -2
  93. package/src/migrations/0179_device_report_limit_text.sql +28 -0
  94. package/src/migrations/0180_device_instance_abandoned.sql +6 -0
package/dist/overrides.js CHANGED
@@ -25,7 +25,6 @@ import { RUN_HOOKS } from "./runtime/run-worker.js";
25
25
  import { SUBAGENT_MESSAGES_HOOKS, } from "./runtime/subagents/messages.js";
26
26
  import { SANDBOX_LEASE_TIMINGS } from "./sandbox/leases.js";
27
27
  import { PERMISSION_AUTO_GRANT_HOOKS, } from "./sandbox/permission-auto-grants.js";
28
- import { PERMISSION_CONTEXT_ACTIVATION } from "./sandbox/permission-context-types.js";
29
28
  import { SETUP_CHECK_TIMEOUT } from "./setup/setup-checks.service.js";
30
29
  import { TOOL_PIPELINE_HOOKS } from "./tools/pipeline.js";
31
30
  import { EMBED_TOKEN_CLOCK } from "./ui/embed-token.js";
@@ -59,7 +58,6 @@ const SEAM_TOKENS = [
59
58
  PLUGIN_PUBLIC_WRITE_LIMIT,
60
59
  EXTENSION_NET_SEAMS,
61
60
  APP_INTERCEPTOR,
62
- PERMISSION_CONTEXT_ACTIVATION,
63
61
  PERMISSION_AUTO_GRANT_HOOKS,
64
62
  ];
65
63
  const allSeamsListed = true;
@@ -5,11 +5,12 @@ import { StorageService } from "../storage/storage.service.js";
5
5
  /**
6
6
  * File references (platform web parity spec §5): a `Platform` write the web does with an upload
7
7
  * takes a file the agent already has instead, a conversation file (`fileId`: an attachment, a
8
- * generated or delivered artifact, a `read` copy). A file on the conversation's device is delivered
9
- * first (`Deliver`: the device rules, the command review and the activation gate apply) and passed
10
- * by the delivered file's id, so device files have one reading path. The tool resolves it at the
11
- * policy step (limits, sha256, a thumbnail for an image: the card's `detail.file`) and again right
12
- * before the run, which refuses bytes that differ from the ones the person confirmed.
8
+ * generated or delivered artifact, a `read` copy). A file on the conversation's device is
9
+ * delivered first (`Deliver`: the device rules, the command review and the permission profile
10
+ * apply) and passed by the delivered file's id, so device files have one reading path. The tool
11
+ * resolves it at the policy step (limits, sha256, a thumbnail for an image: the card's
12
+ * `detail.file`) and again right before the run, which refuses bytes that differ from the ones the
13
+ * person confirmed.
13
14
  */
14
15
  export type FileRef = {
15
16
  fileId: string;
@@ -475,7 +475,7 @@ let AgentSkillsOperations = class AgentSkillsOperations {
475
475
  path: input.filePath,
476
476
  maxBytes: SKILL_PACKAGE_MAX_BYTES,
477
477
  signal: ctx.signal,
478
- // the read is this call's managed operation once the activation gate is on
478
+ // the read is this call's managed operation
479
479
  ...(ctx.callId !== undefined && { callId: ctx.callId }),
480
480
  });
481
481
  const o = await this.agentSkills.register({
@@ -779,7 +779,7 @@ let AgentsOperations = class AgentsOperations {
779
779
  }),
780
780
  defineOperation({
781
781
  id: "agents.readiness",
782
- description: "Whether the org can run agents: modelProvider is ready when a model provider is available in the org; org_fixable when an org admin can make one available on Settings > Models (orgFixableProviders names each provider and its reason: not_enabled, switch it on; needs_config, fill the org's config); none when only the super admin can help; and how many agents you can see.",
782
+ description: "Whether the org can run agents: modelProvider is ready when the org has a chat model an agent can pick (the list agents.create chooses from); no_models when model providers are on but none gives one (unusableProviders names each provider and its reason: list_failed with errorKind, e.g. auth for a rejected key, or no_chat_models; orgCanFix says whether an org admin can fix it on Settings > Models, else only the super admin can on the admin Models page); org_fixable when no provider is on but an org admin can make one available on Settings > Models (orgFixableProviders names each provider and its reason: not_enabled, switch it on; needs_config, fill the org's config); none when only the super admin can help; and how many agents you can see.",
783
783
  input: z.object({}).strict(),
784
784
  example: {},
785
785
  authz: { orgAction: "org.read" },
@@ -96,8 +96,8 @@ export interface ModelStepDeps {
96
96
  * before each agent-history request construction, record (live) or feed (full-run replay) the
97
97
  * permission context, then rebuild from the complete log. Called at every request construction
98
98
  * of the attempt ladder (a retry, a fallback, the rebuild after a forced compaction, wrap-up);
99
- * absent, no call and no reread (old requests build byte for byte). Live runs get the recorder
100
- * only through the paired activation gate (`RunSteps`); full-run replays strip any live one and
99
+ * absent, no call and no reread (old requests build byte for byte). Live runs always get the
100
+ * recorder (`RunSteps`); full-run replays strip any live one and
101
101
  * install only the recorded feeder (`evals/recorded-permission-context.ts`).
102
102
  */
103
103
  permissionContext?: PermissionContextPort;
@@ -88,7 +88,7 @@ export declare const projectUnavailable: {
88
88
  reason: "gone" | "outside_mode" | "removed" | "unreadable" | "unsupported";
89
89
  message: string;
90
90
  };
91
- /** A host machine whose runtime cannot enforce the kernel's read-only read (gate on). */
91
+ /** A host machine whose runtime cannot enforce the kernel's read-only read. */
92
92
  readonly notEnforceable: (root: string) => {
93
93
  reason: "gone" | "outside_mode" | "removed" | "unreadable" | "unsupported";
94
94
  message: string;
@@ -41,7 +41,7 @@ export const projectUnavailable = {
41
41
  /** The device's own error text is logged, never recorded: the message stays the same per root. */
42
42
  unreadable: (root) => unavailable("unreadable", `The project's root ${clipped(root)} could not be read.`),
43
43
  removed: (project) => unavailable("removed", `The project "${clipped(project, 80)}" was removed from the device's projects.`),
44
- /** A host machine whose runtime cannot enforce the kernel's read-only read (gate on). */
44
+ /** A host machine whose runtime cannot enforce the kernel's read-only read. */
45
45
  notEnforceable: (root) => unavailable("unreadable", `The project's root ${clipped(root)} was not read: this device's runtime cannot enforce a read-only read on its host; turn on its sandbox enforcement or use another device.`),
46
46
  /** A device runtime that refused the kernel's read-only read scope (its text is logged). */
47
47
  refused: (root) => unavailable("unreadable", `The project's root ${clipped(root)} was not read: this device's runtime refused the kernel's read-only read.`),
@@ -42,9 +42,8 @@ export interface ProjectKnowledgeInput {
42
42
  * latest snapshot differs from the child's latest; the renderer then shows it to the child as is.
43
43
  *
44
44
  * Reads in the device's effective mode (`DeviceProjectsService.scopeFor`, the same scope the
45
- * binding was checked against) and through `SandboxService.withSandbox`, as a tool call does, so
46
- * a bound conversation starts its device eagerly (the accepted cost, spec §4.4). Once the
47
- * activation gate is on the read goes through `SandboxService.withKernelRead` instead: every
45
+ * binding was checked against) and through `SandboxService.withKernelRead`, so a bound
46
+ * conversation starts its device eagerly (the accepted cost, spec §4.4): every
48
47
  * stat / readFile / list a kernel read under the run's current execution claim while the run is
49
48
  * still queued, acting for the run's trigger, its scope narrowed to the root, `AGENTS.md` and
50
49
  * `.agents/skills` (permission activation L2). A project the
@@ -64,11 +63,7 @@ export declare class ProjectKnowledgeService {
64
63
  private readonly sandbox;
65
64
  private readonly log;
66
65
  private readonly timeoutMs;
67
- /** The paired activation gate: once on, the read is a set of kernel reads. */
68
- private readonly activation?;
69
- constructor(db: KernelDb, eventLog: Pick<EventLog, "appendIn" | "notify">, txHost: TransactionHost, devices: Pick<ConversationDevices, "forTool">, projects: Pick<DeviceProjectsService, "scopeFor" | "keeps">, sandbox: Pick<SandboxService, "withSandbox" | "withKernelRead">, log: KernelLogger, timeoutMs?: () => number,
70
- /** The paired activation gate: once on, the read is a set of kernel reads. */
71
- activation?: boolean | undefined);
66
+ constructor(db: KernelDb, eventLog: Pick<EventLog, "appendIn" | "notify">, txHost: TransactionHost, devices: Pick<ConversationDevices, "forTool">, projects: Pick<DeviceProjectsService, "scopeFor" | "keeps">, sandbox: Pick<SandboxService, "withKernelRead">, log: KernelLogger, timeoutMs?: () => number);
72
67
  /**
73
68
  * Reads and records (see the class); notifies after the commit. False: the run had ended under
74
69
  * the locks (a stop landed while the device was read), so nothing was appended and the run must
@@ -84,9 +79,8 @@ export declare class ProjectKnowledgeService {
84
79
  /** The snapshot read on the device, or null when the device could not be asked (logged). */
85
80
  private read;
86
81
  /**
87
- * How the read enters the device. Gate off: the raw `withSandbox`, acting for the conversation's
88
- * owner (unchanged). Gate on: `withKernelRead` under the run's current execution claim (the run
89
- * start runs inside it; another run's claim or none admits nothing), acting for the run's
82
+ * How the read enters the device: `withKernelRead` under the run's current execution claim (the
83
+ * run start runs inside it; another run's claim or none admits nothing), acting for the run's
90
84
  * trigger, reading the bound root only.
91
85
  */
92
86
  private entry;
@@ -21,9 +21,8 @@ import { Transactional } from "../../infra/database/transactional.decorator.js";
21
21
  import { KERNEL_LOGGER } from "../../infra/tokens.js";
22
22
  import { KernelReadNotAdmitted, KernelReadUnsupported } from "../../sandbox/kernel-read.js";
23
23
  import { SandboxLockLostError, SandboxPathBusyError } from "../../sandbox/leases.js";
24
- import { PERMISSION_CONTEXT_ACTIVATION, permissionContextActive, } from "../../sandbox/permission-context-types.js";
25
24
  import { homeOf } from "../../sandbox/review/rules.js";
26
- import { SandboxService } from "../../sandbox/sandbox.service.js";
25
+ import { SandboxService, } from "../../sandbox/sandbox.service.js";
27
26
  import { providerConnectionFailure } from "../../sandbox/unreachable.js";
28
27
  import { currentExecutionClaim } from "../run-execution.js";
29
28
  import { runEndedIn } from "../run-status.js";
@@ -48,8 +47,8 @@ class KnowledgeClaimMissing extends Error {
48
47
  /**
49
48
  * An error that says the device could not be asked, not that the project is unreadable: the
50
49
  * provider unreachable, a kernel refusal (the device offline, gone or busy, a relay given up), a
51
- * malformed device answer, a lost lease, a kernel read that was not admitted (gate on: nothing
52
- * was sent to the device).
50
+ * malformed device answer, a lost lease, a kernel read that was not admitted (nothing was sent
51
+ * to the device).
53
52
  */
54
53
  function isDeviceFailure(e) {
55
54
  return (providerConnectionFailure(e) !== undefined ||
@@ -72,9 +71,8 @@ function isDeviceFailure(e) {
72
71
  * latest snapshot differs from the child's latest; the renderer then shows it to the child as is.
73
72
  *
74
73
  * Reads in the device's effective mode (`DeviceProjectsService.scopeFor`, the same scope the
75
- * binding was checked against) and through `SandboxService.withSandbox`, as a tool call does, so
76
- * a bound conversation starts its device eagerly (the accepted cost, spec §4.4). Once the
77
- * activation gate is on the read goes through `SandboxService.withKernelRead` instead: every
74
+ * binding was checked against) and through `SandboxService.withKernelRead`, so a bound
75
+ * conversation starts its device eagerly (the accepted cost, spec §4.4): every
78
76
  * stat / readFile / list a kernel read under the run's current execution claim while the run is
79
77
  * still queued, acting for the run's trigger, its scope narrowed to the root, `AGENTS.md` and
80
78
  * `.agents/skills` (permission activation L2). A project the
@@ -94,10 +92,7 @@ let ProjectKnowledgeService = class ProjectKnowledgeService {
94
92
  sandbox;
95
93
  log;
96
94
  timeoutMs;
97
- activation;
98
- constructor(db, eventLog, txHost, devices, projects, sandbox, log, timeoutMs = () => PROJECT_KNOWLEDGE_TIMEOUT_MS,
99
- /** The paired activation gate: once on, the read is a set of kernel reads. */
100
- activation) {
95
+ constructor(db, eventLog, txHost, devices, projects, sandbox, log, timeoutMs = () => PROJECT_KNOWLEDGE_TIMEOUT_MS) {
101
96
  this.db = db;
102
97
  this.eventLog = eventLog;
103
98
  this.txHost = txHost;
@@ -106,7 +101,6 @@ let ProjectKnowledgeService = class ProjectKnowledgeService {
106
101
  this.sandbox = sandbox;
107
102
  this.log = log;
108
103
  this.timeoutMs = timeoutMs;
109
- this.activation = activation;
110
104
  }
111
105
  /**
112
106
  * Reads and records (see the class); notifies after the commit. False: the run had ended under
@@ -195,7 +189,7 @@ let ProjectKnowledgeService = class ProjectKnowledgeService {
195
189
  });
196
190
  return unavailableProject(bound.project, bound.root, projectUnavailable.unsupported());
197
191
  }
198
- const enter = await this.entry(input, bound.accountId, bound.root);
192
+ const enter = await this.entry(input, bound.root);
199
193
  return await enter({
200
194
  orgId: input.orgId,
201
195
  deviceId,
@@ -246,7 +240,7 @@ let ProjectKnowledgeService = class ProjectKnowledgeService {
246
240
  });
247
241
  return unavailableProject(bound.project, bound.root, projectUnavailable.refused(bound.root));
248
242
  }
249
- // gate on: a host runtime without restricted enforcement gets no kernel read; the
243
+ // a host runtime without restricted enforcement gets no kernel read; the
250
244
  // project is recorded unreadable with the reason and the run goes on
251
245
  if (!(e instanceof KernelReadUnsupported))
252
246
  throw e;
@@ -268,14 +262,11 @@ let ProjectKnowledgeService = class ProjectKnowledgeService {
268
262
  }
269
263
  }
270
264
  /**
271
- * How the read enters the device. Gate off: the raw `withSandbox`, acting for the conversation's
272
- * owner (unchanged). Gate on: `withKernelRead` under the run's current execution claim (the run
273
- * start runs inside it; another run's claim or none admits nothing), acting for the run's
265
+ * How the read enters the device: `withKernelRead` under the run's current execution claim (the
266
+ * run start runs inside it; another run's claim or none admits nothing), acting for the run's
274
267
  * trigger, reading the bound root only.
275
268
  */
276
- async entry(input, owner, root) {
277
- if (!permissionContextActive(this.activation))
278
- return Object.assign(this.sandbox.withSandbox.bind(this.sandbox), { accountId: owner });
269
+ async entry(input, root) {
279
270
  const claim = currentExecutionClaim();
280
271
  if (!claim ||
281
272
  claim.runId !== input.runId ||
@@ -350,8 +341,6 @@ ProjectKnowledgeService = __decorate([
350
341
  __param(5, Inject(SandboxService)),
351
342
  __param(6, Inject(KERNEL_LOGGER)),
352
343
  __param(7, Optional()),
353
- __param(7, Inject(PROJECT_KNOWLEDGE_TIMEOUT)),
354
- __param(8, Optional()),
355
- __param(8, Inject(PERMISSION_CONTEXT_ACTIVATION))
344
+ __param(7, Inject(PROJECT_KNOWLEDGE_TIMEOUT))
356
345
  ], ProjectKnowledgeService);
357
346
  export { ProjectKnowledgeService };
@@ -1,4 +1,4 @@
1
- import { type EmbedRequest, type EmbedResult, type ExtensionManifest, type ExtensionPointRef, type ImageGenerateRequest, type ImageGenerateResult, type Logger, type ModelInfo, type ModelKind, type ModelRequest, type ModelStreamEvent } from "@capybara-hq/plugin-sdk";
1
+ import { type EmbedRequest, type EmbedResult, type ExtensionManifest, type ExtensionPointRef, type ImageGenerateRequest, type ImageGenerateResult, type Logger, type ModelErrorKind, type ModelInfo, type ModelKind, type ModelRequest, type ModelStreamEvent } from "@capybara-hq/plugin-sdk";
2
2
  import type { Redis } from "ioredis";
3
3
  import type { ModelRef } from "../agents/definition.js";
4
4
  import { ApiError } from "../errors.js";
@@ -16,6 +16,11 @@ export declare const LIST_MODELS_TIMEOUT: unique symbol;
16
16
  * 只用于列表;`resolve`(运行时)照常每次请求,失败由降级梯子重试。
17
17
  */
18
18
  export declare const LIST_FAILURE_TTL_SECONDS = 15;
19
+ /**
20
+ * Why a provider's model list failed, as the views report it: the provider's `ModelError` kind
21
+ * (`timeout` too when the kernel's `models.listTimeoutMs` passed), else `unknown`.
22
+ */
23
+ export type ListErrorKind = ModelErrorKind | "unknown";
19
24
  /**
20
25
  * The host view the registry needs: a subset of `ExtensionRegistry` (version, digest and
21
26
  * `current` optional, for test doubles).
@@ -83,8 +88,28 @@ export interface ProviderStatus {
83
88
  plugin: string;
84
89
  status: "ok" | "error" | "org_configured";
85
90
  error?: string;
91
+ /** With `error` from a failed list (not a provider that needs configuration): why it failed. */
92
+ errorKind?: ListErrorKind;
86
93
  models: ListedModelInfo[];
87
94
  }
95
+ /**
96
+ * Whether a provider gives an agent something to pick in an org ({@link ProviderRegistry.chatUsability}):
97
+ * `usable`, at least one enabled chat model; `list_failed`, its list failed (`errorKind`);
98
+ * `no_chat_models`, it lists but no chat model is on in the org (`orgCanEnable`: a chat model the
99
+ * platform left on is on the org's own disabled list, so an org admin can switch one on).
100
+ */
101
+ export type ProviderChatUsability = {
102
+ provider: string;
103
+ state: "usable";
104
+ } | {
105
+ provider: string;
106
+ state: "list_failed";
107
+ errorKind: ListErrorKind;
108
+ } | {
109
+ provider: string;
110
+ state: "no_chat_models";
111
+ orgCanEnable: boolean;
112
+ };
88
113
  /**
89
114
  * 供应商的 `listModels()` 失败(上游不可用等)。仍是 `agent.model_unavailable`,HTTP 调用方照常
90
115
  * 得到该错误码;运行时(`runModelStep`)据此类型把它当作可重试的失败交给降级梯子,
@@ -173,6 +198,14 @@ export declare class ProviderRegistry {
173
198
  * `disabled` for the org's own list. Reads the same cached lists (no extra provider call).
174
199
  */
175
200
  catalog(orgId: string): Promise<ProviderStatus[]>;
201
+ /**
202
+ * Whether each provider gives an agent a model to pick in `orgId` (org readiness): the same
203
+ * cached lists, time limit and failure markers as {@link catalog}, and the same rule as the
204
+ * agent form's list (`list(orgId, { kind: "chat" })`: a chat model neither the platform nor the
205
+ * org disabled). Only providers enabled in the org with a valid effective config there are
206
+ * listed (the {@link hasProvider} gate); the others are left out, never called.
207
+ */
208
+ chatUsability(orgId: string): Promise<ProviderChatUsability[]>;
176
209
  /**
177
210
  * Every installed provider with its status (in plugin load order), for `orgId` (the providers it enabled, their enabled
178
211
  * models only), or the platform view when undefined (`/admin/models`: every model, `disabled`
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { createHash } from "node:crypto";
11
- import { assertValidDeclarations, isValidImageGenerationInfo, parseExtensionPoint, } from "@capybara-hq/plugin-sdk";
11
+ import { assertValidDeclarations, isModelError, isValidImageGenerationInfo, ModelError, parseExtensionPoint, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable, Module, Optional } from "@nestjs/common";
13
13
  import { ApiError } from "../errors.js";
14
14
  import { deploymentConfigHash } from "../extensions/config-hash.js";
@@ -54,6 +54,26 @@ const MODELS_CACHE_FORMAT = 2;
54
54
  * it caches bumps it, so during a rolling upgrade it never reads a list an older kernel wrote.
55
55
  */
56
56
  const modelsKey = (p, hash) => `capk:models:${p.plugin}:f${MODELS_CACHE_FORMAT}:${p.version ?? "-"}:${hash ?? "-"}`;
57
+ const MODEL_ERROR_KINDS = new Set([
58
+ "rate_limited",
59
+ "overloaded",
60
+ "server",
61
+ "timeout",
62
+ "network",
63
+ "auth",
64
+ "invalid_request",
65
+ "context_overflow",
66
+ "refusal",
67
+ "aborted",
68
+ ]);
69
+ /** The kind of a failed list (the `ProviderListError`'s cause, or a failure marker's value). */
70
+ function listErrorKindOf(cause) {
71
+ if (isModelError(cause))
72
+ return cause.kind;
73
+ if (typeof cause === "string" && MODEL_ERROR_KINDS.has(cause))
74
+ return cause;
75
+ return "unknown";
76
+ }
57
77
  /** 列表视图的失败标记({@link LIST_FAILURE_TTL_SECONDS}),与模型列表同样按版本与配置摘要区分。 */
58
78
  const listFailedKey = (p, hash) => `capk:models-failed:${p.plugin}:${p.version ?? "-"}:${hash ?? "-"}`;
59
79
  const droppedKey = (plugin, hash, model) => `capk:models-dropped:${plugin}:${hash ?? "-"}:${model}`;
@@ -176,7 +196,7 @@ let ProviderRegistry = class ProviderRegistry {
176
196
  return await Promise.race([
177
197
  call$,
178
198
  new Promise((_, reject) => {
179
- timer = setTimeout(() => reject(new Error(`listModels timed out after ${ms}ms`)), ms);
199
+ timer = setTimeout(() => reject(new ModelError("timeout", `listModels timed out after ${ms}ms`)), ms);
180
200
  }),
181
201
  ]);
182
202
  }
@@ -344,6 +364,32 @@ let ProviderRegistry = class ProviderRegistry {
344
364
  .map((m) => ({ ...m, disabled: org.has(modelKey(p.provider, m.id)) })),
345
365
  }));
346
366
  }
367
+ /**
368
+ * Whether each provider gives an agent a model to pick in `orgId` (org readiness): the same
369
+ * cached lists, time limit and failure markers as {@link catalog}, and the same rule as the
370
+ * agent form's list (`list(orgId, { kind: "chat" })`: a chat model neither the platform nor the
371
+ * org disabled). Only providers enabled in the org with a valid effective config there are
372
+ * listed (the {@link hasProvider} gate); the others are left out, never called.
373
+ */
374
+ async chatUsability(orgId) {
375
+ const out = [];
376
+ for (const p of await this.catalog(orgId)) {
377
+ if (p.status === "error") {
378
+ // a provider that needs configuration here is not past the gate
379
+ if (p.errorKind !== undefined) {
380
+ out.push({ provider: p.provider, state: "list_failed", errorKind: p.errorKind });
381
+ }
382
+ continue;
383
+ }
384
+ if (p.status !== "ok")
385
+ continue;
386
+ const chat = p.models.filter((m) => m.kind === "chat");
387
+ out.push(chat.some((m) => !m.disabled)
388
+ ? { provider: p.provider, state: "usable" }
389
+ : { provider: p.provider, state: "no_chat_models", orgCanEnable: chat.length > 0 });
390
+ }
391
+ return out;
392
+ }
347
393
  /**
348
394
  * Every installed provider with its status (in plugin load order), for `orgId` (the providers it enabled, their enabled
349
395
  * models only), or the platform view when undefined (`/admin/models`: every model, `disabled`
@@ -390,15 +436,17 @@ let ProviderRegistry = class ProviderRegistry {
390
436
  const failed = listFailedKey(p, t.hash);
391
437
  // a provider that failed just now: mark it error for a while without waiting on it (each
392
438
  // provider has its own time limit too)
393
- if ((await this.kv.get(failed)) !== null) {
394
- throw new ProviderListError(p.plugin, new Error("listModels failed recently"));
395
- }
439
+ // the marker holds the failure's kind, so the views report it while they skip the call
440
+ const recent = await this.kv.get(failed);
441
+ if (recent !== null)
442
+ throw new ProviderListError(p.plugin, listErrorKindOf(recent));
396
443
  try {
397
444
  return await this.models(p, t);
398
445
  }
399
446
  catch (err) {
400
447
  if (err instanceof ProviderListError) {
401
- await this.kv.set(failed, "1", "EX", LIST_FAILURE_TTL_SECONDS);
448
+ const kind = listErrorKindOf(err.cause);
449
+ await this.kv.set(failed, kind, "EX", LIST_FAILURE_TTL_SECONDS);
402
450
  }
403
451
  throw err;
404
452
  }
@@ -419,7 +467,8 @@ let ProviderRegistry = class ProviderRegistry {
419
467
  const error = r.reason instanceof ApiError
420
468
  ? r.reason.message
421
469
  : `Model provider ${provider} failed to list its models`;
422
- return { provider, plugin: provider, status: "error", error, models: [] };
470
+ const errorKind = listErrorKindOf(r.reason instanceof ProviderListError ? r.reason.cause : r.reason);
471
+ return { provider, plugin: provider, status: "error", error, errorKind, models: [] };
423
472
  });
424
473
  }
425
474
  /**
@@ -33,16 +33,14 @@ export declare class AgentLoops {
33
33
  /**
34
34
  * What a run's steps use (`LoopDeps`: one model step plus the tool pipeline), over the injected
35
35
  * services. `deps` is a plain object (eval replays copy it without the hooks, the progress, the
36
- * fork dispatch and the live permission recorder). The live permission context recorder is wired
37
- * only when the paired activation gate is on ({@link PERMISSION_CONTEXT_ACTIVATION}).
36
+ * fork dispatch and the live permission recorder).
38
37
  */
39
38
  export declare class RunSteps {
40
39
  readonly deps: LoopDeps;
41
- constructor(kdb: KernelDb, eventLog: EventLog, stepLog: StepLog, registry: ProviderRegistry, tools: ToolRegistry, config: KernelConfigService, log: KernelLogger, toolPipeline: ToolPipeline, host: ExtensionHost, subagents: SubagentsService, attachments: AttachmentsService, compactionSettings: CompactionSettingsService, compactionProgress: CompactionProgressService, permissionContext: PermissionContextRecorder, activation?: boolean);
40
+ constructor(kdb: KernelDb, eventLog: EventLog, stepLog: StepLog, registry: ProviderRegistry, tools: ToolRegistry, config: KernelConfigService, log: KernelLogger, toolPipeline: ToolPipeline, host: ExtensionHost, subagents: SubagentsService, attachments: AttachmentsService, compactionSettings: CompactionSettingsService, compactionProgress: CompactionProgressService, permissionContext: PermissionContextRecorder);
42
41
  }
43
42
  /**
44
43
  * The live request boundary of a run's steps (spec B2): every agent-history request construction
45
- * records the root's current permission context first. Present only when the one activation gate
46
- * is on ({@link PERMISSION_CONTEXT_ACTIVATION}); otherwise no key at all.
44
+ * records the root's current permission context first.
47
45
  */
48
- export declare function livePermissionContext(recorder: Pick<PermissionContextRecorder, "record">, activation: boolean | undefined): Pick<LoopDeps, "permissionContext">;
46
+ export declare function livePermissionContext(recorder: Pick<PermissionContextRecorder, "record">): Required<Pick<LoopDeps, "permissionContext">>;
@@ -14,7 +14,6 @@ import { ExtensionHost } from "../extensions/host.js";
14
14
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
15
  import { KernelDb } from "../infra/database/kernel-db.js";
16
16
  import { KERNEL_LOGGER } from "../infra/tokens.js";
17
- import { PERMISSION_CONTEXT_ACTIVATION, permissionContextActive, } from "../sandbox/permission-context-types.js";
18
17
  import { ToolPipeline } from "../tools/pipeline.js";
19
18
  import { ToolRegistry } from "../tools/registry.js";
20
19
  import { KyselyCheckpointSaver } from "./checkpointer.js";
@@ -51,12 +50,11 @@ export { AgentLoops };
51
50
  /**
52
51
  * What a run's steps use (`LoopDeps`: one model step plus the tool pipeline), over the injected
53
52
  * services. `deps` is a plain object (eval replays copy it without the hooks, the progress, the
54
- * fork dispatch and the live permission recorder). The live permission context recorder is wired
55
- * only when the paired activation gate is on ({@link PERMISSION_CONTEXT_ACTIVATION}).
53
+ * fork dispatch and the live permission recorder).
56
54
  */
57
55
  let RunSteps = class RunSteps {
58
56
  deps;
59
- constructor(kdb, eventLog, stepLog, registry, tools, config, log, toolPipeline, host, subagents, attachments, compactionSettings, compactionProgress, permissionContext, activation) {
57
+ constructor(kdb, eventLog, stepLog, registry, tools, config, log, toolPipeline, host, subagents, attachments, compactionSettings, compactionProgress, permissionContext) {
60
58
  this.deps = {
61
59
  get db() {
62
60
  return kdb.db;
@@ -81,9 +79,8 @@ let RunSteps = class RunSteps {
81
79
  info: (orgId, conversationId, ids) => attachments.mediaInfo(orgId, conversationId, ids),
82
80
  fetch: (orgId, conversationId, ids, caps) => attachments.fetchMedia(orgId, conversationId, ids, caps),
83
81
  },
84
- // the request boundary of the recorded permission context (spec B2); on since the paired
85
- // activation (device protocol 3), off only where a test provides the gate as false
86
- ...livePermissionContext(permissionContext, activation),
82
+ // the request boundary of the recorded permission context (spec B2)
83
+ ...livePermissionContext(permissionContext),
87
84
  };
88
85
  }
89
86
  };
@@ -102,19 +99,14 @@ RunSteps = __decorate([
102
99
  __param(10, Inject(AttachmentsService)),
103
100
  __param(11, Inject(CompactionSettingsService)),
104
101
  __param(12, Inject(CompactionProgressService)),
105
- __param(13, Inject(PermissionContextRecorder)),
106
- __param(14, Optional()),
107
- __param(14, Inject(PERMISSION_CONTEXT_ACTIVATION))
102
+ __param(13, Inject(PermissionContextRecorder))
108
103
  ], RunSteps);
109
104
  export { RunSteps };
110
105
  /**
111
106
  * The live request boundary of a run's steps (spec B2): every agent-history request construction
112
- * records the root's current permission context first. Present only when the one activation gate
113
- * is on ({@link PERMISSION_CONTEXT_ACTIVATION}); otherwise no key at all.
107
+ * records the root's current permission context first.
114
108
  */
115
- export function livePermissionContext(recorder, activation) {
116
- if (!permissionContextActive(activation))
117
- return {};
109
+ export function livePermissionContext(recorder) {
118
110
  return {
119
111
  permissionContext: {
120
112
  beforeRequest: ({ orgId, conversationId, runId, accountId, signal }) => recorder.record({ orgId, conversationId, runId, accountId }, signal),
@@ -77,7 +77,7 @@ RuntimeModule = __decorate([
77
77
  DevicesModule,
78
78
  SandboxModule,
79
79
  // the recorded permission context: the authority projection shared with admission, its locks
80
- // and publication, and the stored root (dormant until the request boundary activates)
80
+ // and publication, and the stored root
81
81
  OperationAuthorityModule,
82
82
  PermissionAuthorityModule,
83
83
  PermissionProfileStoreModule,
@@ -10,8 +10,17 @@ import type { SandboxBoundary, SandboxPermissionSupport } from "@capybara-hq/plu
10
10
  */
11
11
  /** The sandbox network: the open public internet or an allowlist. `allowlist` is narrower. */
12
12
  export type DeviceNetworkMode = "open" | "allowlist";
13
- /** The layer that set a ceiling, named by a disabled option and an actionable error. */
14
- export type DeviceSandboxLayer = "platform" | "org" | "device" | "provider";
13
+ /**
14
+ * The layer that set a ceiling, named by a disabled option and an actionable error. `owner` is the
15
+ * owner of the machine the device runs on, when its provider says that owner keeps the crossing
16
+ * closed (`SandboxPermissionSupport.limitedBy`); `provider` is the provider's own limit.
17
+ */
18
+ export type DeviceSandboxLayer = "platform" | "org" | "device" | "owner" | "provider";
19
+ /**
20
+ * Whether a ceiling's layer is the device's side (its provider, or the owner of the machine it
21
+ * runs on): it clamps the sandbox network, never what an org allows per call.
22
+ */
23
+ export declare const deviceSideLayer: (layer: DeviceSandboxLayer | null | undefined) => boolean;
15
24
  /**
16
25
  * The platform's device sandbox settings, as the settings reader returns them (env > file / Nacos >
17
26
  * the super admin's stored choice > default `allowed`, `open`, `open`).
@@ -71,6 +80,11 @@ export interface DeviceSandboxProviderLayer {
71
80
  perOperationHosts: boolean;
72
81
  };
73
82
  outsideSandbox: boolean;
83
+ /** Who keeps a closed crossing closed when not the provider itself (support `limitedBy`). */
84
+ limitedBy?: {
85
+ outsideSandbox?: "owner";
86
+ openPublic?: "owner";
87
+ };
74
88
  }
75
89
  /** The effective device sandbox: the same under every permission profile. */
76
90
  export interface DeviceSandbox {
@@ -1,4 +1,9 @@
1
1
  import { coversHost, orgEffectiveHosts } from "./modes.js";
2
+ /**
3
+ * Whether a ceiling's layer is the device's side (its provider, or the owner of the machine it
4
+ * runs on): it clamps the sandbox network, never what an org allows per call.
5
+ */
6
+ export const deviceSideLayer = (layer) => layer === "provider" || layer === "owner";
2
7
  /**
3
8
  * The hosts of `a` the list `b` covers and the hosts of `b` that `a` covers (wildcards included),
4
9
  * lowercased, deduplicated and sorted: never wider than either list.
@@ -43,9 +48,11 @@ export function effectiveDeviceSandbox(platform, org, device, provider) {
43
48
  ? "platform"
44
49
  : org.outsideSandbox === "off"
45
50
  ? "org"
46
- : !provider.outsideSandbox || instance
51
+ : instance
47
52
  ? "provider"
48
- : null;
53
+ : !provider.outsideSandbox
54
+ ? (provider.limitedBy?.outsideSandbox ?? "provider")
55
+ : null;
49
56
  // the network ceiling: platform, then org, then what the provider can enforce
50
57
  let ceiling;
51
58
  let networkLayer = null;
@@ -69,7 +76,7 @@ export function effectiveDeviceSandbox(platform, org, device, provider) {
69
76
  }
70
77
  else if (ceiling === "open" && !provider.network.openPublic) {
71
78
  ceiling = "allowlist";
72
- networkLayer = "provider";
79
+ networkLayer = provider.limitedBy?.openPublic ?? "provider";
73
80
  }
74
81
  // the device's choice, else the org default, else the platform default; then the ceiling
75
82
  const chosen = device.networkMode ?? org.deviceNetwork?.default ?? platform.settings.network.default;
@@ -116,6 +123,7 @@ export function providerLayerOf(support) {
116
123
  boundary: support.boundary,
117
124
  network: { ...support.network },
118
125
  outsideSandbox: support.outsideSandbox,
126
+ ...(support.limitedBy !== undefined && { limitedBy: { ...support.limitedBy } }),
119
127
  };
120
128
  return {
121
129
  boundary: "instance",
@@ -131,7 +139,7 @@ export function hostGrantCeiling(box, platform, org) {
131
139
  return { kind: "hosts", hosts: [] };
132
140
  // the platform's or org's allowlist ceiling is hard; a provider that cannot enforce the open
133
141
  // network clamps the sandbox network, not what an org allows per call
134
- const hard = box.networkCeiling === "allowlist" && box.layer?.network !== "provider";
142
+ const hard = box.networkCeiling === "allowlist" && !deviceSideLayer(box.layer?.network);
135
143
  return hard || platform.orgHosts === "within"
136
144
  ? { kind: "hosts", hosts: orgHostsOf(platform, org) }
137
145
  : {
@@ -169,7 +177,7 @@ export function hostGrantRefusal(host, box, platform, org) {
169
177
  return "network access is turned off for this device's sandbox";
170
178
  if (box.boundary === "instance" || box.perCallHosts === false)
171
179
  return `a host cannot be granted per call on this device; add ${host} to the device's network list`;
172
- return (box.networkCeiling === "allowlist" && box.layer?.network !== "provider") ||
180
+ return (box.networkCeiling === "allowlist" && !deviceSideLayer(box.layer?.network)) ||
173
181
  ceiling.kind === "any"
174
182
  ? `an organization admin adds ${host} to the organization's device network list`
175
183
  : `${host} is outside the platform's host list; a super admin adds the host`;
@@ -3,9 +3,8 @@ import { type DeviceProvider, type ExecResult, type SandboxExecOptions, type San
3
3
  export type HeldProvider = Pick<DeviceProvider, "readFile" | "writeFile" | "stat" | "list" | "scan"> & {
4
4
  exec(h: SandboxHandle, args: Omit<Parameters<DeviceProvider["exec"]>[1], "tag" | "actor">): Promise<ExecResult>;
5
5
  /**
6
- * A managed background start (dormant until the paired activation): admitted, persisted and
7
- * acknowledged by the service under the same stable operation identity. Present only on the
8
- * operation-held provider; the protocol-2 adapter has none.
6
+ * A managed background start: admitted, persisted and acknowledged by the service under the
7
+ * same stable operation identity. Present only when the provider owns background executions.
9
8
  */
10
9
  backgroundStart?(h: SandboxHandle, args: ManagedStartArgs): Promise<SandboxExecutionRef>;
11
10
  };
@@ -42,5 +41,3 @@ export declare function checkManagedStart(provider: DeviceProvider, handle: Sand
42
41
  */
43
42
  export declare function withKernelGeneration(provider: DeviceProvider, generation: string): DeviceProvider;
44
43
  export declare function createHeldOperations(provider: DeviceProvider, handle: SandboxHandle, heldSignal: AbortSignal, dispatch: OperationDispatch): HeldProvider;
45
- /** Temporary v2 callback adapter. Removed with the coordinated Task 8 cutover. */
46
- export declare function createLegacyHeldProvider(provider: DeviceProvider, tag: string, actor: Parameters<DeviceProvider["exec"]>[1]["actor"], before: () => Promise<void>): HeldProvider;
@@ -135,17 +135,3 @@ export function createHeldOperations(provider, handle, heldSignal, dispatch) {
135
135
  : {}),
136
136
  };
137
137
  }
138
- /** Temporary v2 callback adapter. Removed with the coordinated Task 8 cutover. */
139
- export function createLegacyHeldProvider(provider, tag, actor, before) {
140
- return {
141
- exec: async (h, args) => {
142
- await before();
143
- return provider.exec(h, { ...args, tag, actor });
144
- },
145
- readFile: provider.readFile.bind(provider),
146
- writeFile: provider.writeFile.bind(provider),
147
- stat: provider.stat.bind(provider),
148
- ...(provider.list ? { list: provider.list.bind(provider) } : {}),
149
- ...(provider.scan ? { scan: provider.scan.bind(provider) } : {}),
150
- };
151
- }
@@ -67,7 +67,7 @@ export type ManagedDeviceContextPort = Pick<ManagedDeviceContextRecorder, "recor
67
67
  * admission use) and admission's working root. Any difference is
68
68
  * {@link ManagedDeviceContextStale}: no rediscovery, no provisioning, no whole-handler retry. The
69
69
  * bus hint follows the commit and is lossy. A lower event writer, not a permission context
70
- * publisher; dormant until the paired activation passes it to `common.ts`.
70
+ * publisher; `BuiltinTools` passes it to `common.ts`, which requires it.
71
71
  */
72
72
  export declare class ManagedDeviceContextRecorder {
73
73
  private readonly db;