@nylorun/harness 0.27.1-beta → 0.28.0-beta

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 (65) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/HOST_CONTRACT.md +15 -13
  3. package/README.md +3 -1
  4. package/dist/api/executors.d.ts +79 -11
  5. package/dist/api/harness.d.ts +83 -2
  6. package/dist/api/harness.js +43 -4
  7. package/dist/api/host.d.ts +30 -2
  8. package/dist/api/host.js +156 -8
  9. package/dist/api/index.d.ts +20 -6
  10. package/dist/api/index.js +18 -4
  11. package/dist/api/run.d.ts +3 -0
  12. package/dist/api/run.js +81 -16
  13. package/dist/flow/context.d.ts +3 -0
  14. package/dist/flow/context.js +2 -1
  15. package/dist/flow/engine.d.ts +2 -0
  16. package/dist/flow/engine.js +10 -7
  17. package/dist/flow/limits.d.ts +8 -5
  18. package/dist/flow/limits.js +11 -7
  19. package/dist/index.d.ts +8 -0
  20. package/dist/index.js +8 -0
  21. package/dist/loop/compaction/config.d.ts +39 -0
  22. package/dist/loop/compaction/config.js +29 -0
  23. package/dist/loop/compaction/index.d.ts +18 -8
  24. package/dist/loop/compaction/index.js +57 -66
  25. package/dist/loop/config.d.ts +20 -0
  26. package/dist/loop/config.js +17 -0
  27. package/dist/loop/delegation.d.ts +3 -0
  28. package/dist/loop/delegation.js +14 -10
  29. package/dist/loop/invocation.d.ts +3 -0
  30. package/dist/loop/invocation.js +2 -0
  31. package/dist/loop/model/files.d.ts +77 -0
  32. package/dist/loop/model/files.js +168 -0
  33. package/dist/loop/model/json-answer.d.ts +26 -0
  34. package/dist/loop/model/json-answer.js +125 -0
  35. package/dist/loop/model/project.d.ts +14 -4
  36. package/dist/loop/model/project.js +69 -41
  37. package/dist/loop/options.js +2 -0
  38. package/dist/loop/run.js +8 -3
  39. package/dist/loop/state.js +4 -0
  40. package/dist/loop/step/run.js +19 -3
  41. package/dist/loop/step/runtime.d.ts +3 -0
  42. package/dist/run/durable.d.ts +51 -3
  43. package/dist/run/durable.js +71 -31
  44. package/dist/tools/artifacts.d.ts +33 -0
  45. package/dist/tools/artifacts.js +323 -0
  46. package/dist/tools/engine-tools.d.ts +42 -0
  47. package/dist/tools/engine-tools.js +26 -0
  48. package/dist/tools/mcp.d.ts +92 -0
  49. package/dist/tools/mcp.js +240 -0
  50. package/dist/tools/outputs.d.ts +23 -0
  51. package/dist/tools/outputs.js +193 -0
  52. package/dist/tools/results.d.ts +108 -0
  53. package/dist/tools/results.js +329 -0
  54. package/dist/tools/sandbox.d.ts +35 -0
  55. package/dist/tools/sandbox.js +129 -0
  56. package/dist/tools/skills.d.ts +94 -0
  57. package/dist/tools/skills.js +243 -0
  58. package/dist/tools/text-page.d.ts +20 -0
  59. package/dist/tools/text-page.js +64 -0
  60. package/dist/tools/tool-search.d.ts +56 -0
  61. package/dist/tools/tool-search.js +174 -0
  62. package/dist/tools/trace.d.ts +13 -0
  63. package/dist/tools/trace.js +34 -0
  64. package/dist/types/execution.d.ts +20 -0
  65. package/package.json +2 -2
@@ -134,7 +134,7 @@ async function runTool(ctx, scope, tool, key, site, input) {
134
134
  if (!checked.ok)
135
135
  throw new FlowNodeError({
136
136
  code: "tool.invalid-input",
137
- message: `HTTP stage '${tool.name}' got ${describe(input)}, which does not match its input schema: ${checked.issues.map((issue) => issue.message).join("; ")}`,
137
+ message: `HTTP stage '${tool.name}' got ${describe(input, ctx.valueChars)}, which does not match its input schema: ${checked.issues.map((issue) => issue.message).join("; ")}`,
138
138
  path: site,
139
139
  });
140
140
  }
