@capybara-hq/kernel 0.1.0-rc.5 → 0.1.0-rc.6

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 (63) hide show
  1. package/dist/admin/admin.controller.d.ts +13 -2
  2. package/dist/admin/admin.controller.js +29 -4
  3. package/dist/agents/agents.service.d.ts +3 -1
  4. package/dist/agents/agents.service.js +8 -6
  5. package/dist/agents/from-template.service.js +3 -3
  6. package/dist/agents/models.controller.d.ts +34 -5
  7. package/dist/agents/models.controller.js +50 -6
  8. package/dist/agents/readiness.controller.d.ts +5 -5
  9. package/dist/agents/readiness.controller.js +6 -6
  10. package/dist/catalog/marketplaces.service.d.ts +1 -1
  11. package/dist/config/schema.d.ts +4 -0
  12. package/dist/config/schema.js +24 -0
  13. package/dist/conversations/conversations.service.d.ts +4 -3
  14. package/dist/conversations/conversations.service.js +9 -8
  15. package/dist/ctx/create-ctx.d.ts +15 -1
  16. package/dist/ctx/create-ctx.js +23 -2
  17. package/dist/db/kernel-schema.d.ts +24 -0
  18. package/dist/errors.d.ts +3 -0
  19. package/dist/errors.js +3 -0
  20. package/dist/evals/run-replay.js +4 -2
  21. package/dist/evals/runs.service.d.ts +2 -1
  22. package/dist/evals/runs.service.js +13 -12
  23. package/dist/evals/step-replay.d.ts +2 -1
  24. package/dist/evals/step-replay.js +3 -2
  25. package/dist/extensions/config-hash.d.ts +10 -0
  26. package/dist/extensions/config-hash.js +38 -0
  27. package/dist/extensions/extensions.module.js +6 -12
  28. package/dist/extensions/host.d.ts +6 -10
  29. package/dist/extensions/host.js +22 -50
  30. package/dist/extensions/state.module.d.ts +9 -0
  31. package/dist/extensions/state.module.js +38 -0
  32. package/dist/http/api.module.js +2 -0
  33. package/dist/http/plugin-dispatch.d.ts +4 -1
  34. package/dist/http/plugin-dispatch.js +14 -2
  35. package/dist/infra/config/kernel-config.service.js +3 -0
  36. package/dist/infra/events/kernel-events.d.ts +8 -0
  37. package/dist/models/embeddings.d.ts +82 -0
  38. package/dist/models/embeddings.js +326 -0
  39. package/dist/models/enablement.controller.d.ts +40 -0
  40. package/dist/models/enablement.controller.js +74 -0
  41. package/dist/models/enablement.d.ts +99 -0
  42. package/dist/models/enablement.js +263 -0
  43. package/dist/models/models.module.d.ts +5 -1
  44. package/dist/models/models.module.js +16 -4
  45. package/dist/models/purposes.d.ts +18 -4
  46. package/dist/models/purposes.js +46 -9
  47. package/dist/platform/exclusions.js +18 -0
  48. package/dist/runtime/hook-calls.d.ts +8 -1
  49. package/dist/runtime/hook-calls.js +40 -9
  50. package/dist/runtime/model-call.d.ts +8 -3
  51. package/dist/runtime/model-call.js +28 -5
  52. package/dist/runtime/providers.d.ts +146 -32
  53. package/dist/runtime/providers.js +321 -67
  54. package/dist/runtime/run-worker.d.ts +1 -1
  55. package/dist/runtime/run-worker.js +4 -4
  56. package/dist/runtime/subagents/definition.js +3 -3
  57. package/dist/runtime/usage-report-jobs.d.ts +88 -0
  58. package/dist/runtime/usage-report-jobs.js +158 -0
  59. package/dist/runtime/usage-report.d.ts +33 -38
  60. package/dist/runtime/usage-report.js +152 -84
  61. package/dist/tools/pipeline.js +6 -0
  62. package/package.json +3 -3
  63. package/src/migrations/0089_model_kinds_usage.sql +38 -0
