@buildanagent/sdk 0.1.0-alpha.0 → 0.1.0-alpha.2

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 (41) hide show
  1. package/README.md +89 -3
  2. package/dist/errors.d.ts +19 -0
  3. package/dist/errors.js +26 -0
  4. package/dist/errors.js.map +1 -0
  5. package/dist/index.d.ts +7 -3
  6. package/dist/index.js +5 -3
  7. package/dist/index.js.map +1 -1
  8. package/dist/testing/scripted-model.d.ts +5 -0
  9. package/dist/testing/scripted-model.js +3 -2
  10. package/dist/testing/scripted-model.js.map +1 -1
  11. package/dist/tools/coerce.d.ts +15 -0
  12. package/dist/tools/coerce.js +93 -0
  13. package/dist/tools/coerce.js.map +1 -0
  14. package/dist/tools/define.d.ts +42 -0
  15. package/dist/tools/define.js +96 -0
  16. package/dist/tools/define.js.map +1 -0
  17. package/dist/tools/format-error.d.ts +13 -0
  18. package/dist/tools/format-error.js +65 -0
  19. package/dist/tools/format-error.js.map +1 -0
  20. package/dist/tools/outcome.d.ts +7 -0
  21. package/dist/tools/outcome.js +30 -0
  22. package/dist/tools/outcome.js.map +1 -0
  23. package/dist/tools/pipeline.d.ts +52 -0
  24. package/dist/tools/pipeline.js +184 -0
  25. package/dist/tools/pipeline.js.map +1 -0
  26. package/dist/tools/schema.d.ts +20 -0
  27. package/dist/tools/schema.js +100 -0
  28. package/dist/tools/schema.js.map +1 -0
  29. package/dist/tools/types.d.ts +144 -0
  30. package/dist/tools/types.js +2 -0
  31. package/dist/tools/types.js.map +1 -0
  32. package/dist/vendor/agent-safety/errors.d.ts +14 -0
  33. package/dist/vendor/agent-safety/errors.js +21 -0
  34. package/dist/vendor/agent-safety/errors.js.map +1 -0
  35. package/dist/vendor/agent-safety/outcome.d.ts +88 -0
  36. package/dist/vendor/agent-safety/outcome.js +140 -0
  37. package/dist/vendor/agent-safety/outcome.js.map +1 -0
  38. package/dist/vendor/agent-safety/render.d.ts +40 -0
  39. package/dist/vendor/agent-safety/render.js +92 -0
  40. package/dist/vendor/agent-safety/render.js.map +1 -0
  41. package/package.json +11 -3
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The tool types: what a tool declares, what its `execute` receives and returns, and the failures the pipeline
3
+ * reports to the model (SDK plan §3.3; agent-SDK guide §4).
4
+ */
5
+ import type { ContentBlock, ModelContent } from "@buildanagent/gateway";
6
+ import type { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
7
+ import type { Clock } from "../testing/determinism.js";
8
+ import type { WriteOutcome } from "../vendor/agent-safety/outcome.js";
9
+ /** A JSON Schema object, draft 2020-12 or draft 7, such as `{ type: "object", properties: { … } }`. */
10
+ export type JsonSchema = Readonly<Record<string, unknown>>;
11
+ /**
12
+ * A tool's input schema: a Standard Schema that can also describe itself as JSON Schema (Zod 4.2 or later, ArkType,
13
+ * or Valibot through `toStandardJsonSchema()` from `@valibot/to-json-schema`), or a raw JSON Schema object. A raw schema whose `$schema` names draft 7 is checked as draft 7, and
14
+ * any other as draft 2020-12.
15
+ */
16
+ export type ToolSchema<I> = (StandardSchemaV1<unknown, I> & StandardJSONSchemaV1<unknown, I>) | JsonSchema;
17
+ /**
18
+ * One reason a tool input failed its schema. `path` is a JSON Pointer, such as `/items/0/sku`, or `""` for the whole
19
+ * input.
20
+ */
21
+ export interface SchemaIssue {
22
+ readonly path: string;
23
+ readonly message: string;
24
+ /** The JSON Schema keyword that failed, such as `required`, when the validator reports one. */
25
+ readonly keyword?: string;
26
+ }
27
+ /** The fields every tool failure carries. `input` is the arguments the model sent. */
28
+ interface FailureBase {
29
+ readonly tool: string;
30
+ readonly callId: string;
31
+ readonly input: unknown;
32
+ }
33
+ /**
34
+ * A failed tool call, as the error formatter receives it. `unknown_tool`: the model named a tool that doesn't exist.
35
+ * `invalid_input`: the arguments failed the schema, even after repair. `execution_error`: `execute` threw; with
36
+ * `redactErrors`, `message` is a fixed line and the thrown message is only in the result's `details`. `truncated`:
37
+ * the response was cut off at the output limit, so the call was not run. `not_run`: the call was not run because the
38
+ * response ended in an error (`response_error`) or was aborted (`response_aborted`), or the run was cancelled before
39
+ * the call started (`run_aborted`).
40
+ */
41
+ export type ToolFailure = (FailureBase & {
42
+ readonly kind: "unknown_tool";
43
+ readonly availableTools: readonly string[];
44
+ }) | (FailureBase & {
45
+ readonly kind: "invalid_input";
46
+ readonly issues: readonly SchemaIssue[];
47
+ }) | (FailureBase & {
48
+ readonly kind: "execution_error";
49
+ readonly message: string;
50
+ readonly redacted: boolean;
51
+ }) | (FailureBase & {
52
+ readonly kind: "truncated";
53
+ }) | (FailureBase & {
54
+ readonly kind: "not_run";
55
+ readonly reason: "response_error" | "response_aborted" | "run_aborted";
56
+ });
57
+ /**
58
+ * Declares that a tool changes the world, such as sending an email. A tool without `effect` counts as read-only, so
59
+ * a run that crashes mid-call may safely run it again. `businessKey` names the real-world operation, such as
60
+ * `refund:<order id>`, so the same write is recognised across retries and sessions.
61
+ */
62
+ export interface ToolEffect<I> {
63
+ readonly kind: "write";
64
+ businessKey?(input: I): string;
65
+ }
66
+ /** What a tool's `execute` receives besides its input. */
67
+ export interface ToolContext {
68
+ readonly runId: string;
69
+ readonly callId: string;
70
+ /** Fires when the run is aborted. */
71
+ readonly signal: AbortSignal;
72
+ /** How deeply this run is nested inside other agents' tool calls; 0 for a top-level run. */
73
+ readonly depth: number;
74
+ /** The deepest nesting allowed; a tool that starts another agent refuses at this depth. */
75
+ readonly maxDepth: number;
76
+ readonly clock: Clock;
77
+ /** Reports progress for a user interface, such as rows processed so far. The model never sees it. */
78
+ update(details: unknown): void;
79
+ }
80
+ /**
81
+ * What a tool returns. `content` is what the model reads, `details` is for logs and user interfaces, and
82
+ * `structured` is typed data for your code; only `content` reaches the model. `isError` marks a failure for the model.
83
+ * `terminate` asks the run to end after this step. `pause` asks the user a question. `outcome` reports what a write
84
+ * did: any kind except `applied` sets `isError`, and the model reads the outcome's sentence and fields before
85
+ * `content`.
86
+ */
87
+ export interface ToolResult<S = unknown> {
88
+ readonly content: readonly ModelContent[];
89
+ readonly details?: unknown;
90
+ readonly structured?: S;
91
+ readonly isError?: boolean;
92
+ readonly terminate?: boolean;
93
+ readonly pause?: {
94
+ readonly kind: "clarification";
95
+ readonly question: string;
96
+ };
97
+ readonly outcome?: WriteOutcome;
98
+ }
99
+ /**
100
+ * A tool the model can call. `I` is the input `execute` receives after validation, and `S` the type of `structured`.
101
+ *
102
+ * Every call runs the same steps: the name is resolved, the input is coerced and validated, `repair` gets one chance
103
+ * to fix invalid input, then `execute` runs. A failure the model caused, such as an unknown tool, invalid input or
104
+ * a throwing `execute`, returns an error result to the model. A result that isn't a list of text and image blocks,
105
+ * or that carries an invalid write outcome, throws an `SdkError` with code `invalid_tool_result`.
106
+ */
107
+ export interface ToolDefinition<I = unknown, S = unknown> {
108
+ /** 1 to 64 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`. */
109
+ readonly name: string;
110
+ readonly description: string;
111
+ /**
112
+ * `function` (the default) runs in your process. The other kinds are for tools that a provider defines or runs:
113
+ * `dynamic` tools have a schema known only at run time, such as one from an MCP server.
114
+ */
115
+ readonly kind?: "function" | "dynamic" | "provider-local" | "provider-executed";
116
+ readonly inputSchema: ToolSchema<I>;
117
+ /** Marks a tool that changes the world. A tool without it counts as read-only. */
118
+ readonly effect?: ToolEffect<I>;
119
+ /**
120
+ * Called once when the input fails its schema, with the coerced input and the issues. Return fixed input to
121
+ * validate again, or `undefined` to report the failure to the model.
122
+ */
123
+ repair?(e: {
124
+ readonly input: unknown;
125
+ readonly issues: readonly SchemaIssue[];
126
+ }): Promise<unknown>;
127
+ /**
128
+ * Builds the content the model reads for a failed call, in place of the default text, which lists the issues and
129
+ * the received arguments and tells the model not to substitute invented data. It runs synchronously; if it throws
130
+ * or returns anything but a list of text and image blocks, the model reads the default text instead.
131
+ */
132
+ formatError?(failure: ToolFailure): readonly ModelContent[];
133
+ /**
134
+ * When true, an error thrown by `execute` reaches the model as a fixed line, and its message goes only to the
135
+ * result's `details`. Default false.
136
+ */
137
+ readonly redactErrors?: boolean;
138
+ execute(input: I, ctx: ToolContext): Promise<ToolResult<S>>;
139
+ }
140
+ /** A tool call block from an assistant message. */
141
+ export type ToolCall = Extract<ContentBlock, {
142
+ type: "tool_call";
143
+ }>;
144
+ export {};
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/tools/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The tool types: what a tool declares, what its `execute` receives and returns, and the failures the pipeline\n * reports to the model (SDK plan §3.3; agent-SDK guide §4).\n */\nimport type { ContentBlock, ModelContent } from \"@buildanagent/gateway\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Clock } from \"../testing/determinism.js\";\nimport type { WriteOutcome } from \"../vendor/agent-safety/outcome.js\";\n\n/** A JSON Schema object, draft 2020-12 or draft 7, such as `{ type: \"object\", properties: { … } }`. */\nexport type JsonSchema = Readonly<Record<string, unknown>>;\n\n/**\n * A tool's input schema: a Standard Schema that can also describe itself as JSON Schema (Zod 4.2 or later, ArkType,\n * or Valibot through `toStandardJsonSchema()` from `@valibot/to-json-schema`), or a raw JSON Schema object. A raw schema whose `$schema` names draft 7 is checked as draft 7, and\n * any other as draft 2020-12.\n */\nexport type ToolSchema<I> = (StandardSchemaV1<unknown, I> & StandardJSONSchemaV1<unknown, I>) | JsonSchema;\n\n/**\n * One reason a tool input failed its schema. `path` is a JSON Pointer, such as `/items/0/sku`, or `\"\"` for the whole\n * input.\n */\nexport interface SchemaIssue {\n readonly path: string;\n readonly message: string;\n /** The JSON Schema keyword that failed, such as `required`, when the validator reports one. */\n readonly keyword?: string;\n}\n\n/** The fields every tool failure carries. `input` is the arguments the model sent. */\ninterface FailureBase {\n readonly tool: string;\n readonly callId: string;\n readonly input: unknown;\n}\n\n/**\n * A failed tool call, as the error formatter receives it. `unknown_tool`: the model named a tool that doesn't exist.\n * `invalid_input`: the arguments failed the schema, even after repair. `execution_error`: `execute` threw; with\n * `redactErrors`, `message` is a fixed line and the thrown message is only in the result's `details`. `truncated`:\n * the response was cut off at the output limit, so the call was not run. `not_run`: the call was not run because the\n * response ended in an error (`response_error`) or was aborted (`response_aborted`), or the run was cancelled before\n * the call started (`run_aborted`).\n */\nexport type ToolFailure =\n | (FailureBase & { readonly kind: \"unknown_tool\"; readonly availableTools: readonly string[] })\n | (FailureBase & { readonly kind: \"invalid_input\"; readonly issues: readonly SchemaIssue[] })\n | (FailureBase & { readonly kind: \"execution_error\"; readonly message: string; readonly redacted: boolean })\n | (FailureBase & { readonly kind: \"truncated\" })\n | (FailureBase & {\n readonly kind: \"not_run\";\n readonly reason: \"response_error\" | \"response_aborted\" | \"run_aborted\";\n });\n\n/**\n * Declares that a tool changes the world, such as sending an email. A tool without `effect` counts as read-only, so\n * a run that crashes mid-call may safely run it again. `businessKey` names the real-world operation, such as\n * `refund:<order id>`, so the same write is recognised across retries and sessions.\n */\nexport interface ToolEffect<I> {\n readonly kind: \"write\";\n businessKey?(input: I): string;\n}\n\n/** What a tool's `execute` receives besides its input. */\nexport interface ToolContext {\n readonly runId: string;\n readonly callId: string;\n /** Fires when the run is aborted. */\n readonly signal: AbortSignal;\n /** How deeply this run is nested inside other agents' tool calls; 0 for a top-level run. */\n readonly depth: number;\n /** The deepest nesting allowed; a tool that starts another agent refuses at this depth. */\n readonly maxDepth: number;\n readonly clock: Clock;\n /** Reports progress for a user interface, such as rows processed so far. The model never sees it. */\n update(details: unknown): void;\n}\n\n/**\n * What a tool returns. `content` is what the model reads, `details` is for logs and user interfaces, and\n * `structured` is typed data for your code; only `content` reaches the model. `isError` marks a failure for the model.\n * `terminate` asks the run to end after this step. `pause` asks the user a question. `outcome` reports what a write\n * did: any kind except `applied` sets `isError`, and the model reads the outcome's sentence and fields before\n * `content`.\n */\nexport interface ToolResult<S = unknown> {\n readonly content: readonly ModelContent[];\n readonly details?: unknown;\n readonly structured?: S;\n readonly isError?: boolean;\n readonly terminate?: boolean;\n readonly pause?: { readonly kind: \"clarification\"; readonly question: string };\n readonly outcome?: WriteOutcome;\n}\n\n/**\n * A tool the model can call. `I` is the input `execute` receives after validation, and `S` the type of `structured`.\n *\n * Every call runs the same steps: the name is resolved, the input is coerced and validated, `repair` gets one chance\n * to fix invalid input, then `execute` runs. A failure the model caused, such as an unknown tool, invalid input or\n * a throwing `execute`, returns an error result to the model. A result that isn't a list of text and image blocks,\n * or that carries an invalid write outcome, throws an `SdkError` with code `invalid_tool_result`.\n */\nexport interface ToolDefinition<I = unknown, S = unknown> {\n /** 1 to 64 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`. */\n readonly name: string;\n readonly description: string;\n /**\n * `function` (the default) runs in your process. The other kinds are for tools that a provider defines or runs:\n * `dynamic` tools have a schema known only at run time, such as one from an MCP server.\n */\n readonly kind?: \"function\" | \"dynamic\" | \"provider-local\" | \"provider-executed\";\n readonly inputSchema: ToolSchema<I>;\n /** Marks a tool that changes the world. A tool without it counts as read-only. */\n readonly effect?: ToolEffect<I>;\n /**\n * Called once when the input fails its schema, with the coerced input and the issues. Return fixed input to\n * validate again, or `undefined` to report the failure to the model.\n */\n repair?(e: { readonly input: unknown; readonly issues: readonly SchemaIssue[] }): Promise<unknown>;\n /**\n * Builds the content the model reads for a failed call, in place of the default text, which lists the issues and\n * the received arguments and tells the model not to substitute invented data. It runs synchronously; if it throws\n * or returns anything but a list of text and image blocks, the model reads the default text instead.\n */\n formatError?(failure: ToolFailure): readonly ModelContent[];\n /**\n * When true, an error thrown by `execute` reaches the model as a fixed line, and its message goes only to the\n * result's `details`. Default false.\n */\n readonly redactErrors?: boolean;\n execute(input: I, ctx: ToolContext): Promise<ToolResult<S>>;\n}\n\n/** A tool call block from an assistant message. */\nexport type ToolCall = Extract<ContentBlock, { type: \"tool_call\" }>;\n"]}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason or
3
+ * an input that has no canonical JSON form.
4
+ */
5
+ /** Why a `SafetyError` was thrown. */
6
+ export type SafetyErrorCode = "invalid_outcome" | "invalid_input";
7
+ /** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */
8
+ export declare class SafetyError extends Error {
9
+ readonly name = "SafetyError";
10
+ readonly code: SafetyErrorCode;
11
+ constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions);
12
+ }
13
+ /** True for a `SafetyError`, including one from another copy of the package. */
14
+ export declare function isSafetyError(error: unknown): error is SafetyError;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason or
3
+ * an input that has no canonical JSON form.
4
+ */
5
+ // A registered symbol, so the guard still works when two copies of the package are bundled.
6
+ const SAFETY_ERROR = Symbol.for("buildanagent.agent-safety.SafetyError");
7
+ /** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */
8
+ export class SafetyError extends Error {
9
+ name = "SafetyError";
10
+ code;
11
+ constructor(code, message, options) {
12
+ super(message, options);
13
+ this.code = code;
14
+ Object.defineProperty(this, SAFETY_ERROR, { value: true });
15
+ }
16
+ }
17
+ /** True for a `SafetyError`, including one from another copy of the package. */
18
+ export function isSafetyError(error) {
19
+ return typeof error === "object" && error !== null && error[SAFETY_ERROR] === true;
20
+ }
21
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,4FAA4F;AAC5F,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;AAEzE,oHAAoH;AACpH,MAAM,OAAO,WAAY,SAAQ,KAAK;IAClB,IAAI,GAAG,aAAa,CAAC;IAC9B,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAAsB;QACxE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF;AAED,gFAAgF;AAChF,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,YAAY,CAAC,KAAK,IAAI,CAAC;AAClH,CAAC","sourcesContent":["/**\n * `SafetyError`: the safety package's error for programmer errors, such as a write outcome with a malformed reason or\n * an input that has no canonical JSON form.\n */\n\n/** Why a `SafetyError` was thrown. */\nexport type SafetyErrorCode = \"invalid_outcome\" | \"invalid_input\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst SAFETY_ERROR = Symbol.for(\"buildanagent.agent-safety.SafetyError\");\n\n/** Thrown for a mistake in how the safety package is called. A write that fails is an outcome, never this error. */\nexport class SafetyError extends Error {\n override readonly name = \"SafetyError\";\n readonly code: SafetyErrorCode;\n\n constructor(code: SafetyErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, SAFETY_ERROR, { value: true });\n }\n}\n\n/** True for a `SafetyError`, including one from another copy of the package. */\nexport function isSafetyError(error: unknown): error is SafetyError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[SAFETY_ERROR] === true;\n}\n"]}
@@ -0,0 +1,88 @@
1
+ /**
2
+ * What a write did. `applied`: it took effect. `not_applied`: it was rejected before any effect. `compensated`: it
3
+ * took effect and was then undone. `partial`: some effects hold and the rest could not be undone. `unknown`: nobody
4
+ * knows whether it took effect, as after a timeout or a lost response.
5
+ */
6
+ export type OutcomeKind = "applied" | "not_applied" | "compensated" | "partial" | "unknown";
7
+ /**
8
+ * When the same write may run again. `same_key`: retry with the same effect key, so it takes effect at most once.
9
+ * `new_operation_only`: only as a new operation, if the user still wants it. `reconcile_first`: check what happened
10
+ * before any retry. `never`: do not retry.
11
+ */
12
+ export type Retry = "same_key" | "new_operation_only" | "reconcile_first" | "never";
13
+ /** The retry rules each outcome kind allows. */
14
+ export interface AllowedRetry {
15
+ applied: "never";
16
+ not_applied: "same_key" | "new_operation_only" | "never";
17
+ compensated: "new_operation_only" | "never";
18
+ partial: "same_key" | "reconcile_first" | "never";
19
+ unknown: "same_key" | "reconcile_first" | "never";
20
+ }
21
+ /** The fields every write outcome carries, whatever its kind. */
22
+ export interface OutcomeFields {
23
+ /** The tool or business operation, such as `send_email`. */
24
+ readonly operation: string;
25
+ /** The key that makes a retry of this write take effect at most once. */
26
+ readonly effectKey?: string;
27
+ /** Effects that hold now. */
28
+ readonly applied: readonly string[];
29
+ /** Effects that were undone. */
30
+ readonly reverted: readonly string[];
31
+ /** Effects that happened and cannot be undone, such as "email delivered 14:02". */
32
+ readonly notReversible: readonly string[];
33
+ /** One line about the current state that the model can trust. */
34
+ readonly currentState?: string;
35
+ /** What the model should do next. */
36
+ readonly next: string;
37
+ /** What the model must not do, beyond what the kind already rules out. */
38
+ readonly avoid?: string;
39
+ /** A stable code for the cause, in upper snake case and at most 63 characters, such as `CARD_DECLINED`. */
40
+ readonly reason?: string;
41
+ }
42
+ /** A write outcome of one kind, whose `retry` is one of the rules that kind allows. */
43
+ export type WriteOutcomeOf<K extends OutcomeKind> = OutcomeFields & {
44
+ readonly kind: K;
45
+ readonly retry: AllowedRetry[K];
46
+ };
47
+ /** What a write reports: one of the five kinds, with its retry rule and what the model should do next. */
48
+ export type WriteOutcome = {
49
+ [K in OutcomeKind]: WriteOutcomeOf<K>;
50
+ }[OutcomeKind];
51
+ /** The fields you can leave out of a write outcome, because `writeOutcome()` fills them in. */
52
+ type Defaulted = "applied" | "reverted" | "notReversible";
53
+ /**
54
+ * The input to `writeOutcome()`. `retry` defaults to the kind's rule in `DEFAULT_RETRY`, and the three effect lists
55
+ * default to empty.
56
+ */
57
+ export type WriteOutcomeInit = {
58
+ [K in OutcomeKind]: Omit<OutcomeFields, Defaulted> & Partial<Pick<OutcomeFields, Defaulted>> & {
59
+ readonly kind: K;
60
+ readonly retry?: AllowedRetry[K];
61
+ };
62
+ }[OutcomeKind];
63
+ /** The five outcome kinds, in the order the docs list them. */
64
+ export declare const OUTCOME_KINDS: readonly OutcomeKind[];
65
+ /**
66
+ * The retry rule each kind gets when the tool sets none: a rejected write may run again with the same key, an undone
67
+ * one only as a new operation, a partial one goes to a person, and an unknown one is checked first.
68
+ */
69
+ export declare const DEFAULT_RETRY: {
70
+ readonly [K in OutcomeKind]: AllowedRetry[K];
71
+ };
72
+ /** The retry rules each kind allows, as `AllowedRetry` lists them. */
73
+ export declare const ALLOWED_RETRIES: {
74
+ readonly [K in OutcomeKind]: readonly AllowedRetry[K][];
75
+ };
76
+ /**
77
+ * Builds a write outcome, filling in the defaults and checking every field. The result is frozen.
78
+ *
79
+ * Throws a `SafetyError`, code `invalid_outcome`, for:
80
+ * - an unknown kind, or a retry rule the kind doesn't allow;
81
+ * - an empty `operation` or `next`, or an `operation` with leading or trailing spaces;
82
+ * - a blank effect or optional text field;
83
+ * - a `reason` that isn't upper snake case of at most 63 characters;
84
+ * - effects the kind contradicts: any effect on `not_applied`, `reverted` on `applied`, `applied` on `compensated`;
85
+ * - a `partial` or `unknown` outcome that allows a `same_key` retry without an `effectKey`.
86
+ */
87
+ export declare function writeOutcome(init: WriteOutcomeInit): WriteOutcome;
88
+ export {};
@@ -0,0 +1,140 @@
1
+ /**
2
+ * The five write outcomes: what a tool that changes the world reports, so the harness can act on it and the model can
3
+ * read it. Each kind allows only the retry rules that are safe for it, and `unknown` never allows a fresh operation,
4
+ * because the first attempt may still have taken effect (close-sdk-gaps SG3).
5
+ */
6
+ import { SafetyError } from "./errors.js";
7
+ /** The five outcome kinds, in the order the docs list them. */
8
+ export const OUTCOME_KINDS = Object.freeze([
9
+ "applied",
10
+ "not_applied",
11
+ "compensated",
12
+ "partial",
13
+ "unknown",
14
+ ]);
15
+ /**
16
+ * The retry rule each kind gets when the tool sets none: a rejected write may run again with the same key, an undone
17
+ * one only as a new operation, a partial one goes to a person, and an unknown one is checked first.
18
+ */
19
+ export const DEFAULT_RETRY = Object.freeze({
20
+ applied: "never",
21
+ not_applied: "same_key",
22
+ compensated: "new_operation_only",
23
+ partial: "never",
24
+ unknown: "reconcile_first",
25
+ });
26
+ /** The retry rules each kind allows, as `AllowedRetry` lists them. */
27
+ export const ALLOWED_RETRIES = Object.freeze({
28
+ applied: Object.freeze(["never"]),
29
+ not_applied: Object.freeze(["same_key", "new_operation_only", "never"]),
30
+ compensated: Object.freeze(["new_operation_only", "never"]),
31
+ partial: Object.freeze(["same_key", "reconcile_first", "never"]),
32
+ unknown: Object.freeze(["same_key", "reconcile_first", "never"]),
33
+ });
34
+ // AIP-193's rule for `reason`: upper snake case, no leading digit or underscore, no trailing underscore.
35
+ const REASON = /^[A-Z][A-Z0-9_]+[A-Z0-9]$/;
36
+ const MAX_REASON_LENGTH = 63;
37
+ function invalid(message) {
38
+ return new SafetyError("invalid_outcome", message);
39
+ }
40
+ function requireText(value, field) {
41
+ if (typeof value !== "string" || value.trim() === "")
42
+ throw invalid(`a write outcome's ${field} must be non-empty`);
43
+ }
44
+ function requireOptionalText(value, field) {
45
+ // A blank value would render as an empty sentence, such as "Current state: .", so it must be left out instead.
46
+ if (value !== undefined && (typeof value !== "string" || value.trim() === "")) {
47
+ throw invalid(`a write outcome's ${field} must be non-empty when it is set`);
48
+ }
49
+ }
50
+ function effectList(value, field) {
51
+ if (value === undefined)
52
+ return Object.freeze([]);
53
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string" && item.trim() !== "")) {
54
+ throw invalid(`a write outcome's ${field} must be a list of non-empty strings`);
55
+ }
56
+ return Object.freeze([...value]);
57
+ }
58
+ function checkReason(reason) {
59
+ if (reason === undefined)
60
+ return;
61
+ if (typeof reason !== "string" || reason.length > MAX_REASON_LENGTH || !REASON.test(reason)) {
62
+ throw invalid(`a write outcome's reason must be upper snake case and at most ${MAX_REASON_LENGTH} characters, ` +
63
+ `got ${JSON.stringify(reason)}`);
64
+ }
65
+ }
66
+ // The effect lists each kind can't hold, because the kind's own sentence would contradict them: a write that changed
67
+ // nothing has no effects, one that took effect undid nothing, and one that was undone holds none of its effects.
68
+ const FORBIDDEN_EFFECTS = {
69
+ applied: ["reverted"],
70
+ not_applied: ["applied", "reverted", "notReversible"],
71
+ compensated: ["applied"],
72
+ partial: [],
73
+ unknown: [],
74
+ };
75
+ function checkEffects(kind, lists) {
76
+ for (const field of FORBIDDEN_EFFECTS[kind]) {
77
+ if (lists[field].length > 0)
78
+ throw invalid(`a ${kind} outcome cannot list ${field} effects`);
79
+ }
80
+ }
81
+ function checkEffectKey(kind, retry, effectKey) {
82
+ // Without a key, a same-key retry of a write that may have taken effect could take effect twice. A not_applied
83
+ // write took no effect, so retrying it is safe with or without one.
84
+ if (retry === "same_key" && effectKey === undefined && (kind === "partial" || kind === "unknown")) {
85
+ throw invalid(`a ${kind} outcome can use retry "same_key" only with an effectKey`);
86
+ }
87
+ }
88
+ function checkKindAndRetry(kind, retry) {
89
+ if (!OUTCOME_KINDS.includes(kind))
90
+ throw invalid(`unknown outcome kind ${JSON.stringify(kind)}`);
91
+ const known = kind;
92
+ // Only a missing retry takes the default; `null` from a JSON caller fails the check below like any other value.
93
+ const chosen = retry === undefined ? DEFAULT_RETRY[known] : retry;
94
+ if (!ALLOWED_RETRIES[known].includes(chosen)) {
95
+ throw invalid(`a ${known} outcome cannot use retry ${JSON.stringify(chosen)}`);
96
+ }
97
+ return chosen;
98
+ }
99
+ /**
100
+ * Builds a write outcome, filling in the defaults and checking every field. The result is frozen.
101
+ *
102
+ * Throws a `SafetyError`, code `invalid_outcome`, for:
103
+ * - an unknown kind, or a retry rule the kind doesn't allow;
104
+ * - an empty `operation` or `next`, or an `operation` with leading or trailing spaces;
105
+ * - a blank effect or optional text field;
106
+ * - a `reason` that isn't upper snake case of at most 63 characters;
107
+ * - effects the kind contradicts: any effect on `not_applied`, `reverted` on `applied`, `applied` on `compensated`;
108
+ * - a `partial` or `unknown` outcome that allows a `same_key` retry without an `effectKey`.
109
+ */
110
+ export function writeOutcome(init) {
111
+ const retry = checkKindAndRetry(init.kind, init.retry);
112
+ requireText(init.operation, "operation");
113
+ if (init.operation !== init.operation.trim())
114
+ throw invalid("a write outcome's operation must not start or end with spaces");
115
+ requireText(init.next, "next");
116
+ for (const field of ["effectKey", "currentState", "avoid"])
117
+ requireOptionalText(init[field], field);
118
+ checkReason(init.reason);
119
+ checkEffectKey(init.kind, retry, init.effectKey);
120
+ const lists = {
121
+ applied: effectList(init.applied, "applied"),
122
+ reverted: effectList(init.reverted, "reverted"),
123
+ notReversible: effectList(init.notReversible, "notReversible"),
124
+ };
125
+ checkEffects(init.kind, lists);
126
+ const outcome = {
127
+ kind: init.kind,
128
+ operation: init.operation,
129
+ ...(init.effectKey === undefined ? {} : { effectKey: init.effectKey }),
130
+ ...lists,
131
+ ...(init.currentState === undefined ? {} : { currentState: init.currentState }),
132
+ retry,
133
+ next: init.next,
134
+ ...(init.avoid === undefined ? {} : { avoid: init.avoid }),
135
+ ...(init.reason === undefined ? {} : { reason: init.reason }),
136
+ };
137
+ // checkKindAndRetry has shown that `retry` is one the kind allows, which the spread above can't carry in its type.
138
+ return Object.freeze(outcome);
139
+ }
140
+ //# sourceMappingURL=outcome.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outcome.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/outcome.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAoE1C,+DAA+D;AAC/D,MAAM,CAAC,MAAM,aAAa,GAA2B,MAAM,CAAC,MAAM,CAAC;IACjE,SAAS;IACT,aAAa;IACb,aAAa;IACb,SAAS;IACT,SAAS;CACV,CAAC,CAAC;AAE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AE,YAAY,EAAE,IAAI,CAAC,YAAY,EAAE,CAAC;QAC/E,KAAK;QACL,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,GAAG,CAAC,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;QAC1D,GAAG,CAAC,IAAI,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC;KAC9D,CAAC;IACF,mHAAmH;IACnH,OAAO,MAAM,CAAC,MAAM,CAAC,OAAO,CAAiB,CAAC;AAChD,CAAC","sourcesContent":["/**\n * The five write outcomes: what a tool that changes the world reports, so the harness can act on it and the model can\n * read it. Each kind allows only the retry rules that are safe for it, and `unknown` never allows a fresh operation,\n * because the first attempt may still have taken effect (close-sdk-gaps SG3).\n */\nimport { SafetyError } from \"./errors.js\";\n\n/**\n * What a write did. `applied`: it took effect. `not_applied`: it was rejected before any effect. `compensated`: it\n * took effect and was then undone. `partial`: some effects hold and the rest could not be undone. `unknown`: nobody\n * knows whether it took effect, as after a timeout or a lost response.\n */\nexport type OutcomeKind = \"applied\" | \"not_applied\" | \"compensated\" | \"partial\" | \"unknown\";\n\n/**\n * When the same write may run again. `same_key`: retry with the same effect key, so it takes effect at most once.\n * `new_operation_only`: only as a new operation, if the user still wants it. `reconcile_first`: check what happened\n * before any retry. `never`: do not retry.\n */\nexport type Retry = \"same_key\" | \"new_operation_only\" | \"reconcile_first\" | \"never\";\n\n/** The retry rules each outcome kind allows. */\nexport interface AllowedRetry {\n applied: \"never\";\n not_applied: \"same_key\" | \"new_operation_only\" | \"never\";\n compensated: \"new_operation_only\" | \"never\";\n partial: \"same_key\" | \"reconcile_first\" | \"never\";\n unknown: \"same_key\" | \"reconcile_first\" | \"never\";\n}\n\n/** The fields every write outcome carries, whatever its kind. */\nexport interface OutcomeFields {\n /** The tool or business operation, such as `send_email`. */\n readonly operation: string;\n /** The key that makes a retry of this write take effect at most once. */\n readonly effectKey?: string;\n /** Effects that hold now. */\n readonly applied: readonly string[];\n /** Effects that were undone. */\n readonly reverted: readonly string[];\n /** Effects that happened and cannot be undone, such as \"email delivered 14:02\". */\n readonly notReversible: readonly string[];\n /** One line about the current state that the model can trust. */\n readonly currentState?: string;\n /** What the model should do next. */\n readonly next: string;\n /** What the model must not do, beyond what the kind already rules out. */\n readonly avoid?: string;\n /** A stable code for the cause, in upper snake case and at most 63 characters, such as `CARD_DECLINED`. */\n readonly reason?: string;\n}\n\n/** A write outcome of one kind, whose `retry` is one of the rules that kind allows. */\nexport type WriteOutcomeOf<K extends OutcomeKind> = OutcomeFields & {\n readonly kind: K;\n readonly retry: AllowedRetry[K];\n};\n\n/** What a write reports: one of the five kinds, with its retry rule and what the model should do next. */\nexport type WriteOutcome = { [K in OutcomeKind]: WriteOutcomeOf<K> }[OutcomeKind];\n\n/** The fields you can leave out of a write outcome, because `writeOutcome()` fills them in. */\ntype Defaulted = \"applied\" | \"reverted\" | \"notReversible\";\n\n/**\n * The input to `writeOutcome()`. `retry` defaults to the kind's rule in `DEFAULT_RETRY`, and the three effect lists\n * default to empty.\n */\nexport type WriteOutcomeInit = {\n [K in OutcomeKind]: Omit<OutcomeFields, Defaulted> &\n Partial<Pick<OutcomeFields, Defaulted>> & { readonly kind: K; readonly retry?: AllowedRetry[K] };\n}[OutcomeKind];\n\n/** The five outcome kinds, in the order the docs list them. */\nexport const OUTCOME_KINDS: readonly OutcomeKind[] = Object.freeze([\n \"applied\",\n \"not_applied\",\n \"compensated\",\n \"partial\",\n \"unknown\",\n]);\n\n/**\n * The retry rule each kind gets when the tool sets none: a rejected write may run again with the same key, an undone\n * one only as a new operation, a partial one goes to a person, and an unknown one is checked first.\n */\nexport const DEFAULT_RETRY: { readonly [K in OutcomeKind]: AllowedRetry[K] } = Object.freeze({\n applied: \"never\",\n not_applied: \"same_key\",\n compensated: \"new_operation_only\",\n partial: \"never\",\n unknown: \"reconcile_first\",\n});\n\n/** The retry rules each kind allows, as `AllowedRetry` lists them. */\nexport const ALLOWED_RETRIES: { readonly [K in OutcomeKind]: readonly AllowedRetry[K][] } = Object.freeze({\n applied: Object.freeze([\"never\"] as const),\n not_applied: Object.freeze([\"same_key\", \"new_operation_only\", \"never\"] as const),\n compensated: Object.freeze([\"new_operation_only\", \"never\"] as const),\n partial: Object.freeze([\"same_key\", \"reconcile_first\", \"never\"] as const),\n unknown: Object.freeze([\"same_key\", \"reconcile_first\", \"never\"] as const),\n});\n\n// AIP-193's rule for `reason`: upper snake case, no leading digit or underscore, no trailing underscore.\nconst REASON = /^[A-Z][A-Z0-9_]+[A-Z0-9]$/;\nconst MAX_REASON_LENGTH = 63;\n\nfunction invalid(message: string): SafetyError {\n return new SafetyError(\"invalid_outcome\", message);\n}\n\nfunction requireText(value: unknown, field: string): void {\n if (typeof value !== \"string\" || value.trim() === \"\") throw invalid(`a write outcome's ${field} must be non-empty`);\n}\n\nfunction requireOptionalText(value: unknown, field: string): void {\n // A blank value would render as an empty sentence, such as \"Current state: .\", so it must be left out instead.\n if (value !== undefined && (typeof value !== \"string\" || value.trim() === \"\")) {\n throw invalid(`a write outcome's ${field} must be non-empty when it is set`);\n }\n}\n\nfunction effectList(value: unknown, field: string): readonly string[] {\n if (value === undefined) return Object.freeze([]);\n if (!Array.isArray(value) || !value.every((item) => typeof item === \"string\" && item.trim() !== \"\")) {\n throw invalid(`a write outcome's ${field} must be a list of non-empty strings`);\n }\n return Object.freeze([...value]);\n}\n\nfunction checkReason(reason: unknown): void {\n if (reason === undefined) return;\n if (typeof reason !== \"string\" || reason.length > MAX_REASON_LENGTH || !REASON.test(reason)) {\n throw invalid(\n `a write outcome's reason must be upper snake case and at most ${MAX_REASON_LENGTH} characters, ` +\n `got ${JSON.stringify(reason)}`,\n );\n }\n}\n\n// The effect lists each kind can't hold, because the kind's own sentence would contradict them: a write that changed\n// nothing has no effects, one that took effect undid nothing, and one that was undone holds none of its effects.\nconst FORBIDDEN_EFFECTS: { readonly [K in OutcomeKind]: readonly Defaulted[] } = {\n applied: [\"reverted\"],\n not_applied: [\"applied\", \"reverted\", \"notReversible\"],\n compensated: [\"applied\"],\n partial: [],\n unknown: [],\n};\n\nfunction checkEffects(kind: OutcomeKind, lists: Readonly<Record<Defaulted, readonly string[]>>): void {\n for (const field of FORBIDDEN_EFFECTS[kind]) {\n if (lists[field].length > 0) throw invalid(`a ${kind} outcome cannot list ${field} effects`);\n }\n}\n\nfunction checkEffectKey(kind: OutcomeKind, retry: Retry, effectKey: unknown): void {\n // Without a key, a same-key retry of a write that may have taken effect could take effect twice. A not_applied\n // write took no effect, so retrying it is safe with or without one.\n if (retry === \"same_key\" && effectKey === undefined && (kind === \"partial\" || kind === \"unknown\")) {\n throw invalid(`a ${kind} outcome can use retry \"same_key\" only with an effectKey`);\n }\n}\n\nfunction checkKindAndRetry(kind: unknown, retry: unknown): Retry {\n if (!OUTCOME_KINDS.includes(kind as OutcomeKind)) throw invalid(`unknown outcome kind ${JSON.stringify(kind)}`);\n const known = kind as OutcomeKind;\n // Only a missing retry takes the default; `null` from a JSON caller fails the check below like any other value.\n const chosen = retry === undefined ? DEFAULT_RETRY[known] : retry;\n if (!(ALLOWED_RETRIES[known] as readonly unknown[]).includes(chosen)) {\n throw invalid(`a ${known} outcome cannot use retry ${JSON.stringify(chosen)}`);\n }\n return chosen as Retry;\n}\n\n/**\n * Builds a write outcome, filling in the defaults and checking every field. The result is frozen.\n *\n * Throws a `SafetyError`, code `invalid_outcome`, for:\n * - an unknown kind, or a retry rule the kind doesn't allow;\n * - an empty `operation` or `next`, or an `operation` with leading or trailing spaces;\n * - a blank effect or optional text field;\n * - a `reason` that isn't upper snake case of at most 63 characters;\n * - effects the kind contradicts: any effect on `not_applied`, `reverted` on `applied`, `applied` on `compensated`;\n * - a `partial` or `unknown` outcome that allows a `same_key` retry without an `effectKey`.\n */\nexport function writeOutcome(init: WriteOutcomeInit): WriteOutcome {\n const retry = checkKindAndRetry(init.kind, init.retry);\n requireText(init.operation, \"operation\");\n if (init.operation !== init.operation.trim())\n throw invalid(\"a write outcome's operation must not start or end with spaces\");\n requireText(init.next, \"next\");\n for (const field of [\"effectKey\", \"currentState\", \"avoid\"] as const) requireOptionalText(init[field], field);\n checkReason(init.reason);\n checkEffectKey(init.kind, retry, init.effectKey);\n const lists = {\n applied: effectList(init.applied, \"applied\"),\n reverted: effectList(init.reverted, \"reverted\"),\n notReversible: effectList(init.notReversible, \"notReversible\"),\n };\n checkEffects(init.kind, lists);\n const outcome = {\n kind: init.kind,\n operation: init.operation,\n ...(init.effectKey === undefined ? {} : { effectKey: init.effectKey }),\n ...lists,\n ...(init.currentState === undefined ? {} : { currentState: init.currentState }),\n retry,\n next: init.next,\n ...(init.avoid === undefined ? {} : { avoid: init.avoid }),\n ...(init.reason === undefined ? {} : { reason: init.reason }),\n };\n // checkKindAndRetry has shown that `retry` is one the kind allows, which the spread above can't carry in its type.\n return Object.freeze(outcome) as WriteOutcome;\n}\n"]}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `renderOutcome()`: turns a write outcome into what the model reads. The outcome travels in the tool result's body,
3
+ * as a sentence and a structured payload, with the provider's error flag set as well, because some adapters drop the
4
+ * flag and some SDKs hide text blocks once structured content is set (server rollback report).
5
+ */
6
+ import { type OutcomeKind, type Retry, type WriteOutcome } from "./outcome.js";
7
+ /**
8
+ * The structured half of a rendered outcome: the outcome's own fields, as plain JSON. Optional fields the outcome
9
+ * leaves out are left out here too.
10
+ */
11
+ export type OutcomePayload = {
12
+ readonly kind: OutcomeKind;
13
+ readonly operation: string;
14
+ readonly effectKey?: string;
15
+ readonly applied: readonly string[];
16
+ readonly reverted: readonly string[];
17
+ readonly notReversible: readonly string[];
18
+ readonly currentState?: string;
19
+ readonly retry: Retry;
20
+ readonly next: string;
21
+ readonly avoid?: string;
22
+ readonly reason?: string;
23
+ };
24
+ /** A write outcome as the model reads it. */
25
+ export interface RenderedOutcome {
26
+ /** Sentences that say what happened, what to do next and what not to do. */
27
+ readonly text: string;
28
+ /** The outcome's fields, for a model or a harness that reads structured results. */
29
+ readonly payload: OutcomePayload;
30
+ /** True for every kind except `applied`: the provider's error flag, where the provider has one. */
31
+ readonly isError: boolean;
32
+ }
33
+ /**
34
+ * Renders a write outcome for the model: sentences that name what happened, what to do next and what not to do, the
35
+ * outcome's fields as a JSON payload, and whether the provider's error flag should be set. Put both the text and the
36
+ * payload in the tool result, because some SDKs show the model only one of them. It first checks the outcome as
37
+ * `writeOutcome()` does, so an outcome built by hand that breaks a rule throws a `SafetyError`, code
38
+ * `invalid_outcome`.
39
+ */
40
+ export declare function renderOutcome(outcome: WriteOutcome): RenderedOutcome;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * `renderOutcome()`: turns a write outcome into what the model reads. The outcome travels in the tool result's body,
3
+ * as a sentence and a structured payload, with the provider's error flag set as well, because some adapters drop the
4
+ * flag and some SDKs hide text blocks once structured content is set (server rollback report).
5
+ */
6
+ import { writeOutcome } from "./outcome.js";
7
+ // What happened, per kind. `{op}` is the operation's name.
8
+ const HAPPENED = {
9
+ applied: "The {op} call took effect.",
10
+ not_applied: "The {op} call did not take effect, and nothing changed.",
11
+ compensated: "The {op} call took effect and was then undone.",
12
+ partial: "The {op} call only partly took effect, and the rest could not be undone.",
13
+ unknown: "It is not known whether the {op} call took effect.",
14
+ };
15
+ // What the model must not do, per kind, from the server rollback report's outcome table.
16
+ const MUST_NOT = {
17
+ applied: "Do not run it again for the same request.",
18
+ not_applied: "Do not say that it happened.",
19
+ compensated: "Do not say that it took effect, and do not hide what could not be undone.",
20
+ partial: "Do not present it as a success.",
21
+ unknown: "Do not say that it happened or that it failed, and do not retry it as a new request.",
22
+ };
23
+ // What a retry may look like, per rule. `applied` takes no retry sentence, because its kind sentence covers it.
24
+ const RETRY = {
25
+ same_key: "Retrying this same call is safe; it takes effect at most once.",
26
+ new_operation_only: "Try again only as a new request, and only if the user still wants it.",
27
+ reconcile_first: "Check its current status before any retry.",
28
+ never: "Do not retry it.",
29
+ };
30
+ // A same-key retry with no key is safe only for not_applied, whose first attempt changed nothing.
31
+ const KEYLESS_SAME_KEY = "Retrying this same call is safe, because this attempt changed nothing.";
32
+ function sentence(text) {
33
+ const trimmed = text.trim();
34
+ return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;
35
+ }
36
+ function effects(label, list) {
37
+ // Each effect loses its own end punctuation, so "email sent." doesn't render as "email sent..".
38
+ const items = list.map((item) => item.trim().replace(/[.!?]+$/, ""));
39
+ return items.length === 0 ? [] : [`${label}: ${items.join("; ")}.`];
40
+ }
41
+ // A same-key retry takes effect at most once only when there is a key. renderOutcome() checks the outcome first, and
42
+ // writeOutcome() allows a keyless one only for not_applied, so only that kind reaches the keyless sentence.
43
+ function retrySentence(outcome) {
44
+ if (outcome.retry === "same_key" && outcome.effectKey === undefined && outcome.kind === "not_applied") {
45
+ return KEYLESS_SAME_KEY;
46
+ }
47
+ return RETRY[outcome.retry];
48
+ }
49
+ function describe(outcome) {
50
+ const parts = [
51
+ // A function replacer, so `$&` or `$'` in an operation's name is copied, not read as a replacement pattern.
52
+ HAPPENED[outcome.kind].replace("{op}", () => outcome.operation),
53
+ ...effects("Still in effect", outcome.applied),
54
+ ...effects("Undone", outcome.reverted),
55
+ ...effects("Cannot be undone", outcome.notReversible),
56
+ ...(outcome.currentState === undefined ? [] : [`Current state: ${sentence(outcome.currentState)}`]),
57
+ `Next: ${sentence(outcome.next)}`,
58
+ ...(outcome.kind === "applied" ? [] : [retrySentence(outcome)]),
59
+ MUST_NOT[outcome.kind],
60
+ ...(outcome.avoid === undefined ? [] : [sentence(outcome.avoid)]),
61
+ ];
62
+ return parts.join(" ");
63
+ }
64
+ function toPayload(outcome) {
65
+ return {
66
+ kind: outcome.kind,
67
+ operation: outcome.operation,
68
+ ...(outcome.effectKey === undefined ? {} : { effectKey: outcome.effectKey }),
69
+ applied: [...outcome.applied],
70
+ reverted: [...outcome.reverted],
71
+ notReversible: [...outcome.notReversible],
72
+ ...(outcome.currentState === undefined ? {} : { currentState: outcome.currentState }),
73
+ retry: outcome.retry,
74
+ next: outcome.next,
75
+ ...(outcome.avoid === undefined ? {} : { avoid: outcome.avoid }),
76
+ ...(outcome.reason === undefined ? {} : { reason: outcome.reason }),
77
+ };
78
+ }
79
+ /**
80
+ * Renders a write outcome for the model: sentences that name what happened, what to do next and what not to do, the
81
+ * outcome's fields as a JSON payload, and whether the provider's error flag should be set. Put both the text and the
82
+ * payload in the tool result, because some SDKs show the model only one of them. It first checks the outcome as
83
+ * `writeOutcome()` does, so an outcome built by hand that breaks a rule throws a `SafetyError`, code
84
+ * `invalid_outcome`.
85
+ */
86
+ export function renderOutcome(outcome) {
87
+ // `WriteOutcome` is a plain type, so a tool can build one as a literal or revive one from JSON. Checking it again
88
+ // here holds every outcome the model reads to the rules writeOutcome() enforces.
89
+ const checked = writeOutcome(outcome);
90
+ return { text: describe(checked), payload: toPayload(checked), isError: checked.kind !== "applied" };
91
+ }
92
+ //# sourceMappingURL=render.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.js","sourceRoot":"","sources":["../../../src/vendor/agent-safety/render.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAmD,YAAY,EAAE,MAAM,cAAc,CAAC;AA8B7F,2DAA2D;AAC3D,MAAM,QAAQ,GAA4C;IACxD,OAAO,EAAE,4BAA4B;IACrC,WAAW,EAAE,yDAAyD;IACtE,WAAW,EAAE,gDAAgD;IAC7D,OAAO,EAAE,0EAA0E;IACnF,OAAO,EAAE,oDAAoD;CAC9D,CAAC;AAEF,yFAAyF;AACzF,MAAM,QAAQ,GAA4C;IACxD,OAAO,EAAE,2CAA2C;IACpD,WAAW,EAAE,8BAA8B;IAC3C,WAAW,EAAE,2EAA2E;IACxF,OAAO,EAAE,iCAAiC;IAC1C,OAAO,EAAE,sFAAsF;CAChG,CAAC;A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AAQ,CAAC;QAC/B,aAAa,EAAE,CAAC,GAAG,OAAO,CAAC,aAAa,CAAC;QACzC,GAAG,CAAC,OAAO,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,OAAO,CAAC,YAAY,EAAE,CAAC;QACrF,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,IAAI,EAAE,OAAO,CAAC,IAAI;QAClB,GAAG,CAAC,OAAO,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC;QAChE,GAAG,CAAC,OAAO,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC;KACpE,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAAC,OAAqB;IACjD,kHAAkH;IAClH,iFAAiF;IACjF,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC;IACtC,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;AACvG,CAAC","sourcesContent":["/**\n * `renderOutcome()`: turns a write outcome into what the model reads. The outcome travels in the tool result's body,\n * as a sentence and a structured payload, with the provider's error flag set as well, because some adapters drop the\n * flag and some SDKs hide text blocks once structured content is set (server rollback report).\n */\nimport { type OutcomeKind, type Retry, type WriteOutcome, writeOutcome } from \"./outcome.js\";\n\n/**\n * The structured half of a rendered outcome: the outcome's own fields, as plain JSON. Optional fields the outcome\n * leaves out are left out here too.\n */\nexport type OutcomePayload = {\n readonly kind: OutcomeKind;\n readonly operation: string;\n readonly effectKey?: string;\n readonly applied: readonly string[];\n readonly reverted: readonly string[];\n readonly notReversible: readonly string[];\n readonly currentState?: string;\n readonly retry: Retry;\n readonly next: string;\n readonly avoid?: string;\n readonly reason?: string;\n};\n\n/** A write outcome as the model reads it. */\nexport interface RenderedOutcome {\n /** Sentences that say what happened, what to do next and what not to do. */\n readonly text: string;\n /** The outcome's fields, for a model or a harness that reads structured results. */\n readonly payload: OutcomePayload;\n /** True for every kind except `applied`: the provider's error flag, where the provider has one. */\n readonly isError: boolean;\n}\n\n// What happened, per kind. `{op}` is the operation's name.\nconst HAPPENED: { readonly [K in OutcomeKind]: string } = {\n applied: \"The {op} call took effect.\",\n not_applied: \"The {op} call did not take effect, and nothing changed.\",\n compensated: \"The {op} call took effect and was then undone.\",\n partial: \"The {op} call only partly took effect, and the rest could not be undone.\",\n unknown: \"It is not known whether the {op} call took effect.\",\n};\n\n// What the model must not do, per kind, from the server rollback report's outcome table.\nconst MUST_NOT: { readonly [K in OutcomeKind]: string } = {\n applied: \"Do not run it again for the same request.\",\n not_applied: \"Do not say that it happened.\",\n compensated: \"Do not say that it took effect, and do not hide what could not be undone.\",\n partial: \"Do not present it as a success.\",\n unknown: \"Do not say that it happened or that it failed, and do not retry it as a new request.\",\n};\n\n// What a retry may look like, per rule. `applied` takes no retry sentence, because its kind sentence covers it.\nconst RETRY: { readonly [R in Retry]: string } = {\n same_key: \"Retrying this same call is safe; it takes effect at most once.\",\n new_operation_only: \"Try again only as a new request, and only if the user still wants it.\",\n reconcile_first: \"Check its current status before any retry.\",\n never: \"Do not retry it.\",\n};\n\n// A same-key retry with no key is safe only for not_applied, whose first attempt changed nothing.\nconst KEYLESS_SAME_KEY = \"Retrying this same call is safe, because this attempt changed nothing.\";\n\nfunction sentence(text: string): string {\n const trimmed = text.trim();\n return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;\n}\n\nfunction effects(label: string, list: readonly string[]): string[] {\n // Each effect loses its own end punctuation, so \"email sent.\" doesn't render as \"email sent..\".\n const items = list.map((item) => item.trim().replace(/[.!?]+$/, \"\"));\n return items.length === 0 ? [] : [`${label}: ${items.join(\"; \")}.`];\n}\n\n// A same-key retry takes effect at most once only when there is a key. renderOutcome() checks the outcome first, and\n// writeOutcome() allows a keyless one only for not_applied, so only that kind reaches the keyless sentence.\nfunction retrySentence(outcome: WriteOutcome): string {\n if (outcome.retry === \"same_key\" && outcome.effectKey === undefined && outcome.kind === \"not_applied\") {\n return KEYLESS_SAME_KEY;\n }\n return RETRY[outcome.retry];\n}\n\nfunction describe(outcome: WriteOutcome): string {\n const parts = [\n // A function replacer, so `$&` or `$'` in an operation's name is copied, not read as a replacement pattern.\n HAPPENED[outcome.kind].replace(\"{op}\", () => outcome.operation),\n ...effects(\"Still in effect\", outcome.applied),\n ...effects(\"Undone\", outcome.reverted),\n ...effects(\"Cannot be undone\", outcome.notReversible),\n ...(outcome.currentState === undefined ? [] : [`Current state: ${sentence(outcome.currentState)}`]),\n `Next: ${sentence(outcome.next)}`,\n ...(outcome.kind === \"applied\" ? [] : [retrySentence(outcome)]),\n MUST_NOT[outcome.kind],\n ...(outcome.avoid === undefined ? [] : [sentence(outcome.avoid)]),\n ];\n return parts.join(\" \");\n}\n\nfunction toPayload(outcome: WriteOutcome): OutcomePayload {\n return {\n kind: outcome.kind,\n operation: outcome.operation,\n ...(outcome.effectKey === undefined ? {} : { effectKey: outcome.effectKey }),\n applied: [...outcome.applied],\n reverted: [...outcome.reverted],\n notReversible: [...outcome.notReversible],\n ...(outcome.currentState === undefined ? {} : { currentState: outcome.currentState }),\n retry: outcome.retry,\n next: outcome.next,\n ...(outcome.avoid === undefined ? {} : { avoid: outcome.avoid }),\n ...(outcome.reason === undefined ? {} : { reason: outcome.reason }),\n };\n}\n\n/**\n * Renders a write outcome for the model: sentences that name what happened, what to do next and what not to do, the\n * outcome's fields as a JSON payload, and whether the provider's error flag should be set. Put both the text and the\n * payload in the tool result, because some SDKs show the model only one of them. It first checks the outcome as\n * `writeOutcome()` does, so an outcome built by hand that breaks a rule throws a `SafetyError`, code\n * `invalid_outcome`.\n */\nexport function renderOutcome(outcome: WriteOutcome): RenderedOutcome {\n // `WriteOutcome` is a plain type, so a tool can build one as a literal or revive one from JSON. Checking it again\n // here holds every outcome the model reads to the rules writeOutcome() enforces.\n const checked = writeOutcome(outcome);\n return { text: describe(checked), payload: toPayload(checked), isError: checked.kind !== \"applied\" };\n}\n"]}