@@ -170,10 +170,13 @@ async function runChain(ctx, scope, steps, position, input) {
170
170
  function isRecord(value) {
171
171
  return !!value && typeof value === "object" && !Array.isArray(value);
172
172
  }
173
- /** A short description of a value for a failure message. */
174
- function describe(value) {
173
+ const ELLIPSIS = "...";
174
+ /** A short description of a value for a failure message: at most `chars` characters. */
175
+ function describe(value, chars) {
175
176
  const text = JSON.stringify(value) ?? String(value);
176
- return text.length > 80 ? `${text.slice(0, 77)}...` : text;
177
+ return text.length > chars
178
+ ? `${text.slice(0, Math.max(0, chars - ELLIPSIS.length))}${ELLIPSIS}`
179
+ : text;
177
180
  }
178
181
  /** The case the previous output names: itself when a string, else its `route` field. */
179
182
  async function runSwitch(ctx, scope, node, site, position, input) {
@@ -190,7 +193,7 @@ async function runSwitch(ctx, scope, node, site, position, input) {
190
193
  throw new FlowNodeError({
191
194
  code: "switch.no-match",
192
195
  message: name === undefined
193
- ? `Switch read ${describe(input)}, which names no case: the previous output must be a case name or an object with a string route field, and there is no default case`
196
+ ? `Switch read ${describe(input, ctx.valueChars)}, which names no case: the previous output must be a case name or an object with a string route field, and there is no default case`
194
197
  : `Switch read the case name ${JSON.stringify(name)}, but no case has that name (cases: ${Object.keys(node.cases).join(", ")}) and there is no default case`,
195
198
  path: site,
196
199
  });
@@ -246,7 +249,7 @@ async function runMap(ctx, scope, each, site, position, input) {
246
249
  if (!items)
247
250
  throw new FlowNodeError({
248
251
  code: "map.not-a-list",
249
- message: `A Map runs over an array or { items: [...] }; got ${describe(input)}`,
252
+ message: `A Map runs over an array or { items: [...] }; got ${describe(input, ctx.valueChars)}`,
250
253
  path: site,
251
254
  });
252
255
  assertMapItemCount(items.length, ctx.limits, site);
@@ -320,7 +323,7 @@ async function runVerify(ctx, scope, verify, site, position, args) {
320
323
  if (!isVerdict(value))
321
324
  throw new FlowNodeError({
322
325
  code: "loop.verify-failed",
323
- message: `The verifier must return { pass: boolean, feedback?: string }, with feedback when pass is false; got ${describe(value)}`,
326
+ message: `The verifier must return { pass: boolean, feedback?: string }, with feedback when pass is false; got ${describe(value, ctx.valueChars)}`,
324
327
  path: site,
325
328
  });
326
329
  return value;
@@ -1,15 +1,18 @@
1
1
  /**
2
- * Operator flow ceilings for the engine (`workflows.md` §13).
3
- * Host-side assert helpers live in the Runtime package; harness duplicates the
4
- * codes here so the engine never depends on Runtime.
5
- * Codes must stay identical: `map.too-many-items`, `loop.too-many-iterations`.
2
+ * Flow ceilings for the engine (`workflows.md` §13): the Tenant's Runtime limits `flowMapItems`
3
+ * and `flowLoopIterations`, which a flow's `turn.start.options.flowLimits` carries.
6
4
  */
7
5
  export type FlowOperatorLimits = {
8
6
  readonly maxMapItems: number;
9
7
  readonly maxLoopIterations: number;
10
8
  };
11
- /** Same defaults as Runtime `FLOW_LIMIT_DEFAULTS` (item/iteration ceilings). */
9
+ /**
10
+ * What the engine holds a flow to when its `turn.start` names no limits: the defaults of the
11
+ * Runtime limits `flowMapItems` and `flowLoopIterations`, which a Tenant sets.
12
+ */
12
13
  export declare const FLOW_OPERATOR_DEFAULTS: FlowOperatorLimits;
14
+ /** How many characters of a value a flow's failure message quotes, by default (engine config). */
15
+ export declare const DEFAULT_FLOW_VALUE_CHARS = 80;
13
16
  export declare function resolveOperatorLimits(limits?: Partial<FlowOperatorLimits> | null): FlowOperatorLimits;
14
17
  /**
15
18
  * Map item ceiling. Exceeding raises `map.too-many-items` and nothing should start.
@@ -1,15 +1,19 @@
1
1
  /**
2
- * Operator flow ceilings for the engine (`workflows.md` §13).
3
- * Host-side assert helpers live in the Runtime package; harness duplicates the
4
- * codes here so the engine never depends on Runtime.
5
- * Codes must stay identical: `map.too-many-items`, `loop.too-many-iterations`.
2
+ * Flow ceilings for the engine (`workflows.md` §13): the Tenant's Runtime limits `flowMapItems`
3
+ * and `flowLoopIterations`, which a flow's `turn.start.options.flowLimits` carries.
6
4
  */
5
+ import { RUNTIME_LIMIT_DEFAULTS } from "@nylorun/core/contracts";
7
6
  import { FlowNodeError } from "./types.js";
8
- /** Same defaults as Runtime `FLOW_LIMIT_DEFAULTS` (item/iteration ceilings). */
7
+ /**
8
+ * What the engine holds a flow to when its `turn.start` names no limits: the defaults of the
9
+ * Runtime limits `flowMapItems` and `flowLoopIterations`, which a Tenant sets.
10
+ */
9
11
  export const FLOW_OPERATOR_DEFAULTS = {
10
- maxMapItems: 1000,
11
- maxLoopIterations: 100,
12
+ maxMapItems: RUNTIME_LIMIT_DEFAULTS.flowMapItems,
13
+ maxLoopIterations: RUNTIME_LIMIT_DEFAULTS.flowLoopIterations,
12
14
  };
15
+ /** How many characters of a value a flow's failure message quotes, by default (engine config). */
16
+ export const DEFAULT_FLOW_VALUE_CHARS = 80;
13
17
  export function resolveOperatorLimits(limits) {
14
18
  return {
15
19
  maxMapItems: limits?.maxMapItems ?? FLOW_OPERATOR_DEFAULTS.maxMapItems,
package/dist/index.d.ts CHANGED
@@ -1,3 +1,11 @@
1
1
  export * from "./run/index.js";
2
2
  export type * from "./types/execution.js";
3
3
  export type * from "./types/client.js";
4
+ export * from "./loop/model/files.js";
5
+ export { DEFAULT_SANDBOX_TOOL_LIMITS, sandboxInstructions, sandboxToolLimitsOf, sandboxTools, type SandboxToolLimits, } from "./tools/sandbox.js";
6
+ export { DEFAULT_SKILL_READ_BYTES, LOAD_SKILL_TOOL, READ_SKILL_RESOURCE_TOOL, SKILLS_USAGE, definitionFileChunks, formatSkillCatalog, skillCatalogText, skillFolderNote, mountSkills, sandboxSkillsOf, skillTools, type SkillFiles, } from "./tools/skills.js";
7
+ export { engineToolsFor, type EngineToolOptions, type EngineTools } from "./tools/engine-tools.js";
8
+ export { DEFAULT_MCP_TOOL_CONFIG, MODEL_TOOL_NAME_MAX, mcpToolConfigOf, mcpToolKey, mcpToolName, mcpToolNames, mcpToolSet, type McpLayout, type McpRenamedTool, type McpToolConfig, type McpToolSet, } from "./tools/mcp.js";
9
+ export { TOOL_CALL_TOOL, TOOL_SEARCH_TOOL, deferredToolsNote, deferredToolsTools, isToolSearch, rank, runToolSearch, tokens, type DeferredServerNote, } from "./tools/tool-search.js";
10
+ export { DEFAULT_TOOL_RESULT_CONFIG, StepBudget, cutMessage, jsonBytes, mayNeedShaping, previewOf, resultBytes, shapeToolOutcome, spillKey, toolResultConfigOf, utf8Boundary, type ShapeContext, type Stored, type ToolResultConfig, } from "./tools/results.js";
11
+ export { DEFAULT_OUTPUTS_CONFIG, outputsConfigOf, saveOutputs, type OutputsConfig, type OutputsContext, } from "./tools/outputs.js";
package/dist/index.js CHANGED
@@ -1 +1,9 @@
1
1
  export * from "./run/index.js";
2
+ export * from "./loop/model/files.js";
3
+ export { DEFAULT_SANDBOX_TOOL_LIMITS, sandboxInstructions, sandboxToolLimitsOf, sandboxTools, } from "./tools/sandbox.js";
4
+ export { DEFAULT_SKILL_READ_BYTES, LOAD_SKILL_TOOL, READ_SKILL_RESOURCE_TOOL, SKILLS_USAGE, definitionFileChunks, formatSkillCatalog, skillCatalogText, skillFolderNote, mountSkills, sandboxSkillsOf, skillTools, } from "./tools/skills.js";
5
+ export { engineToolsFor } from "./tools/engine-tools.js";
6
+ export { DEFAULT_MCP_TOOL_CONFIG, MODEL_TOOL_NAME_MAX, mcpToolConfigOf, mcpToolKey, mcpToolName, mcpToolNames, mcpToolSet, } from "./tools/mcp.js";
7
+ export { TOOL_CALL_TOOL, TOOL_SEARCH_TOOL, deferredToolsNote, deferredToolsTools, isToolSearch, rank, runToolSearch, tokens, } from "./tools/tool-search.js";
8
+ export { DEFAULT_TOOL_RESULT_CONFIG, StepBudget, cutMessage, jsonBytes, mayNeedShaping, previewOf, resultBytes, shapeToolOutcome, spillKey, toolResultConfigOf, utf8Boundary, } from "./tools/results.js";
9
+ export { DEFAULT_OUTPUTS_CONFIG, outputsConfigOf, saveOutputs, } from "./tools/outputs.js";
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Our engine's configuration of compaction (Model Calls §8): how much history it keeps verbatim,
3
+ * the room it holds back for the reply, and the estimate it makes of what a prompt takes. A
4
+ * harness sets any part of it (`createHarness({ compaction })`); each left out is its default.
5
+ */
6
+ export interface CompactionConfig {
7
+ /** The kept tail is at most this many tokens... */
8
+ readonly keepTokens: number;
9
+ /** ...and at most this share of the context window. */
10
+ readonly keepShare: number;
11
+ /** Room held back for the reply when the model reports no output limit. */
12
+ readonly reserveTokens: number;
13
+ /** The most room held back for the reply... */
14
+ readonly maxReserveTokens: number;
15
+ /** ...and at most this share of the context window. */
16
+ readonly maxReserveShare: number;
17
+ /** Tool inputs and results are clipped to this many characters in the summarizer's input. */
18
+ readonly clipChars: number;
19
+ /** Tokens the summary instructions, format and previous summary take in a summary call. */
20
+ readonly summaryOverheadTokens: number;
21
+ /** Tokens one image counts for in the estimate. */
22
+ readonly imageTokens: number;
23
+ /** Bytes per token of a file other than text or an image, in the estimate... */
24
+ readonly fileBytesPerToken: number;
25
+ /** ...and the most one such file counts for. */
26
+ readonly fileTokensMax: number;
27
+ /** The fewest tokens of history one summary call takes, however small the window. */
28
+ readonly minChunkTokens: number;
29
+ /** The fewest tokens a summary may have... */
30
+ readonly minSummaryTokens: number;
31
+ /** ...and the share of the reserve it may have. */
32
+ readonly summaryShare: number;
33
+ /** Characters per token for the heuristic estimate; the reserve absorbs its error. */
34
+ readonly charsPerToken: number;
35
+ }
36
+ /** Compaction when the harness sets none. */
37
+ export declare const DEFAULT_COMPACTION_CONFIG: CompactionConfig;
38
+ /** `set` over the defaults. */
39
+ export declare function compactionConfigOf(set?: Partial<CompactionConfig>): CompactionConfig;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Our engine's configuration of compaction (Model Calls §8): how much history it keeps verbatim,
3
+ * the room it holds back for the reply, and the estimate it makes of what a prompt takes. A
4
+ * harness sets any part of it (`createHarness({ compaction })`); each left out is its default.
5
+ */
6
+ /** Compaction when the harness sets none. */
7
+ export const DEFAULT_COMPACTION_CONFIG = Object.freeze({
8
+ keepTokens: 20_000,
9
+ keepShare: 0.3,
10
+ reserveTokens: 8_192,
11
+ maxReserveTokens: 16_384,
12
+ maxReserveShare: 0.25,
13
+ clipChars: 2_000,
14
+ summaryOverheadTokens: 1_024,
15
+ imageTokens: 1_600,
16
+ fileBytesPerToken: 8,
17
+ fileTokensMax: 100_000,
18
+ minChunkTokens: 1_000,
19
+ minSummaryTokens: 256,
20
+ summaryShare: 0.8,
21
+ charsPerToken: 4,
22
+ });
23
+ /** `set` over the defaults. */
24
+ export function compactionConfigOf(set) {
25
+ return Object.freeze({
26
+ ...DEFAULT_COMPACTION_CONFIG,
27
+ ...Object.fromEntries(Object.entries(set ?? {}).filter(([, value]) => value !== undefined)),
28
+ });
29
+ }
@@ -6,31 +6,37 @@
6
6
  * `pi-agent-core` (MIT, Copyright (c) Earendil Works), rewritten for Nylorun's transcript.
7
7
  */
8
8
  import type { ModelAdapter, TranscriptCompactionEntry, TranscriptEntry } from "@nylorun/core/define";
9
+ import type { ModelDescriptor } from "@nylorun/core/harness-api";
10
+ import { type FileViewContext } from "../model/files.js";
11
+ import { type CompactionConfig } from "./config.js";
12
+ export { DEFAULT_COMPACTION_CONFIG, compactionConfigOf, type CompactionConfig } from "./config.js";
9
13
  export interface ContextBudget {
10
14
  readonly contextWindow: number;
11
15
  readonly reserve: number;
12
16
  }
13
17
  /**
14
18
  * The window and output limit the adapter reported on the latest candidate
15
- * (`evidence.extras.contextWindow`, `maxOutputTokens`). Undefined until a model has answered.
19
+ * (`evidence.extras.contextWindow`, `maxOutputTokens`). Before any answer reports them, the
20
+ * turn's model descriptor's (`turn.start.model`); undefined without either. The reserve is the
21
+ * output limit, held to `maxReserveTokens` and `maxReserveShare` of the window.
16
22
  */
17
- export declare function contextBudget(transcript: readonly TranscriptEntry[]): ContextBudget | undefined;
23
+ export declare function contextBudget(transcript: readonly TranscriptEntry[], model?: Pick<ModelDescriptor, "contextWindow" | "maxOutputTokens">, config?: CompactionConfig): ContextBudget | undefined;
18
24
  /**
19
25
  * Tokens the next prompt needs: the last reported usage, which already counts the
20
26
  * instructions, tools and everything before it, plus an estimate of what came after.
21
- * Without usage, everything is estimated. The files of turn `turnId` go to the model as media
22
- * (protocol 12) and count by their size; those of an earlier turn the reported call carried are
23
- * reference lines now, and come off it.
27
+ * Without usage, everything is estimated. The files of turn `turnId` go to the model as `files`
28
+ * shows them (`fileView`, protocol 15) and count by how; those of an earlier turn the reported
29
+ * call carried are reference lines now, and come off it.
24
30
  */
25
- export declare function estimateTokens(transcript: readonly TranscriptEntry[], turnId?: string): number;
31
+ export declare function estimateTokens(transcript: readonly TranscriptEntry[], turnId?: string, files?: FileViewContext, config?: CompactionConfig): number;
26
32
  /** A rough token count of what one entry contributes to a prompt. */
27
- export declare function entryTokens(entry: TranscriptEntry): number;
33
+ export declare function entryTokens(entry: TranscriptEntry, config?: CompactionConfig): number;
28
34
  /**
29
35
  * Where the kept tail starts. It keeps about `keepTokens` of the newest entries, never
30
36
  * starts with tool results (their call stays with them), and never keeps the previous
31
37
  * summary. Returns 0 or 1 when there is nothing older to summarize.
32
38
  */
33
- export declare function findCut(transcript: readonly TranscriptEntry[], keepTokens: number): number;
39
+ export declare function findCut(transcript: readonly TranscriptEntry[], keepTokens: number, config?: CompactionConfig): number;
34
40
  export interface CompactionInput {
35
41
  readonly transcript: readonly TranscriptEntry[];
36
42
  readonly executionId: string;
@@ -38,8 +44,12 @@ export interface CompactionInput {
38
44
  readonly stepId: string;
39
45
  readonly trigger: "threshold" | "overflow";
40
46
  readonly budget: ContextBudget | undefined;
47
+ /** How the turn's files reach the model, for the estimate (`fileView`). */
48
+ readonly files?: FileViewContext;
41
49
  readonly invoke: ModelAdapter;
42
50
  readonly signal: AbortSignal;
51
+ /** The harness's configuration of compaction. Default `DEFAULT_COMPACTION_CONFIG`. */
52
+ readonly config?: CompactionConfig;
43
53
  }
44
54
  /**
45
55
  * Summarize everything before the cut with one model call and return the new transcript,
@@ -1,21 +1,16 @@
1
- import { HarnessError, isModelFailureOutcome, mediaReferenceLine, mediaReferenceOf, } from "@nylorun/core/define";
2
- /** Characters per token for the heuristic estimate; the reserve absorbs its error. */
3
- const CHARS_PER_TOKEN = 4;
4
- /** The kept tail is at most this many tokens, and at most this share of the window. */
5
- const KEEP_TOKENS = 20_000;
6
- const KEEP_SHARE = 0.3;
7
- /** Room held back for the reply when the adapter does not report an output limit. */
8
- const DEFAULT_RESERVE = 8_192;
9
- const MAX_RESERVE = 16_384;
10
- /** Tool inputs and results are clipped to this many characters in the summarizer's input. */
11
- const CLIP = 2_000;
12
- /** Tokens the summary instructions, format and previous summary take in a summary call. */
13
- const SUMMARY_OVERHEAD = 1_024;
1
+ import { HarnessError, isModelFailureOutcome, mediaReferenceOf } from "@nylorun/core/define";
2
+ import { isText, modelInputOf } from "@nylorun/core/contracts";
3
+ import { fileView, mediaReferenceLine } from "../model/files.js";
4
+ import { DEFAULT_COMPACTION_CONFIG } from "./config.js";
5
+ export { DEFAULT_COMPACTION_CONFIG, compactionConfigOf } from "./config.js";
14
6
  /**
15
7
  * The window and output limit the adapter reported on the latest candidate
16
- * (`evidence.extras.contextWindow`, `maxOutputTokens`). Undefined until a model has answered.
8
+ * (`evidence.extras.contextWindow`, `maxOutputTokens`). Before any answer reports them, the
9
+ * turn's model descriptor's (`turn.start.model`); undefined without either. The reserve is the
10
+ * output limit, held to `maxReserveTokens` and `maxReserveShare` of the window.
17
11
  */
18
- export function contextBudget(transcript) {
12
+ export function contextBudget(transcript, model, config = DEFAULT_COMPACTION_CONFIG) {
13
+ const reserveOf = (output, window) => Math.min(output, config.maxReserveTokens, Math.floor(window * config.maxReserveShare));
19
14
  for (let index = transcript.length - 1; index >= 0; index--) {
20
15
  const entry = transcript[index];
21
16
  if (entry.kind !== "candidate")
@@ -25,19 +20,26 @@ export function contextBudget(transcript) {
25
20
  if (typeof window !== "number" || window <= 0)
26
21
  continue;
27
22
  const output = extras?.maxOutputTokens;
28
- const reserve = Math.min(typeof output === "number" && output > 0 ? output : DEFAULT_RESERVE, MAX_RESERVE, Math.floor(window / 4));
23
+ const reserve = reserveOf(typeof output === "number" && output > 0 ? output : config.reserveTokens, window);
29
24
  return { contextWindow: window, reserve };
30
25
  }
31
- return undefined;
26
+ if (!model)
27
+ return undefined;
28
+ return {
29
+ contextWindow: model.contextWindow,
30
+ reserve: reserveOf(model.maxOutputTokens, model.contextWindow),
31
+ };
32
32
  }
33
33
  /**
34
34
  * Tokens the next prompt needs: the last reported usage, which already counts the
35
35
  * instructions, tools and everything before it, plus an estimate of what came after.
36
- * Without usage, everything is estimated. The files of turn `turnId` go to the model as media
37
- * (protocol 12) and count by their size; those of an earlier turn the reported call carried are
38
- * reference lines now, and come off it.
36
+ * Without usage, everything is estimated. The files of turn `turnId` go to the model as `files`
37
+ * shows them (`fileView`, protocol 15) and count by how; those of an earlier turn the reported
38
+ * call carried are reference lines now, and come off it.
39
39
  */
40
- export function estimateTokens(transcript, turnId) {
40
+ export function estimateTokens(transcript, turnId, files, config = DEFAULT_COMPACTION_CONFIG) {
41
+ const fileTokens = (item) => filesTokens(item, files, config);
42
+ const tokens = (item) => entryTokens(item, config);
41
43
  const live = (item) => (item.turnId === turnId ? fileTokens(item) : 0);
42
44
  for (let index = transcript.length - 1; index >= 0; index--) {
43
45
  const entry = transcript[index];
@@ -58,37 +60,27 @@ export function estimateTokens(transcript, turnId) {
58
60
  .reduce((sum, item) => sum + (item.turnId === entry.turnId ? fileTokens(item) : 0), 0);
59
61
  return Math.max(0, reported -
60
62
  dropped +
61
- transcript.slice(index + 1).reduce((sum, item) => sum + entryTokens(item) + live(item), 0));
63
+ transcript.slice(index + 1).reduce((sum, item) => sum + tokens(item) + live(item), 0));
62
64
  }
63
- return transcript.reduce((sum, item) => sum + entryTokens(item) + live(item), 0);
65
+ return transcript.reduce((sum, item) => sum + tokens(item) + live(item), 0);
64
66
  }
65
- /** Tokens per image, and the most one other file counts for, in the estimate. */
66
- const IMAGE_TOKENS = 1_600;
67
- const FILE_TOKENS_MAX = 100_000;
68
- /** A rough token count of the files an entry names, as media: by type and size. */
69
- function fileTokens(entry) {
67
+ /**
68
+ * A rough token count of the files an entry names, as the model gets them: a note counts
69
+ * nothing (its line is text), inlined text by its size, an image `imageTokens`, another file by
70
+ * its size (`fileBytesPerToken`) up to `fileTokensMax`. Without `files`, each counts by its type.
71
+ */
72
+ function filesTokens(entry, files, config) {
70
73
  return filesOf(entry).reduce((sum, { part }) => {
71
74
  const size = mediaReferenceOf(part.reference)?.size ?? 0;
72
- const type = part.mediaType.split(";")[0].trim().toLowerCase();
73
- if (type.startsWith("image/"))
74
- return sum + IMAGE_TOKENS;
75
- if (isTextType(type))
76
- return sum + Math.ceil(size / CHARS_PER_TOKEN);
77
- return sum + Math.min(Math.ceil(size / 8), FILE_TOKENS_MAX);
75
+ if (files && fileView(part, files.model, files.limits).kind === "note")
76
+ return sum;
77
+ if (isText(part.mediaType))
78
+ return sum + Math.ceil(size / config.charsPerToken);
79
+ if (modelInputOf(part.mediaType) === "image")
80
+ return sum + config.imageTokens;
81
+ return sum + Math.min(Math.ceil(size / config.fileBytesPerToken), config.fileTokensMax);
78
82
  }, 0);
79
83
  }
80
- function isTextType(type) {
81
- return (type.startsWith("text/") ||
82
- type.endsWith("+json") ||
83
- type.endsWith("+xml") ||
84
- [
85
- "application/json",
86
- "application/xml",
87
- "application/yaml",
88
- "application/x-yaml",
89
- "application/javascript",
90
- ].includes(type));
91
- }
92
84
  /** The files an entry names (protocol 12): a message's media parts, and a tool result's files. */
93
85
  function filesOf(entry) {
94
86
  if (entry.kind === "input") {
@@ -109,20 +101,20 @@ function filesOf(entry) {
109
101
  return [];
110
102
  }
111
103
  /** A rough token count of what one entry contributes to a prompt. */
112
- export function entryTokens(entry) {
113
- return Math.ceil(entryText(entry, Number.POSITIVE_INFINITY).length / CHARS_PER_TOKEN);
104
+ export function entryTokens(entry, config = DEFAULT_COMPACTION_CONFIG) {
105
+ return Math.ceil(entryText(entry, Number.POSITIVE_INFINITY).length / config.charsPerToken);
114
106
  }
115
107
  /**
116
108
  * Where the kept tail starts. It keeps about `keepTokens` of the newest entries, never
117
109
  * starts with tool results (their call stays with them), and never keeps the previous
118
110
  * summary. Returns 0 or 1 when there is nothing older to summarize.
119
111
  */
120
- export function findCut(transcript, keepTokens) {
112
+ export function findCut(transcript, keepTokens, config = DEFAULT_COMPACTION_CONFIG) {
121
113
  const first = transcript[0]?.kind === "compaction" ? 1 : 0;
122
114
  let kept = 0;
123
115
  let cut = transcript.length;
124
116
  while (cut > first) {
125
- const tokens = entryTokens(transcript[cut - 1]);
117
+ const tokens = entryTokens(transcript[cut - 1], config);
126
118
  if (kept + tokens > keepTokens && cut < transcript.length)
127
119
  break;
128
120
  kept += tokens;
@@ -140,10 +132,11 @@ export function findCut(transcript, keepTokens) {
140
132
  */
141
133
  export async function compact(input) {
142
134
  const { transcript } = input;
143
- const tokensBefore = estimateTokens(transcript, input.turnId);
135
+ const config = input.config ?? DEFAULT_COMPACTION_CONFIG;
136
+ const tokensBefore = estimateTokens(transcript, input.turnId, input.files, config);
144
137
  const window = input.budget?.contextWindow ?? tokensBefore;
145
- const keepTokens = Math.max(1, Math.min(KEEP_TOKENS, Math.floor(window * KEEP_SHARE)));
146
- const cut = findCut(transcript, keepTokens);
138
+ const keepTokens = Math.max(1, Math.min(config.keepTokens, Math.floor(window * config.keepShare)));
139
+ const cut = findCut(transcript, keepTokens, config);
147
140
  const previous = transcript[0]?.kind === "compaction" ? transcript[0] : undefined;
148
141
  const start = previous ? 1 : 0;
149
142
  if (cut <= start)
@@ -163,22 +156,21 @@ export async function compact(input) {
163
156
  .flatMap((entry) => filesOf(entry).map(({ line }) => line)),
164
157
  ]),
165
158
  ];
166
- const keptTokens = tail.reduce((sum, entry) => sum + entryTokens(entry), 0);
167
- const reserve = input.budget?.reserve ?? DEFAULT_RESERVE;
168
- const maxOutputTokens = Math.max(256, Math.floor(reserve * 0.8));
159
+ const keptTokens = tail.reduce((sum, entry) => sum + entryTokens(entry, config), 0);
160
+ const reserve = input.budget?.reserve ?? config.reserveTokens;
161
+ const maxOutputTokens = Math.max(config.minSummaryTokens, Math.floor(reserve * config.summaryShare));
169
162
  // The summarizer sees at most what fits its window: older history is summarized in
170
163
  // chunks, each merged into the running summary. A single call would fail on a provider,
171
164
  // or lose the start of the history on a server that truncates silently.
172
165
  const chunkTokens = input.budget
173
- ? Math.max(1_000, input.budget.contextWindow - reserve - SUMMARY_OVERHEAD)
166
+ ? Math.max(config.minChunkTokens, input.budget.contextWindow - reserve - config.summaryOverheadTokens)
174
167
  : Number.POSITIVE_INFINITY;
175
- const chunks = chunked(older, chunkTokens);
168
+ const chunks = chunked(older, chunkTokens, config);
176
169
  // A step can compact before its call and again after an overflow; each is its own effect.
177
170
  const base = `compaction-${input.stepId}${input.trigger === "overflow" ? "-overflow" : ""}`;
178
171
  let summary = previous?.summary;
179
172
  for (const [index, chunk] of chunks.entries()) {
180
- const last = index === chunks.length - 1;
181
- const outcome = await input.invoke(summaryCall(input, chunk, summary, maxOutputTokens), {
173
+ const outcome = await input.invoke(summaryCall(input, chunk, summary, maxOutputTokens, config.clipChars), {
182
174
  request: summaryRequest(input),
183
175
  invocationId: index === 0 ? base : `${base}-${index}`,
184
176
  signal: input.signal,
@@ -186,7 +178,6 @@ export async function compact(input) {
186
178
  trigger: input.trigger,
187
179
  tokensBefore,
188
180
  keptTokens,
189
- ...(last ? {} : { partial: true }),
190
181
  },
191
182
  reportPreparedCall() { },
192
183
  });
@@ -205,7 +196,7 @@ export async function compact(input) {
205
196
  summary,
206
197
  trigger: input.trigger,
207
198
  tokensBefore,
208
- tokensAfter: keptTokens + Math.ceil(summary.length / CHARS_PER_TOKEN),
199
+ tokensAfter: keptTokens + Math.ceil(summary.length / config.charsPerToken),
209
200
  ...(files.length > 0 ? { files } : {}),
210
201
  };
211
202
  return Object.freeze([Object.freeze(entry), ...tail]);
@@ -237,12 +228,12 @@ const FORMAT = [
237
228
  "If a previous summary is given, merge it with the new conversation into one summary.",
238
229
  ].join("\n");
239
230
  /** Consecutive runs of entries whose summarizer input stays under `limit` tokens. */
240
- function chunked(entries, limit) {
231
+ function chunked(entries, limit, config) {
241
232
  const chunks = [];
242
233
  let current = [];
243
234
  let size = 0;
244
235
  for (const entry of entries) {
245
- const tokens = Math.ceil(entryText(entry, CLIP).length / CHARS_PER_TOKEN);
236
+ const tokens = Math.ceil(entryText(entry, config.clipChars).length / config.charsPerToken);
246
237
  if (current.length && size + tokens > limit) {
247
238
  chunks.push(current);
248
239
  current = [];
@@ -255,9 +246,9 @@ function chunked(entries, limit) {
255
246
  chunks.push(current);
256
247
  return chunks;
257
248
  }
258
- function summaryCall(input, older, previous, maxOutputTokens) {
249
+ function summaryCall(input, older, previous, maxOutputTokens, clip) {
259
250
  const conversation = older
260
- .map((entry) => entryText(entry, CLIP))
251
+ .map((entry) => entryText(entry, clip))
261
252
  .filter((text) => text !== "")
262
253
  .join("\n\n");
263
254
  const text = [
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Our engine's loop settings: compaction, and what an agent used as a tool shows its parent when
3
+ * it fails. A harness sets them (`createHarness({ compaction, partialOutputChars })`); a local
4
+ * `run()` and each one left out get the defaults. An invocation hands its settings to the agents
5
+ * it uses as tools.
6
+ */
7
+ import { type CompactionConfig } from "./compaction/config.js";
8
+ export interface LoopConfig {
9
+ readonly compaction: CompactionConfig;
10
+ /** How many characters of a failed agent-as-tool's last output its parent sees. */
11
+ readonly partialOutputChars: number;
12
+ }
13
+ /** The characters of a failed agent-as-tool's last output its parent sees, by default. */
14
+ export declare const DEFAULT_PARTIAL_OUTPUT_CHARS = 4000;
15
+ /** `set` over the defaults. */
16
+ export declare function loopConfigOf(set?: {
17
+ readonly compaction?: Partial<CompactionConfig>;
18
+ readonly partialOutputChars?: number;
19
+ }): LoopConfig;
20
+ export declare const DEFAULT_LOOP_CONFIG: LoopConfig;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Our engine's loop settings: compaction, and what an agent used as a tool shows its parent when
3
+ * it fails. A harness sets them (`createHarness({ compaction, partialOutputChars })`); a local
4
+ * `run()` and each one left out get the defaults. An invocation hands its settings to the agents
5
+ * it uses as tools.
6
+ */
7
+ import { compactionConfigOf } from "./compaction/config.js";
8
+ /** The characters of a failed agent-as-tool's last output its parent sees, by default. */
9
+ export const DEFAULT_PARTIAL_OUTPUT_CHARS = 4_000;
10
+ /** `set` over the defaults. */
11
+ export function loopConfigOf(set = {}) {
12
+ return Object.freeze({
13
+ compaction: compactionConfigOf(set.compaction),
14
+ partialOutputChars: set.partialOutputChars ?? DEFAULT_PARTIAL_OUTPUT_CHARS,
15
+ });
16
+ }
17
+ export const DEFAULT_LOOP_CONFIG = loopConfigOf();
@@ -2,6 +2,7 @@ import type { AgentRef, Delegate, JsonObject, JsonValue, ModelAdapter, ToolOutco
2
2
  import type { AgentDefinition } from "../definition/agent-definition.js";
3
3
  import type { RunOptions, RunResult } from "../types/execution.js";
4
4
  import type { Invocation } from "./invocation.js";
5
+ import type { LoopConfig } from "./config.js";
5
6
  /** How one agent used as a tool is built and journaled. Durable hosts supply their own. */
6
7
  export interface DelegationHost {
7
8
  child(delegate: Delegate, ref: AgentRef): {
@@ -35,6 +36,8 @@ export interface ExecuteInternals {
35
36
  readonly steps?: number;
36
37
  readonly ms?: number;
37
38
  };
39
+ /** The loop's settings (compaction, a failed child's partial output). Default `DEFAULT_LOOP_CONFIG`. */
40
+ readonly loop?: LoopConfig;
38
41
  }
39
42
  /** Codes are curated: a child's provider error bodies never reach the parent's context. */
40
43
  export declare const INTERACTION_UNSUPPORTED = "Agents used as tools can't ask for input, approval or a wait yet; do this work on the parent agent.";
@@ -6,7 +6,6 @@ import { textFromOutput } from "./model/normalize.js";
6
6
  import { HostSuspension } from "./host-suspension.js";
7
7
  /** Codes are curated: a child's provider error bodies never reach the parent's context. */
8
8
  export const INTERACTION_UNSUPPORTED = "Agents used as tools can't ask for input, approval or a wait yet; do this work on the parent agent.";
9
- const PARTIAL_LIMIT = 4_000;
10
9
  /** In-process children, built from the authored agent and sharing the parent's model callable. */
11
10
  export function localDelegation(onModelCall) {
12
11
  return {
@@ -43,7 +42,7 @@ export async function runDelegation(invocation, execute, call, delegate) {
43
42
  if (isFlowDelegate(delegate)) {
44
43
  if (!host.flow)
45
44
  throw new HarnessError("execution.invalid-input", `Agent '${ref.id}' is a flow agent; flow agents used as tools run on the Runtime`);
46
- outcome = settleFlow(await host.flow(delegate, ref, task));
45
+ outcome = settleFlow(await host.flow(delegate, ref, task), invocation.loop.partialOutputChars);
47
46
  status = outcome.kind === "completed" ? "completed" : "failed";
48
47
  }
49
48
  else {
@@ -53,14 +52,19 @@ export async function runDelegation(invocation, execute, call, delegate) {
53
52
  input: task,
54
53
  onModelCall: child.onModelCall,
55
54
  signal,
55
+ // A child calls the same model, and reads its files as the parent does.
56
+ ...(options.model === undefined ? {} : { model: options.model }),
57
+ ...(options.files === undefined ? {} : { files: options.files }),
56
58
  ...(options.info === undefined ? {} : { info: options.info }),
57
59
  state: initializeExecutionState(child.definition, {
58
60
  executionId: `${invocation.state.executionId}/${call.invocationId}`,
59
61
  }),
60
62
  ...(listener ? { onEvent: (event) => listener({ ...event, agent: ref }) } : {}),
61
- }, { delegated: ref }));
63
+ },
64
+ // A child runs with its parent's loop settings.
65
+ { delegated: ref, loop: invocation.loop }));
62
66
  status = result.status;
63
- outcome = settle(result);
67
+ outcome = settle(result, invocation.loop.partialOutputChars);
64
68
  }
65
69
  }
66
70
  catch (cause) {
@@ -99,7 +103,7 @@ export async function runDelegation(invocation, execute, call, delegate) {
99
103
  return outcome;
100
104
  }
101
105
  /** "Done" means settled with real output; empty or unfinished work is a failure with evidence. */
102
- function settle(result) {
106
+ function settle(result, partialChars) {
103
107
  if (result.status === "completed") {
104
108
  const output = result.output;
105
109
  if (output === null || (typeof output === "string" && output.trim() === ""))
@@ -123,7 +127,7 @@ function settle(result) {
123
127
  return { kind: "failed", code: "delegation.failed", message: "The agent stopped early." };
124
128
  const reason = result.error.code;
125
129
  const curated = reason.startsWith("execution.") ? reason : `${reason}: ${result.error.message}`;
126
- const partial = lastText(result);
130
+ const partial = lastText(result, partialChars);
127
131
  return {
128
132
  kind: "failed",
129
133
  code: "delegation.failed",
@@ -131,19 +135,19 @@ function settle(result) {
131
135
  (partial ? `\nPartial output (evidence, not an answer):\n${partial}` : ""),
132
136
  };
133
137
  }
134
- function lastText(result) {
138
+ function lastText(result, limit) {
135
139
  for (let index = result.state.transcript.length - 1; index >= 0; index--) {
136
140
  const entry = result.state.transcript[index];
137
141
  if (entry.kind !== "candidate")
138
142
  continue;
139
143
  const text = textFromOutput(entry.candidate.output).trim();
140
144
  if (text)
141
- return text.length > PARTIAL_LIMIT ? `${text.slice(0, PARTIAL_LIMIT)}…` : text;
145
+ return text.length > limit ? `${text.slice(0, limit)}…` : text;
142
146
  }
143
147
  return undefined;
144
148
  }
145
149
  /** A flow's settled value: its output, or the `{ kind: "failed" }` value the host records. */
146
- function settleFlow(value) {
150
+ function settleFlow(value, partialChars) {
147
151
  if (value && typeof value === "object" && !Array.isArray(value)) {
148
152
  const record = value;
149
153
  if (record.kind === "failed" && typeof record.code === "string")
@@ -153,5 +157,5 @@ function settleFlow(value) {
153
157
  message: `The agent failed (${record.code}: ${typeof record.message === "string" ? record.message : record.code}).`,
154
158
  };
155
159
  }
156
- return settle({ status: "completed", output: value });
160
+ return settle({ status: "completed", output: value }, partialChars);
157
161
  }