@buildanagent/sdk 0.1.0-alpha.1 → 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 (38) hide show
  1. package/README.md +88 -2
  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/tools/coerce.d.ts +15 -0
  9. package/dist/tools/coerce.js +93 -0
  10. package/dist/tools/coerce.js.map +1 -0
  11. package/dist/tools/define.d.ts +42 -0
  12. package/dist/tools/define.js +96 -0
  13. package/dist/tools/define.js.map +1 -0
  14. package/dist/tools/format-error.d.ts +13 -0
  15. package/dist/tools/format-error.js +65 -0
  16. package/dist/tools/format-error.js.map +1 -0
  17. package/dist/tools/outcome.d.ts +7 -0
  18. package/dist/tools/outcome.js +30 -0
  19. package/dist/tools/outcome.js.map +1 -0
  20. package/dist/tools/pipeline.d.ts +52 -0
  21. package/dist/tools/pipeline.js +184 -0
  22. package/dist/tools/pipeline.js.map +1 -0
  23. package/dist/tools/schema.d.ts +20 -0
  24. package/dist/tools/schema.js +100 -0
  25. package/dist/tools/schema.js.map +1 -0
  26. package/dist/tools/types.d.ts +144 -0
  27. package/dist/tools/types.js +2 -0
  28. package/dist/tools/types.js.map +1 -0
  29. package/dist/vendor/agent-safety/errors.d.ts +14 -0
  30. package/dist/vendor/agent-safety/errors.js +21 -0
  31. package/dist/vendor/agent-safety/errors.js.map +1 -0
  32. package/dist/vendor/agent-safety/outcome.d.ts +88 -0
  33. package/dist/vendor/agent-safety/outcome.js +140 -0
  34. package/dist/vendor/agent-safety/outcome.js.map +1 -0
  35. package/dist/vendor/agent-safety/render.d.ts +40 -0
  36. package/dist/vendor/agent-safety/render.js +92 -0
  37. package/dist/vendor/agent-safety/render.js.map +1 -0
  38. package/package.json +11 -3
@@ -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/vend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S;QACzB,GAAG,CAAC,IAAI,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC;QACtE,GAAG,KAAK;QACR,GAAG,CAAC,IAAI,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,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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AC,SAAS;QAC5B,GAAG,CAAC,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC;QAC5E,OAAO,EAAE,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;QAC7B,QAAQ,EAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@buildanagent/sdk",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.2",
4
4
  "description": "The buildanagent SDK: the agent loop, tools, hooks, signed pauses and budgets over the gateway.",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "repository": {
@@ -12,7 +12,7 @@
12
12
  "type": "module",
13
13
  "sideEffects": false,
14
14
  "engines": {
15
- "node": ">=22"
15
+ "node": ">=22.19.0"
16
16
  },
17
17
  "files": [
18
18
  "dist",
@@ -35,7 +35,15 @@
35
35
  }
36
36
  },
37
37
  "dependencies": {
38
- "@buildanagent/gateway": "0.1.0-alpha.1"
38
+ "@earendil-works/pi-schema": "1.5.2",
39
+ "@standard-schema/spec": "1.1.0",
40
+ "@buildanagent/gateway": "0.1.0-alpha.2"
41
+ },
42
+ "devDependencies": {
43
+ "@cfworker/json-schema": "4.1.6",
44
+ "miniflare": "5.20261103.0-beta",
45
+ "zod": "4.6.7",
46
+ "@buildanagent/agent-safety": "0.0.0"
39
47
  },
40
48
  "scripts": {
41
49
  "build": "node ../../scripts/clean-dist.mjs && tsc -p tsconfig.build.json",