@capybara-hq/kernel 0.1.0-rc.114 → 0.1.0-rc.116

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 (79) hide show
  1. package/bootstrap.json +9 -9
  2. package/dist/admin/admin.schemas.d.ts +1 -0
  3. package/dist/agents/agents.controller.d.ts +13 -1
  4. package/dist/agents/agents.controller.js +24 -2
  5. package/dist/catalog/catalog.service.d.ts +11 -1
  6. package/dist/catalog/catalog.service.js +36 -2
  7. package/dist/catalog/marketplaces.service.d.ts +1 -1
  8. package/dist/catalog/platform-components.js +13 -0
  9. package/dist/catalog/plugin-connectors.d.ts +35 -0
  10. package/dist/catalog/plugin-connectors.js +81 -0
  11. package/dist/channels/supervisor.d.ts +5 -1
  12. package/dist/channels/supervisor.js +17 -1
  13. package/dist/conversations/conversations.controller.d.ts +46 -14
  14. package/dist/conversations/conversations.controller.js +82 -47
  15. package/dist/conversations/conversations.service.d.ts +93 -59
  16. package/dist/conversations/conversations.service.js +255 -72
  17. package/dist/conversations/events.d.ts +39 -0
  18. package/dist/conversations/events.js +52 -2
  19. package/dist/conversations/inline-tokens.d.ts +87 -0
  20. package/dist/conversations/inline-tokens.js +154 -0
  21. package/dist/conversations/permission-profiles.controller.d.ts +14 -7
  22. package/dist/conversations/permission-profiles.controller.js +1 -5
  23. package/dist/conversations/prompt-suggestions.js +2 -4
  24. package/dist/conversations/queue.d.ts +0 -2
  25. package/dist/conversations/queue.service.js +9 -13
  26. package/dist/db/kernel-schema.d.ts +5 -0
  27. package/dist/errors.d.ts +12 -0
  28. package/dist/errors.js +12 -0
  29. package/dist/evals/snapshot.js +4 -2
  30. package/dist/files/library-files.service.d.ts +13 -0
  31. package/dist/files/library-files.service.js +33 -6
  32. package/dist/identity/settings.d.ts +5 -0
  33. package/dist/identity/settings.js +4 -0
  34. package/dist/models/purposes.js +5 -0
  35. package/dist/net/safe-fetch.js +1 -1
  36. package/dist/orgs/settings.service.d.ts +2 -0
  37. package/dist/platform/exclusions.js +6 -1
  38. package/dist/platform/ops/org-settings.ops.js +1 -1
  39. package/dist/runtime/compaction-model.d.ts +57 -0
  40. package/dist/runtime/compaction-model.js +87 -0
  41. package/dist/runtime/compaction.service.d.ts +23 -8
  42. package/dist/runtime/compaction.service.js +15 -10
  43. package/dist/runtime/context/build.d.ts +7 -2
  44. package/dist/runtime/context/build.js +17 -6
  45. package/dist/runtime/context/compaction.d.ts +22 -5
  46. package/dist/runtime/context/compaction.js +35 -15
  47. package/dist/runtime/context/idle-compaction-rules.d.ts +17 -2
  48. package/dist/runtime/context/idle-compaction-rules.js +20 -5
  49. package/dist/runtime/idle-arm.d.ts +12 -2
  50. package/dist/runtime/idle-arm.js +66 -18
  51. package/dist/runtime/idle-compaction-jobs.d.ts +24 -3
  52. package/dist/runtime/idle-compaction.d.ts +11 -3
  53. package/dist/runtime/idle-compaction.js +61 -30
  54. package/dist/runtime/model-call.d.ts +52 -16
  55. package/dist/runtime/model-call.js +71 -24
  56. package/dist/runtime/run-finish.d.ts +12 -3
  57. package/dist/runtime/run-finish.js +14 -7
  58. package/dist/runtime/run-queue.d.ts +5 -2
  59. package/dist/runtime/run-queue.js +7 -4
  60. package/dist/runtime/run-steps.d.ts +4 -1
  61. package/dist/runtime/run-steps.js +9 -2
  62. package/dist/runtime/run-worker.js +4 -2
  63. package/dist/runtime/runtime.module.js +3 -0
  64. package/dist/sandbox/review/classifier.js +5 -1
  65. package/dist/tools/connector-content.controller.d.ts +6 -2
  66. package/dist/tools/connector-content.controller.js +13 -3
  67. package/dist/tools/connector-content.d.ts +55 -15
  68. package/dist/tools/connector-content.js +112 -54
  69. package/dist/tools/connectors.service.d.ts +3 -2
  70. package/dist/tools/connectors.service.js +6 -20
  71. package/dist/tools/mentionable-connectors.d.ts +88 -0
  72. package/dist/tools/mentionable-connectors.js +218 -0
  73. package/dist/tools/pipeline.js +43 -6
  74. package/dist/tools/specs.d.ts +13 -4
  75. package/dist/tools/specs.js +22 -8
  76. package/dist/tools/tools.module.js +7 -0
  77. package/package.json +3 -3
  78. package/src/migrations/0200_runs_idle_mode.sql +4 -0
  79. package/src/migrations/0201_tool_specs_text.sql +8 -0
