@buildanagent/agent-safety 0.0.0-bootstrap.0 → 0.1.0-alpha.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +54 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +515 -0
- package/dist/agents/index.d.ts +5 -0
- package/dist/agents/index.js +6 -0
- package/dist/agents/index.js.map +1 -0
- package/dist/ai/index.d.ts +10 -0
- package/dist/ai/index.js +11 -0
- package/dist/ai/index.js.map +1 -0
- package/dist/ai/interrupted-write.d.ts +28 -0
- package/dist/ai/interrupted-write.js +52 -0
- package/dist/ai/interrupted-write.js.map +1 -0
- package/dist/ai/settle-denied.d.ts +17 -0
- package/dist/ai/settle-denied.js +25 -0
- package/dist/ai/settle-denied.js.map +1 -0
- package/dist/ai/tool-approval.d.ts +68 -0
- package/dist/ai/tool-approval.js +219 -0
- package/dist/ai/tool-approval.js.map +1 -0
- package/dist/ai/tool-result.d.ts +23 -0
- package/dist/ai/tool-result.js +20 -0
- package/dist/ai/tool-result.js.map +1 -0
- package/dist/byok/default-provider.d.ts +12 -0
- package/dist/byok/default-provider.js +72 -0
- package/dist/byok/default-provider.js.map +1 -0
- package/dist/byok/explicit-provider.d.ts +39 -0
- package/dist/byok/explicit-provider.js +80 -0
- package/dist/byok/explicit-provider.js.map +1 -0
- package/dist/byok/index.d.ts +8 -0
- package/dist/byok/index.js +9 -0
- package/dist/byok/index.js.map +1 -0
- package/dist/bytes.d.ts +17 -0
- package/dist/bytes.js +59 -0
- package/dist/bytes.js.map +1 -0
- package/dist/cost/ai-types.d.ts +26 -0
- package/dist/cost/ai-types.js +2 -0
- package/dist/cost/ai-types.js.map +1 -0
- package/dist/cost/budget-exceeded.d.ts +39 -0
- package/dist/cost/budget-exceeded.js +49 -0
- package/dist/cost/budget-exceeded.js.map +1 -0
- package/dist/cost/cost-guard.d.ts +63 -0
- package/dist/cost/cost-guard.js +278 -0
- package/dist/cost/cost-guard.js.map +1 -0
- package/dist/cost/estimate.d.ts +76 -0
- package/dist/cost/estimate.js +320 -0
- package/dist/cost/estimate.js.map +1 -0
- package/dist/cost/guarded-provider.d.ts +24 -0
- package/dist/cost/guarded-provider.js +19 -0
- package/dist/cost/guarded-provider.js.map +1 -0
- package/dist/cost/index.d.ts +12 -0
- package/dist/cost/index.js +12 -0
- package/dist/cost/index.js.map +1 -0
- package/dist/cost/spend.d.ts +13 -0
- package/dist/cost/spend.js +15 -0
- package/dist/cost/spend.js.map +1 -0
- package/dist/effect-key.d.ts +31 -0
- package/dist/effect-key.js +61 -0
- package/dist/effect-key.js.map +1 -0
- package/dist/effect-store-conformance.d.ts +24 -0
- package/dist/effect-store-conformance.js +140 -0
- package/dist/effect-store-conformance.js.map +1 -0
- package/dist/effect-store.d.ts +71 -0
- package/dist/effect-store.js +38 -0
- package/dist/effect-store.js.map +1 -0
- package/dist/egress.d.ts +74 -0
- package/dist/egress.js +174 -0
- package/dist/egress.js.map +1 -0
- package/dist/errors.d.ts +32 -0
- package/dist/errors.js +26 -0
- package/dist/errors.js.map +1 -0
- package/dist/guarded-write.d.ts +99 -0
- package/dist/guarded-write.js +245 -0
- package/dist/guarded-write.js.map +1 -0
- package/dist/hash.d.ts +24 -0
- package/dist/hash.js +121 -0
- package/dist/hash.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +28 -0
- package/dist/index.js.map +1 -0
- package/dist/key-store.d.ts +37 -0
- package/dist/key-store.js +53 -0
- package/dist/key-store.js.map +1 -0
- package/dist/model-routes.d.ts +54 -0
- package/dist/model-routes.js +117 -0
- package/dist/model-routes.js.map +1 -0
- package/dist/model-url.d.ts +39 -0
- package/dist/model-url.js +79 -0
- package/dist/model-url.js.map +1 -0
- package/dist/outcome.d.ts +88 -0
- package/dist/outcome.js +140 -0
- package/dist/outcome.js.map +1 -0
- package/dist/pending-store.d.ts +45 -0
- package/dist/pending-store.js +36 -0
- package/dist/pending-store.js.map +1 -0
- package/dist/pending.d.ts +144 -0
- package/dist/pending.js +161 -0
- package/dist/pending.js.map +1 -0
- package/dist/plan-approval.d.ts +196 -0
- package/dist/plan-approval.js +357 -0
- package/dist/plan-approval.js.map +1 -0
- package/dist/plan-card.d.ts +34 -0
- package/dist/plan-card.js +56 -0
- package/dist/plan-card.js.map +1 -0
- package/dist/plan-ledger-conformance.d.ts +24 -0
- package/dist/plan-ledger-conformance.js +99 -0
- package/dist/plan-ledger-conformance.js.map +1 -0
- package/dist/plan-ledger.d.ts +14 -0
- package/dist/plan-ledger.js +42 -0
- package/dist/plan-ledger.js.map +1 -0
- package/dist/plan-run.d.ts +133 -0
- package/dist/plan-run.js +438 -0
- package/dist/plan-run.js.map +1 -0
- package/dist/render.d.ts +40 -0
- package/dist/render.js +92 -0
- package/dist/render.js.map +1 -0
- package/dist/signer.d.ts +42 -0
- package/dist/signer.js +128 -0
- package/dist/signer.js.map +1 -0
- package/dist/stores/cloudflare.d.ts +34 -0
- package/dist/stores/cloudflare.js +84 -0
- package/dist/stores/cloudflare.js.map +1 -0
- package/dist/stores/dynamodb.d.ts +27 -0
- package/dist/stores/dynamodb.js +139 -0
- package/dist/stores/dynamodb.js.map +1 -0
- package/dist/stores/lost-claim.d.ts +8 -0
- package/dist/stores/lost-claim.js +11 -0
- package/dist/stores/lost-claim.js.map +1 -0
- package/dist/stores/postgres.d.ts +30 -0
- package/dist/stores/postgres.js +79 -0
- package/dist/stores/postgres.js.map +1 -0
- package/dist/test-signer.d.ts +13 -0
- package/dist/test-signer.js +18 -0
- package/dist/test-signer.js.map +1 -0
- package/dist/testing.d.ts +8 -0
- package/dist/testing.js +9 -0
- package/dist/testing.js.map +1 -0
- package/llms.txt +212 -0
- package/package.json +108 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dynamodb.js","sourceRoot":"","sources":["../../src/stores/dynamodb.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAEL,cAAc,E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ACF,MAAM,OAAO,GACX,SAAS,KAAK,CAAC;gBACb,CAAC,CAAC,EAAE;gBACJ,CAAC,CAAC;oBACE;wBACE,cAAc,EAAE;4BACd,SAAS,EAAE,SAAS;4BACpB,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,GAAG,CAAC,CAAC,EAAE,EAAE;4BACjD,mBAAmB,EAAE,uBAAuB;4BAC5C,wBAAwB,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE;yBAC1C;qBACF;iBACF,CAAC;YACR,IAAI,CAAC;gBACH,MAAM,MAAM,CAAC,IAAI,CACf,IAAI,yBAAyB,CAAC,EAAE,aAAa,EAAE,CAAC,GAAG,OAAO,EAAE,GAAG,CAAC,EAAE,kBAAkB,EAAE,MAAM,CAAC,UAAU,EAAE,EAAE,CAAC,CAC7G,CAAC;gBACF,OAAO,SAAkB,CAAC;YAC5B,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC;oBAAE,MAAM,KAAK,CAAC;gBAC5C,OAAO,CAAC,MAAM,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAE,UAAoB,CAAC,CAAC,CAAE,cAAwB,CAAC;YAC/F,CAAC;QACH,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * `@buildanagent/agent-safety/stores/dynamodb`: the effect store and the plan ledger on DynamoDB, through an\n * `@aws-sdk/client-dynamodb` client. Every change is a conditional write, so DynamoDB decides a race: `begin` is a put\n * that needs the key to be absent, `takeOver` a put that needs the stored attempt to be the one before, and `settle` a\n * put that needs the record to be `started` at this attempt. A plan's step claim is one transaction that checks the\n * step before it and puts this one.\n *\n * Reads are consistent reads. The table needs one string partition key named `pk` and no sort key.\n */\nimport {\n type DynamoDBClient,\n GetItemCommand,\n PutItemCommand,\n TransactWriteItemsCommand,\n} from \"@aws-sdk/client-dynamodb\";\nimport type { EffectClaim, EffectRecord, EffectStore } from \"../effect-store.js\";\nimport type { PlanLedger } from \"../plan-approval.js\";\nimport { assertStepIndex } from \"../plan-ledger.js\";\nimport { lostClaim } from \"./lost-claim.js\";\n\n/** The options of the DynamoDB stores. */\nexport interface DynamoStoreOptions {\n /** The table that holds the records and the plan steps. */\n readonly tableName: string;\n}\n\nconst effectPk = (key: string) => `effect#${key}`;\nconst stepPk = (planId: string, stepIndex: number) => `plan#${planId}#${stepIndex}`;\n\ntype Attributes = Record<string, { S: string } | { N: string }>;\n\n/** The item for a record. `token` names the call that wrote it, so that call can tell its own retried write apart. */\nfunction item(record: EffectRecord, token: string) {\n return {\n pk: { S: effectPk(record.key) },\n attempt: { N: String(record.attempt) },\n state: { S: record.state },\n record: { S: JSON.stringify(record) },\n token: { S: token },\n };\n}\n\n// The parts of an SDK error these stores read. They compare an error's `name`, not its class, so a host that loads\n// its own copy of the SDK next to this package's still gets its errors recognised.\ninterface SdkErrorLike {\n readonly name?: string;\n readonly Item?: { readonly token?: { readonly S?: string } };\n readonly CancellationReasons?: readonly { readonly Code?: string }[];\n}\n\nconst asSdkError = (error: unknown): SdkErrorLike => (typeof error === \"object\" && error !== null ? error : {});\n\n/**\n * The token on the item that made a put's condition false, or `undefined` when the answer isn't \"the condition was\n * false\".\n */\nfunction failedConditionToken(error: unknown): { readonly token: string | undefined } | undefined {\n const { name, Item } = asSdkError(error);\n return name === \"ConditionalCheckFailedException\" ? { token: Item?.token?.S } : undefined;\n}\n\n/**\n * Whether a transaction was refused because a condition was false. A cancellation for another reason, such as a\n * conflict with another transaction or throttling, says nothing about the items, so it is not a refusal.\n */\nfunction transactionRefused(error: unknown): boolean {\n const { name, CancellationReasons } = asSdkError(error);\n return (\n name === \"TransactionCanceledException\" &&\n CancellationReasons?.some((r) => r.Code === \"ConditionalCheckFailed\") === true\n );\n}\n\n/** An `EffectStore` on DynamoDB. */\nexport function dynamoEffectStore(client: DynamoDBClient, options: DynamoStoreOptions): EffectStore {\n const { tableName } = options;\n const read = async (key: string): Promise<EffectRecord | undefined> => {\n const { Item } = await client.send(\n new GetItemCommand({ TableName: tableName, Key: { pk: { S: effectPk(key) } }, ConsistentRead: true }),\n );\n return Item?.record?.S === undefined ? undefined : (JSON.parse(Item.record.S) as EffectRecord);\n };\n const lost = async (key: string): Promise<EffectClaim> => lostClaim(key, await read(key));\n /**\n * A put that needs `condition`, answering whether it took effect. The SDK retries a put after a timeout or a server\n * error, and a retry of a put that already took effect fails its own condition. DynamoDB then returns the item that\n * made it fail, and when that item carries this call's token it is this call's own write, so the put counts as won.\n * Each call has a token of its own, so another caller's write never does.\n */\n const put = async (\n record: EffectRecord,\n condition: string,\n names: Record<string, string>,\n values?: Attributes,\n ): Promise<boolean> => {\n const token = crypto.randomUUID();\n try {\n await client.send(\n new PutItemCommand({\n TableName: tableName,\n Item: item(record, token),\n ConditionExpression: condition,\n ExpressionAttributeNames: names,\n ...(values === undefined ? {} : { ExpressionAttributeValues: values }),\n ReturnValuesOnConditionCheckFailure: \"ALL_OLD\",\n }),\n );\n return true;\n } catch (error) {\n const failed = failedConditionToken(error);\n if (failed === undefined) throw error;\n return failed.token === token;\n }\n };\n return {\n async begin(record) {\n return (await put(record, \"attribute_not_exists(#pk)\", { \"#pk\": \"pk\" })) ? \"started\" : lost(record.key);\n },\n async takeOver(record) {\n const won = await put(\n record,\n \"attribute_not_exists(#pk) OR #attempt = :previous\",\n { \"#pk\": \"pk\", \"#attempt\": \"attempt\" },\n { \":previous\": { N: String(record.attempt - 1) } },\n );\n return won ? \"started\" : lost(record.key);\n },\n async settle(record) {\n return put(\n record,\n \"#state = :started AND #attempt = :attempt\",\n { \"#state\": \"state\", \"#attempt\": \"attempt\" },\n { \":started\": { S: \"started\" }, \":attempt\": { N: String(record.attempt) } },\n );\n },\n get: read,\n };\n}\n\n/**\n * A `PlanLedger` on DynamoDB. Step `n` is an item that exists once the step passed. A claim of step `n` is one\n * transaction: put the item for `n` if it is absent, and check that the item for `n - 1` exists. The transaction\n * carries a `ClientRequestToken`, so an SDK retry of a claim that already took effect is answered as the same claim,\n * not as a replay. When the transaction is refused because a condition was false, a read of the item for `n` tells\n * `replayed` from `out_of_order`; a cancellation for any other reason is rethrown.\n */\nexport function dynamoPlanLedger(client: DynamoDBClient, options: DynamoStoreOptions): PlanLedger {\n const { tableName } = options;\n const exists = async (planId: string, stepIndex: number): Promise<boolean> => {\n const { Item } = await client.send(\n new GetItemCommand({ TableName: tableName, Key: { pk: { S: stepPk(planId, stepIndex) } }, ConsistentRead: true }),\n );\n return Item !== undefined;\n };\n return Object.freeze({\n async claim(planId: string, stepIndex: number) {\n assertStepIndex(stepIndex);\n const put = {\n Put: {\n TableName: tableName,\n Item: { pk: { S: stepPk(planId, stepIndex) } },\n ConditionExpression: \"attribute_not_exists(#pk)\",\n ExpressionAttributeNames: { \"#pk\": \"pk\" },\n },\n };\n const earlier =\n stepIndex === 0\n ? []\n : [\n {\n ConditionCheck: {\n TableName: tableName,\n Key: { pk: { S: stepPk(planId, stepIndex - 1) } },\n ConditionExpression: \"attribute_exists(#pk)\",\n ExpressionAttributeNames: { \"#pk\": \"pk\" },\n },\n },\n ];\n try {\n await client.send(\n new TransactWriteItemsCommand({ TransactItems: [...earlier, put], ClientRequestToken: crypto.randomUUID() }),\n );\n return \"claimed\" as const;\n } catch (error) {\n if (!transactionRefused(error)) throw error;\n return (await exists(planId, stepIndex)) ? (\"replayed\" as const) : (\"out_of_order\" as const);\n }\n },\n });\n}\n"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** The answer the durable effect stores give when their conditional write lost: the record that is already there. */
|
|
2
|
+
import type { EffectClaim, EffectRecord } from "../effect-store.js";
|
|
3
|
+
/**
|
|
4
|
+
* The claim for a write that lost to another process, given the record read back after the loss. A record that vanished
|
|
5
|
+
* between the failed write and the read would mean that another process won and was then deleted, which no store method
|
|
6
|
+
* does. The claim can't be answered, so this throws.
|
|
7
|
+
*/
|
|
8
|
+
export declare function lostClaim(key: string, existing: EffectRecord | undefined): EffectClaim;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The claim for a write that lost to another process, given the record read back after the loss. A record that vanished
|
|
3
|
+
* between the failed write and the read would mean that another process won and was then deleted, which no store method
|
|
4
|
+
* does. The claim can't be answered, so this throws.
|
|
5
|
+
*/
|
|
6
|
+
export function lostClaim(key, existing) {
|
|
7
|
+
if (existing === undefined)
|
|
8
|
+
throw new Error(`the effect record ${key} changed while it was being claimed`);
|
|
9
|
+
return { existing };
|
|
10
|
+
}
|
|
11
|
+
//# sourceMappingURL=lost-claim.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lost-claim.js","sourceRoot":"","sources":["../../src/stores/lost-claim.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,MAAM,UAAU,SAAS,CAAC,GAAW,EAAE,QAAkC;IACvE,IAAI,QAAQ,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,qBAAqB,GAAG,qCAAqC,CAAC,CAAC;IAC3G,OAAO,EAAE,QAAQ,EAAE,CAAC;AACtB,CAAC","sourcesContent":["/** The answer the durable effect stores give when their conditional write lost: the record that is already there. */\nimport type { EffectClaim, EffectRecord } from \"../effect-store.js\";\n\n/**\n * The claim for a write that lost to another process, given the record read back after the loss. A record that vanished\n * between the failed write and the read would mean that another process won and was then deleted, which no store method\n * does. The claim can't be answered, so this throws.\n */\nexport function lostClaim(key: string, existing: EffectRecord | undefined): EffectClaim {\n if (existing === undefined) throw new Error(`the effect record ${key} changed while it was being claimed`);\n return { existing };\n}\n"]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@buildanagent/agent-safety/stores/postgres`: the effect store and the plan ledger on Postgres, through any client
|
|
3
|
+
* with a `query(text, values)` method that resolves to `{ rows }`, such as `pg`'s `Pool` or `Client` and PGlite. Every
|
|
4
|
+
* change is one statement that Postgres runs atomically (`INSERT … ON CONFLICT`, or an `UPDATE … WHERE` on the
|
|
5
|
+
* attempt), never a read followed by a write, so two processes can't both start one write.
|
|
6
|
+
*/
|
|
7
|
+
import type { EffectStore } from "../effect-store.js";
|
|
8
|
+
import type { PlanLedger } from "../plan-approval.js";
|
|
9
|
+
/** The part of a Postgres client these stores use. */
|
|
10
|
+
export interface PgClientLike {
|
|
11
|
+
/** Runs one SQL statement with its `$1`, `$2` … placeholders bound to `values`, and resolves with its rows. */
|
|
12
|
+
query(text: string, values?: unknown[]): Promise<{
|
|
13
|
+
rows: Record<string, unknown>[];
|
|
14
|
+
}>;
|
|
15
|
+
}
|
|
16
|
+
/** The statements that create the two tables. Run them once, as a migration or at deploy. */
|
|
17
|
+
export declare const POSTGRES_SCHEMA: readonly string[];
|
|
18
|
+
/** Creates the two tables if they are not there. */
|
|
19
|
+
export declare function createPostgresTables(client: PgClientLike): Promise<void>;
|
|
20
|
+
/**
|
|
21
|
+
* An `EffectStore` on Postgres. Each record is one row: its key, the attempt and state that the conditions read, and
|
|
22
|
+
* the record as JSON text. Run `POSTGRES_SCHEMA` first.
|
|
23
|
+
*/
|
|
24
|
+
export declare function postgresEffectStore(client: PgClientLike): EffectStore;
|
|
25
|
+
/**
|
|
26
|
+
* A `PlanLedger` on Postgres. A plan's claimed steps are rows `0` to `n - 1`, so a claim inserts its row only when the
|
|
27
|
+
* row count equals its index, in one statement. Two claims of one step insert the same primary key, and one of them
|
|
28
|
+
* loses, so a step is claimed once.
|
|
29
|
+
*/
|
|
30
|
+
export declare function postgresPlanLedger(client: PgClientLike): PlanLedger;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { assertStepIndex } from "../plan-ledger.js";
|
|
2
|
+
import { lostClaim } from "./lost-claim.js";
|
|
3
|
+
/** The statements that create the two tables. Run them once, as a migration or at deploy. */
|
|
4
|
+
export const POSTGRES_SCHEMA = [
|
|
5
|
+
`CREATE TABLE IF NOT EXISTS effect_records (
|
|
6
|
+
key TEXT PRIMARY KEY,
|
|
7
|
+
attempt INTEGER NOT NULL,
|
|
8
|
+
state TEXT NOT NULL,
|
|
9
|
+
record TEXT NOT NULL
|
|
10
|
+
)`,
|
|
11
|
+
`CREATE TABLE IF NOT EXISTS plan_steps (
|
|
12
|
+
plan_id TEXT NOT NULL,
|
|
13
|
+
step_index INTEGER NOT NULL,
|
|
14
|
+
PRIMARY KEY (plan_id, step_index)
|
|
15
|
+
)`,
|
|
16
|
+
];
|
|
17
|
+
/** Creates the two tables if they are not there. */
|
|
18
|
+
export async function createPostgresTables(client) {
|
|
19
|
+
for (const statement of POSTGRES_SCHEMA)
|
|
20
|
+
await client.query(statement);
|
|
21
|
+
}
|
|
22
|
+
// The record is stored as the JSON text it was written as, so a read gives back exactly what was stored: a JSONB column
|
|
23
|
+
// would reorder an object's keys and normalise its numbers.
|
|
24
|
+
function parse(value) {
|
|
25
|
+
return JSON.parse(String(value));
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* An `EffectStore` on Postgres. Each record is one row: its key, the attempt and state that the conditions read, and
|
|
29
|
+
* the record as JSON text. Run `POSTGRES_SCHEMA` first.
|
|
30
|
+
*/
|
|
31
|
+
export function postgresEffectStore(client) {
|
|
32
|
+
const read = async (key) => {
|
|
33
|
+
const { rows } = await client.query("SELECT record FROM effect_records WHERE key = $1", [key]);
|
|
34
|
+
return rows[0] === undefined ? undefined : parse(rows[0].record);
|
|
35
|
+
};
|
|
36
|
+
const lost = async (key) => lostClaim(key, await read(key));
|
|
37
|
+
const values = (record) => [record.key, record.attempt, record.state, JSON.stringify(record)];
|
|
38
|
+
return {
|
|
39
|
+
async begin(record) {
|
|
40
|
+
const { rows } = await client.query(`INSERT INTO effect_records (key, attempt, state, record) VALUES ($1, $2, $3, $4)
|
|
41
|
+
ON CONFLICT (key) DO NOTHING RETURNING key`, values(record));
|
|
42
|
+
return rows.length === 1 ? "started" : lost(record.key);
|
|
43
|
+
},
|
|
44
|
+
async takeOver(record) {
|
|
45
|
+
const { rows } = await client.query(`INSERT INTO effect_records AS current (key, attempt, state, record) VALUES ($1, $2, $3, $4)
|
|
46
|
+
ON CONFLICT (key) DO UPDATE SET attempt = EXCLUDED.attempt, state = EXCLUDED.state, record = EXCLUDED.record
|
|
47
|
+
WHERE current.attempt = EXCLUDED.attempt - 1
|
|
48
|
+
RETURNING key`, values(record));
|
|
49
|
+
return rows.length === 1 ? "started" : lost(record.key);
|
|
50
|
+
},
|
|
51
|
+
async settle(record) {
|
|
52
|
+
const { rows } = await client.query(`UPDATE effect_records SET state = 'settled', record = $3
|
|
53
|
+
WHERE key = $1 AND state = 'started' AND attempt = $2
|
|
54
|
+
RETURNING key`, [record.key, record.attempt, JSON.stringify(record)]);
|
|
55
|
+
return rows.length === 1;
|
|
56
|
+
},
|
|
57
|
+
get: read,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* A `PlanLedger` on Postgres. A plan's claimed steps are rows `0` to `n - 1`, so a claim inserts its row only when the
|
|
62
|
+
* row count equals its index, in one statement. Two claims of one step insert the same primary key, and one of them
|
|
63
|
+
* loses, so a step is claimed once.
|
|
64
|
+
*/
|
|
65
|
+
export function postgresPlanLedger(client) {
|
|
66
|
+
return Object.freeze({
|
|
67
|
+
async claim(planId, stepIndex) {
|
|
68
|
+
assertStepIndex(stepIndex);
|
|
69
|
+
const { rows } = await client.query(`INSERT INTO plan_steps (plan_id, step_index)
|
|
70
|
+
SELECT $1::text, $2::int WHERE (SELECT count(*) FROM plan_steps WHERE plan_id = $1::text) = $2::int
|
|
71
|
+
ON CONFLICT DO NOTHING RETURNING step_index`, [planId, stepIndex]);
|
|
72
|
+
if (rows.length === 1)
|
|
73
|
+
return "claimed";
|
|
74
|
+
const { rows: counted } = await client.query("SELECT count(*)::int AS passed FROM plan_steps WHERE plan_id = $1", [planId]);
|
|
75
|
+
return stepIndex < Number(counted[0]?.passed ?? 0) ? "replayed" : "out_of_order";
|
|
76
|
+
},
|
|
77
|
+
});
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B,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,KAAK,CACjC;;qDAE6C,EAC7C,CAAC,MAAM,EAAE,SAAS,CAAC,CACpB,CAAC;YACF,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO,SAAkB,CAAC;YACjD,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,MAAM,MAAM,CAAC,KAAK,CAC1C,mEAAmE,EACnE,CAAC,MAAM,CAAC,CACT,CAAC;YACF,OAAO,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,CAAE,UAAoB,CAAC,CAAC,CAAE,cAAwB,CAAC;QACzG,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * `@buildanagent/agent-safety/stores/postgres`: the effect store and the plan ledger on Postgres, through any client\n * with a `query(text, values)` method that resolves to `{ rows }`, such as `pg`'s `Pool` or `Client` and PGlite. Every\n * change is one statement that Postgres runs atomically (`INSERT … ON CONFLICT`, or an `UPDATE … WHERE` on the\n * attempt), never a read followed by a write, so two processes can't both start one write.\n */\nimport type { EffectClaim, EffectRecord, EffectStore } from \"../effect-store.js\";\nimport type { PlanLedger } from \"../plan-approval.js\";\nimport { assertStepIndex } from \"../plan-ledger.js\";\nimport { lostClaim } from \"./lost-claim.js\";\n\n/** The part of a Postgres client these stores use. */\nexport interface PgClientLike {\n /** Runs one SQL statement with its `$1`, `$2` … placeholders bound to `values`, and resolves with its rows. */\n query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;\n}\n\n/** The statements that create the two tables. Run them once, as a migration or at deploy. */\nexport const POSTGRES_SCHEMA: readonly string[] = [\n `CREATE TABLE IF NOT EXISTS effect_records (\n key TEXT PRIMARY KEY,\n attempt INTEGER NOT NULL,\n state TEXT NOT NULL,\n record TEXT NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS plan_steps (\n plan_id TEXT NOT NULL,\n step_index INTEGER NOT NULL,\n PRIMARY KEY (plan_id, step_index)\n )`,\n];\n\n/** Creates the two tables if they are not there. */\nexport async function createPostgresTables(client: PgClientLike): Promise<void> {\n for (const statement of POSTGRES_SCHEMA) await client.query(statement);\n}\n\n// The record is stored as the JSON text it was written as, so a read gives back exactly what was stored: a JSONB column\n// would reorder an object's keys and normalise its numbers.\nfunction parse(value: unknown): EffectRecord {\n return JSON.parse(String(value)) as EffectRecord;\n}\n\n/**\n * An `EffectStore` on Postgres. Each record is one row: its key, the attempt and state that the conditions read, and\n * the record as JSON text. Run `POSTGRES_SCHEMA` first.\n */\nexport function postgresEffectStore(client: PgClientLike): EffectStore {\n const read = async (key: string): Promise<EffectRecord | undefined> => {\n const { rows } = await client.query(\"SELECT record FROM effect_records WHERE key = $1\", [key]);\n return rows[0] === undefined ? undefined : parse(rows[0].record);\n };\n const lost = async (key: string): Promise<EffectClaim> => lostClaim(key, await read(key));\n const values = (record: EffectRecord) => [record.key, record.attempt, record.state, JSON.stringify(record)];\n return {\n async begin(record) {\n const { rows } = await client.query(\n `INSERT INTO effect_records (key, attempt, state, record) VALUES ($1, $2, $3, $4)\n ON CONFLICT (key) DO NOTHING RETURNING key`,\n values(record),\n );\n return rows.length === 1 ? \"started\" : lost(record.key);\n },\n async takeOver(record) {\n const { rows } = await client.query(\n `INSERT INTO effect_records AS current (key, attempt, state, record) VALUES ($1, $2, $3, $4)\n ON CONFLICT (key) DO UPDATE SET attempt = EXCLUDED.attempt, state = EXCLUDED.state, record = EXCLUDED.record\n WHERE current.attempt = EXCLUDED.attempt - 1\n RETURNING key`,\n values(record),\n );\n return rows.length === 1 ? \"started\" : lost(record.key);\n },\n async settle(record) {\n const { rows } = await client.query(\n `UPDATE effect_records SET state = 'settled', record = $3\n WHERE key = $1 AND state = 'started' AND attempt = $2\n RETURNING key`,\n [record.key, record.attempt, JSON.stringify(record)],\n );\n return rows.length === 1;\n },\n get: read,\n };\n}\n\n/**\n * A `PlanLedger` on Postgres. A plan's claimed steps are rows `0` to `n - 1`, so a claim inserts its row only when the\n * row count equals its index, in one statement. Two claims of one step insert the same primary key, and one of them\n * loses, so a step is claimed once.\n */\nexport function postgresPlanLedger(client: PgClientLike): PlanLedger {\n return Object.freeze({\n async claim(planId: string, stepIndex: number) {\n assertStepIndex(stepIndex);\n const { rows } = await client.query(\n `INSERT INTO plan_steps (plan_id, step_index)\n SELECT $1::text, $2::int WHERE (SELECT count(*) FROM plan_steps WHERE plan_id = $1::text) = $2::int\n ON CONFLICT DO NOTHING RETURNING step_index`,\n [planId, stepIndex],\n );\n if (rows.length === 1) return \"claimed\" as const;\n const { rows: counted } = await client.query(\n \"SELECT count(*)::int AS passed FROM plan_steps WHERE plan_id = $1\",\n [planId],\n );\n return stepIndex < Number(counted[0]?.passed ?? 0) ? (\"replayed\" as const) : (\"out_of_order\" as const);\n },\n });\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fixed-key test signer, which `@buildanagent/agent-safety/testing` exports. It sits in its own file so the SDK
|
|
3
|
+
* can carry a copy of it without the `EffectStore` conformance cases.
|
|
4
|
+
*/
|
|
5
|
+
import { type ApprovalSigner } from "./signer.js";
|
|
6
|
+
/** The key id of `testSigner()`. */
|
|
7
|
+
export declare const TEST_KEY_ID = "test-fixed-key";
|
|
8
|
+
/**
|
|
9
|
+
* A signer with a fixed, published key, for tests and fixtures: every process produces the same signatures, so a
|
|
10
|
+
* signed pause can be checked into a test. Anyone can forge its signatures. Never use it outside tests, and never add
|
|
11
|
+
* its key id, `test-fixed-key`, to a real key ring.
|
|
12
|
+
*/
|
|
13
|
+
export declare function testSigner(): ApprovalSigner;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fixed-key test signer, which `@buildanagent/agent-safety/testing` exports. It sits in its own file so the SDK
|
|
3
|
+
* can carry a copy of it without the `EffectStore` conformance cases.
|
|
4
|
+
*/
|
|
5
|
+
import { hmacSigner } from "./signer.js";
|
|
6
|
+
/** The key id of `testSigner()`. */
|
|
7
|
+
export const TEST_KEY_ID = "test-fixed-key";
|
|
8
|
+
// Public on purpose: tests in any process, and fixtures checked into the repo, must produce the same signatures.
|
|
9
|
+
const TEST_KEY = new TextEncoder().encode("buildanagent testSigner fixed key, never for production");
|
|
10
|
+
/**
|
|
11
|
+
* A signer with a fixed, published key, for tests and fixtures: every process produces the same signatures, so a
|
|
12
|
+
* signed pause can be checked into a test. Anyone can forge its signatures. Never use it outside tests, and never add
|
|
13
|
+
* its key id, `test-fixed-key`, to a real key ring.
|
|
14
|
+
*/
|
|
15
|
+
export function testSigner() {
|
|
16
|
+
return hmacSigner({ keys: { [TEST_KEY_ID]: TEST_KEY }, current: TEST_KEY_ID });
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=test-signer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"test-signer.js","sourceRoot":"","sources":["../src/test-signer.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAuB,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9D,oCAAoC;AACpC,MAAM,CAAC,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAC5C,iHAAiH;AACjH,MAAM,QAAQ,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,yDAAyD,CAAC,CAAC;AAErG;;;;GAIG;AACH,MAAM,UAAU,UAAU;IACxB,OAAO,UAAU,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC;AACjF,CAAC","sourcesContent":["/**\n * The fixed-key test signer, which `@buildanagent/agent-safety/testing` exports. It sits in its own file so the SDK\n * can carry a copy of it without the `EffectStore` conformance cases.\n */\nimport { type ApprovalSigner, hmacSigner } from \"./signer.js\";\n\n/** The key id of `testSigner()`. */\nexport const TEST_KEY_ID = \"test-fixed-key\";\n// Public on purpose: tests in any process, and fixtures checked into the repo, must produce the same signatures.\nconst TEST_KEY = new TextEncoder().encode(\"buildanagent testSigner fixed key, never for production\");\n\n/**\n * A signer with a fixed, published key, for tests and fixtures: every process produces the same signatures, so a\n * signed pause can be checked into a test. Anyone can forge its signatures. Never use it outside tests, and never add\n * its key id, `test-fixed-key`, to a real key ring.\n */\nexport function testSigner(): ApprovalSigner {\n return hmacSigner({ keys: { [TEST_KEY_ID]: TEST_KEY }, current: TEST_KEY_ID });\n}\n"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@buildanagent/agent-safety/testing`: the fixed-key test signer and the conformance cases for `EffectStore` and
|
|
3
|
+
* `PlanLedger`. The signer has its own subpath, apart from the real signers, so code that imports the root entry can't
|
|
4
|
+
* reach a key anyone can forge.
|
|
5
|
+
*/
|
|
6
|
+
export { type EffectStoreCase, effectStoreConformance } from "./effect-store-conformance.js";
|
|
7
|
+
export { type PlanLedgerCase, planLedgerConformance } from "./plan-ledger-conformance.js";
|
|
8
|
+
export { TEST_KEY_ID, testSigner } from "./test-signer.js";
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@buildanagent/agent-safety/testing`: the fixed-key test signer and the conformance cases for `EffectStore` and
|
|
3
|
+
* `PlanLedger`. The signer has its own subpath, apart from the real signers, so code that imports the root entry can't
|
|
4
|
+
* reach a key anyone can forge.
|
|
5
|
+
*/
|
|
6
|
+
export { effectStoreConformance } from "./effect-store-conformance.js";
|
|
7
|
+
export { planLedgerConformance } from "./plan-ledger-conformance.js";
|
|
8
|
+
export { TEST_KEY_ID, testSigner } from "./test-signer.js";
|
|
9
|
+
//# sourceMappingURL=testing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"testing.js","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAwB,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAC7F,OAAO,EAAuB,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAC1F,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["/**\n * `@buildanagent/agent-safety/testing`: the fixed-key test signer and the conformance cases for `EffectStore` and\n * `PlanLedger`. The signer has its own subpath, apart from the real signers, so code that imports the root entry can't\n * reach a key anyone can forge.\n */\n\nexport { type EffectStoreCase, effectStoreConformance } from \"./effect-store-conformance.js\";\nexport { type PlanLedgerCase, planLedgerConformance } from \"./plan-ledger-conformance.js\";\nexport { TEST_KEY_ID, testSigner } from \"./test-signer.js\";\n"]}
|
package/llms.txt
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
# @buildanagent/agent-safety
|
|
2
|
+
|
|
3
|
+
> Safety core for buildanagent agents: typed write outcomes the model can read, a canonical input hash, signed approvals, model calls on the user's own key and a USD cap checked before each model call.
|
|
4
|
+
|
|
5
|
+
The sections of README.md and every public export, generated from this package's README and declaration files in the same commit as its code.
|
|
6
|
+
|
|
7
|
+
## Docs
|
|
8
|
+
|
|
9
|
+
- [Install the alpha with `pnpm add @buildanagent/agent-safety@alpha`](README.md#install-the-alpha-with-pnpm-add-buildanagentagent-safetyalpha)
|
|
10
|
+
- [A failed write reports one of five outcomes](README.md#a-failed-write-reports-one-of-five-outcomes)
|
|
11
|
+
- [Build an outcome with `writeOutcome()`](README.md#build-an-outcome-with-writeoutcome)
|
|
12
|
+
- [The model reads a sentence and a payload](README.md#the-model-reads-a-sentence-and-a-payload)
|
|
13
|
+
- [Use an outcome as an AI SDK tool result](README.md#use-an-outcome-as-an-ai-sdk-tool-result)
|
|
14
|
+
- [Hash a tool input with `canonicalInputHash()`](README.md#hash-a-tool-input-with-canonicalinputhash)
|
|
15
|
+
- [A write gets its identity before it runs, and a crash leaves it `unknown`](README.md#a-write-gets-its-identity-before-it-runs-and-a-crash-leaves-it-unknown)
|
|
16
|
+
- [Declare a business key for every tool that sends, submits, pays or deletes](README.md#declare-a-business-key-for-every-tool-that-sends-submits-pays-or-deletes)
|
|
17
|
+
- [Say how a retry finds the first attempt with `dedupe`](README.md#say-how-a-retry-finds-the-first-attempt-with-dedupe)
|
|
18
|
+
- [Keep effect records in a store that outlives the process](README.md#keep-effect-records-in-a-store-that-outlives-the-process)
|
|
19
|
+
- [Pick a durable store for the target: Durable Object SQLite, DynamoDB or Postgres](README.md#pick-a-durable-store-for-the-target-durable-object-sqlite-dynamodb-or-postgres)
|
|
20
|
+
- [On Cloudflare, repair an interrupted write as `unknown`](README.md#on-cloudflare-repair-an-interrupted-write-as-unknown)
|
|
21
|
+
- [An approved call runs only after its signed pause verifies](README.md#an-approved-call-runs-only-after-its-signed-pause-verifies)
|
|
22
|
+
- [`recheck` lets current policy stop an approved call](README.md#recheck-lets-current-policy-stop-an-approved-call)
|
|
23
|
+
- [Use a persistent key ring wherever a pause can resume in another process](README.md#use-a-persistent-key-ring-wherever-a-pause-can-resume-in-another-process)
|
|
24
|
+
- [Keep pending requests where the resume can find them](README.md#keep-pending-requests-where-the-resume-can-find-them)
|
|
25
|
+
- [On Cloudflare, settle denied approvals before the next turn](README.md#on-cloudflare-settle-denied-approvals-before-the-next-turn)
|
|
26
|
+
- [Sign and verify a pause without an SDK](README.md#sign-and-verify-a-pause-without-an-sdk)
|
|
27
|
+
- [One signed approval covers a whole plan whose pivot can't be undone](README.md#one-signed-approval-covers-a-whole-plan-whose-pivot-cant-be-undone)
|
|
28
|
+
- [Classify every step as compensable, the pivot, or retryable](README.md#classify-every-step-as-compensable-the-pivot-or-retryable)
|
|
29
|
+
- [List in `state` every value the plan's inputs were computed from](README.md#list-in-state-every-value-the-plans-inputs-were-computed-from)
|
|
30
|
+
- [Show the card, then sign the plan the person approved](README.md#show-the-card-then-sign-the-plan-the-person-approved)
|
|
31
|
+
- [Verify the approval before every step](README.md#verify-the-approval-before-every-step)
|
|
32
|
+
- [The ledger lets each step pass once, in order](README.md#the-ledger-lets-each-step-pass-once-in-order)
|
|
33
|
+
- [`runPlan()` runs the approved plan and says what is true afterwards](README.md#runplan-runs-the-approved-plan-and-says-what-is-true-afterwards)
|
|
34
|
+
- [Every model call carries the user's own key, or it fails](README.md#every-model-call-carries-the-users-own-key-or-it-fails)
|
|
35
|
+
- [`egressGuard()` checks each request on its way out](README.md#egressguard-checks-each-request-on-its-way-out)
|
|
36
|
+
- [An authenticated Cloudflare AI Gateway takes one more credential, set on purpose](README.md#an-authenticated-cloudflare-ai-gateway-takes-one-more-credential-set-on-purpose)
|
|
37
|
+
- [Run model calls through Cloudflare AI Gateway with `byok_only`, never through Vercel AI Gateway](README.md#run-model-calls-through-cloudflare-ai-gateway-with-byok_only-never-through-vercel-ai-gateway)
|
|
38
|
+
- [A model call that could pass the USD cap is never sent](README.md#a-model-call-that-could-pass-the-usd-cap-is-never-sent)
|
|
39
|
+
- [Cap each run with a fresh `Spend`, and the session with a shared one](README.md#cap-each-run-with-a-fresh-spend-and-the-session-with-a-shared-one)
|
|
40
|
+
- [The root entry loads without any third-party SDK](README.md#the-root-entry-loads-without-any-third-party-sdk)
|
|
41
|
+
|
|
42
|
+
## Exports from `@buildanagent/agent-safety`
|
|
43
|
+
|
|
44
|
+
- `ALLOWED_RETRIES`: The retry rules each kind allows, as `AllowedRetry` lists them.
|
|
45
|
+
- `interface AllowedRetry`: The retry rules each outcome kind allows.
|
|
46
|
+
- `interface ApprovalSigner`: Signs and verifies the payload of a pending request.
|
|
47
|
+
- `canonicalInputHash()`: Hashes a tool input: the SHA-256 of its canonical JSON (RFC 8785), as 64 lowercase hex digits.
|
|
48
|
+
- `checkModelRoutes()`: Checks the model routes a deploy configures and reports every problem, so a deploy gate can fail on any of them.
|
|
49
|
+
- `CLOUDFLARE_AI_GATEWAY_HOST`: The host of Cloudflare AI Gateway's provider endpoints, as in `https://gateway.ai.cloudflare.com/v1/…`.
|
|
50
|
+
- `CLOUDFLARE_GATEWAY_TOKEN_HEADER`: The header that carries the token of a Cloudflare AI Gateway with authentication turned on.
|
|
51
|
+
- `CLOUDFLARE_NO_WHOLESALE_HEADER`: The header that tells Cloudflare AI Gateway never to bill a request to Cloudflare's own credentials.
|
|
52
|
+
- `interface CloudflareAiGatewaySettings`: The Cloudflare AI Gateway settings a route through that gateway must record.
|
|
53
|
+
- `CREDENTIAL_HEADERS`: Headers that carry a credential for some model provider or gateway.
|
|
54
|
+
- `type CredentialHeader`: The header that carries a provider's key: `x-api-key` for Anthropic, `authorization` for OpenAI.
|
|
55
|
+
- `DEFAULT_RETRY`: The retry rule each kind gets when the tool sets none: a rejected write may run again with the same key, an undone one only as a new operation, a partial one goes to a person, and an unknown one is checked first.
|
|
56
|
+
- `type EffectClaim`: What `begin()` and `takeOver()` return: `"started"` if the caller now holds the record, or the record that won.
|
|
57
|
+
- `effectKey()`: Returns the effect key of a write, as 64 lowercase hex digits.
|
|
58
|
+
- `interface EffectRecord`: One write's entry in the effects ledger.
|
|
59
|
+
- `interface EffectScope`: Where a write was asked for: the tenant, the session and branch of the conversation, and the model's tool call.
|
|
60
|
+
- `interface EffectStore`: Stores effect records by key.
|
|
61
|
+
- `interface EgressCredential`: The one credential a guarded request must carry.
|
|
62
|
+
- `egressGuard()`: Wraps `fetch` so a model request leaves only for `baseURL` and only with `credential`.
|
|
63
|
+
- `interface EgressGuardOptions`: The options of `egressGuard()`.
|
|
64
|
+
- `ephemeralSigner()`: A signer whose key is random and lives only in this process: every call in one process returns the same signer, and no other process can verify what it signs.
|
|
65
|
+
- `guardedWrite()`: Runs a write at most once per effect key.
|
|
66
|
+
- `interface GuardedWriteOptions`: The options of `guardedWrite()`.
|
|
67
|
+
- `hmacSigner()`: A signer over a key ring, for any host where a pause may resume in another process: it signs with the key named `current` and verifies with any key in `keys`.
|
|
68
|
+
- `interface HmacSignerOptions`: The options of `hmacSigner()`: every key the signer may verify with, by id, and the id of the one it signs with.
|
|
69
|
+
- `isSafetyError()`: True for a `SafetyError`, including one from another copy of the package.
|
|
70
|
+
- `interface KeyRing`: A key ring: every key a signer may verify with, by id, and the id of the key that signs.
|
|
71
|
+
- `interface KeyStore`: A host's key ring store.
|
|
72
|
+
- `lintPlan()`: Checks the order of a plan's steps: every compensable step comes before the pivot, a plan has at most one pivot, and every retryable step comes after it, so a plan without a pivot holds compensable steps only.
|
|
73
|
+
- `memoryEffectStore()`: An `EffectStore` in this process's memory, for tests and single-process hosts.
|
|
74
|
+
- `memoryPendingStore()`: A `PendingStore` in this process's memory, for tests and single-process hosts.
|
|
75
|
+
- `interface MemoryPendingStoreOptions`: The options of `memoryPendingStore()`.
|
|
76
|
+
- `memoryPlanLedger()`: A `PlanLedger` that keeps each plan's progress in memory, for tests and single-process hosts.
|
|
77
|
+
- `MIN_KEY_BYTES`: The shortest key `hmacSigner()` accepts: one SHA-256 output, the length RFC 2104 recommends as the minimum.
|
|
78
|
+
- `MODEL_ROUTE_SETTINGS_AS_OF`: The date of the gateway documentation the checker's setting names come from: Cloudflare AI Gateway's Unified Billing page (`byok_only`, "Require provider credentials") and Vercel AI Gateway's BYOK page ("Fallback to Vercel Keys").
|
|
79
|
+
- `interface ModelRoute`: One model route a deploy configures: which provider, at which base URL, and the gateway's settings if it has one.
|
|
80
|
+
- `interface ModelRouteProblem`: One reason a configuration failed.
|
|
81
|
+
- `type ModelRouteProblemCode`: Why a configuration failed.
|
|
82
|
+
- `type ModelRouteProvider`: The providers a model route may name.
|
|
83
|
+
- `interface ModelRoutesConfig`: The model routes a deploy step produces, which `checkModelRoutes()` reads.
|
|
84
|
+
- `interface ModelRoutesReport`: What `checkModelRoutes()` found.
|
|
85
|
+
- `OUTCOME_KINDS`: The five outcome kinds, in the order the docs list them.
|
|
86
|
+
- `interface OutcomeFields`: The fields every write outcome carries, whatever its kind.
|
|
87
|
+
- `type OutcomeKind`: What a write did.
|
|
88
|
+
- `type OutcomePayload`: The structured half of a rendered outcome: the outcome's own fields, as plain JSON.
|
|
89
|
+
- `parseKeyRing()`: Reads a key ring from JSON text such as a secret's value: `{"current":"2026-11","keys":{"2026-11":"<key>"}}`, where each key is base64url without padding.
|
|
90
|
+
- `interface PendingCall`: The call a host is about to run, which a pending request must match before it runs.
|
|
91
|
+
- `interface PendingFields`: The fields `signPending()` signs and stores, with the call's input in place of its hash.
|
|
92
|
+
- `pendingPayload()`: The bytes a pending request's signature covers: a JSON array of a fixed tag, then the request id, kind, call id, tool name, input hash and policy version, in that order, with `null` for an absent policy version.
|
|
93
|
+
- `interface PendingStore`: Holds signed pending requests by call id.
|
|
94
|
+
- `interface PlanApproval`: A signed plan approval.
|
|
95
|
+
- `planCard()`: Builds the approval card for a plan, from the same fields you will pass to `signPlan()` once the person approves.
|
|
96
|
+
- `interface PlanCard`: The approval card's payload: the steps in the order they run, the pivot's id, and the state the plan read.
|
|
97
|
+
- `interface PlanCardStep`: One step as the approval card shows it.
|
|
98
|
+
- `type PlanFailureReason`: Why a plan that began could not finish.
|
|
99
|
+
- `interface PlanFields`: The plan a person approved: its steps, the state it was computed from, and how long the approval lasts.
|
|
100
|
+
- `interface PlanLedger`: Records which steps of each plan have passed verification.
|
|
101
|
+
- `type PlanLint`: What `lintPlan()` returns: `ok`, or every problem it found with the order of the steps.
|
|
102
|
+
- `type PlanOutcome`: What a plan did, computed by the harness and never by the model.
|
|
103
|
+
- `type PlanScope`: Where a plan runs: the tenant, session and branch its writes are keyed under.
|
|
104
|
+
- `interface PlanStep`: One signed step of a plan: its tool and the hash of its exact input, with a summary for the approval card.
|
|
105
|
+
- `interface PlanStepCall`: The step a host is about to run, as it has the step now, not as the approval records it.
|
|
106
|
+
- `type PlanStepCheck`: What `verifyPlanBeforeStep()` found.
|
|
107
|
+
- `interface PlanStepImpl`: One signed step as the host runs it: the step, its exact input and the calls that perform and undo it.
|
|
108
|
+
- `interface PlanStepInit`: A step as the host plans it, with its input in place of the input's hash.
|
|
109
|
+
- `planWriteOutcome()`: The write outcome a plan outcome stands for, in the five kinds the model already reads: `completed` is `applied`, `failed_compensated` is `compensated`, `failed_needs_human` is `partial`, `pending` is `unknown`, and the three statuses that mean no step ran are `not_applied`.
|
|
110
|
+
- `type Recheck`: Runs current policy for an approved call just before it runs, after its pending request has verified.
|
|
111
|
+
- `type RejectionCause`: Why `verifyResolution()` refused.
|
|
112
|
+
- `interface RenderedOutcome`: A write outcome as the model reads it.
|
|
113
|
+
- `renderOutcome()`: Renders a write outcome for the model: sentences that name what happened, what to do next and what not to do, the outcome's fields as a JSON payload, and whether the provider's error flag should be set.
|
|
114
|
+
- `renderPlanOutcome()`: Renders a plan outcome for the model: `planWriteOutcome()` through `renderOutcome()`.
|
|
115
|
+
- `type Resolution`: A person's answer to a pending request: allow or deny for an approval, an answer for a clarification.
|
|
116
|
+
- `type ResolutionCheck`: What `verifyResolution()` returns: the resolution, once every check passed, or why it refused.
|
|
117
|
+
- `type Retry`: When the same write may run again.
|
|
118
|
+
- `runPlan()`: Runs the approved plan, in order, and reports what is true afterwards.
|
|
119
|
+
- `interface RunPlanOptions`: The options of `runPlan()`.
|
|
120
|
+
- `class SafetyError`: Thrown for a mistake in how the safety package is called, and, as its subclass `BudgetExceeded`, for a model call refused under a USD cap.
|
|
121
|
+
- `type SafetyErrorCode`: Why a `SafetyError` was thrown.
|
|
122
|
+
- `interface SignedPendingRequest`: A pause waiting for a person: an approval of one tool call, or a question about it.
|
|
123
|
+
- `signerFromKeyStore()`: Loads the ring from `store` and returns `hmacSigner()` over it.
|
|
124
|
+
- `signPending()`: Signs a pending request for a tool call.
|
|
125
|
+
- `interface SignPendingOptions`: Where `signPending()` takes its request id and time from.
|
|
126
|
+
- `signPlan()`: Signs a plan approval.
|
|
127
|
+
- `interface SignPlanOptions`: Where `signPlan()` takes its plan id and time from.
|
|
128
|
+
- `stateHash()`: Hashes the values a plan was computed from: the SHA-256 of the canonical JSON (RFC 8785) of each value with its source and key, in order, under a fixed tag, as 64 lowercase hex digits.
|
|
129
|
+
- `interface StateRead`: A value the plan was computed from: where to read it, and under which key.
|
|
130
|
+
- `interface StateValue`: A value the plan read, with where it was read from.
|
|
131
|
+
- `type StepClass`: How a step behaves if the plan fails.
|
|
132
|
+
- `verifyPlanBeforeStep()`: Checks a plan approval before one of its steps runs, failing closed.
|
|
133
|
+
- `interface VerifyPlanStepOptions`: The options of `verifyPlanBeforeStep()`.
|
|
134
|
+
- `verifyResolution()`: Checks a resolution against its stored pending request before the call runs, failing closed.
|
|
135
|
+
- `interface VerifyResolutionOptions`: The options of `verifyResolution()`.
|
|
136
|
+
- `type WriteDedupe`: How a retry can find out what an earlier attempt of the write did.
|
|
137
|
+
- `writeOutcome()`: Builds a write outcome, filling in the defaults and checking every field.
|
|
138
|
+
- `type WriteOutcome`: What a write reports: one of the five kinds, with its retry rule and what the model should do next.
|
|
139
|
+
- `type WriteOutcomeInit`: The input to `writeOutcome()`.
|
|
140
|
+
- `type WriteOutcomeOf`: A write outcome of one kind, whose `retry` is one of the rules that kind allows.
|
|
141
|
+
|
|
142
|
+
## Exports from `@buildanagent/agent-safety/ai`
|
|
143
|
+
|
|
144
|
+
- `interface ApprovalRejection`: What `onRejected` receives when an approved call is denied.
|
|
145
|
+
- `type ApprovalRejectionCause`: Why `signedToolApproval()` denied an approved call: one of `verifyResolution()`'s causes, `unknown_request` when the store holds no pending request for the call, `policy_denied` when current policy or `recheck` said no, or `error` when a step threw.
|
|
146
|
+
- `repairInterruptedWrite()`: Returns `part` settled as `output-available` with an `unknown` write outcome as its output, if its tool is one of `writes` and `execute` may have started, or `undefined` for any other tool or a part still streaming its input or awaiting approval, so the caller keeps the default repair for those.
|
|
147
|
+
- `settleDeniedApprovals()`: Returns `messages` with every tool part whose call id is in `denied`, and whose state is still `approval-responded`, moved to `output-denied` with its approval marked `approved: false`, as `ai`'s UI message types and validator require for that state.
|
|
148
|
+
- `signedToolApproval()`: Wraps an approval policy so every approval is signed, fails closed on resume, and is checked against current policy before the approved call runs.
|
|
149
|
+
- `interface SignedToolApprovalOptions`: The options of `signedToolApproval()`.
|
|
150
|
+
- `toAiToolResult()`: Turns a write outcome into the result the model reads, for use as a tool's `toModelOutput`.
|
|
151
|
+
|
|
152
|
+
## Exports from `@buildanagent/agent-safety/byok`
|
|
153
|
+
|
|
154
|
+
- `assertNoDefaultProvider()`: Makes every string model id fail with a `SafetyError`, code `default_provider`, before any request.
|
|
155
|
+
- `explicitProvider()`: Builds an Anthropic provider on the user's key and base URL alone.
|
|
156
|
+
- `type ExplicitProviderName`: The providers `explicitProvider()` builds.
|
|
157
|
+
- `interface ExplicitProviderOptions`: The options of `explicitProvider()`.
|
|
158
|
+
|
|
159
|
+
## Exports from `@buildanagent/agent-safety/cost`
|
|
160
|
+
|
|
161
|
+
- `class BudgetExceeded`: Thrown by a cost guard instead of sending a model call.
|
|
162
|
+
- `budgetRefusal()`: The `BudgetExceeded` behind an error from `generateText`, `streamText` or an agent, or `undefined` when the error isn't a budget refusal.
|
|
163
|
+
- `type BudgetRefusalCode`: Why a call was refused: its projection would pass the cap, or its price is unknown, so the cap can't be checked.
|
|
164
|
+
- `interface BudgetRefusalInit`: What a refusal reports.
|
|
165
|
+
- `costGuard()`: A language-model middleware that caps what calls through it may spend.
|
|
166
|
+
- `interface CostGuardOptions`: Options for `costGuard()`.
|
|
167
|
+
- `interface FileRef`: A file a request points at, by URL or by provider reference, so the request holds none of its bytes.
|
|
168
|
+
- `type FileSize`: What the caller knows of a file's size: its bytes, or its pages.
|
|
169
|
+
- `type FileSizer`: Looks up the size of a file a request points at, or returns `undefined` when it isn't known.
|
|
170
|
+
- `type GuardableModel`: A language model the AI SDK accepts: a `LanguageModelV4`, `LanguageModelV3` or `LanguageModelV2`.
|
|
171
|
+
- `type GuardableProvider`: A provider the AI SDK accepts: a `ProviderV4`, `ProviderV3` or `ProviderV2`.
|
|
172
|
+
- `interface GuardedCall`: One call the guard let through, reported once its cost is known.
|
|
173
|
+
- `guardedModel()`: One model with `guards` around it, through the AI SDK's `wrapLanguageModel()`.
|
|
174
|
+
- `type GuardedModel`: A language model wrapped in guards: a `LanguageModelV4`.
|
|
175
|
+
- `guardedProvider()`: The provider with `guards` around each language model it returns, through the AI SDK's `wrapProvider()`.
|
|
176
|
+
- `type GuardedProvider`: A provider whose language models all run through the guards: a `ProviderV4`.
|
|
177
|
+
- `memorySpend()`: A `Spend` held in memory, starting at `initialUsd`, which lasts as long as the object does.
|
|
178
|
+
- `interface Spend`: The USD a run or session has spent on model calls so far.
|
|
179
|
+
|
|
180
|
+
## Exports from `@buildanagent/agent-safety/agents`
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
## Exports from `@buildanagent/agent-safety/stores/cloudflare`
|
|
184
|
+
|
|
185
|
+
- `createCloudflareTables()`: Creates the two tables if they are not there, as every store of this module needs; call it once per object.
|
|
186
|
+
- `durableObjectEffectStore()`: An `EffectStore` on Durable Object SQLite.
|
|
187
|
+
- `durableObjectPlanLedger()`: A `PlanLedger` on Durable Object SQLite.
|
|
188
|
+
- `interface SqlCursorLike`: What a query returns here: the rows, and `RETURNING` makes the written ones count.
|
|
189
|
+
- `interface SqlStorageLike`: The part of `SqlStorage` (`ctx.storage.sql`) these stores use.
|
|
190
|
+
|
|
191
|
+
## Exports from `@buildanagent/agent-safety/stores/postgres`
|
|
192
|
+
|
|
193
|
+
- `createPostgresTables()`: Creates the two tables if they are not there.
|
|
194
|
+
- `interface PgClientLike`: The part of a Postgres client these stores use.
|
|
195
|
+
- `POSTGRES_SCHEMA`: The statements that create the two tables.
|
|
196
|
+
- `postgresEffectStore()`: An `EffectStore` on Postgres.
|
|
197
|
+
- `postgresPlanLedger()`: A `PlanLedger` on Postgres.
|
|
198
|
+
|
|
199
|
+
## Exports from `@buildanagent/agent-safety/stores/dynamodb`
|
|
200
|
+
|
|
201
|
+
- `dynamoEffectStore()`: An `EffectStore` on DynamoDB.
|
|
202
|
+
- `dynamoPlanLedger()`: A `PlanLedger` on DynamoDB.
|
|
203
|
+
- `interface DynamoStoreOptions`: The options of the DynamoDB stores.
|
|
204
|
+
|
|
205
|
+
## Exports from `@buildanagent/agent-safety/testing`
|
|
206
|
+
|
|
207
|
+
- `interface EffectStoreCase`: One conformance case: a name a test runner can show, and a check that rejects if the store breaks the rule.
|
|
208
|
+
- `effectStoreConformance()`: The cases every `EffectStore` must pass.
|
|
209
|
+
- `interface PlanLedgerCase`: One conformance case: a name a test runner can show, and a check that rejects if the ledger breaks the rule.
|
|
210
|
+
- `planLedgerConformance()`: The cases every `PlanLedger` must pass.
|
|
211
|
+
- `TEST_KEY_ID`: The key id of `testSigner()`.
|
|
212
|
+
- `testSigner()`: A signer with a fixed, published key, for tests and fixtures: every process produces the same signatures, so a signed pause can be checked into a test.
|
package/package.json
CHANGED
|
@@ -1,7 +1,110 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@buildanagent/agent-safety",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
5
|
-
"license": "
|
|
6
|
-
"
|
|
7
|
-
|
|
3
|
+
"version": "0.1.0-alpha.28",
|
|
4
|
+
"description": "Safety core for buildanagent agents: typed write outcomes the model can read, a canonical input hash, signed approvals, model calls on the user's own key and a USD cap checked before each model call.",
|
|
5
|
+
"license": "Apache-2.0 OR MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/laudebugs/buildanagent.git",
|
|
9
|
+
"directory": "packages/agent-safety"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/laudebugs/buildanagent/tree/main/packages/agent-safety#readme",
|
|
12
|
+
"type": "module",
|
|
13
|
+
"sideEffects": false,
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=22"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"llms.txt",
|
|
20
|
+
"LICENSE",
|
|
21
|
+
"LICENSE-APACHE",
|
|
22
|
+
"LICENSE-MIT"
|
|
23
|
+
],
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"default": "./dist/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./ai": {
|
|
30
|
+
"types": "./dist/ai/index.d.ts",
|
|
31
|
+
"default": "./dist/ai/index.js"
|
|
32
|
+
},
|
|
33
|
+
"./byok": {
|
|
34
|
+
"types": "./dist/byok/index.d.ts",
|
|
35
|
+
"default": "./dist/byok/index.js"
|
|
36
|
+
},
|
|
37
|
+
"./cost": {
|
|
38
|
+
"types": "./dist/cost/index.d.ts",
|
|
39
|
+
"default": "./dist/cost/index.js"
|
|
40
|
+
},
|
|
41
|
+
"./agents": {
|
|
42
|
+
"types": "./dist/agents/index.d.ts",
|
|
43
|
+
"default": "./dist/agents/index.js"
|
|
44
|
+
},
|
|
45
|
+
"./stores/cloudflare": {
|
|
46
|
+
"types": "./dist/stores/cloudflare.d.ts",
|
|
47
|
+
"default": "./dist/stores/cloudflare.js"
|
|
48
|
+
},
|
|
49
|
+
"./stores/postgres": {
|
|
50
|
+
"types": "./dist/stores/postgres.d.ts",
|
|
51
|
+
"default": "./dist/stores/postgres.js"
|
|
52
|
+
},
|
|
53
|
+
"./stores/dynamodb": {
|
|
54
|
+
"types": "./dist/stores/dynamodb.d.ts",
|
|
55
|
+
"default": "./dist/stores/dynamodb.js"
|
|
56
|
+
},
|
|
57
|
+
"./testing": {
|
|
58
|
+
"types": "./dist/testing.d.ts",
|
|
59
|
+
"default": "./dist/testing.js"
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
"dependencies": {
|
|
63
|
+
"@buildanagent/gateway": "0.1.0-alpha.28"
|
|
64
|
+
},
|
|
65
|
+
"peerDependencies": {
|
|
66
|
+
"@ai-sdk/anthropic": "4.0.96",
|
|
67
|
+
"@ai-sdk/openai": "4.0.108",
|
|
68
|
+
"@ai-sdk/provider-utils": "5.0.74",
|
|
69
|
+
"ai": "7.0.162",
|
|
70
|
+
"@aws-sdk/client-dynamodb": "3.1169.0"
|
|
71
|
+
},
|
|
72
|
+
"peerDependenciesMeta": {
|
|
73
|
+
"@ai-sdk/anthropic": {
|
|
74
|
+
"optional": true
|
|
75
|
+
},
|
|
76
|
+
"@ai-sdk/openai": {
|
|
77
|
+
"optional": true
|
|
78
|
+
},
|
|
79
|
+
"@ai-sdk/provider-utils": {
|
|
80
|
+
"optional": true
|
|
81
|
+
},
|
|
82
|
+
"ai": {
|
|
83
|
+
"optional": true
|
|
84
|
+
},
|
|
85
|
+
"@aws-sdk/client-dynamodb": {
|
|
86
|
+
"optional": true
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
"devDependencies": {
|
|
90
|
+
"@ai-sdk/anthropic": "4.0.96",
|
|
91
|
+
"@ai-sdk/openai": "4.0.108",
|
|
92
|
+
"@ai-sdk/provider": "4.0.35",
|
|
93
|
+
"@ai-sdk/provider-utils": "5.0.74",
|
|
94
|
+
"@aws-sdk/client-dynamodb": "3.1169.0",
|
|
95
|
+
"@cloudflare/ai-chat": "0.12.2",
|
|
96
|
+
"@cloudflare/think": "0.23.0",
|
|
97
|
+
"@cloudflare/workers-types": "5.20261103.1",
|
|
98
|
+
"@electric-sql/pglite": "0.5.16",
|
|
99
|
+
"agents": "0.33.0",
|
|
100
|
+
"ai": "7.0.162",
|
|
101
|
+
"esbuild": "0.28.2",
|
|
102
|
+
"miniflare": "5.20261103.0-beta",
|
|
103
|
+
"zod": "4.6.7"
|
|
104
|
+
},
|
|
105
|
+
"scripts": {
|
|
106
|
+
"build": "node ../../scripts/clean-dist.mjs && tsc -p tsconfig.build.json",
|
|
107
|
+
"typecheck": "tsc -p tsconfig.json && tsc -p test/workerd/tsconfig.json",
|
|
108
|
+
"test": "vitest run"
|
|
109
|
+
}
|
|
110
|
+
}
|