@clearideas/agent-runtime-contracts 0.6.3 → 0.7.1

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.
package/dist/index.d.ts CHANGED
@@ -212,6 +212,134 @@ export declare const agentVariableDefinitionSchema: z.ZodType<AgentVariableDefin
212
212
  export declare const agentVariableOverrideSchema: z.ZodType<AgentVariableOverride>;
213
213
  export declare const agentVariableOverridesSchema: z.ZodArray<z.ZodType<AgentVariableOverride, unknown, z.core.$ZodTypeInternals<AgentVariableOverride, unknown>>>;
214
214
  export declare const parseAgentVariableOverrides: (input: unknown) => AgentVariableOverride[];
215
+ /**
216
+ * How a prompt step reduces model input that is, or would become, too large.
217
+ *
218
+ * - `summarize`: a summarizer model condenses oversized content; failure fails the step.
219
+ * - `prune`: deterministic reduction without a model call (clip, stub, drop).
220
+ * - `summarize-or-prune`: summarize, and prune when summarizing fails or is not enough.
221
+ * - `fail`: never reduce; an oversized input fails the step.
222
+ */
223
+ export declare const CONTEXT_STRATEGIES: readonly ["summarize", "prune", "summarize-or-prune", "fail"];
224
+ export type ContextStrategy = (typeof CONTEXT_STRATEGIES)[number];
225
+ /** The model and instructions used when a context strategy summarizes. */
226
+ /** What the summarizer condenses. */
227
+ export declare const SUMMARY_KINDS: readonly ["input", "transcript", "tool-result"];
228
+ export type SummaryKind = (typeof SUMMARY_KINDS)[number];
229
+ export interface ContextSummarizer {
230
+ /** Defaults to the step model, then the manifest model. */
231
+ model?: ModelReference;
232
+ /** Replaces the built-in summarizer system prompt. Templated over step variables and `context.*`. */
233
+ systemPrompt?: string;
234
+ /** Replaces the built-in instruction for every kind. Templated over step variables and `context.*`. */
235
+ prompt?: string;
236
+ /** Replaces the built-in instruction for one kind; takes precedence over `prompt`. */
237
+ prompts?: {
238
+ input?: string;
239
+ transcript?: string;
240
+ toolResult?: string;
241
+ };
242
+ /** Output-token limit for each summarizer call. Defaults from the target size. */
243
+ maxOutputTokens?: number;
244
+ /**
245
+ * A transcript summary's target, as a share of the content it replaces
246
+ * (default 0.25), bounded by `minSummaryBytes` and `maxSummaryBytes` and by
247
+ * the room left under `reduceTo`.
248
+ */
249
+ summaryShare?: number;
250
+ /** Smallest transcript summary to ask for, in bytes (default 1024). */
251
+ minSummaryBytes?: number;
252
+ /** Largest transcript summary to ask for, in bytes (default 16384). */
253
+ maxSummaryBytes?: number;
254
+ /**
255
+ * Most material sent in one summarizer call, in bytes. Larger material is
256
+ * split into chunks. Defaults to half the summarizer model's described input
257
+ * window, else 48000. Chunks are reduced further so the full rendered
258
+ * summarizer request fits `limits.maxInputBytes`.
259
+ */
260
+ chunkBytes?: number;
261
+ /** Summarizer calls allowed per step execution (default 8 × maxCompactions, at least 16). */
262
+ maxCalls?: number;
263
+ /** Condensing passes over chunked material before giving up (default 4). */
264
+ maxPasses?: number;
265
+ }
266
+ /** When a prompt step reduces its input. Any satisfied criterion triggers. */
267
+ export interface ContextTrigger {
268
+ /** Model input JSON size, measured like `limits.maxInputBytes`. */
269
+ inputBytes?: number;
270
+ /** Estimated model input tokens, calibrated from reported usage. */
271
+ inputTokens?: number;
272
+ /** Fraction of the model's input window; requires an adapter that describes the model. */
273
+ contextRatio?: number;
274
+ /** Tool rounds completed since the step started or last compacted. */
275
+ toolRounds?: number;
276
+ }
277
+ /** Per-variable overrides for reducing a step's interpolated opening prompt. */
278
+ export interface ContextVariablePolicy {
279
+ /** Never shorten this variable. */
280
+ keep?: boolean;
281
+ strategy?: ContextStrategy;
282
+ /** Always cap this variable's interpolated text at this size. */
283
+ maxBytes?: number;
284
+ }
285
+ export interface ContextPolicy {
286
+ strategy?: ContextStrategy;
287
+ summarizer?: ContextSummarizer;
288
+ trigger?: ContextTrigger;
289
+ retain?: {
290
+ /** Newest tool rounds kept verbatim when older rounds are compacted. */
291
+ recentToolRounds?: number;
292
+ };
293
+ /**
294
+ * Size a reduction aims for, as a fraction of the trigger (default 0.25).
295
+ * Lower values reduce less often but cut deeper each time; higher values
296
+ * reduce more often and keep more history.
297
+ */
298
+ reduceTo?: number;
299
+ /**
300
+ * Largest share of the trigger the opening prompt may use before its
301
+ * interpolated variables are reduced. Defaults to 0.5 for a step with tools
302
+ * (leaving room for the tool loop) and 0.9 for a step without tools.
303
+ */
304
+ openingShare?: number;
305
+ /** Summarizing compactions per step execution; later reductions prune. */
306
+ maxCompactions?: number;
307
+ /** Reduce-and-retry attempts after a provider rejects a request as too long (default 3). */
308
+ overflowRetries?: number;
309
+ /** Cap for a single tool result as seen by the model. */
310
+ maxToolResultBytes?: number;
311
+ /**
312
+ * Cap for a single tool result as a fraction of the trigger (default 0.4).
313
+ * `maxToolResultBytes`, when set, takes precedence.
314
+ */
315
+ toolResultShare?: number;
316
+ /** Keyed by variable path as written in templates, or by its root variable. */
317
+ variables?: Record<string, ContextVariablePolicy>;
318
+ }
319
+ export interface ModelRetryPolicy {
320
+ /** Total attempts for one model request, including the first. */
321
+ maxAttempts?: number;
322
+ initialDelayMs?: number;
323
+ maxDelayMs?: number;
324
+ }
325
+ export interface OutputRepairPolicy {
326
+ /** Extra model turns allowed to repair invalid, empty, or truncated final output. */
327
+ maxAttempts?: number;
328
+ }
329
+ /**
330
+ * Execution policies. Hosts set defaults; a manifest's `policies` override the
331
+ * host; a step's `policies` override the manifest. Prompt-only fields are
332
+ * rejected on other step types.
333
+ */
334
+ export interface ExecutionPolicies {
335
+ context?: ContextPolicy;
336
+ /** finalize: answer without tools once the tool-call limit is reached. */
337
+ toolCallLimit?: "finalize" | "fail";
338
+ modelRetry?: ModelRetryPolicy;
339
+ outputRepair?: OutputRepairPolicy;
340
+ /** continue: record the error as the step output and run the next step. */
341
+ onError?: "fail" | "continue";
342
+ }
215
343
  export interface AgentStepBase {
216
344
  id: string;
217
345
  name?: string;
@@ -219,6 +347,7 @@ export interface AgentStepBase {
219
347
  when?: string;
220
348
  outputVariable?: string;
221
349
  includeInFinalOutput?: boolean;
350
+ policies?: ExecutionPolicies;
222
351
  metadata?: JsonObject;
223
352
  extensions?: JsonObject;
224
353
  }
@@ -275,7 +404,14 @@ export interface WebhookStep extends AgentStepBase {
275
404
  export interface ApprovalStep extends AgentStepBase {
276
405
  type: "approval";
277
406
  prompt: string;
407
+ /** Informational; forwarded in events and on ApprovalRejectedError. */
278
408
  action?: "pause" | "complete" | "cancel";
409
+ /**
410
+ * What a rejection does. fail (default) fails the run; cancel cancels it;
411
+ * complete ends the run successfully without running later steps; continue
412
+ * records `{ approved: false }` and runs the next step.
413
+ */
414
+ onReject?: "fail" | "cancel" | "complete" | "continue";
279
415
  }
280
416
  export interface SubRunStep extends AgentStepBase {
281
417
  type: "sub-run";
@@ -295,6 +431,10 @@ export interface CodeStep extends AgentStepBase {
295
431
  sandbox?: "run" | "step";
296
432
  }
297
433
  export type AgentStep = PromptStep | LoopStep | WebhookStep | ApprovalStep | SubRunStep | CodeStep;
434
+ export declare const contextPolicySchema: z.ZodType<ContextPolicy>;
435
+ export declare const executionPoliciesSchema: z.ZodType<ExecutionPolicies>;
436
+ /** Policy fields that only a prompt step can use. */
437
+ export declare const PROMPT_ONLY_POLICY_FIELDS: readonly ["context", "toolCallLimit", "modelRetry", "outputRepair"];
298
438
  export declare const promptMessageSchema: z.ZodType<PromptMessage>;
299
439
  export declare const agentWorkspaceBindingSchema: z.ZodType<AgentWorkspaceBinding>;
300
440
  export declare const agentStepSchema: z.ZodType<AgentStep>;
@@ -309,6 +449,8 @@ export interface AgentManifest {
309
449
  /** Host-defined file collections available to workspace tools and code steps. */
310
450
  workspaces?: AgentWorkspaceBinding[];
311
451
  steps: AgentStep[];
452
+ /** Manifest-wide execution policy defaults; steps may override them. */
453
+ policies?: ExecutionPolicies;
312
454
  limits?: {
313
455
  maxSteps?: number;
314
456
  maxMessagesPerPrompt?: number;
@@ -1116,7 +1258,7 @@ export declare const runCheckpointSchema: z.ZodObject<{
1116
1258
  metadata: z.ZodOptional<z.ZodType<JsonObject, unknown, z.core.$ZodTypeInternals<JsonObject, unknown>>>;
1117
1259
  }, z.core.$strict>;
1118
1260
  export declare const parseRunCheckpoint: (input: unknown) => RunCheckpoint;
1119
- export type RunEventType = "run.started" | "run.resumed" | "run.completed" | "run.failed" | "run.cancelled" | "run.suspended" | "run.heartbeat" | "step.started" | "step.skipped" | "step.completed" | "step.failed" | "checkpoint.saved" | "loop.iteration.started" | "loop.iteration.completed" | "loop.iteration.skipped" | "loop.goal.met" | "approval.requested" | "approval.resolved" | "webhook.attempt.started" | "webhook.attempt.completed" | "webhook.retry.scheduled" | "code.execution.started" | "code.execution.completed" | "workspace.bound" | "sandbox.opened" | "sandbox.command.started" | "sandbox.command.completed" | "sandbox.closed" | "sub-run.started" | "sub-run.completed" | "model.started" | "model.text.delta" | "model.reasoning.delta" | "model.tool.requested" | "model.tool.started" | "model.tool.completed" | "model.usage" | "model.completed" | "artifact.created" | "diagnostic";
1261
+ export type RunEventType = "run.started" | "run.resumed" | "run.completed" | "run.failed" | "run.cancelled" | "run.suspended" | "run.interrupted" | "run.heartbeat" | "step.started" | "step.skipped" | "step.completed" | "step.failed" | "checkpoint.saved" | "loop.iteration.started" | "loop.iteration.completed" | "loop.iteration.skipped" | "loop.goal.met" | "approval.requested" | "approval.resolved" | "webhook.attempt.started" | "webhook.attempt.completed" | "webhook.retry.scheduled" | "code.execution.started" | "code.execution.completed" | "workspace.bound" | "sandbox.opened" | "sandbox.command.started" | "sandbox.command.completed" | "sandbox.closed" | "sub-run.started" | "sub-run.completed" | "model.started" | "model.text.delta" | "model.reasoning.delta" | "model.tool.requested" | "model.tool.started" | "model.tool.completed" | "model.usage" | "model.completed" | "model.retry" | "context.reduced" | "artifact.created" | "diagnostic";
1120
1262
  export interface RunEvent {
1121
1263
  id: string;
1122
1264
  runId: string;
package/dist/index.js CHANGED
@@ -91,16 +91,23 @@ export const agentVariableOverridesSchema = z
91
91
  });
92
92
  });
93
93
  export const parseAgentVariableOverrides = (input) => agentVariableOverridesSchema.parse(input);
94
- const stepBaseShape = {
95
- id: z.string().min(1),
96
- name: z.string().min(1).optional(),
97
- description: z.string().optional(),
98
- when: z.string().optional(),
99
- outputVariable: agentVariableKeySchema.optional(),
100
- includeInFinalOutput: z.boolean().optional(),
101
- metadata: jsonObjectSchema.optional(),
102
- extensions: jsonObjectSchema.optional(),
103
- };
94
+ /**
95
+ * How a prompt step reduces model input that is, or would become, too large.
96
+ *
97
+ * - `summarize`: a summarizer model condenses oversized content; failure fails the step.
98
+ * - `prune`: deterministic reduction without a model call (clip, stub, drop).
99
+ * - `summarize-or-prune`: summarize, and prune when summarizing fails or is not enough.
100
+ * - `fail`: never reduce; an oversized input fails the step.
101
+ */
102
+ export const CONTEXT_STRATEGIES = [
103
+ "summarize",
104
+ "prune",
105
+ "summarize-or-prune",
106
+ "fail",
107
+ ];
108
+ /** The model and instructions used when a context strategy summarizes. */
109
+ /** What the summarizer condenses. */
110
+ export const SUMMARY_KINDS = ["input", "transcript", "tool-result"];
104
111
  const explicitModelReferenceSchema = z.strictObject({
105
112
  provider: z.string().min(1),
106
113
  model: z.string().min(1),
@@ -114,6 +121,95 @@ const modelReferenceSchema = z.union([
114
121
  explicitModelReferenceSchema,
115
122
  profileModelReferenceSchema,
116
123
  ]);
124
+ const contextStrategySchema = z.enum(CONTEXT_STRATEGIES);
125
+ export const contextPolicySchema = z.strictObject({
126
+ strategy: contextStrategySchema.optional(),
127
+ summarizer: z
128
+ .strictObject({
129
+ model: modelReferenceSchema.optional(),
130
+ systemPrompt: z.string().min(1).optional(),
131
+ prompt: z.string().min(1).optional(),
132
+ prompts: z
133
+ .strictObject({
134
+ input: z.string().min(1).optional(),
135
+ transcript: z.string().min(1).optional(),
136
+ toolResult: z.string().min(1).optional(),
137
+ })
138
+ .optional(),
139
+ maxOutputTokens: z.number().int().positive().optional(),
140
+ summaryShare: z.number().gt(0).max(1).optional(),
141
+ minSummaryBytes: z.number().int().min(128).optional(),
142
+ maxSummaryBytes: z.number().int().min(256).optional(),
143
+ chunkBytes: z.number().int().min(1024).optional(),
144
+ maxCalls: z.number().int().positive().optional(),
145
+ maxPasses: z.number().int().min(1).max(10).optional(),
146
+ })
147
+ .refine((summarizer) => summarizer.minSummaryBytes == null ||
148
+ summarizer.maxSummaryBytes == null ||
149
+ summarizer.minSummaryBytes <= summarizer.maxSummaryBytes, "summarizer.minSummaryBytes cannot exceed maxSummaryBytes.")
150
+ .optional(),
151
+ trigger: z
152
+ .strictObject({
153
+ inputBytes: z.number().int().positive().optional(),
154
+ inputTokens: z.number().int().positive().optional(),
155
+ contextRatio: z.number().gt(0).max(1).optional(),
156
+ toolRounds: z.number().int().positive().optional(),
157
+ })
158
+ .optional(),
159
+ retain: z
160
+ .strictObject({
161
+ recentToolRounds: z.number().int().nonnegative().optional(),
162
+ })
163
+ .optional(),
164
+ reduceTo: z.number().min(0.05).max(0.95).optional(),
165
+ openingShare: z.number().min(0.05).max(1).optional(),
166
+ maxCompactions: z.number().int().nonnegative().optional(),
167
+ overflowRetries: z.number().int().min(0).max(10).optional(),
168
+ maxToolResultBytes: z.number().int().positive().optional(),
169
+ toolResultShare: z.number().min(0.05).max(1).optional(),
170
+ variables: z
171
+ .record(variablePathSchema, z.strictObject({
172
+ keep: z.boolean().optional(),
173
+ strategy: contextStrategySchema.optional(),
174
+ maxBytes: z.number().int().positive().optional(),
175
+ }))
176
+ .optional(),
177
+ });
178
+ export const executionPoliciesSchema = z.strictObject({
179
+ context: contextPolicySchema.optional(),
180
+ toolCallLimit: z.enum(["finalize", "fail"]).optional(),
181
+ modelRetry: z
182
+ .strictObject({
183
+ maxAttempts: z.number().int().min(1).max(10).optional(),
184
+ initialDelayMs: z.number().int().nonnegative().optional(),
185
+ maxDelayMs: z.number().int().nonnegative().optional(),
186
+ })
187
+ .optional(),
188
+ outputRepair: z
189
+ .strictObject({
190
+ maxAttempts: z.number().int().min(0).max(5).optional(),
191
+ })
192
+ .optional(),
193
+ onError: z.enum(["fail", "continue"]).optional(),
194
+ });
195
+ /** Policy fields that only a prompt step can use. */
196
+ export const PROMPT_ONLY_POLICY_FIELDS = [
197
+ "context",
198
+ "toolCallLimit",
199
+ "modelRetry",
200
+ "outputRepair",
201
+ ];
202
+ const stepBaseShape = {
203
+ id: z.string().min(1),
204
+ name: z.string().min(1).optional(),
205
+ description: z.string().optional(),
206
+ when: z.string().optional(),
207
+ outputVariable: agentVariableKeySchema.optional(),
208
+ includeInFinalOutput: z.boolean().optional(),
209
+ policies: executionPoliciesSchema.optional(),
210
+ metadata: jsonObjectSchema.optional(),
211
+ extensions: jsonObjectSchema.optional(),
212
+ };
117
213
  export const promptMessageSchema = z.lazy(() => z
118
214
  .strictObject({
119
215
  role: z.enum(["system", "user", "assistant", "tool"]),
@@ -332,6 +428,7 @@ export const agentStepSchema = z.lazy(() => z.discriminatedUnion("type", [
332
428
  type: z.literal("approval"),
333
429
  prompt: z.string(),
334
430
  action: z.enum(["pause", "complete", "cancel"]).optional(),
431
+ onReject: z.enum(["fail", "cancel", "complete", "continue"]).optional(),
335
432
  }),
336
433
  z
337
434
  .object({
@@ -413,6 +510,24 @@ const validateCodeStepWorkspaces = (steps, workspaceAliases, context, path) => {
413
510
  });
414
511
  });
415
512
  };
513
+ const validateStepPolicies = (steps, context, path) => {
514
+ steps.forEach((step, index) => {
515
+ if (step.type === "loop") {
516
+ validateStepPolicies(step.steps, context, [...path, index, "steps"]);
517
+ }
518
+ if (step.type === "prompt" || !step.policies)
519
+ return;
520
+ for (const field of PROMPT_ONLY_POLICY_FIELDS) {
521
+ if (step.policies[field] !== undefined) {
522
+ context.addIssue({
523
+ code: "custom",
524
+ message: `policies.${field} applies only to prompt steps; ${step.type} step ${step.id} cannot set it.`,
525
+ path: [...path, index, "policies", field],
526
+ });
527
+ }
528
+ }
529
+ });
530
+ };
416
531
  const MAXIMUM_AGENT_MANIFEST_STRUCTURE_DEPTH = 128;
417
532
  const MAXIMUM_AGENT_MANIFEST_STRUCTURE_NODES = 100_000;
418
533
  const agentManifestStructureIssue = (input) => {
@@ -466,6 +581,7 @@ const agentManifestObjectSchema = z
466
581
  connections: z.array(agentConnectionBindingSchema).optional(),
467
582
  workspaces: z.array(agentWorkspaceBindingSchema).optional(),
468
583
  steps: z.array(agentStepSchema),
584
+ policies: executionPoliciesSchema.optional(),
469
585
  limits: z
470
586
  .object({
471
587
  maxSteps: z.number().int().positive().optional(),
@@ -514,6 +630,7 @@ const agentManifestObjectSchema = z
514
630
  workspaceAliases.add(alias);
515
631
  });
516
632
  validateSiblingStepIds(manifest.steps, context, ["steps"]);
633
+ validateStepPolicies(manifest.steps, context, ["steps"]);
517
634
  validateCodeStepWorkspaces(manifest.steps, workspaceAliases, context, [
518
635
  "steps",
519
636
  ]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clearideas/agent-runtime-contracts",
3
- "version": "0.6.3",
3
+ "version": "0.7.1",
4
4
  "description": "Versioned, persistence-independent contracts for Clear Ideas Agent Runtime.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Clear Ideas Incorporated",