@@ -4,6 +4,7 @@ import { MEDIA_EXCLUDED_MAX_IDS } from "../conversations/events.js";
4
4
  import { ApiError } from "../errors.js";
5
5
  import { ExtensionUnloadedError } from "../extensions/inflight.js";
6
6
  import { hasInvocation, skillLoadOffered } from "../skills/catalog.js";
7
+ import { chooseSummarizer } from "./compaction-model.js";
7
8
  import { buildModelRequest, latestSummary, mediaRefs, planMedia, } from "./context/build.js";
8
9
  import { selectCacheTtl } from "./context/cache-ttl.js";
9
10
  import { acceptSummary, buildCompactionRequest, chunkTranscript, compactionBackoff, compactionChunkSize, compactionInputBudget, compactionPlan, compactionRequestOverhead, extractSummary, MIN_COMPACTION_CHUNK_TOKENS, manualOpeningSeqs, manualTailBudget, nextTranscriptChunk, openingSeqs, shouldCompact, summarySavedTokens, turnsSinceSummary, } from "./context/compaction.js";
@@ -843,10 +844,13 @@ async function inContextSummary(deps, input, events, ref, info, tools, settings,
843
844
  /**
844
845
  * The preparation of one compaction (idle compaction spec §4.3): resolve the model, load the media,
845
846
  * build the next step's request and calibrate its estimate, apply the trigger and the backoff (unless
846
- * `opts.force`), plan, and build the in-context summary request ({@link inContextSummary}). It writes
847
- * nothing and sends no model call; the outcomes a manual compaction records (`compaction_skipped`,
848
- * `compaction_failed` for an unavailable model) are {@link runCompaction}'s. `hooks.planned` runs once
849
- * the plan exists, before the in-context build reads the live snapshot.
847
+ * `opts.force`), plan, choose the summarizer ({@link chooseSummarizer}: the org's compaction model
848
+ * when it is usable and eligible, else V), and build the in-context summary request
849
+ * ({@link inContextSummary}; skipped when the compaction model summarizes). It writes nothing and
850
+ * sends no model call; the outcomes a manual compaction records (`compaction_skipped`,
851
+ * `compaction_failed` for an unavailable model) are {@link runCompaction}'s. `hooks.planned` runs
852
+ * once the summarizer is chosen (an idle run in compaction-model mode without one ends before it),
853
+ * before the in-context build reads the live snapshot.
850
854
  */
851
855
  export async function prepareCompaction(deps, input, events, runtime, compaction, tools, opts = {}, hooks = {}) {
852
856
  const modelRef = opts.ref ?? input.agent.model;
@@ -906,18 +910,40 @@ export async function prepareCompaction(deps, input, events, runtime, compaction
906
910
  : compactionPlan(events, compaction, tailBudget);
907
911
  if (!plan)
908
912
  return { skipped: "no_plan", estimate, window: info.contextWindow };
913
+ // compaction model spec §4.2: the purpose is read only now (the trigger passed, a plan exists),
914
+ // so a step that does not compact pays nothing; the plan above is V's either way
915
+ let summarizer;
916
+ try {
917
+ ({ summarizer } = await chooseSummarizer(deps, input.orgId, { ref: modelRef, provider, info }, compaction));
918
+ }
919
+ catch (err) {
920
+ // the purpose could not be read (not "unconfigured": that is V by today's rules): the
921
+ // compaction ends as an unavailable model does, never on V, and the step continues
922
+ deps.log.warn("compaction skipped: the compaction model is unavailable", {
923
+ context: "Compaction",
924
+ conversationId: input.conversationId,
925
+ err,
926
+ });
927
+ return { skipped: "unavailable", reason: "the compaction model is unavailable" };
928
+ }
929
+ if (opts.idle === "compaction_model" && summarizer.source !== "compaction_model") {
930
+ return { skipped: "no_compaction_model" };
931
+ }
909
932
  hooks.planned?.();
910
- // the summary call's output cap: the org's effective setting, never above the model's own cap
911
- // (context compaction spec §4.8)
912
- const summaryCap = Math.min(compaction.maxOutputTokens, info.maxOutputTokens);
933
+ // the summary call's output cap: the org's effective setting, never above V's own cap nor, on
934
+ // the compaction model, above its cap (context compaction spec §4.8, compaction model spec §5.1)
935
+ const summaryCap = summarizer.cap;
913
936
  // idle compaction spec §9.4: an automatic compaction tries the summary from the conversation's
914
937
  // last request first (its cached prefix); a skip (always for a manual one, ruling R13)
915
- // summarizes the transcript exactly as before, or ends an idle one (`requireInContext`)
916
- const inContext = await inContextSummary(deps, input, events, modelRef, info, tools, { reserveTokens: compaction.reserveTokens, summaryCap }, plan, opts);
938
+ // summarizes the transcript exactly as before, or ends a cache-mode idle one. A compaction
939
+ // model always summarizes the transcript (compaction model spec §4.4, Q2).
940
+ const inContext = summarizer.source === "compaction_model"
941
+ ? { skip: "compaction_model" }
942
+ : await inContextSummary(deps, input, events, modelRef, info, tools, { reserveTokens: compaction.reserveTokens, summaryCap }, plan, opts);
917
943
  return {
918
- provider,
919
944
  info,
920
945
  ref: modelRef,
946
+ summarizer,
921
947
  estimate,
922
948
  window: info.contextWindow,
923
949
  growthTokens: textTokens(plan.transcript),
@@ -938,8 +964,12 @@ export async function prepareCompaction(deps, input, events, runtime, compaction
938
964
  *
939
965
  * `opts.force` (the reactive path, spec §4.4, and a manual compact run, spec §4.7) bypasses the
940
966
  * trigger, `enabled` and the backoff, and `opts.ref` makes it summarise with the rung's model rather
941
- * than the agent's main model. `opts.requireInContext` (the idle compact run, idle compaction spec
942
- * §4.3) ends the compaction with nothing written when the in-context summary does not apply.
967
+ * than the agent's main model. `opts.idle` (the idle compact run, idle compaction spec §4.3)
968
+ * ends the compaction with nothing written when its summarizer does not apply: the in-context
969
+ * summary in `cache` mode, the compaction model in `compaction_model` mode. The summary calls go
970
+ * to the prepared summarizer (compaction model spec §3): the org's compaction model when one is
971
+ * usable and eligible, else the conversation model; a failed or denied call on it is never
972
+ * retried on the other (decision Q1).
943
973
  *
944
974
  * The one execution every path runs: the automatic step path through {@link maybeCompact} and a
945
975
  * compact run (manual or idle) through `CompactionService.force`. The preparation is
@@ -975,8 +1005,9 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
975
1005
  return { events: merged, summarySeq: null, failed: true };
976
1006
  };
977
1007
  // §4.6 progress: from the plan on the compaction is certain, so the conversation may show a row.
978
- // It is display-only (Redis + a bus message, never the log); a lost update costs nothing. An idle
979
- // compaction is certain only once its in-context request exists, so it shows the row after it.
1008
+ // It is display-only (Redis + a bus message, never the log); a lost update costs nothing. A
1009
+ // cache-mode idle compaction is certain only once its in-context request exists, so it shows the
1010
+ // row after it; a compaction-model one once its summarizer is chosen (the planned hook).
980
1011
  let startedAt = 0;
981
1012
  const progressOf = (progress) => {
982
1013
  deps.compactionProgress?.update({
@@ -992,13 +1023,16 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
992
1023
  };
993
1024
  const prepared = await prepareCompaction(deps, input, events, runtime, compaction, tools, opts, {
994
1025
  planned: () => {
995
- if (opts.requireInContext !== true)
1026
+ if (opts.idle !== "cache")
996
1027
  preparing();
997
1028
  },
998
1029
  });
999
1030
  if ("skipped" in prepared) {
1000
1031
  if (prepared.skipped === "unavailable")
1001
1032
  return unavailable(prepared.reason);
1033
+ // an idle run in compaction-model mode without the compaction model: nothing written
1034
+ if (prepared.skipped === "no_compaction_model")
1035
+ return skipped(events);
1002
1036
  if (prepared.skipped !== "no_plan" || opts.manual !== true)
1003
1037
  return skipped(events);
1004
1038
  // a manual compaction that finds nothing to summarize says so (display only, never
@@ -1021,8 +1055,9 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
1021
1055
  failed: false,
1022
1056
  };
1023
1057
  }
1024
- const { provider, info, plan, manual, summaryCap, inContext } = prepared;
1025
- const modelRef = prepared.ref;
1058
+ // the call part uses only the summarizer: the plan above was V's (compaction model spec §5.1)
1059
+ const { summarizer, plan, manual, summaryCap, inContext } = prepared;
1060
+ const { provider, info } = summarizer;
1026
1061
  const ic = "skip" in inContext ? null : inContext;
1027
1062
  if ("skip" in inContext) {
1028
1063
  deps.log.debug?.("in-context summary skipped", {
@@ -1030,16 +1065,18 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
1030
1065
  conversationId: input.conversationId,
1031
1066
  reason: inContext.skip,
1032
1067
  });
1033
- // the idle compact run never falls back to the transcript request (idle compaction spec
1034
- // §4.3 check 9): it ends with nothing written
1035
- if (opts.requireInContext === true)
1068
+ // the cache-mode idle compact run never falls back to the transcript request (idle compaction
1069
+ // spec §4.3 check 9): it ends with nothing written
1070
+ if (opts.idle === "cache")
1036
1071
  return skipped(events);
1037
1072
  }
1038
- else if (opts.requireInContext === true) {
1073
+ else if (opts.idle === "cache") {
1039
1074
  preparing();
1040
1075
  }
1041
1076
  const { runId, step, signal, conversationId } = input;
1042
- const ref = modelRef;
1077
+ const ref = summarizer.ref;
1078
+ /** The model a summary or a failed call names (compaction model spec §7.1; not model-visible). */
1079
+ const writtenBy = { provider: ref.provider, model: ref.model };
1043
1080
  // review M6: the preparation awaited the snapshot read; an abort meanwhile sends no call
1044
1081
  if (signal.aborted) {
1045
1082
  deps.compactionProgress?.clear(runId);
@@ -1153,7 +1190,10 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
1153
1190
  ? retry
1154
1191
  ? ic.retryRequest
1155
1192
  : ic.request
1156
- : buildCompactionRequest(callInput, info.id, summaryCap, { retry });
1193
+ : buildCompactionRequest(callInput, info.id, summaryCap, {
1194
+ retry,
1195
+ params: summarizer.params,
1196
+ });
1157
1197
  if (hookBase && deps.hooks?.has("model.request")) {
1158
1198
  let verdict;
1159
1199
  try {
@@ -1313,6 +1353,7 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
1313
1353
  attempt: attemptNo,
1314
1354
  step,
1315
1355
  reason: `compaction request blocked by the "${verdict.plugin}" policy hook (${verdict.cause})${chunkNote(multiChunk ? denial.chunk : null)}`,
1356
+ model: writtenBy,
1316
1357
  },
1317
1358
  };
1318
1359
  deps.log.warn("compaction blocked by a policy hook", {
@@ -1357,13 +1398,19 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
1357
1398
  savedTokens: summarySavedTokens(savedFrom, summary),
1358
1399
  method: ic !== null ? "in_context" : "transcript",
1359
1400
  step,
1401
+ model: writtenBy,
1360
1402
  },
1361
1403
  }
1362
1404
  : {
1363
1405
  type: "compaction_failed",
1364
1406
  runId,
1365
1407
  idemKey: idem.compactionFailed(runId, step, ordinal),
1366
- payload: { attempt: attemptNo, step, reason: `${failure}${chunkNote(failedChunk)}` },
1408
+ payload: {
1409
+ attempt: attemptNo,
1410
+ step,
1411
+ reason: `${failure}${chunkNote(failedChunk)}`,
1412
+ model: writtenBy,
1413
+ },
1367
1414
  };
1368
1415
  // the compaction calls' usage (I-1): logged with the outcome in one append (one transaction),
1369
1416
  // marked `purpose: "compaction"` so step consumers (calibration, trajectory steps, replay plans)
@@ -28,13 +28,22 @@ export interface FinishRunArgs {
28
28
  */
29
29
  idleCompaction?: IdleCompactionIntent;
30
30
  }
31
- /** What {@link FinishRunArgs.idleCompaction} carries (`runAt` and `expiresAt` in epoch ms). */
32
- export interface IdleCompactionIntent {
31
+ /**
32
+ * What {@link FinishRunArgs.idleCompaction} carries (`runAt` and `expiresAt` in epoch ms), by the
33
+ * job's mode (compaction model spec §6.2): a cache-mode job carries the armed call and its expiry,
34
+ * a compaction-model job only its due time.
35
+ */
36
+ export type IdleCompactionIntent = {
33
37
  orgId: string;
38
+ mode: "cache";
34
39
  cacheCallSeq: number;
35
40
  expiresAt: number;
36
41
  runAt: number;
37
- }
42
+ } | {
43
+ orgId: string;
44
+ mode: "compaction_model";
45
+ runAt: number;
46
+ };
38
47
  /**
39
48
  * Writes runs' terminal states (one instance; the run worker, the run queue's orphan abort, the
40
49
  * `run-orphan-check`, the waits and the eval replays finish runs through it).
@@ -181,21 +181,28 @@ let RunFinish = class RunFinish {
181
181
  await oweEnsureRun(this.outbox, a.conversationId, seq, conv.org_id);
182
182
  }
183
183
  // the idle compaction job armed for this run's end (idle compaction spec §4.2, S4): due before
184
- // the prompt cache expires, stale as soon as anything but a run-less side-call usage follows
184
+ // the prompt cache expires (cache mode) or `idleDelayMinutes` after the run (compaction-model
185
+ // mode), stale as soon as anything but a run-less side-call usage follows
185
186
  if (a.idleCompaction !== undefined &&
186
187
  conv?.org_live &&
187
188
  isLive(conv.deleted_at) &&
188
189
  conv.kind === "chat" &&
189
190
  a.idleCompaction.orgId === conv.org_id) {
190
- const { orgId, cacheCallSeq, expiresAt, runAt } = a.idleCompaction;
191
- await oweIdleCompaction(this.outbox, {
192
- orgId,
191
+ const intent = a.idleCompaction;
192
+ const job = {
193
+ orgId: intent.orgId,
193
194
  conversationId: a.conversationId,
194
195
  runId: a.runId,
195
196
  armedSeq: seq,
196
- cacheCallSeq,
197
- expiresAt,
198
- }, runAt);
197
+ };
198
+ await oweIdleCompaction(this.outbox, intent.mode === "cache"
199
+ ? {
200
+ ...job,
201
+ mode: "cache",
202
+ cacheCallSeq: intent.cacheCallSeq,
203
+ expiresAt: intent.expiresAt,
204
+ }
205
+ : { ...job, mode: "compaction_model" }, intent.runAt);
199
206
  }
200
207
  if (conv?.org_live)
201
208
  await this.oweTreeWork(a, conv.kind, conv.org_id);
@@ -1,5 +1,6 @@
1
1
  import type { Logger } from "@capybara-hq/plugin-sdk";
2
2
  import { EventLog } from "../conversations/event-log.js";
3
+ import type { IdleMode } from "../db/kernel-schema.js";
3
4
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
5
  import { KernelDb } from "../infra/database/kernel-db.js";
5
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -93,9 +94,11 @@ export declare class RunQueue {
93
94
  * after `armedSeq`, and that the conversation is not busy: no active run (queued, running or
94
95
  * waiting), no unconsumed message, no queue head. The run is a `compact` run with
95
96
  * `compact_origin = 'idle'`, run as the conversation's owner, its boundary the current
96
- * `consumed_seq`, exactly as a manual one.
97
+ * `consumed_seq`, exactly as a manual one. `mode` is the mode the job was armed in, stored as
98
+ * `idle_mode` so the run worker runs it in that mode (compaction model spec §6.3: a run never
99
+ * switches modes between arm, fire and run).
97
100
  */
98
- startIdleCompaction(conversationId: string, armedSeq: number): Promise<string | null>;
101
+ startIdleCompaction(conversationId: string, armedSeq: number, mode: IdleMode): Promise<string | null>;
99
102
  /** {@link startIdleCompaction}'s transaction: the re-checks, the run row and its owed job. */
100
103
  private startIdleCompactionIn;
101
104
  /** {@link ensureRun}'s transaction: what it decided goes back through `st`. */
@@ -229,11 +229,13 @@ let RunQueue = class RunQueue {
229
229
  * after `armedSeq`, and that the conversation is not busy: no active run (queued, running or
230
230
  * waiting), no unconsumed message, no queue head. The run is a `compact` run with
231
231
  * `compact_origin = 'idle'`, run as the conversation's owner, its boundary the current
232
- * `consumed_seq`, exactly as a manual one.
232
+ * `consumed_seq`, exactly as a manual one. `mode` is the mode the job was armed in, stored as
233
+ * `idle_mode` so the run worker runs it in that mode (compaction model spec §6.3: a run never
234
+ * switches modes between arm, fire and run).
233
235
  */
234
- async startIdleCompaction(conversationId, armedSeq) {
236
+ async startIdleCompaction(conversationId, armedSeq, mode) {
235
237
  try {
236
- return await this.startIdleCompactionIn(conversationId, armedSeq);
238
+ return await this.startIdleCompactionIn(conversationId, armedSeq, mode);
237
239
  }
238
240
  catch (err) {
239
241
  this.log.warn("idle compaction run not started", { conversationId, err });
@@ -244,7 +246,7 @@ let RunQueue = class RunQueue {
244
246
  // org-filter: the idle-compaction job's kernel-written conversation id (owed by the run finish
245
247
  // that armed it), run in runJob under the job's org; the conversation's own org is read under its
246
248
  // row lock
247
- async startIdleCompactionIn(conversationId, armedSeq) {
249
+ async startIdleCompactionIn(conversationId, armedSeq, mode) {
248
250
  const t = this.db;
249
251
  const conv = await t
250
252
  .selectFrom("conversations")
@@ -322,6 +324,7 @@ let RunQueue = class RunQueue {
322
324
  job_id: jobId.recorded,
323
325
  compact: true,
324
326
  compact_origin: "idle",
327
+ idle_mode: mode,
325
328
  })
326
329
  .execute();
327
330
  return runId;
@@ -4,6 +4,7 @@ import { ConversationMedia } from "../files/conversation-media.js";
4
4
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
5
  import { KernelDb } from "../infra/database/kernel-db.js";
6
6
  import type { KernelLogger } from "../log.js";
7
+ import { ModelPurposesService } from "../models/purposes.js";
7
8
  import { ToolPipeline } from "../tools/pipeline.js";
8
9
  import { ToolRegistry } from "../tools/registry.js";
9
10
  import { KyselyCheckpointSaver } from "./checkpointer.js";
@@ -40,7 +41,9 @@ export declare class RunSteps {
40
41
  readonly deps: LoopDeps;
41
42
  constructor(kdb: KernelDb, eventLog: EventLog, stepLog: StepLog, registry: ProviderRegistry, tools: ToolRegistry, config: KernelConfigService, log: KernelLogger, toolPipeline: ToolPipeline, host: ExtensionHost, subagents: SubagentsService,
42
43
  /** The conversation's media: library files it refers to, and `read` copies. */
43
- media: ConversationMedia, compactionSettings: CompactionSettingsService, compactionProgress: CompactionProgressService, permissionContext: PermissionContextRecorder, writeBase: WriteBaseService);
44
+ media: ConversationMedia, compactionSettings: CompactionSettingsService, compactionProgress: CompactionProgressService, permissionContext: PermissionContextRecorder, writeBase: WriteBaseService,
45
+ /** The org's `compaction` purpose (compaction model spec §4.2). */
46
+ purposes: ModelPurposesService);
44
47
  }
45
48
  /**
46
49
  * The live request boundary of a run's steps (spec B2): every agent-history request construction
@@ -15,9 +15,11 @@ import { ConversationMedia } from "../files/conversation-media.js";
15
15
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
16
  import { KernelDb } from "../infra/database/kernel-db.js";
17
17
  import { KERNEL_LOGGER } from "../infra/tokens.js";
18
+ import { ModelPurposesService } from "../models/purposes.js";
18
19
  import { ToolPipeline } from "../tools/pipeline.js";
19
20
  import { ToolRegistry } from "../tools/registry.js";
20
21
  import { KyselyCheckpointSaver } from "./checkpointer.js";
22
+ import { compactionModelPort } from "./compaction-model.js";
21
23
  import { CompactionProgressService } from "./compaction-progress.js";
22
24
  import { CompactionSettingsService } from "./compaction-settings.service.js";
23
25
  import { LangGraphLoop } from "./langgraph-loop.js";
@@ -58,7 +60,9 @@ let RunSteps = class RunSteps {
58
60
  deps;
59
61
  constructor(kdb, eventLog, stepLog, registry, tools, config, log, toolPipeline, host, subagents,
60
62
  /** The conversation's media: library files it refers to, and `read` copies. */
61
- media, compactionSettings, compactionProgress, permissionContext, writeBase) {
63
+ media, compactionSettings, compactionProgress, permissionContext, writeBase,
64
+ /** The org's `compaction` purpose (compaction model spec §4.2). */
65
+ purposes) {
62
66
  this.deps = {
63
67
  get db() {
64
68
  return kdb.db;
@@ -71,6 +75,8 @@ let RunSteps = class RunSteps {
71
75
  compactionSettings,
72
76
  // ephemeral, display-only: the run's progress on its own conversation's stream
73
77
  compactionProgress,
78
+ // the summarizer of every compaction: the org's compaction model when it is usable
79
+ compactionModel: compactionModelPort(purposes),
74
80
  log,
75
81
  toolPipeline,
76
82
  // plugin hooks for chat runs; the full-run replay drops them (P-18)
@@ -108,7 +114,8 @@ RunSteps = __decorate([
108
114
  __param(11, Inject(CompactionSettingsService)),
109
115
  __param(12, Inject(CompactionProgressService)),
110
116
  __param(13, Inject(PermissionContextRecorder)),
111
- __param(14, Inject(WriteBaseService))
117
+ __param(14, Inject(WriteBaseService)),
118
+ __param(15, Inject(ModelPurposesService))
112
119
  ], RunSteps);
113
120
  export { RunSteps };
114
121
  /**
@@ -422,6 +422,7 @@ let RunWorker = class RunWorker {
422
422
  "budget_run_id",
423
423
  "compact",
424
424
  "compact_origin",
425
+ "idle_mode",
425
426
  ])
426
427
  .where("id", "=", runId)
427
428
  .executeTakeFirst();
@@ -1042,8 +1043,9 @@ let RunWorker = class RunWorker {
1042
1043
  absorbedUpToSeq: Number(consumed_seq),
1043
1044
  signal: ac.signal,
1044
1045
  },
1045
- // R13: an idle run requires the in-context summary and never sets `manual`
1046
- origin);
1046
+ // R13: an idle run never sets `manual`; it runs in the mode it was armed in (a row from
1047
+ // before 0200 has none: cache, the in-context summary or nothing)
1048
+ origin === "idle" ? { origin, idleMode: run.idle_mode ?? "cache" } : { origin });
1047
1049
  }
1048
1050
  catch (err) {
1049
1051
  if (state.abandoned)
@@ -22,6 +22,7 @@ import { IdentityModule } from "../identity/identity.module.js";
22
22
  import { LockService } from "../infra/lock/lock.service.js";
23
23
  import { QueueModule } from "../infra/queue/queue.module.js";
24
24
  import { REDIS } from "../infra/tokens.js";
25
+ import { ModelsModule } from "../models/models.module.js";
25
26
  import { OrgSettingsModule } from "../orgs/settings.service.js";
26
27
  import { OperationAuthorityModule } from "../sandbox/operation-authority.module.js";
27
28
  import { PermissionAuthorityModule } from "../sandbox/permission-authority.module.js";
@@ -90,6 +91,8 @@ RuntimeModule = __decorate([
90
91
  PermissionProfileStoreModule,
91
92
  GitModule,
92
93
  ProvidersModule,
94
+ // the `compaction` purpose the run steps summarize with (compaction model spec §4.2)
95
+ ModelsModule,
93
96
  RunJobsModule,
94
97
  SubagentsModule,
95
98
  UsageReportModule,
@@ -296,7 +296,11 @@ export const PERSON_MESSAGES_READ = 20;
296
296
  * blocks `1 .. attachments.length`) are content read from a connector, not the person's
297
297
  * instructions, so they are skipped, like images, documents and uploaded files. So are the
298
298
  * referenced conversations' blocks (`payload.conversationRefs`, after the project file lines):
299
- * quoted material, not the person's intent.
299
+ * quoted material, not the person's intent. A message with inline tokens (composer inline tokens
300
+ * spec §3.3) keeps that layout: its placeholders stand in `content[0]`, and its connector mention
301
+ * blocks and `[file: …]` lines come after the referenced conversations, so they are skipped too.
302
+ * An upload-only message has no typed text: its `content[0]` is the first file's `[file: <name>]`
303
+ * line, which is read as its words (a file name, harmless to the verdict).
300
304
  */
301
305
  function textOfUserMessage(payload) {
302
306
  const p = payload;
@@ -6,6 +6,7 @@ declare const PromptBody: z.ZodObject<{
6
6
  arguments: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
7
7
  }, z.core.$strict>;
8
8
  declare const ResourcesQuery: z.ZodObject<{
9
+ connectorId: z.ZodUUID;
9
10
  query: z.ZodOptional<z.ZodString>;
10
11
  }, z.core.$strip>;
11
12
  /**
@@ -21,10 +22,13 @@ export declare class ConnectorContentController {
21
22
  prompts: ConnectorPromptView[];
22
23
  unavailable: ConnectorUnavailable[];
23
24
  }>;
24
- /** 发起人可用的资源,`query` 按名称 / URI / 描述子串过滤。 */
25
+ /**
26
+ * One connector's resources the sender can use (the `@` menu's second level): one session on
27
+ * that connector, UI templates and empty resources hidden; `query` filters by name, URI or
28
+ * description substring.
29
+ */
25
30
  resources(principal: Principal, org: OrgContext, q: z.infer<typeof ResourcesQuery>): Promise<{
26
31
  resources: ConnectorResourceView[];
27
- unavailable: ConnectorUnavailable[];
28
32
  }>;
29
33
  /** 按参数渲染一个提示模板为文本(放进输入框,由用户发送)。 */
30
34
  renderPrompt(principal: Principal, org: OrgContext, connectorId: string, name: string, body: z.infer<typeof PromptBody>): Promise<{
@@ -22,7 +22,10 @@ const PromptBody = z
22
22
  .default({}),
23
23
  })
24
24
  .strict();
25
- const ResourcesQuery = z.object({ query: z.string().max(200).optional() });
25
+ const ResourcesQuery = z.object({
26
+ connectorId: z.uuid(),
27
+ query: z.string().max(200).optional(),
28
+ });
26
29
  class ConnectorPromptBody extends createZodDto(PromptBody, "ConnectorPromptBody") {
27
30
  }
28
31
  class ConnectorResourcesQuery extends createZodDto(ResourcesQuery, "ConnectorResourcesQuery") {
@@ -42,10 +45,17 @@ let ConnectorContentController = class ConnectorContentController {
42
45
  const p = requireUser(principal);
43
46
  return this.content.listPrompts(org.orgId, p.account.id);
44
47
  }
45
- /** 发起人可用的资源,`query` 按名称 / URI / 描述子串过滤。 */
48
+ /**
49
+ * One connector's resources the sender can use (the `@` menu's second level): one session on
50
+ * that connector, UI templates and empty resources hidden; `query` filters by name, URI or
51
+ * description substring.
52
+ */
46
53
  async resources(principal, org, q) {
47
54
  const p = requireUser(principal);
48
- return this.content.listResources(org.orgId, p.account.id, q.query);
55
+ return this.content.listResources(org.orgId, p.account.id, {
56
+ connectorId: q.connectorId,
57
+ ...(q.query !== undefined && { query: q.query }),
58
+ });
49
59
  }
50
60
  /** 按参数渲染一个提示模板为文本(放进输入框,由用户发送)。 */
51
61
  async renderPrompt(principal, org, connectorId, name, body) {
@@ -25,6 +25,7 @@ export interface ConnectorResourceView {
25
25
  name: string;
26
26
  description?: string;
27
27
  mimeType?: string;
28
+ size?: number;
28
29
  }
29
30
  /** 列表时某个连接器不可用:发起人没有连接个人凭据,或连接 / 列出失败(含熔断打开)。 */
30
31
  export interface ConnectorUnavailable {
@@ -42,6 +43,34 @@ export interface AttachmentMeta {
42
43
  uri: string;
43
44
  name: string;
44
45
  }
46
+ /** An MCP app UI template (not content a person can attach): `ui:` URI or the mcp-app HTML profile. */
47
+ export declare function isUiTemplate(r: {
48
+ uri: string;
49
+ mimeType?: string;
50
+ }): boolean;
51
+ /** Whether a resource is offered to a person: not a UI template, not empty. */
52
+ export declare function listableResource(r: {
53
+ uri: string;
54
+ name?: string;
55
+ mimeType?: string;
56
+ size?: number;
57
+ }): boolean;
58
+ /** One resource a message references, as read for it (the body redacted and capped). */
59
+ export interface ReadResource {
60
+ connectorId: string;
61
+ connectorName: string;
62
+ uri: string;
63
+ /** The listed name, or the URI. */
64
+ name: string;
65
+ body: string;
66
+ }
67
+ /**
68
+ * The model-visible block of a read resource: its placeholder first when it was a token
69
+ * (`[resource: <label> from <connector label>] `), then the English head and the body.
70
+ */
71
+ export declare const resourceBlockText: (r: ReadResource, placeholder?: string) => string;
72
+ /** The `payload.attachments` entry of a read resource (field names kept, C27). */
73
+ export declare const attachmentMeta: (r: ReadResource) => AttachmentMeta;
45
74
  export declare class ConnectorContent {
46
75
  private readonly db;
47
76
  private readonly registry;
@@ -77,25 +106,36 @@ export declare class ConnectorContent {
77
106
  getPrompt(orgId: string, connectorId: string, name: string, args: Record<string, string>, accountId: string): Promise<{
78
107
  text: string;
79
108
  }>;
80
- /** 发起人可用的资源;`query` 按名称 / URI / 描述的子串过滤(不区分大小写),最多 {@link MAX_RESOURCES} 条。 */
81
- listResources(orgId: string, accountId: string, query?: string): Promise<{
109
+ /**
110
+ * One connector's resources the sender can use (the `@` menu's second level, composer inline
111
+ * tokens spec §5): one session on that connector with the sender's credential, UI templates and
112
+ * empty resources hidden, at most {@link MAX_CONNECTOR_RESOURCES}; `query` filters by name, URI
113
+ * or description substring (case insensitive). A connector that is not live and active →
114
+ * `connector.not_found`; one whose `read_resource` is off → `connector.resources_disabled`; a
115
+ * missing credential or a failed connection is thrown (`credential.missing`,
116
+ * `connector.connect_failed`).
117
+ */
118
+ listResources(orgId: string, accountId: string, opts: {
119
+ connectorId: string;
120
+ query?: string;
121
+ }): Promise<{
82
122
  resources: ConnectorResourceView[];
83
- unavailable: ConnectorUnavailable[];
84
123
  }>;
85
124
  /**
86
- * 解析消息附件:以发送者的凭据**并行**读取每个资源(打码、每个限 {@link MAX_ATTACHMENT_CHARS} 字符;总时限
87
- * min(`tools.timeoutMs`, 30s)),按请求顺序返回要追加在用户消息后的文本块与元数据。名称取资源清单里的 name
88
- * (读不到清单时用 URI)。连接器的 `read_resource` 工具被管理员停用 → 409 `connector.resources_disabled`。
89
- * 任一附件失败整条消息失败(不写入)。
125
+ * Reads the resources a message references with the sender's credentials, **in parallel**
126
+ * (redacted, each capped at {@link MAX_ATTACHMENT_CHARS} characters; total time limit
127
+ * min(`tools.timeoutMs`, 30s)), in request order. The name is the one in the resource listing
128
+ * (the URI when the listing does not have it). Refusals, any of which fails the whole message
129
+ * (nothing is written):
130
+ * - the connector is not live and active, or provides no resources → `connector.not_found`;
131
+ * - its `read_resource` tool is switched off by an admin (Ruling A23), or `readOffered` is given
132
+ * and does not hold the connector (the conversation's agent is not offered that tool) →
133
+ * 409 `connector.resources_disabled`;
134
+ * - an MCP Apps UI template, or a body that is empty after trimming → 422
135
+ * `connector.resource_unreadable` (`details: [{ connectorId, uri, reason }]`).
90
136
  */
91
- resolveAttachments(orgId: string, accountId: string, refs: {
137
+ readResources(orgId: string, accountId: string, refs: readonly {
92
138
  connectorId: string;
93
139
  uri: string;
94
- }[]): Promise<{
95
- blocks: {
96
- type: "text";
97
- text: string;
98
- }[];
99
- attachments: AttachmentMeta[];
100
- }>;
140
+ }[], readOffered?: ReadonlySet<string>): Promise<ReadResource[]>;
101
141
  }