@@ -32,8 +32,11 @@ export const TOOLS_AVAILABLE_AGAIN = "All previously unavailable tools are avail
32
32
  export function toolsUnavailableReminder(unavailable) {
33
33
  return `${TOOLS_UNAVAILABLE_PREFIX}${unavailable.map((u) => `${u.ref} (${u.reason})`).join(", ")}`;
34
34
  }
35
- /** `run_failed` message of a model request denied by a policy hook (user-facing, never model-visible). */
36
- const modelDeniedText = (plugin, reason) => `Model request blocked by the "${plugin}" policy hook: ${reason}`;
35
+ /**
36
+ * `run_failed` message of a model request denied by a policy hook (user-facing, never model-visible);
37
+ * also the message of the `model.hook_denied` error a denied `ctx.models.embed` call rejects with.
38
+ */
39
+ export const modelDeniedText = (plugin, reason) => `Model request blocked by the "${plugin}" policy hook: ${reason}`;
37
40
  /** 可重试错误在同一模型上重试前的默认等待(供应商未给 retryAfterMs 时)。 */
38
41
  const DEFAULT_RETRY_DELAY_MS = 1000;
39
42
  /**
@@ -531,7 +534,7 @@ async function maybeCompact(deps, input, events, runtime, tools) {
531
534
  let provider;
532
535
  let info;
533
536
  try {
534
- ({ provider, info } = await deps.registry.resolve(input.agent.model));
537
+ ({ provider, info } = await deps.registry.resolve(input.orgId, input.agent.model));
535
538
  }
536
539
  catch (err) {
537
540
  deps.log.warn("compaction skipped: model unavailable", { model: input.agent.model, err });
@@ -701,7 +704,10 @@ function mergeLocal(events, written) {
701
704
  * 每次尝试解析出模型后、写 `model_call` 之前写本步的尾部提醒(均按本步幂等,只写一次):所用模型不支持工具而本步有工具
702
705
  * → {@link TOOLS_UNSUPPORTED_REMINDER};然后是轮次提醒或收尾提醒(收尾提醒因此位于请求末尾)。
703
706
  * 每次实际尝试写自己的 `model_call`(attempt 从 1 连续递增,跳过的不计);重试前经 sink 发 `step_reset`。
704
- * 不可重试的失败或梯子用尽 → `RunError`。
707
+ * 不可重试的失败或梯子用尽 → `RunError`; except that the agent's own model failing to resolve as
708
+ * `agent.model_unavailable` (gone from the list, disabled since the agent was saved, its provider
709
+ * not configured in the org: spec B §5.3) goes straight to `agent.fallback` when there is one,
710
+ * without the same-model retry.
705
711
  */
706
712
  async function ladder(deps, input, events, runtime, tools, wrapUpReason, streamed) {
707
713
  const { conversationId, runId, step, signal, sink, agent } = input;
@@ -719,12 +725,16 @@ async function ladder(deps, input, events, runtime, tools, wrapUpReason, streame
719
725
  if (agent.fallback)
720
726
  rungs.push({ ref: agent.fallback, fallback: true });
721
727
  let last;
728
+ /** The agent's model did not resolve (`agent.model_unavailable`): only the fallback is left. */
729
+ let mainUnavailable = false;
722
730
  let attempt = 0;
723
731
  // hooks fire only for chat runs that have a registry (eval replays omit it, P-18)
724
732
  const scope = hookScope(deps.hooks, input);
725
733
  /** 本次尝试发出的请求里带了字节的附件(供应商拒收时写 media_excluded)。 */
726
734
  let sentMedia = [];
727
735
  for (const rung of rungs) {
736
+ if (mainUnavailable && !rung.fallback)
737
+ continue;
728
738
  if (last && !rung.fallback && (last.retryAfterMs ?? 0) > MAX_RETRY_AFTER_MS) {
729
739
  deps.log.warn("model retry skipped: suggested wait exceeds cap", {
730
740
  conversationId,
@@ -744,8 +754,11 @@ async function ladder(deps, input, events, runtime, tools, wrapUpReason, streame
744
754
  sentMedia = [];
745
755
  /** When the request went out (model.response fires only for sent requests). */
746
756
  let sentAt;
757
+ /** Whether this attempt resolved its model (a failure before it is a resolve failure). */
758
+ let resolved = false;
747
759
  try {
748
- const { provider, info } = await deps.registry.resolve(rung.ref);
760
+ const { provider, info } = await deps.registry.resolve(input.orgId, rung.ref);
761
+ resolved = true;
749
762
  if (tools.list.length > 0 && !info.capabilities.tools) {
750
763
  evs = await appendLocal(deps.eventLog, conversationId, evs, {
751
764
  type: "reminder",
@@ -886,6 +899,16 @@ async function ladder(deps, input, events, runtime, tools, wrapUpReason, streame
886
899
  retryable: f.retryable,
887
900
  error: f.message,
888
901
  });
902
+ if (!resolved &&
903
+ !rung.fallback &&
904
+ agent.fallback &&
905
+ err instanceof ApiError &&
906
+ !(err instanceof ProviderListError) &&
907
+ err.code === "agent.model_unavailable") {
908
+ mainUnavailable = true;
909
+ last = f;
910
+ continue;
911
+ }
889
912
  if (!f.retryable) {
890
913
  if (REJECTS_MEDIA.has(f.code) && sentMedia.length > 0) {
891
914
  // 记录失败不能掩盖原来的失败码:只记 warn,本次运行照常以原错误失败
@@ -1,18 +1,25 @@
1
- import { type ExtensionPointRef, type Logger, type ModelInfo, type ModelProvider, type ModelProviderV1 } from "@capybara-hq/plugin-sdk";
1
+ import { type EmbedRequest, type EmbedResult, type ExtensionManifest, type ExtensionPointRef, type Logger, type ModelInfo, type ModelKind, type ModelProvider, type ModelProviderV1, 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";
5
+ import { EffectiveConfigs } from "../extensions/effective-config.js";
5
6
  import { CacheService } from "../infra/cache/cache.service.js";
6
- /** 单个供应商 `listModels()` 的时限(毫秒):一个卡住的供应商不拖住整个列表与解析。 */
7
- export declare const LIST_MODELS_TIMEOUT_MS = 10000;
8
- /** Optional provider: the `listModels()` time limit (ms) instead of {@link LIST_MODELS_TIMEOUT_MS} (tests). */
7
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
8
+ import { ModelEnablement } from "../models/enablement.js";
9
+ /**
10
+ * Optional provider: the `listModels()` time limit (ms) instead of the config's
11
+ * `models.listTimeoutMs` (tests).
12
+ */
9
13
  export declare const LIST_MODELS_TIMEOUT: unique symbol;
10
14
  /**
11
15
  * 列表视图(后台模型页、组织模型页)里列模型失败的供应商在这么多秒内直接标 error、不再请求(Redis,多副本共享)。
12
16
  * 只用于列表;`resolve`(运行时)照常每次请求,失败由降级梯子重试。
13
17
  */
14
18
  export declare const LIST_FAILURE_TTL_SECONDS = 15;
15
- /** The host view the registry needs: a subset of `ExtensionHost.list` (version and digest optional, for test doubles). */
19
+ /**
20
+ * The host view the registry needs: a subset of `ExtensionRegistry` (version, digest and
21
+ * `current` optional, for test doubles).
22
+ */
16
23
  export interface ProviderHost {
17
24
  list(extensionPointName: string): {
18
25
  plugin: string;
@@ -21,14 +28,58 @@ export interface ProviderHost {
21
28
  version?: string;
22
29
  configHash?: string;
23
30
  }[];
31
+ /** The running instance: its manifest (deployment schema) and platform config. */
32
+ current?(plugin: string): {
33
+ manifest: ExtensionManifest;
34
+ config: unknown;
35
+ } | undefined;
36
+ }
37
+ /** A listed model with its kind normalised: absent means `chat`, an unknown kind is `other`. */
38
+ export type KernelModelInfo = Omit<ModelInfo, "kind"> & {
39
+ kind: ModelKind | "other";
40
+ };
41
+ /**
42
+ * A model of a view that shows disabled models too: the platform view of `listWithStatus` (`disabled`
43
+ * = on the platform's list) and an org's `catalog` (`disabled` = on the org's list). Absent in the
44
+ * enabled-only views.
45
+ */
46
+ export type ListedModelInfo = KernelModelInfo & {
47
+ disabled?: boolean;
48
+ };
49
+ /** A model `resolve` returns: only `chat` and `embedding` models are callable. */
50
+ export type ResolvedModelInfo = Omit<ModelInfo, "kind"> & {
51
+ kind: "chat" | "embedding";
52
+ };
53
+ /**
54
+ * The kind a `resolve` caller needs (default `chat`: every streaming caller); `callable` accepts
55
+ * either callable kind (a purpose target checked against the purpose's own kind).
56
+ */
57
+ export type ExpectedKind = "chat" | "embedding" | "callable";
58
+ /**
59
+ * A provider bound to one org's call options (`orgId` and the effective config, spec B §5.5): the
60
+ * kernel's callers pass only the signal. Built per `resolve`, never cached; the config stays in
61
+ * the closure (never on the object, so logging or serialising it shows no secret).
62
+ */
63
+ export interface BoundProvider {
64
+ stream(req: ModelRequest, opts: {
65
+ signal: AbortSignal;
66
+ }): AsyncIterable<ModelStreamEvent>;
67
+ /** Present when the provider implements `embed`. */
68
+ embed?(req: EmbedRequest, opts: {
69
+ signal: AbortSignal;
70
+ }): Promise<EmbedResult>;
24
71
  }
25
- /** 一个供应商在后台的视图:供应商名即插件名;`status: "error"` 时 `models` 为空、`error` 为内核的说明。 */
72
+ /**
73
+ * 一个供应商在后台的视图:供应商名即插件名;`status: "error"` 时 `models` 为空、`error` 为内核的说明。
74
+ * `org_configured` (the platform view only): the platform config leaves a required overridable
75
+ * field empty, so each org configures the provider itself; no list.
76
+ */
26
77
  export interface ProviderStatus {
27
78
  provider: string;
28
79
  plugin: string;
29
- status: "ok" | "error";
80
+ status: "ok" | "error" | "org_configured";
30
81
  error?: string;
31
- models: ModelInfo[];
82
+ models: ListedModelInfo[];
32
83
  }
33
84
  /**
34
85
  * 供应商的 `listModels()` 失败(上游不可用等)。仍是 `agent.model_unavailable`,HTTP 调用方照常
@@ -42,61 +93,124 @@ export declare class ProviderListError extends ApiError {
42
93
  /**
43
94
  * 把 `model-provider@1` 实现包成 `@2`:
44
95
  * - `listModels`:`parameters` 由 `capabilities.effort` 推导(为真时只有 effort 旋钮,否则为空);
96
+ * an `@1` model is always a chat model: `kind` and `embedding` are dropped (an `@1` provider has
97
+ * no `embed`); the per-call options are not passed (an `@1` provider reads `ctx.config`);
45
98
  * - `stream`:`params.effort` 映射为 `req.effort`,其余参数丢弃(`@1` 没有对应字段);
46
- * 没有 `params.effort` 时保留请求自带的 `effort`。
99
+ * 没有 `params.effort` 时保留请求自带的 `effort`;only the signal is passed.
47
100
  */
48
101
  export declare function adaptModelProviderV1(impl: ModelProviderV1): ModelProvider;
49
102
  /**
50
103
  * 模型供应商注册表:供应商即提供 `model-provider` 能力的插件(以插件名为供应商名)。
51
104
  * 同时支持 `model-provider@1`(经 {@link adaptModelProviderV1} 适配)与 `@2`;
52
- * 同一插件两者都提供时用 `@2`。`@2` 的 `listModels()` 结果先过 `assertValidDeclarations`,
53
- * 不合规的供应商不可用(不可重试)。
54
- * Each provider's model list (`@2`-shaped) is cached in Redis (`@Cacheable`, key
105
+ * 同一插件两者都提供时用 `@2`。
106
+ *
107
+ * Org-bound (spec B §5.5, A §6): every list and call is made for an org with the provider's
108
+ * effective config there (`EffectiveConfigs.get`), passed as `{ orgId, config }`; a provider whose
109
+ * effective config is not valid in the org offers no models there, and neither does one the org
110
+ * explicitly turned off (its own extension switch row off, spec A §8; a provider with no switch row
111
+ * stays usable). The admin view (no org) lists with the platform config.
112
+ *
113
+ * Each list is validated per model (spec B §5.1): kinds are normalised (absent = `chat`, unknown =
114
+ * `other`); a chat model failing `assertValidDeclarations`, or an `embedding` model without
115
+ * `embedding` info or from a provider without `embed`, is dropped with a warn, the rest of the
116
+ * provider stays usable. Only `chat` and `embedding` models resolve.
117
+ *
118
+ * Each list (`@2`-shaped) is cached in Redis (`@Cacheable`, key
55
119
  * `cache:capk:models:<provider>:v<major>:<plugin version>:<config digest>`, 600 s), never in
56
- * process memory: every replica shares it.
120
+ * process memory: every replica shares it. The digest is the platform config's for every org that
121
+ * follows the platform (one shared list), and a per-org digest for an org's own copy.
57
122
  */
58
123
  export declare class ProviderRegistry {
59
124
  private readonly host;
125
+ private readonly effective;
60
126
  readonly cacheService: CacheService;
61
127
  private readonly kv;
128
+ private readonly config;
129
+ private readonly enablement;
62
130
  private readonly log?;
63
- /** The `listModels()` time limit. */
64
- private readonly listTimeoutMs;
65
- constructor(host: ProviderHost, cacheService: CacheService, kv: Redis, log?: Pick<Logger, "warn"> | undefined,
66
- /** The `listModels()` time limit. */
67
- listTimeoutMs?: number);
131
+ /** Overrides `models.listTimeoutMs` (tests). */
132
+ private readonly listTimeoutOverride?;
133
+ constructor(host: ProviderHost, effective: Pick<EffectiveConfigs, "get">, cacheService: CacheService, kv: Redis, config: Pick<KernelConfigService, "get">, enablement: Pick<ModelEnablement, "disabled" | "switchedOff">, log?: Pick<Logger, "warn"> | undefined,
134
+ /** Overrides `models.listTimeoutMs` (tests). */
135
+ listTimeoutOverride?: number | undefined);
68
136
  /** `listModels()` 加时限(到时按失败处理,供应商的调用留在后台、结果丢弃)。 */
69
137
  private listModelsWithTimeout;
70
138
  /**
71
139
  * Whether at least one model-provider extension is loaded on this replica (enabled, configured,
72
- * set up). Read from the extension host only: never calls a vendor, so a provider whose vendor
73
- * is down still counts (org readiness, web-order spec §3.8).
140
+ * set up) with a valid effective config in `orgId`. Read from extension state and the org's
141
+ * config only: never calls a vendor, so a provider whose vendor is down still counts (org
142
+ * readiness, web-order spec §3.8).
74
143
  */
75
- hasProvider(): boolean;
144
+ hasProvider(orgId: string): Promise<boolean>;
76
145
  /** 每个插件取一个实现(`@2` 优先),按插件首次出现的顺序;不支持的主版本记 warn 后忽略。 */
77
146
  private providers;
147
+ /**
148
+ * The call options and list digest of `p` for `orgId`, or for the platform when `orgId` is
149
+ * undefined (the admin view). An org: its effective config (not valid -> `needs_config`); the
150
+ * platform's digest while it follows the platform, a per-org one for its copy. The platform: its
151
+ * own config (a required overridable field left empty -> `org_configured`). `off`: the
152
+ * extensions the org explicitly turned off (`ModelEnablement.switchedOff`) -> `switched_off`.
153
+ */
154
+ private target;
78
155
  private models;
79
156
  /** The provider's validated model list, cached under `key` (see {@link modelsKey}). */
80
157
  private validatedModels;
81
- /** 每个已安装供应商及其模型(按插件加载顺序);列模型失败或声明不合规的供应商跳过并记 warn。 */
82
- list(): Promise<{
158
+ /** One warn per (provider, model, config digest) within {@link DROPPED_WARN_TTL_SECONDS}. */
159
+ private warnDropped;
160
+ /**
161
+ * 每个供应商及其模型(按插件加载顺序),for `orgId`:列模型失败或在该组织需要配置的供应商跳过。Only
162
+ * enabled models (neither the platform nor the org disabled them, spec B §5.3), optionally of
163
+ * one `kind`.
164
+ */
165
+ list(orgId: string, opts?: {
166
+ kind?: ModelKind | "other";
167
+ }): Promise<{
83
168
  provider: string;
84
- models: ModelInfo[];
169
+ models: KernelModelInfo[];
85
170
  }[]>;
86
171
  /**
87
- * 每个已安装供应商及其状态(按插件加载顺序,后台用):列模型失败(含超过 {@link LIST_MODELS_TIMEOUT_MS})或声明
88
- * 不合规的标 `error`、`models` 为空,不影响其他供应商;列模型失败的在 {@link LIST_FAILURE_TTL_SECONDS} 秒内不再请求。`error` 只是内核自己的英文说明(不透出上游错误原文,原文记 warn 日志)。
172
+ * An org's catalog (the org settings page, spec B §5.3): every provider as in
173
+ * {@link listWithStatus} for the org, with every model the platform left on, each carrying
174
+ * `disabled` for the org's own list. Reads the same cached lists (no extra provider call).
89
175
  */
90
- listWithStatus(): Promise<ProviderStatus[]>;
176
+ catalog(orgId: string): Promise<ProviderStatus[]>;
91
177
  /**
92
- * 解析模型引用,返回 `@2` 形状的供应商实现(`@1` 已适配)与模型信息。
93
- * 供应商未安装、模型不存在或参数声明不合规 → `agent.model_unavailable`;
178
+ * 每个已安装供应商及其状态(按插件加载顺序),for `orgId` (enabled models only), or the platform
179
+ * view when undefined (`/admin/models`: every model, `disabled` from the platform's list only).
180
+ * See {@link statuses} for the statuses.
181
+ */
182
+ listWithStatus(orgId?: string): Promise<ProviderStatus[]>;
183
+ /**
184
+ * 每个已安装供应商的完整列表与状态,for `orgId` or the platform: 列模型失败(含超过
185
+ * `models.listTimeoutMs`)的标 `error`、`models` 为空,不影响其他供应商;列模型失败的在
186
+ * {@link LIST_FAILURE_TTL_SECONDS} 秒内不再请求。An org where the provider needs configuration gets
187
+ * `error`; the platform view of a provider whose platform config leaves a required overridable
188
+ * field empty gets `org_configured`. `error` 只是内核自己的英文说明(不透出上游错误原文,原文记 warn
189
+ * 日志)。No disabled list applied.
190
+ */
191
+ private statuses;
192
+ /**
193
+ * 解析模型引用 for `orgId`,返回绑定到该组织调用选项的供应商与模型信息。
194
+ * 供应商未安装、在该组织需要配置、模型不存在(或被丢弃)、不是 `opts.kind`(default `chat`: a
195
+ * streaming caller never gets an embedding model)或被平台 / 该组织停用 → `agent.model_unavailable`;
94
196
  * 供应商 `listModels()` 失败 → `ProviderListError`(同一错误码,运行时视为可重试)。
95
197
  */
96
- resolve(ref: ModelRef): Promise<{
97
- provider: ModelProvider;
98
- info: ModelInfo;
198
+ resolve(orgId: string, ref: ModelRef, opts?: {
199
+ kind?: ExpectedKind;
200
+ }): Promise<{
201
+ provider: BoundProvider;
202
+ info: ResolvedModelInfo;
99
203
  }>;
204
+ /**
205
+ * The model's info in the platform view (deployment-level settings such as a purpose's
206
+ * deployment default; no call is ever made there), by {@link resolve}'s rules. A provider each
207
+ * org configures itself has no platform list: `agent.model_unavailable`. Only the platform's
208
+ * disabled list applies.
209
+ */
210
+ platformInfo(ref: ModelRef, opts?: {
211
+ kind?: ExpectedKind;
212
+ }): Promise<ResolvedModelInfo>;
213
+ private lookup;
100
214
  }
101
215
  /** The model provider registry (one instance; the models and agents domains read it). */
102
216
  export declare class ProvidersModule {