diff --git a/README.md b/README.md index 928a1f8f..e51ce13d 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ Codemode is a Bun workspace. It was called runline through 0.45; see [Migrate fr | [`packages/codemode-node`](packages/codemode-node) | The `node` plugin as a package, published as `@shiftlabs/codemode-node` | | [`packages/codemode-websearch`](packages/codemode-websearch) | The `websearch` plugin as a package, published as `@shiftlabs/codemode-websearch` | | [`packages/codemode-imagegen`](packages/codemode-imagegen) | The `imagegen` plugin as a package, published as `@shiftlabs/codemode-imagegen` | +| [`packages/codemode-decision`](packages/codemode-decision) | The `decision` plugin as a package, published as `@shiftlabs/codemode-decision` | | [`packages/package-tests`](packages/package-tests) | What the tests of those packages share. Not published | | [`packages/runline`](packages/runline) | The `runline` package on npm, which forwards to codemode until 0.48.0 | diff --git a/bun.lock b/bun.lock index 38c06156..2f2378c3 100644 --- a/bun.lock +++ b/bun.lock @@ -67,6 +67,21 @@ "@shiftlabs/codemode": ">0.46.0", }, }, + "packages/codemode-decision": { + "name": "@shiftlabs/codemode-decision", + "version": "0.1.0", + "devDependencies": { + "@shiftlabs/codemode": "workspace:*", + "@types/bun": "^1.2.17", + "@types/node": "^25.5.0", + "typebox": "^1.1.35", + "typescript": "^5.8.0", + }, + "peerDependencies": { + "@shiftlabs/codemode": ">0.46.0", + "typebox": "*", + }, + }, "packages/codemode-duckdb": { "name": "@shiftlabs/codemode-duckdb", "version": "0.1.0", @@ -300,6 +315,8 @@ "@shiftlabs/codemode-bash": ["@shiftlabs/codemode-bash@workspace:packages/codemode-bash"], + "@shiftlabs/codemode-decision": ["@shiftlabs/codemode-decision@workspace:packages/codemode-decision"], + "@shiftlabs/codemode-duckdb": ["@shiftlabs/codemode-duckdb@workspace:packages/codemode-duckdb"], "@shiftlabs/codemode-imagegen": ["@shiftlabs/codemode-imagegen@workspace:packages/codemode-imagegen"], diff --git a/docs/bundled-plugins.md b/docs/bundled-plugins.md index 596ae6ab..a9d5002e 100644 --- a/docs/bundled-plugins.md +++ b/docs/bundled-plugins.md @@ -2,7 +2,7 @@ Codemode ships with plugins for SaaS, DevOps, productivity, and image-generation APIs. They are part of the `codemode` package and need no installation. -Host capabilities are separate packages to install: [`codemode-node`](../packages/codemode-node/README.md) for Node.js scripts, [`codemode-bash`](../packages/codemode-bash/README.md) and [`codemode-powershell`](../packages/codemode-powershell/README.md) for commands, and [`codemode-duckdb`](../packages/codemode-duckdb/README.md) for SQL. Web search across providers is the [`codemode-websearch`](../packages/codemode-websearch/README.md) package, and image generation across providers is [`codemode-imagegen`](../packages/codemode-imagegen/README.md). +Host capabilities are separate packages to install: [`codemode-node`](../packages/codemode-node/README.md) for Node.js scripts, [`codemode-bash`](../packages/codemode-bash/README.md) and [`codemode-powershell`](../packages/codemode-powershell/README.md) for commands, and [`codemode-duckdb`](../packages/codemode-duckdb/README.md) for SQL. Web search across providers is the [`codemode-websearch`](../packages/codemode-websearch/README.md) package, image generation across providers is [`codemode-imagegen`](../packages/codemode-imagegen/README.md), and decision models across providers are [`codemode-decision`](../packages/codemode-decision/README.md). A bundled plugin becomes available to `codemode exec` once it has a connection. The last column lists each required connection field and, in parentheses, the environment variable that can supply it: diff --git a/docs/credentials.md b/docs/credentials.md index b218358d..56bf07ff 100644 --- a/docs/credentials.md +++ b/docs/credentials.md @@ -67,6 +67,7 @@ Find what the API requires in the first column: | One token or key, in `Authorization: Bearer`, a named header, a query parameter, or Basic auth | `staticCredential` with `bearer`, `apiKey`, `queryKey` or `basic` | [A key or token](#a-key-or-token) | | Several values (a key and a secret, a token per API), or a secret in the path, the body, a signed JWT, an HMAC of the query | `staticCredential` with `kind: "static"` | [Several parts](#several-parts-or-an-unusual-placement) | | A key that is optional: the API answers without one, with lower limits | `staticCredential({ …, optional: true })` | [An optional key](#an-optional-key) | +| Several providers behind one plugin, each with a key of its own | `routerCredential`, with `routerConnectionFields`, `namedProvider` and `keyedProviders` | [A key per provider](#a-key-per-provider) | | A host the user configures (self-hosted, a subdomain, a region) | `targets` as a function of config, with `httpsBase`, `hostLabel`, `configChoice` | [A host from config](#a-host-from-config) | | OAuth where a person consents in a browser, then a refresh token | an `oauth2` declaration, `renewal: "refresh"`, plus `setOAuth` | [OAuth with consent](#oauth-with-a-persons-consent) | | OAuth with no person: client credentials, a username and password, a service account's JWT | an `oauth2` declaration, `renewal: "clientCredentials"`, `"password"` or `"jwtBearer"` | [OAuth without a person](#oauth-without-a-person) | @@ -202,6 +203,30 @@ staticCredential({ `optional: true` adds a `none` method that sends requests unsigned, held to the same targets. A connection signs when it holds the `local` fields (the CLI), or when its public config says `authenticated: true` (a host that stores the key). Use `optional: { targets: { … } }` when the provider serves unsigned requests from different hosts. +### A key per provider + +A plugin that routes to one of several providers declares one credential for all of them with `routerCredential`: + + +```typescript +const PROVIDERS = [ + { name: "acme", env: "ACME_API_KEY", key: { header: "Authorization", prefix: "Bearer " } }, + { name: "globex", env: "GLOBEX_API_KEY", key: { query: "api_key" } }, +]; +const BASES: Record = { + acme: "https://api.acme.example/v1/", + globex: "https://api.globex.example/", +}; + +const credential = routerCredential("acmeOrGlobex", PROVIDERS, ({ name }) => ({ + [name]: { baseUrl: BASES[name], methods: ["GET"] }, +})); +``` + +Each provider's key is a part of its own, optional, and placed only on that provider's targets, so a connection holds the keys it has and a key is sent to its own provider alone. A provider's key is the connection field `ApiKey`. + +The connection chooses the provider. `routerConnectionFields(PROVIDERS, description)` gives the connection schema its `provider` field and a key field per provider, each filled from the provider's `env`. In an action, `namedProvider(plugin, PROVIDERS, config, !ctx.credentials)` answers the provider the connection names, or nothing, and `keyedProviders(plugin, kind, PROVIDERS, config)` answers those it holds a key for, in order. Both reject with what to set when the connection has no key to use. + ### A host from config When a connection names its host, `targets` is a function of config, and the config values pass through a helper that refuses anything that could send the secret elsewhere: diff --git a/packages/codemode-decision/README.md b/packages/codemode-decision/README.md new file mode 100644 index 00000000..c65fd4eb --- /dev/null +++ b/packages/codemode-decision/README.md @@ -0,0 +1,207 @@ +# codemode-decision + +A [codemode](../../README.md) package with one plugin, `decision`, that asks a decision model questions through the provider you have a key for. + +A decision model returns typed answers with probabilities instead of text: how likely a yes, one of a set of options, or a place on a scale. It answers much faster than a chat model, for classifying, routing and scoring inside code. Code calls `decision.ask` the same way whichever provider answers, and never names a provider: the connection chooses it. + +## Install + +Install the package and set the key of one provider: + +```bash +codemode install npm:@shiftlabs/codemode-decision +export OPENAI_API_KEY=... +``` + +It needs a codemode newer than 0.46.0. + +## Ask questions + +`decision.ask` takes the evidence as `input` and the questions under names you choose, and returns an answer under each name: + +```bash +codemode exec 'return await decision.ask({ + input: "I was charged twice for my order. Please refund one.", + questions: { + refund: { type: "yesNo", instructions: "Does the customer ask for a refund?" }, + department: { + type: "choice", + instructions: "Which department should handle this?", + options: [ + { value: "billing", description: "Payments, invoices and refunds." }, + { value: "technical", description: "Problems using the product." }, + { value: "other", description: "Anything else." }, + ], + }, + severity: { + type: "score", + instructions: "How severe is this for the customer?", + levels: [ + { label: "Minor", description: "An annoyance; nothing is lost." }, + { label: "Costly", description: "Money or time is lost." }, + { label: "Blocked", description: "The customer cannot use the product." }, + ], + }, + }, +})' +``` + +```json +{ + "provider": "openai", + "model": "gpt-6-luna", + "inputTokens": 96, + "answers": { + "refund": { "type": "yesNo", "probability": 0.97 }, + "department": { + "type": "choice", + "choice": "billing", + "confidence": 0.93, + "probabilities": [ + { "value": "billing", "probability": 0.95 }, + { "value": "technical", "probability": 0.02 }, + { "value": "other", "probability": 0.03 } + ] + }, + "severity": { + "type": "score", + "score": 1.1, + "confidence": 0.55, + "probabilities": [ + { "level": 0, "label": "Minor", "probability": 0.1 }, + { "level": 1, "label": "Costly", "probability": 0.7 }, + { "level": 2, "label": "Blocked", "probability": 0.2 } + ] + } + } +} +``` + +| Input | Form | Meaning | +|---|---|---| +| `input` | Text, or a JSON object | What every question is about. Needed unless `images` is set | +| `images` | 1 to 8 paths of PNG or JPEG files | Images that are part of what every question is about | +| `questions` | An object of 1 to 400 questions | Each question, under the name its answer comes back under | + +Every question is answered on its own: one answer is no input to another. Ask a question that depends on an answer in a second call. + +## Choose a question type + +Each question has a `type` and `instructions`, which say what to decide: + +| Type | Also takes | Answer | +|---|---|---| +| `yesNo` | Nothing | `probability`: how likely the answer is yes, from 0 to 1 | +| `choice` | `options`: 2 to 255 of `{ value, description? }`, with different values | `choice`: one option's value, with `confidence` and every option's probability | +| `score` | `levels`: 2 to 10 of `{ label, description? }`, from the lowest to the highest | `score`: the probability-weighted average of the levels' positions, from 0, with `confidence` and every level's probability | + +A `score` can fall between levels: 1.1 is a little above the second level. Use `choice` for options with no order. + +A model can decline a question. Its answer is then `{ "type": "refusal" }`, and the other questions are still answered. + +## Act on an answer + +Compare a probability with a threshold you choose, by what a wrong answer costs: + +```js +const { answers } = await decision.ask({ input: ticket, questions }); +if (answers.refund.type === "yesNo" && answers.refund.probability > 0.7) await refund(ticket); +if (answers.department.type === "choice" && answers.department.confidence < 0.5) await review(ticket); +``` + +`confidence` is the provider's own summary of how settled a `choice` or `score` answer is, from 0 to 1. Each provider calculates it its own way, so tune a threshold against the provider and model the connection uses, and keep to them. + +## Send images + +`images` takes paths of image files on the codemode host. They are part of the evidence, beside `input` or in place of it: + +```js +await decision.ask({ + input: "A photo of a returned product.", + images: ["/data/returns/4471.jpg"], + questions: { damaged: { type: "yesNo", instructions: "Is the product in the image visibly damaged?" } }, +}); +``` + +What a file is, its bytes say: one that is no PNG or JPEG is refused, whatever its name. A file is at most 16 MiB. + +## Choose a provider + +The connection chooses the provider, and the action has no input for it. A request goes to the connection's `provider` when it names one, else to the first provider in this table that has a key: + +| Provider | Key | Default model | Images | +|---|---|---|---| +| `openai` | `OPENAI_API_KEY` | `gpt-6-luna` | No bounds documented | +| `typesafe` | `TYPESAFE_API_KEY` | `jev-latest` | Each side from 280 to 1568 pixels | + +The result's `provider` and `model` say which answered. `model` is the version that answered, which can differ from an alias such as `jev-latest`. + +## Configure the connection + +Add a connection to keep keys in codemode, or to choose the provider and its model. Every field is optional: + +```bash +codemode connection add decision --plugin decision --set provider=typesafe --set model=jev-1.14.0 +``` + +| Field | Meaning | +|---|---| +| `provider` | The provider every request goes to. The default is the first with a key | +| `model` | The model every request uses. The default is the provider's | +| `ApiKey` | The provider's key, such as `openaiApiKey`. The default is its environment variable | + +An alias moves to a new version when one is released, and answers can change with it. Set `model` to a version once thresholds are tuned against it. + +Each key is declared with the one address that may receive it. A request to one provider sends no other provider's key. + +## Add a provider + +A host that embeds codemode builds the plugin from its own list of providers. A provider is its key's place in a request, its address, its default model, and two functions: the request a decision becomes, and the answers in its response, in the questions' order: + +```typescript +import { Codemode } from "@shiftlabs/codemode"; +import { type DecisionProvider, decision, PROVIDERS } from "@shiftlabs/codemode-decision"; + +const acme: DecisionProvider = { + name: "acme", + env: "ACME_DECISION_KEY", + key: { header: "X-Acme-Key" }, + baseUrl: "https://decide.acme.example/", + path: "ask", + model: "acme-1", + request: ({ model, input, questions }) => ({ json: { model, input, questions } }), + answers: (response, { questions }) => ({ + model: "acme-1", + answers: questions.map(({ name }) => ({ + type: "yesNo", + probability: (response as Record)[name], + })), + }), +}; + +const codemode = Codemode.create({ plugins: [decision([acme, ...PROVIDERS])] }); +``` + +The list's order is the order a provider is chosen in. The package is TypeScript source, so the host imports it with a runtime that runs TypeScript, such as Bun. + +## Handle failures + +| Outcome | Result | +|---|---| +| No provider has a key | The call rejects and names the environment variables | +| A question has fields that are not its type's, or two options with one value | The call rejects and names the question | +| A file in `images` is not a PNG or JPEG image, or is a size the provider does not take | The call rejects before any request is made | +| The provider refuses the request | The call rejects with `decision.: request failed (HTTP )` | +| The provider answers a question with nothing that reads | The call rejects and names the question | +| The model declines a question | The call resolves, and that answer is `{ "type": "refusal" }` | + +A provider's error text is not included in the message, because it can repeat the key it was sent. + +## Understand the limits + +- The action has what both providers do. Locating something in an image, a conversation as input, and an image inside one question are not in it. +- The bundled `typesafe` plugin is separate from this package, with its own connection. It reaches what only TypeSafe has. +- TypeSafe calls its image input not yet ready for production. A request with images turns it on. +- A request that is too long for the model is refused by the provider. TypeSafe's long context is not turned on. +- A request is not retried. A provider that is over its rate limit answers HTTP 429. +- A request to a provider is not ended when the run ends. diff --git a/packages/codemode-decision/package.json b/packages/codemode-decision/package.json new file mode 100644 index 00000000..28d17085 --- /dev/null +++ b/packages/codemode-decision/package.json @@ -0,0 +1,49 @@ +{ + "name": "@shiftlabs/codemode-decision", + "version": "0.1.0", + "description": "Ask a decision model yes-or-no, choice and score questions from codemode, whichever provider you have a key for", + "type": "module", + "keywords": [ + "codemode-plugin", + "decision-model", + "classification", + "scoring", + "openai", + "typesafe" + ], + "codemode": { + "plugins": [ + "./src/index.ts" + ] + }, + "files": [ + "src", + "README.md" + ], + "scripts": { + "test": "bun test tests", + "typecheck": "tsc --noEmit -p ." + }, + "repository": { + "type": "git", + "url": "git+https://github.com/shift-labs-ai/codemode.git", + "directory": "packages/codemode-decision" + }, + "homepage": "https://github.com/shift-labs-ai/codemode/tree/main/packages/codemode-decision#readme", + "bugs": { + "url": "https://github.com/shift-labs-ai/codemode/issues" + }, + "license": "MIT", + "peerDependencies": { + "@shiftlabs/codemode": ">0.46.0", + "typebox": "*" + }, + "devDependencies": { + "@shiftlabs/codemode": "workspace:*", + "@types/bun": "^1.2.17", + "@types/node": "^25.5.0", + "typebox": "^1.1.35", + "typescript": "^5.8.0" + }, + "exports": "./src/index.ts" +} diff --git a/packages/codemode-decision/src/index.ts b/packages/codemode-decision/src/index.ts new file mode 100644 index 00000000..7d3396f3 --- /dev/null +++ b/packages/codemode-decision/src/index.ts @@ -0,0 +1,350 @@ +/** + * Decision models for codemode: ask yes-or-no, choice and score questions + * about some evidence and get typed answers with probabilities, through the + * provider the connection chooses. Code never names a provider. + * + * const { answers } = await decision.ask({ + * input: "I was charged twice for my order.", + * questions: { refund: { type: "yesNo", instructions: "Does the customer ask for a refund?" } }, + * }) + * // answers.refund -> { type: "yesNo", probability: 0.97 } + * + * A connection holds a key per provider. Each key is declared with the one + * address that may receive it, so a request to one provider sends no other + * provider's key. + */ + +import { + type ActionContext, + type CodemodePluginAPI, + credentialJson, + keyedProviders, + type LocalImage, + namedProvider, + type PluginFunction, + readLocalImage, + routerConnectionFields, + routerCredential, +} from "@shiftlabs/codemode"; +import { packageVersion } from "@shiftlabs/codemode/utils/cli"; +import * as t from "typebox"; +import { PROVIDERS } from "./providers.js"; +import type { DecisionProvider, Question } from "./types.js"; + +export * from "./providers.js"; +export * from "./types.js"; + +const NAME = "decision"; +/** The most questions every provider takes in one request. */ +const MAX_QUESTIONS = 400; +const MIN_OPTIONS = 2; +const MAX_OPTIONS = 255; +const MIN_LEVELS = 2; +const MAX_LEVELS = 10; +const MAX_IMAGES = 8; +/** The largest image file every provider takes. */ +const MAX_IMAGE_BYTES = 16 * 1024 * 1024; +/** The types of image every provider takes. */ +const IMAGE_TYPES = ["image/png", "image/jpeg"]; +const TIMEOUT_MS = 60_000; + +const text = (description: string) => t.String({ minLength: 1, description }); + +const question = t.Object( + { + type: t.String({ + enum: ["yesNo", "choice", "score"], + description: + "yesNo: how likely the answer is yes. choice: one of options. score: a place on the scale of levels", + }), + instructions: text( + "What to decide about the input, as a question or a statement. Ask about one thing that can be observed", + ), + options: t.Optional( + t.Array( + t.Object( + { + value: text( + "The value the answer returns. A meaningful label, such as billing", + ), + description: t.Optional(text("When this option applies")), + }, + { additionalProperties: false }, + ), + { + minItems: MIN_OPTIONS, + maxItems: MAX_OPTIONS, + description: `For choice: ${MIN_OPTIONS} to ${MAX_OPTIONS} options with different values. Add one such as other when the options may not cover every input`, + }, + ), + ), + levels: t.Optional( + t.Array( + t.Object( + { + label: text("A short name for the level, such as Fully blocked"), + description: t.Optional(text("What puts the input at this level")), + }, + { additionalProperties: false }, + ), + { + minItems: MIN_LEVELS, + maxItems: MAX_LEVELS, + description: `For score: ${MIN_LEVELS} to ${MAX_LEVELS} levels, from the lowest to the highest`, + }, + ), + ), + }, + { additionalProperties: false }, +); + +type QuestionInput = t.Static; + +/** A question as the providers receive it, or an error that says what its type takes. */ +function asked(name: string, input: QuestionInput): Question { + if (!name.trim()) throw new Error(`${NAME}: a question has no name.`); + const { instructions, options, levels } = input; + const needs = (field: "options" | "levels" | undefined) => { + for (const other of ["options", "levels"] as const) + if (other !== field && input[other]) + throw new Error( + `${NAME}: question ${JSON.stringify(name)} is a ${input.type} question, which takes no ${other}.`, + ); + if (field && !input[field]) + throw new Error( + `${NAME}: question ${JSON.stringify(name)} is a ${input.type} question, which needs ${field}.`, + ); + }; + if (input.type === "choice") { + needs("options"); + const values = (options ?? []).map(({ value }) => value); + const repeated = values.find( + (value, index) => values.indexOf(value) !== index, + ); + if (repeated !== undefined) + throw new Error( + `${NAME}: question ${JSON.stringify(name)} has the option ${JSON.stringify(repeated)} twice.`, + ); + return { type: "choice", name, instructions, options: options ?? [] }; + } + if (input.type === "score") { + needs("levels"); + return { type: "score", name, instructions, levels: levels ?? [] }; + } + needs(undefined); + return { type: "yesNo", name, instructions }; +} + +const probability = { type: "number", minimum: 0, maximum: 1 }; + +/** + * The `decision` plugin over `providers`, in the order one is chosen when + * the connection names none. A host adds a provider of its own by passing a + * list that includes it. + */ +export function decision( + providers: DecisionProvider[] = PROVIDERS, +): PluginFunction { + const credential = routerCredential( + "codemodeDecision", + providers, + ({ name, baseUrl, headers }) => ({ + [name]: { + baseUrl, + methods: ["POST"], + ...(headers ? { allowedHeaders: headers } : {}), + timeoutMs: TIMEOUT_MS, + }, + }), + ); + + /** + * The provider a request goes to. The connection decides, never the call: + * its `provider` when it names one, else the first provider it has a key + * for. + */ + function chosen(ctx: ActionContext): DecisionProvider { + const { config } = ctx.connection; + return ( + namedProvider(NAME, providers, config, !ctx.credentials) ?? + keyedProviders(NAME, "decision", providers, config)[0] + ); + } + + /** Read an image of the evidence, and refuse one the provider's model does not take. */ + async function evidence( + provider: DecisionProvider, + path: string, + ): Promise { + const image = await readLocalImage(path, { + subject: `${NAME}: ${path}`, + maxBytes: MAX_IMAGE_BYTES, + types: IMAGE_TYPES, + }); + const sides = provider.imageSides; + const { width, height } = image; + if ( + sides && + width !== undefined && + height !== undefined && + (Math.min(width, height) < sides.min || + Math.max(width, height) > sides.max) + ) + throw new Error( + `${NAME}: ${path} is ${width}x${height} pixels. Resize it so each side is from ${sides.min} to ${sides.max} pixels.`, + ); + return image; + } + + return function plugin(rl: CodemodePluginAPI): void { + rl.setName(NAME); + rl.setVersion(packageVersion(import.meta.url)); + rl.setDescription( + "Ask a decision model yes-or-no, choice and score questions, and get typed answers with probabilities.", + ); + rl.setCredential(credential); + rl.setConnectionSchema( + t.Object({ + ...routerConnectionFields( + providers, + "The provider every request goes to. The default is the first provider with a key", + ), + model: t.Optional( + t.String({ + minLength: 1, + description: + "The model every request uses. The default is the provider's", + }), + ), + }), + ); + + rl.registerAction("ask", { + access: "read", + description: + "Ask questions about some text, JSON or images and get a typed answer with probabilities for each: how likely a yes, one of a set of options, or a place on a scale. For classifying, routing and scoring, in one fast call. Billed by the provider.", + hints: { openWorld: true }, + inputSchema: t.Object( + { + input: t.Optional( + t.Union( + [t.String({ minLength: 1 }), t.Record(t.String(), t.Unknown())], + { + description: + "What every question is about: text, or a JSON object of named fields. Needed unless images is set", + }, + ), + ), + images: t.Optional( + t.Array(t.String({ minLength: 1 }), { + minItems: 1, + maxItems: MAX_IMAGES, + description: `Paths of 1 to ${MAX_IMAGES} image files (PNG or JPEG) that are part of what every question is about`, + }), + ), + questions: t.Record(t.String(), question, { + minProperties: 1, + maxProperties: MAX_QUESTIONS, + description: `1 to ${MAX_QUESTIONS} questions, each under the name its answer comes back under. Each is answered on its own: one answer is no input to another`, + }), + }, + { additionalProperties: false }, + ), + outputSchema: { + type: "object", + properties: { + provider: { type: "string" }, + model: { type: "string" }, + inputTokens: { type: "integer" }, + answers: { + type: "object", + description: "An answer for each question, under its name", + additionalProperties: { + type: "object", + properties: { + type: { + type: "string", + enum: ["yesNo", "choice", "score", "refusal"], + }, + probability, + choice: { type: "string" }, + score: { type: "number" }, + confidence: probability, + probabilities: { + type: "array", + items: { + type: "object", + properties: { + value: { type: "string" }, + level: { type: "integer" }, + label: { type: "string" }, + probability, + }, + required: ["probability"], + }, + }, + }, + required: ["type"], + }, + }, + }, + required: ["provider", "model", "answers"], + }, + async execute(input, ctx) { + if (input.input === undefined && !input.images) + throw new Error(`${NAME}: set input, images, or both.`); + const questions = Object.entries(input.questions).map(([name, one]) => + asked(name, one), + ); + const provider = chosen(ctx); + const configured = ctx.connection.config.model; + const images = await Promise.all( + (input.images ?? []).map((path) => evidence(provider, path)), + ); + const request = { + model: + typeof configured === "string" && configured + ? configured + : provider.model, + input: input.input, + images, + questions, + }; + const { json, headers } = provider.request(request); + const response = await credentialJson( + ctx, + credential, + `${NAME}.${provider.name}`, + { + target: provider.name, + path: provider.path, + method: "POST", + json, + ...(headers ? { headers } : {}), + }, + ); + const { model, answers, inputTokens } = provider.answers( + response, + request, + ); + return { + provider: provider.name, + model: model || request.model, + ...(inputTokens === undefined ? {} : { inputTokens }), + answers: Object.fromEntries( + questions.map(({ name }, index) => { + const answer = answers[index]; + if (!answer) + throw new Error( + `${NAME}: ${provider.name} answered nothing that reads for question ${JSON.stringify(name)}.`, + ); + return [name, answer]; + }), + ), + }; + }, + }); + }; +} + +export default decision(); diff --git a/packages/codemode-decision/src/providers.ts b/packages/codemode-decision/src/providers.ts new file mode 100644 index 00000000..5234e721 --- /dev/null +++ b/packages/codemode-decision/src/providers.ts @@ -0,0 +1,253 @@ +/** + * The providers of decision models: for each, where its key goes, the + * request a decision becomes, and how its response reads as answers. A + * provider is data and two functions; the plugin sends the request. + */ + +import { randomUUID } from "node:crypto"; +import { imageBase64, imageDataUrl } from "@shiftlabs/codemode"; +import type { Answer, Answered, DecisionProvider, Question } from "./types.js"; + +type Json = Record; + +function object(value: unknown): Json { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Json) + : {}; +} + +function number(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) + ? value + : undefined; +} + +/** + * A choice or score answer over `probabilities`, one for each option or + * level in the question's order, or nothing when a number it needs is not + * there. + */ +function distributed( + question: Question, + answer: Json, + probability: (index: number) => unknown, +): Answer | undefined { + const confidence = number(answer.confidence); + if (confidence === undefined) return undefined; + if (question.type === "choice") { + const probabilities = question.options.map(({ value }, index) => ({ + value, + probability: number(probability(index)) ?? 0, + })); + return typeof answer.choice === "string" + ? { type: "choice", choice: answer.choice, confidence, probabilities } + : undefined; + } + if (question.type === "score") { + const score = number(answer.score); + const probabilities = question.levels.map(({ label }, level) => ({ + level, + label, + probability: number(probability(level)) ?? 0, + })); + return score === undefined + ? undefined + : { type: "score", score, confidence, probabilities }; + } + return undefined; +} + +/** + * OpenAI's Decisions API. Questions are a list, each with its name, and the + * answers come back in the same order. Evidence is a string, or one user + * message of text, JSON and image parts. + */ +export const openai: DecisionProvider = { + name: "openai", + env: "OPENAI_API_KEY", + key: { header: "Authorization", prefix: "Bearer " }, + baseUrl: "https://api.openai.com/v1/", + path: "decisions", + model: "gpt-6-luna", + request({ model, input, images, questions }) { + const parts = [ + ...(typeof input === "string" + ? [{ type: "input_text", text: input }] + : input + ? [{ type: "input_json", data: input }] + : []), + ...images.map((image) => ({ + type: "input_image", + image_url: imageDataUrl(image), + })), + ]; + return { + json: { + model, + input: + typeof input === "string" && !images.length + ? input + : [{ role: "user", content: parts }], + questions: questions.map((question) => { + const { name, instructions } = question; + if (question.type === "choice") + return { + type: "choice", + name, + instructions, + choices: question.options, + }; + if (question.type === "score") + return { + type: "score", + name, + instructions, + levels: question.levels, + }; + return { type: "predicate", name, instructions }; + }), + }, + }; + }, + answers(response, { questions }): Answered { + const body = object(response); + const answers = Array.isArray(body.answers) ? body.answers : []; + return { + model: typeof body.model === "string" ? body.model : "", + inputTokens: number(object(body.usage).input_tokens), + answers: questions.map((question, index): Answer | undefined => { + const answer = object(answers[index]); + if (answer.type === "refusal") return { type: "refusal" }; + if (question.type === "yesNo") { + const probability = number(answer.probability); + return answer.type === "predicate" && probability !== undefined + ? { type: "yesNo", probability } + : undefined; + } + if (answer.type !== question.type) return undefined; + // Each probability names its option's value, or its level's position. + const listed = Array.isArray(answer.probabilities) + ? answer.probabilities.map(object) + : []; + return distributed(question, answer, (index) => { + const key = + question.type === "choice" ? question.options[index].value : index; + return listed.find((one) => one.value === key)?.probability; + }); + }), + }; + }, +}; + +/** + * TypeSafe's System One API. Questions and answers are objects keyed by the + * question's name; a choice's options and a score's levels are its + * `criteria`. An image is an asset, and stands wherever its reference is + * written in the state. + */ +export const typesafe: DecisionProvider = { + name: "typesafe", + env: "TYPESAFE_API_KEY", + key: { header: "Authorization", prefix: "Bearer " }, + baseUrl: "https://api.typesafe.ai/v1/", + path: "systemone", + model: "jev-latest", + imageSides: { min: 280, max: 1568 }, + headers: ["TypeSafe-Danger-Zone-Images"], + request({ model, input, images, questions }) { + // A reference stands for its image wherever it is written, so each is one no text holds by accident. + const assets = images.map((image) => ({ + reference: randomUUID(), + asset: { + type: "image", + format: image.mimeType === "image/png" ? "png" : "jpg", + data_base64: imageBase64(image), + }, + })); + return { + json: { + model, + state: assets.length + ? { + ...(input === undefined ? {} : { input }), + images: assets.map(({ reference }) => reference), + } + : input, + questions: Object.fromEntries( + questions.map((question) => { + const { name, instructions } = question; + if (question.type === "choice") + return [ + name, + { + type: "choice", + instructions, + criteria: Object.fromEntries( + question.options.map(({ value, description }) => [ + value, + description ?? null, + ]), + ), + }, + ]; + if (question.type === "score") + return [ + name, + { + type: "score", + instructions, + criteria: question.levels.map(({ label, description }) => + description ? `${label}: ${description}` : label, + ), + }, + ]; + return [name, { type: "noul", instructions }]; + }), + ), + ...(assets.length + ? { + assets: Object.fromEntries( + assets.map(({ reference, asset }) => [reference, asset]), + ), + } + : {}), + }, + ...(assets.length + ? { headers: { "TypeSafe-Danger-Zone-Images": "true" } } + : {}), + }; + }, + answers(response, { questions }): Answered { + const body = object(response); + const answers = object(body.answers); + return { + model: typeof body.model === "string" ? body.model : "", + inputTokens: number(object(body.usage).input_tokens), + answers: questions.map((question): Answer | undefined => { + const answer = object(answers[question.name]); + if (question.type === "yesNo") { + const probability = number(answer.noul); + return answer.type === "noul" && probability !== undefined + ? { type: "yesNo", probability } + : undefined; + } + if (answer.type !== question.type) return undefined; + // Probabilities are keyed by the option's value, or the level's position. + const probabilities = object(answer.probabilities); + return distributed( + question, + answer, + (index) => + probabilities[ + question.type === "choice" + ? question.options[index].value + : String(index) + ], + ); + }), + }; + }, +}; + +/** Every provider, in the order one is chosen when the connection names none. */ +export const PROVIDERS: DecisionProvider[] = [openai, typesafe]; diff --git a/packages/codemode-decision/src/types.ts b/packages/codemode-decision/src/types.ts new file mode 100644 index 00000000..01193b8c --- /dev/null +++ b/packages/codemode-decision/src/types.ts @@ -0,0 +1,95 @@ +/** + * What a decision is to the plugin, whichever provider answers: evidence, + * questions of three types about it, and a typed answer with probabilities + * for each. And what a provider of decision models is. + */ + +import type { LocalImage, RoutedProvider } from "@shiftlabs/codemode"; + +/** One of the values a choice question selects among. */ +export interface Option { + value: string; + /** When the option applies. An option without one is read by its value alone. */ + description?: string; +} + +/** One level of a score question's scale. */ +export interface Level { + label: string; + /** What puts the evidence at this level. */ + description?: string; +} + +/** A question about the evidence, by the name its answer comes back under. */ +export type Question = { name: string; instructions: string } & ( + | { type: "yesNo" } + | { type: "choice"; options: Option[] } + | { type: "score"; levels: Level[] } +); + +/** One request for decisions, the same for every provider. */ +export interface Decision { + model: string; + /** The evidence every question is about: text, or a JSON object. */ + input?: string | Record; + /** Images that are part of the evidence, in order. */ + images: LocalImage[]; + questions: Question[]; +} + +/** The answer to one question. */ +export type Answer = + /** How likely the answer is yes, from 0 to 1. */ + | { type: "yesNo"; probability: number } + | { + type: "choice"; + /** The option's value. */ + choice: string; + confidence: number; + /** Every option's probability, in the question's order. */ + probabilities: Array<{ value: string; probability: number }>; + } + | { + type: "score"; + /** The probability-weighted average of the levels' positions, from 0. It can fall between levels. */ + score: number; + confidence: number; + /** Every level's probability, from the lowest level. */ + probabilities: Array<{ + level: number; + label: string; + probability: number; + }>; + } + /** The model declined to answer this question. */ + | { type: "refusal" }; + +/** What a provider answered for one request. */ +export interface Answered { + /** The model that answered, which can be a version of the one asked for. */ + model: string; + /** An answer for each question, in the questions' order, or nothing where the provider gave none that reads. */ + answers: Array; + inputTokens?: number; +} + +/** A decision API: where it is, where its key goes, and how a decision reads to and from it. */ +export interface DecisionProvider extends RoutedProvider { + /** The HTTPS address the key may be sent beneath, ending in `/`. */ + baseUrl: string; + /** The path of the decision endpoint beneath `baseUrl`. */ + path: string; + /** The model a request uses when the connection names none. */ + model: string; + /** The least and most pixels it takes on each side of an image. */ + imageSides?: { min: number; max: number }; + /** The request a decision becomes: its JSON body, and any headers beside the key's. */ + request(decision: Decision): { + json: unknown; + headers?: Record; + }; + /** The headers `request` may set. */ + headers?: string[]; + /** The answers in the provider's response to `decision`. */ + answers(response: unknown, decision: Decision): Answered; +} diff --git a/packages/codemode-decision/tests/decision.test.ts b/packages/codemode-decision/tests/decision.test.ts new file mode 100644 index 00000000..0a0d65d2 --- /dev/null +++ b/packages/codemode-decision/tests/decision.test.ts @@ -0,0 +1,647 @@ +/** + * The decision package: its action through a real engine with the + * providers' hosts stood in for, and the package as codemode's package + * manager loads it. + */ + +import assert from "node:assert/strict"; +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { afterEach, describe, it } from "node:test"; +import { fileURLToPath } from "node:url"; +import { png } from "../../codemode/src/tests/helpers/image.js"; +import { stubFetch } from "../../codemode/src/tests/helpers/plugin.js"; +import { describePackage, pluginHarness } from "../../package-tests/harness.js"; +import decisionPlugin, { + type DecisionProvider, + decision, + PROVIDERS, +} from "../src/index.js"; + +const PACKAGE = fileURLToPath(new URL("..", import.meta.url)); + +interface Sent { + url: string; + headers: Record; + body: Record; +} + +const originalFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +/** Answer every request with `answer`, and collect what was sent. */ +function serve(answer: unknown, status = 200): Sent[] { + const all: Sent[] = []; + stubFetch(async (url, init) => { + all.push({ + url: String(url), + headers: Object.fromEntries(new Headers(init?.headers)), + body: JSON.parse(Buffer.from(init?.body as Uint8Array).toString()), + }); + return Response.json(answer, { status }); + }); + return all; +} + +const harness = pluginHarness(decisionPlugin, "decision"); + +/** A connection with a key for every provider. */ +const ALL_KEYS = Object.fromEntries( + PROVIDERS.map(({ name }) => [`${name}ApiKey`, `KEY-${name}`]), +); +/** A connection with a key for every provider, whose provider is `name`. */ +const through = (name: string) => ({ ...ALL_KEYS, provider: name }); + +async function run( + input: Record, + config: Record, +) { + return harness + .codemode(config) + .execute(`return await decision.ask(${JSON.stringify(input)})`); +} + +async function ask>( + input: Record, + config: Record, +): Promise { + const { result, error } = await run(input, config); + assert.equal(error, undefined); + return result as T; +} + +async function refused( + input: Record, + config: Record, +): Promise { + const { error } = await run(input, config); + assert.ok(error, "the call should fail"); + return error.split("\n")[0]; +} + +function image(name: string, width = 640, height = 480): string { + const path = join(harness.tmp, name); + writeFileSync(path, png(width, height)); + return path; +} + +const TICKET = "I was charged twice for my order."; +/** One question of each type. */ +const QUESTIONS = { + refund: { + type: "yesNo", + instructions: "Does the customer ask for a refund?", + }, + department: { + type: "choice", + instructions: "Which department should handle this?", + options: [ + { value: "billing", description: "Payments, invoices and refunds." }, + { value: "technical" }, + ], + }, + severity: { + type: "score", + instructions: "How severe is this?", + levels: [ + { label: "Cosmetic", description: "Appearance only." }, + { label: "Blocked" }, + ], + }, +}; +/** What both providers' answers below read as. */ +const ANSWERS = { + refund: { type: "yesNo", probability: 0.9 }, + department: { + type: "choice", + choice: "billing", + confidence: 0.8, + probabilities: [ + { value: "billing", probability: 0.95 }, + { value: "technical", probability: 0.05 }, + ], + }, + severity: { + type: "score", + score: 0.7, + confidence: 0.4, + probabilities: [ + { level: 0, label: "Cosmetic", probability: 0.3 }, + { level: 1, label: "Blocked", probability: 0.7 }, + ], + }, +}; + +const OPENAI_ANSWER = { + model: "gpt-6-luna", + answers: [ + { type: "predicate", name: "refund", probability: 0.9 }, + { + type: "choice", + name: "department", + choice: "billing", + confidence: 0.8, + probabilities: [ + { value: "technical", probability: 0.05 }, + { value: "billing", probability: 0.95 }, + ], + }, + { + type: "score", + name: "severity", + score: 0.7, + confidence: 0.4, + probabilities: [ + { value: 0, label: "Cosmetic", probability: 0.3 }, + { value: 1, label: "Blocked", probability: 0.7 }, + ], + }, + ], + usage: { input_tokens: 42, output_tokens: 0 }, +}; +const TYPESAFE_ANSWER = { + model: "jev-1.14.0", + answers: { + severity: { + type: "score", + score: 0.7, + confidence: 0.4, + legend: { "0": "Cosmetic: Appearance only.", "1": "Blocked" }, + probabilities: { "0": 0.3, "1": 0.7 }, + }, + refund: { type: "noul", noul: 0.9 }, + department: { + type: "choice", + choice: "billing", + confidence: 0.8, + probabilities: { billing: 0.95, technical: 0.05 }, + }, + }, + usage: { input_tokens: 120, output_tokens: 12 }, +}; + +describe("decision.ask through each provider", () => { + it("openai: sends its API's request with its own key alone, and reads its answers", async () => { + const sent = serve(OPENAI_ANSWER); + const result = await ask( + { input: TICKET, questions: QUESTIONS }, + through("openai"), + ); + assert.equal(sent.length, 1); + assert.equal(sent[0].url, "https://api.openai.com/v1/decisions"); + assert.equal(sent[0].headers.authorization, "Bearer KEY-openai"); + assert.ok(!JSON.stringify(sent).includes("KEY-typesafe")); + assert.deepEqual(sent[0].body, { + model: "gpt-6-luna", + input: TICKET, + questions: [ + { + type: "predicate", + name: "refund", + instructions: "Does the customer ask for a refund?", + }, + { + type: "choice", + name: "department", + instructions: "Which department should handle this?", + choices: [ + { + value: "billing", + description: "Payments, invoices and refunds.", + }, + { value: "technical" }, + ], + }, + { + type: "score", + name: "severity", + instructions: "How severe is this?", + levels: [ + { label: "Cosmetic", description: "Appearance only." }, + { label: "Blocked" }, + ], + }, + ], + }); + assert.deepEqual(result, { + provider: "openai", + model: "gpt-6-luna", + inputTokens: 42, + answers: ANSWERS, + }); + }); + + it("typesafe: sends its API's request with its own key alone, and reads the same answers", async () => { + const sent = serve(TYPESAFE_ANSWER); + const result = await ask( + { input: TICKET, questions: QUESTIONS }, + through("typesafe"), + ); + assert.equal(sent[0].url, "https://api.typesafe.ai/v1/systemone"); + assert.equal(sent[0].headers.authorization, "Bearer KEY-typesafe"); + assert.equal(sent[0].headers["typesafe-danger-zone-images"], undefined); + assert.ok(!JSON.stringify(sent).includes("KEY-openai")); + assert.deepEqual(sent[0].body, { + model: "jev-latest", + state: TICKET, + questions: { + refund: { + type: "noul", + instructions: "Does the customer ask for a refund?", + }, + department: { + type: "choice", + instructions: "Which department should handle this?", + criteria: { + billing: "Payments, invoices and refunds.", + technical: null, + }, + }, + severity: { + type: "score", + instructions: "How severe is this?", + criteria: ["Cosmetic: Appearance only.", "Blocked"], + }, + }, + }); + assert.deepEqual(result, { + provider: "typesafe", + // The version that answered, not the alias that was asked for. + model: "jev-1.14.0", + inputTokens: 120, + answers: ANSWERS, + }); + }); + + it("sends a JSON object as each provider takes structured evidence", async () => { + const order = { ticket: { body: TICKET }, order: { charges: [49, 49] } }; + const questions = { refund: QUESTIONS.refund }; + const openai = serve({ answers: [OPENAI_ANSWER.answers[0]] }); + await ask({ input: order, questions }, through("openai")); + assert.deepEqual(openai[0].body.input, [ + { role: "user", content: [{ type: "input_json", data: order }] }, + ]); + const typesafe = serve({ answers: { refund: { type: "noul", noul: 1 } } }); + await ask({ input: order, questions }, through("typesafe")); + assert.deepEqual(typesafe[0].body.state, order); + }); + + it("answers a refusal as an answer, beside the questions that were answered", async () => { + serve({ + model: "gpt-6-luna", + answers: [{ type: "refusal", name: "refund" }, OPENAI_ANSWER.answers[1]], + }); + const { answers } = await ask<{ answers: Record }>( + { + input: TICKET, + questions: { + refund: QUESTIONS.refund, + department: QUESTIONS.department, + }, + }, + through("openai"), + ); + assert.deepEqual(answers, { + refund: { type: "refusal" }, + department: ANSWERS.department, + }); + }); +}); + +describe("images", () => { + const questions = { + damaged: { type: "yesNo", instructions: "Is it damaged?" }, + }; + const dataUrl = `data:image/png;base64,${png(640, 480).toString("base64")}`; + + it("openai: go beside the input, as parts of one message", async () => { + const sent = serve({ answers: [{ type: "predicate", probability: 0.2 }] }); + await ask( + { input: "Inspect the product.", images: [image("a.png")], questions }, + through("openai"), + ); + assert.deepEqual(sent[0].body.input, [ + { + role: "user", + content: [ + { type: "input_text", text: "Inspect the product." }, + { type: "input_image", image_url: dataUrl }, + ], + }, + ]); + await ask({ images: [image("a.png")], questions }, through("openai")); + assert.deepEqual(sent[1].body.input, [ + { role: "user", content: [{ type: "input_image", image_url: dataUrl }] }, + ]); + }); + + it("typesafe: are assets the state refers to, with images turned on", async () => { + const sent = serve({ answers: { damaged: { type: "noul", noul: 0.2 } } }); + await ask( + { + input: "Inspect the product.", + images: [image("a.png"), image("b.png")], + questions, + }, + through("typesafe"), + ); + const { state, assets } = sent[0].body as { + state: { input: string; images: string[] }; + assets: Record; + }; + assert.equal(sent[0].headers["typesafe-danger-zone-images"], "true"); + assert.equal(state.input, "Inspect the product."); + assert.equal(new Set(state.images).size, 2); + assert.deepEqual(Object.keys(assets), state.images); + assert.deepEqual(assets[state.images[0]], { + type: "image", + format: "png", + data_base64: png(640, 480).toString("base64"), + }); + }); + + it("are refused before any request when a file is no PNG or JPEG, or is a size the provider does not take", async () => { + const sent = serve({}); + const gif = join(harness.tmp, "anim.png"); + writeFileSync( + gif, + Buffer.concat([Buffer.from("GIF89a"), Buffer.alloc(20)]), + ); + assert.match( + await refused({ images: [gif], questions }, through("openai")), + /anim\.png is not a PNG or JPEG image\./, + ); + assert.match( + await refused( + { images: [image("small.png", 200, 400)], questions }, + through("typesafe"), + ), + /small\.png is 200x400 pixels\. Resize it so each side is from 280 to 1568 pixels\./, + ); + assert.match( + await refused( + { images: [image("large.png", 1600, 1200)], questions }, + through("typesafe"), + ), + /large\.png is 1600x1200 pixels\./, + ); + assert.equal(sent.length, 0); + // OpenAI documents no such bounds, so the same file goes to it. + serve({ answers: [{ type: "predicate", probability: 0.2 }] }); + await ask( + { images: [image("large.png", 1600, 1200)], questions }, + through("openai"), + ); + }); +}); + +describe("the provider and model a request uses", () => { + const questions = { refund: QUESTIONS.refund }; + const answer = { answers: { refund: { type: "noul", noul: 0.5 } } }; + + it("are the first provider with a key, and its own model", async () => { + const sent = serve(answer); + const result = await ask<{ provider: string; model: string }>( + { input: TICKET, questions }, + { typesafeApiKey: "t" }, + ); + assert.equal(sent[0].body.model, "jev-latest"); + // A provider that names no model in its answer used the one it was asked for. + assert.deepEqual( + [result.provider, result.model], + ["typesafe", "jev-latest"], + ); + serve({ answers: [OPENAI_ANSWER.answers[0]] }); + assert.equal( + (await ask<{ provider: string }>({ input: TICKET, questions }, ALL_KEYS)) + .provider, + "openai", + ); + }); + + it("are the connection's when it names them", async () => { + const sent = serve(answer); + await ask( + { input: TICKET, questions }, + { ...through("typesafe"), model: "jev-1.13.0" }, + ); + assert.equal(sent[0].body.model, "jev-1.13.0"); + }); + + it("are never the call's: the action has no input that names either", async () => { + serve(answer); + for (const extra of [{ provider: "typesafe" }, { model: "jev-1.13.0" }]) + assert.match( + await refused({ input: TICKET, questions, ...extra }, ALL_KEYS), + /Invalid input for decision\.ask/, + ); + }); + + it("are refused when no provider has a key, or the connection's has none", async () => { + serve(answer); + const none = await refused({ input: TICKET, questions }, {}); + assert.match( + none, + /decision: no decision provider has a key\. Set one of /, + ); + for (const { env } of PROVIDERS) assert.ok(none.includes(env), env); + assert.equal( + await refused( + { input: TICKET, questions }, + { openaiApiKey: "o", provider: "typesafe" }, + ), + "Error: decision: no key for typesafe, the connection's provider. Set TYPESAFE_API_KEY.", + ); + }); +}); + +describe("what a request accepts", () => { + const yesNo = QUESTIONS.refund; + + it("refuses a question whose fields are not its type's, before any request", async () => { + const sent = serve({}); + const cases: Array<[Record, string]> = [ + [ + { type: "choice", instructions: "Which?" }, + 'Error: decision: question "q" is a choice question, which needs options.', + ], + [ + { type: "score", instructions: "How?" }, + 'Error: decision: question "q" is a score question, which needs levels.', + ], + [ + { ...yesNo, options: QUESTIONS.department.options }, + 'Error: decision: question "q" is a yesNo question, which takes no options.', + ], + [ + { ...QUESTIONS.department, levels: QUESTIONS.severity.levels }, + 'Error: decision: question "q" is a choice question, which takes no levels.', + ], + [ + { + type: "choice", + instructions: "Which?", + options: [{ value: "a" }, { value: "a" }], + }, + 'Error: decision: question "q" has the option "a" twice.', + ], + ]; + for (const [question, message] of cases) + assert.equal( + await refused({ input: TICKET, questions: { q: question } }, ALL_KEYS), + message, + ); + assert.equal( + await refused({ questions: { q: yesNo } }, ALL_KEYS), + "Error: decision: set input, images, or both.", + ); + assert.equal( + await refused({ input: TICKET, questions: { " ": yesNo } }, ALL_KEYS), + "Error: decision: a question has no name.", + ); + assert.equal(sent.length, 0); + }); + + it("refuses a value in another form than the one each input has", async () => { + const sent = serve({}); + for (const input of [ + { input: TICKET, questions: {} }, + { input: "", questions: { q: yesNo } }, + { input: ["a"], questions: { q: yesNo } }, + { + input: TICKET, + questions: { q: { type: "predicate", instructions: "?" } }, + }, + { input: TICKET, questions: { q: { type: "yesNo" } } }, + { + input: TICKET, + questions: { + q: { type: "choice", instructions: "?", options: [{ value: "a" }] }, + }, + }, + { + input: TICKET, + questions: { + q: { type: "score", instructions: "?", levels: [{ label: "a" }] }, + }, + }, + { input: TICKET, images: [], questions: { q: yesNo } }, + ]) + assert.match( + await refused(input, ALL_KEYS), + /Invalid input for decision\.ask/, + JSON.stringify(input), + ); + assert.equal(sent.length, 0); + }); +}); + +describe("the action's description", () => { + it("shows what a question takes, so code need not guess", async () => { + const { result, error } = await harness + .codemode(ALL_KEYS) + .execute('return actions.describe("decision.ask")'); + assert.equal(error, undefined); + const question = ( + result as { + inputs: { + questions: { + values: { properties: Record }; + }; + }; + } + ).inputs.questions.values.properties; + assert.deepEqual(Object.keys(question), [ + "type", + "instructions", + "options", + "levels", + ]); + assert.deepEqual(question.type.enum, ["yesNo", "choice", "score"]); + }); +}); + +describe("a provider that fails", () => { + const questions = { refund: QUESTIONS.refund }; + + it("is reported by provider and status, without what it answered", async () => { + serve({ detail: "the key KEY-typesafe is not valid" }, 401); + assert.equal( + await refused({ input: TICKET, questions }, through("typesafe")), + "Error: decision.typesafe: request failed (HTTP 401)", + ); + }); + + it("is refused when it answers a question with nothing that reads", async () => { + for (const [name, answer] of [ + ["openai", { answers: [] }], + ["openai", { answers: [{ type: "choice", choice: "a", confidence: 1 }] }], + ["typesafe", { answers: { refund: { type: "noul" } } }], + ] as const) { + serve(answer); + assert.equal( + await refused({ input: TICKET, questions }, through(name)), + `Error: decision: ${name} answered nothing that reads for question "refund".`, + ); + } + }); +}); + +describe("a provider a host adds", () => { + const acme: DecisionProvider = { + name: "acme", + env: "ACME_DECISION_KEY", + key: { header: "X-Acme-Key" }, + baseUrl: "https://decide.acme.example/", + path: "ask", + model: "acme-1", + request: ({ model, input, questions }) => ({ + json: { model, input, ask: questions.map(({ name }) => name) }, + }), + answers: (_response, { questions }) => ({ + model: "acme-1", + answers: questions.map(() => ({ type: "yesNo", probability: 1 })), + }), + }; + const extended = pluginHarness(decision([acme, ...PROVIDERS]), "decision"); + + it("is used like the others, with a key of its own", async () => { + const sent = serve({}); + const { result, error } = await extended + .codemode({ ...ALL_KEYS, acmeApiKey: "KEY-acme" }) + .execute( + `return await decision.ask(${JSON.stringify({ input: TICKET, questions: { refund: QUESTIONS.refund } })})`, + ); + assert.equal(error, undefined); + assert.deepEqual(result, { + provider: "acme", + model: "acme-1", + answers: { refund: { type: "yesNo", probability: 1 } }, + }); + assert.equal(sent[0].url, "https://decide.acme.example/ask"); + assert.equal(sent[0].headers["x-acme-key"], "KEY-acme"); + assert.ok(!JSON.stringify(sent).includes("KEY-openai")); + }); +}); + +describe("the README", () => { + it("lists the providers in their order, with each key and default model", () => { + const readme = readFileSync(join(PACKAGE, "README.md"), "utf8"); + const rows = [ + ...readme.matchAll(/^\| `(\w+)` \| `(\w+)` \| `([\w.-]+)` \|/gm), + ].map(([, name, env, model]) => [name, env, model]); + assert.deepEqual( + rows, + PROVIDERS.map(({ name, env, model }) => [name, env, model]), + ); + }); +}); + +describePackage(PACKAGE, { + package: "@shiftlabs/codemode-decision", + plugin: "decision", + actions: 1, + write: 0, +}); diff --git a/packages/codemode-decision/tsconfig.json b/packages/codemode-decision/tsconfig.json new file mode 100644 index 00000000..956f602c --- /dev/null +++ b/packages/codemode-decision/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "esnext", + "module": "nodenext", + "moduleResolution": "nodenext", + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "types": ["node", "bun"] + }, + "include": ["src", "tests"] +} diff --git a/packages/codemode-imagegen/src/index.ts b/packages/codemode-imagegen/src/index.ts index 48c1308f..26bf30cc 100644 --- a/packages/codemode-imagegen/src/index.ts +++ b/packages/codemode-imagegen/src/index.ts @@ -11,30 +11,31 @@ * provider's key. Code never names a provider. */ -import { basename } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { type ActionContext, type CodemodePluginAPI, - type CredentialDeclaration, type CredentialTarget, credentialJson, downloadResource, + IMAGE_EXTENSIONS, + imageFacts, + keyedProviders, + namedProvider, type PluginFunction, - readLocalFile, - staticCredential, + readLocalImage, + routerConnectionFields, + routerCredential, writeOutputFile, } from "@shiftlabs/codemode"; import { packageVersion } from "@shiftlabs/codemode/utils/cli"; import * as t from "typebox"; -import { EXTENSIONS, imageFacts } from "./image.js"; import { PROVIDERS } from "./providers/index.js"; import type { ImageModel, ImageProvider, ProducedImage, ProviderApi, - SourceImage, } from "./types.js"; export * from "./providers/index.js"; @@ -58,97 +59,6 @@ const MODELS_TTL_MS = 10 * 60_000; /** What `create` and `edit` do, by the name of the action. */ type Kind = "create" | "edit"; -/** The connection field that holds a provider's key. */ -function keyField(provider: ImageProvider): string { - return `${provider.name}ApiKey`; -} - -/** Whether the connection holds a key for the provider. */ -function hasKey( - provider: ImageProvider, - config: Readonly>, -): boolean { - return Boolean(config[keyField(provider)]); -} - -/** - * One credential for every provider: a part per provider, each optional and - * each placed only on that provider's targets, so a connection holds the - * keys it has and a key is sent to its own provider alone. - */ -function credentialOf(providers: ImageProvider[]): CredentialDeclaration { - const names = providers.map((provider) => provider.name); - return staticCredential({ - id: "codemodeImagegen", - auth: { - kind: "static", - parts: names, - optionalParts: names, - placements: providers.map(({ name, key, targets }) => - "query" in key - ? { - in: "query", - part: name, - name: key.query, - targets: Object.keys(targets), - } - : { - in: "header", - part: name, - name: key.header, - ...(key.prefix === undefined ? {} : { prefix: key.prefix }), - targets: Object.keys(targets), - }, - ), - }, - local: Object.fromEntries( - providers.map((provider) => [provider.name, keyField(provider)]), - ), - targets: Object.fromEntries( - providers.flatMap((provider) => - Object.entries(provider.targets).map( - ([name, target]): [string, CredentialTarget] => [ - name, - { ...target, timeoutMs: TIMEOUT_MS }, - ], - ), - ), - ), - }); -} - -/** - * The provider a request goes to. The connection decides, never the call: - * its `provider` when it names one, else the first provider it has a key - * for. A host that signs requests keeps the keys, so only a connection that - * signs for itself (`signsItself`) is asked to hold the key of the provider - * it names. - */ -function chosen( - providers: ImageProvider[], - config: Readonly>, - signsItself: boolean, -): ImageProvider { - const name = config.provider; - if (name === undefined) { - const first = providers.find((candidate) => hasKey(candidate, config)); - if (first) return first; - throw new Error( - `${NAME}: no image provider has a key. Set one of ${providers.map((candidate) => candidate.env).join(", ")}, or the connection's "provider" when the host keeps the keys.`, - ); - } - const provider = providers.find((candidate) => candidate.name === name); - if (!provider) - throw new Error( - `${NAME}: the connection names the provider ${JSON.stringify(name)}. The providers are ${providers.map((candidate) => candidate.name).join(", ")}.`, - ); - if (signsItself && !hasKey(provider, config)) - throw new Error( - `${NAME}: no key for ${provider.name}, the connection's provider. Set ${provider.env}.`, - ); - return provider; -} - /** The model an action uses when the call names none: the connection's, else the provider's. */ function defaultModel( provider: ImageProvider, @@ -175,19 +85,6 @@ function described({ id, name, description, create, edit }: ImageModel) { /** The types of image every provider documents taking to edit. */ const SOURCE_TYPES = ["image/png", "image/jpeg", "image/webp"]; -/** Read an image to edit. What it is, its bytes say: a file that is none of the types a model edits is refused. */ -async function sourceImage(path: string): Promise { - const bytes = await readLocalFile(path, { - subject: `${NAME}: ${path}`, - maxBytes: MAX_SOURCE_BYTES, - oversize: `${NAME}: ${path} is larger than ${MAX_SOURCE_BYTES / (1024 * 1024)} MiB`, - }); - const facts = imageFacts(bytes); - if (!facts || !SOURCE_TYPES.includes(facts.mimeType)) - throw new Error(`${NAME}: ${path} is not a PNG, JPEG or WebP image.`); - return { bytes, mimeType: facts.mimeType, fileName: basename(path) }; -} - const sizeInputs = { width: t.Optional( t.Integer({ @@ -252,8 +149,33 @@ const imagesOutput = { export function imagegen( providers: ImageProvider[] = PROVIDERS, ): PluginFunction { - const credential = credentialOf(providers); - const names = providers.map((provider) => provider.name); + const credential = routerCredential( + "codemodeImagegen", + providers, + (provider) => + Object.fromEntries( + Object.entries(provider.targets).map( + ([name, target]): [string, CredentialTarget] => [ + name, + { ...target, timeoutMs: TIMEOUT_MS }, + ], + ), + ), + ); + + /** + * The provider a request goes to. The connection decides, never the call: + * its `provider` when it names one, else the first provider it has a key + * for. + */ + function chosen(ctx: ActionContext): ImageProvider { + const { config } = ctx.connection; + return ( + namedProvider(NAME, providers, config, !ctx.credentials) ?? + keyedProviders(NAME, "image", providers, config)[0] + ); + } + /** Each provider's models, by the connection that listed them, with when the list was made. */ const lists = new Map(); /** A provider's models, and whether the provider itself could be asked for them. */ @@ -370,9 +292,17 @@ export function imagegen( ) { if ((input.width === undefined) !== (input.height === undefined)) throw new Error(`${NAME}: set width and height together, or neither.`); - const provider = chosen(providers, ctx.connection.config, !ctx.credentials); + const provider = chosen(ctx); const model = await modelFor(ctx, provider, input.model, kind); - const images = await Promise.all((input.images ?? []).map(sourceImage)); + const images = await Promise.all( + (input.images ?? []).map((path) => + readLocalImage(path, { + subject: `${NAME}: ${path}`, + maxBytes: MAX_SOURCE_BYTES, + types: SOURCE_TYPES, + }), + ), + ); const produced = await provider.generate(apiOf(ctx, provider), { prompt: input.prompt, model, @@ -397,7 +327,7 @@ export function imagegen( written.push({ path: writeOutputFile( `${NAME}-${provider.name}`, - EXTENSIONS[facts.mimeType], + IMAGE_EXTENSIONS[facts.mimeType], bytes, ctx.outputDir, ), @@ -420,12 +350,9 @@ export function imagegen( rl.setCredential(credential); rl.setConnectionSchema( t.Object({ - provider: t.Optional( - t.String({ - enum: names, - description: - "The provider every request goes to. The default is the first provider with a key", - }), + ...routerConnectionFields( + providers, + "The provider every request goes to. The default is the first provider with a key", ), createModel: t.Optional( t.String({ @@ -439,17 +366,6 @@ export function imagegen( "The model edit uses when a call names none. The default is the provider's", }), ), - ...Object.fromEntries( - providers.map((provider) => [ - keyField(provider), - t.Optional( - t.String({ - env: provider.env, - description: `API key for ${provider.name}`, - }), - ), - ]), - ), }), ); @@ -549,7 +465,7 @@ export function imagegen( }, async execute(input, ctx) { const { config } = ctx.connection; - const provider = chosen(providers, config, !ctx.credentials); + const provider = chosen(ctx); const words = input.query?.toLowerCase().split(/\s+/).filter(Boolean); const matches = (model: ImageModel) => !words || diff --git a/packages/codemode-imagegen/src/providers/fal.ts b/packages/codemode-imagegen/src/providers/fal.ts index 946d3178..6de4e253 100644 --- a/packages/codemode-imagegen/src/providers/fal.ts +++ b/packages/codemode-imagegen/src/providers/fal.ts @@ -1,5 +1,4 @@ -import { pathSegments } from "@shiftlabs/codemode"; -import { dataUrlOf } from "../image.js"; +import { imageDataUrl, pathSegments } from "@shiftlabs/codemode"; import { inputFor } from "../schema.js"; import type { ImageModel, ImageProvider, ProviderApi } from "../types.js"; import { describedModel, finished, hostedModel } from "./hosted.js"; @@ -112,7 +111,7 @@ export const fal: ImageProvider = { headers: JSON_BODY, // fal's API takes no upload, so an image to edit goes inside the request. body: new TextEncoder().encode( - JSON.stringify(await inputFor(fields, request, dataUrlOf)), + JSON.stringify(await inputFor(fields, request, imageDataUrl)), ), }); const { request_id } = queued; diff --git a/packages/codemode-imagegen/src/providers/google.ts b/packages/codemode-imagegen/src/providers/google.ts index 2a24eaab..ac752fc3 100644 --- a/packages/codemode-imagegen/src/providers/google.ts +++ b/packages/codemode-imagegen/src/providers/google.ts @@ -1,5 +1,4 @@ -import { pathSegment } from "@shiftlabs/codemode"; -import { base64Of } from "../image.js"; +import { imageBase64, pathSegment } from "@shiftlabs/codemode"; import { nearestRatio } from "../size.js"; import type { ImageModel, ImageProvider } from "../types.js"; @@ -95,7 +94,7 @@ export const google: ImageProvider = { ...images.map((image) => ({ inlineData: { mimeType: image.mimeType, - data: base64Of(image), + data: imageBase64(image), }, })), ], diff --git a/packages/codemode-imagegen/src/providers/recraft.ts b/packages/codemode-imagegen/src/providers/recraft.ts index 9703015c..ee8a0fa8 100644 --- a/packages/codemode-imagegen/src/providers/recraft.ts +++ b/packages/codemode-imagegen/src/providers/recraft.ts @@ -1,4 +1,4 @@ -import { dataUrlOf } from "../image.js"; +import { imageDataUrl } from "@shiftlabs/codemode"; import { nearestRatio } from "../size.js"; import type { ImageModel, ImageProvider } from "../types.js"; import { type ImagesAnswer, imagesOf } from "./answer.js"; @@ -81,7 +81,7 @@ export const recraft: ImageProvider = { method: "POST", json: { ...common, - image_url: dataUrlOf(images[0]), + image_url: imageDataUrl(images[0]), strength: EDIT_STRENGTH, }, } diff --git a/packages/codemode-imagegen/src/providers/replicate.ts b/packages/codemode-imagegen/src/providers/replicate.ts index 23d4b812..bbc8483e 100644 --- a/packages/codemode-imagegen/src/providers/replicate.ts +++ b/packages/codemode-imagegen/src/providers/replicate.ts @@ -1,11 +1,11 @@ -import { multipartBody, pathSegment, pathSegments } from "@shiftlabs/codemode"; +import { + type LocalImage, + multipartBody, + pathSegment, + pathSegments, +} from "@shiftlabs/codemode"; import { inputFor } from "../schema.js"; -import type { - ImageModel, - ImageProvider, - ProviderApi, - SourceImage, -} from "../types.js"; +import type { ImageModel, ImageProvider, ProviderApi } from "../types.js"; import { describedModel, finished, hostedModel } from "./hosted.js"; /** Replicate's collections for the two things this package does. */ @@ -58,7 +58,7 @@ function listed( } /** Upload an image to edit as a file, and answer the address a model reads it from. */ -async function uploaded(api: ProviderApi, image: SourceImage): Promise { +async function uploaded(api: ProviderApi, image: LocalImage): Promise { const form = new FormData(); form.append( "content", diff --git a/packages/codemode-imagegen/src/providers/together.ts b/packages/codemode-imagegen/src/providers/together.ts index 29a44113..690087c3 100644 --- a/packages/codemode-imagegen/src/providers/together.ts +++ b/packages/codemode-imagegen/src/providers/together.ts @@ -1,4 +1,4 @@ -import { dataUrlOf } from "../image.js"; +import { imageDataUrl } from "@shiftlabs/codemode"; import { fitSize } from "../size.js"; import type { ImageModel, ImageProvider } from "../types.js"; import { type ImagesAnswer, imagesOf } from "./answer.js"; @@ -89,7 +89,7 @@ export const together: ImageProvider = { async generate(api, { prompt, model: { id }, numImages, size, images }) { if (takesOneImage(id) && images.length > 1) throw new Error(`${id} takes one image. Pass one path in images.`); - const urls = images.map(dataUrlOf); + const urls = images.map(imageDataUrl); const answer = await api.request({ path: "images/generations", method: "POST", diff --git a/packages/codemode-imagegen/src/providers/xai.ts b/packages/codemode-imagegen/src/providers/xai.ts index 3e11d5d9..68029952 100644 --- a/packages/codemode-imagegen/src/providers/xai.ts +++ b/packages/codemode-imagegen/src/providers/xai.ts @@ -1,4 +1,4 @@ -import { dataUrlOf } from "../image.js"; +import { imageDataUrl } from "@shiftlabs/codemode"; import { nearestRatio, type Size } from "../size.js"; import type { ImageProvider } from "../types.js"; import { type ImagesAnswer, imagesOf } from "./answer.js"; @@ -61,7 +61,7 @@ export const xai: ImageProvider = { ); }, async generate(api, { prompt, model, numImages, size, images }) { - const sources = images.map((image) => ({ url: dataUrlOf(image) })); + const sources = images.map((image) => ({ url: imageDataUrl(image) })); const answer = await api.request({ path: images.length ? "images/edits" : "images/generations", method: "POST", diff --git a/packages/codemode-imagegen/src/schema.ts b/packages/codemode-imagegen/src/schema.ts index 549076ed..6c52f392 100644 --- a/packages/codemode-imagegen/src/schema.ts +++ b/packages/codemode-imagegen/src/schema.ts @@ -6,8 +6,9 @@ * images, so one request can be written as that model's input. */ +import type { LocalImage } from "@shiftlabs/codemode"; import { nearestRatio, nearestSize, parseSize, type Size } from "./size.js"; -import type { ImageRequest, SourceImage } from "./types.js"; +import type { ImageRequest } from "./types.js"; type Schema = Record; @@ -123,7 +124,7 @@ function choiceFor(size: Size, choices: string[]): string { export async function inputFor( fields: ModelFields, request: ImageRequest, - source: (image: SourceImage) => string | Promise, + source: (image: LocalImage) => string | Promise, ): Promise> { const { model, size, images, numImages } = request; const input: Record = { [fields.prompt]: request.prompt }; diff --git a/packages/codemode-imagegen/src/types.ts b/packages/codemode-imagegen/src/types.ts index 59249990..0fe1802a 100644 --- a/packages/codemode-imagegen/src/types.ts +++ b/packages/codemode-imagegen/src/types.ts @@ -3,6 +3,7 @@ * goes, the models it has, and how one request for images is made of it. */ +import type { LocalImage, RoutedProvider } from "@shiftlabs/codemode"; import type { Size } from "./size.js"; /** A model a provider makes images with. */ @@ -17,13 +18,6 @@ export interface ImageModel { edit: boolean; } -/** An image read from disk to edit. */ -export interface SourceImage { - bytes: Uint8Array; - mimeType: string; - fileName: string; -} - /** One request for images, the same for every provider. */ export interface ImageRequest { prompt: string; @@ -32,7 +26,7 @@ export interface ImageRequest { /** The pixels asked for. A provider gets as close as its model allows. */ size?: Size; /** The images to edit, in order. Empty when the request creates one. */ - images: SourceImage[]; + images: LocalImage[]; } /** An image as a provider hands it over: its bytes in base64, or where to fetch them. */ @@ -69,13 +63,7 @@ export interface ProviderTarget { } /** An image API: where it is, where its key goes, its models, and how it makes images. */ -export interface ImageProvider { - /** The name a connection gives as its `provider`, and the stem of the key's connection field. */ - name: string; - /** The environment variable that fills the key. */ - env: string; - /** Where the key goes in a request: a header, or a query parameter. */ - key: { header: string; prefix?: string } | { query: string }; +export interface ImageProvider extends RoutedProvider { /** The addresses the key may be sent beneath, by a name no other provider uses. The first is the default. */ targets: Record; /** Hosts its images are fetched from, each with its subdomains. Fetches carry no key. */ diff --git a/packages/codemode-imagegen/tests/imagegen.test.ts b/packages/codemode-imagegen/tests/imagegen.test.ts index 6a9d6606..8e89a36a 100644 --- a/packages/codemode-imagegen/tests/imagegen.test.ts +++ b/packages/codemode-imagegen/tests/imagegen.test.ts @@ -11,26 +11,15 @@ import { dirname, join } from "node:path"; import { afterEach, describe, it } from "node:test"; import { fileURLToPath } from "node:url"; import type { PluginFunction } from "@shiftlabs/codemode"; +import { png } from "../../codemode/src/tests/helpers/image.js"; import { stubFetch } from "../../codemode/src/tests/helpers/plugin.js"; import { describePackage, pluginHarness } from "../../package-tests/harness.js"; -import { imageFacts } from "../src/image.js"; import { type ImageProvider, imagegen, PROVIDERS } from "../src/index.js"; import { fieldsOf, inputFor } from "../src/schema.js"; import { fitSize, nearestRatio, nearestSize } from "../src/size.js"; const PACKAGE = fileURLToPath(new URL("..", import.meta.url)); -/** The first bytes of a PNG of this size: all that tells an image's type and size. */ -function png(width: number, height: number): Buffer { - const bytes = Buffer.alloc(33); - Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(bytes); - bytes.writeUInt32BE(13, 8); - bytes.write("IHDR", 12); - bytes.writeUInt32BE(width, 16); - bytes.writeUInt32BE(height, 20); - return bytes; -} - const PNG = png(1024, 768); const B64 = PNG.toString("base64"); @@ -1248,54 +1237,6 @@ describe("a size in pixels", () => { }); }); -describe("an image's first bytes", () => { - it("tell its type and size", () => { - assert.deepEqual(imageFacts(png(640, 480)), { - mimeType: "image/png", - width: 640, - height: 480, - }); - const gif = Buffer.alloc(16); - gif.write("GIF89a"); - gif.writeUInt16LE(320, 6); - gif.writeUInt16LE(200, 8); - assert.deepEqual(imageFacts(gif), { - mimeType: "image/gif", - width: 320, - height: 200, - }); - const jpeg = Buffer.from([ - 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, 0xff, 0xc0, 0x00, 0x11, - 0x08, 0x01, 0xe0, 0x02, 0x80, 0x03, 0x00, 0x00, - ]); - assert.deepEqual(imageFacts(jpeg), { - mimeType: "image/jpeg", - width: 640, - height: 480, - }); - const webp = Buffer.alloc(30); - webp.write("RIFF"); - webp.write("WEBP", 8); - webp.write("VP8X", 12); - webp.writeUIntLE(799, 24, 3); - webp.writeUIntLE(599, 27, 3); - assert.deepEqual(imageFacts(webp), { - mimeType: "image/webp", - width: 800, - height: 600, - }); - assert.deepEqual( - imageFacts( - Buffer.from( - '\n', - ), - ), - { mimeType: "image/svg+xml" }, - ); - assert.equal(imageFacts(Buffer.from("plain text, long enough")), undefined); - }); -}); - describe("a hosted model's schema", () => { const request = { prompt: "p", @@ -1305,7 +1246,7 @@ describe("a hosted model's schema", () => { images: [], }; const image = { - bytes: new Uint8Array([0]), + bytes: Buffer.from([0]), mimeType: "image/png", fileName: "a.png", }; diff --git a/packages/codemode-websearch/src/index.ts b/packages/codemode-websearch/src/index.ts index b2fe1cc6..de3e50d9 100644 --- a/packages/codemode-websearch/src/index.ts +++ b/packages/codemode-websearch/src/index.ts @@ -12,11 +12,12 @@ import { type CodemodePluginAPI, - type CredentialDeclaration, - type CredentialTarget, credentialJson, + keyedProviders, + namedProvider, type PluginFunction, - staticCredential, + routerConnectionFields, + routerCredential, } from "@shiftlabs/codemode"; import { packageVersion } from "@shiftlabs/codemode/utils/cli"; import * as t from "typebox"; @@ -49,66 +50,6 @@ const FILTERS = ["includeDomains", "excludeDomains", "freshness"] as const; /** A hostname, such as `duckdb.org`: no scheme, path or spaces. */ const DOMAIN = "^[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+$"; -/** The connection field that holds a provider's key. */ -function keyField(provider: SearchProvider): string { - return `${provider.name}ApiKey`; -} - -/** Whether the connection holds a key for the provider. */ -function hasKey( - provider: SearchProvider, - config: Readonly>, -): boolean { - return Boolean(config[keyField(provider)]); -} - -/** - * One credential for every provider: a part per provider, each optional and - * each placed only on that provider's target, so a connection holds the keys - * it has and a key is sent to its own provider alone. A target is the - * provider's address, the method a search uses and the headers it carries. - */ -function credentialOf(providers: SearchProvider[]): CredentialDeclaration { - const names = providers.map((provider) => provider.name); - return staticCredential({ - id: "codemodeWebsearch", - auth: { - kind: "static", - parts: names, - optionalParts: names, - placements: providers.map(({ name, key }) => - "query" in key - ? { in: "query", part: name, name: key.query, targets: [name] } - : { - in: "header", - part: name, - name: key.header, - ...(key.prefix === undefined ? {} : { prefix: key.prefix }), - targets: [name], - }, - ), - }, - local: Object.fromEntries( - providers.map((provider) => [provider.name, keyField(provider)]), - ), - targets: (config) => - Object.fromEntries( - providers.map( - ({ name, baseUrl, method, headers }): [string, CredentialTarget] => [ - name, - { - baseUrl: - typeof baseUrl === "function" ? baseUrl(config) : baseUrl, - methods: [method], - ...(headers ? { allowedHeaders: Object.keys(headers) } : {}), - timeoutMs: TIMEOUT_MS, - }, - ], - ), - ), - }); -} - /** * The filters of a search that a provider does not apply: those whose * removal leaves the request the provider would send unchanged. @@ -132,9 +73,7 @@ function unapplied(provider: SearchProvider, search: SearchRequest): string[] { /** * The provider a search goes to. The connection decides, never the call: * its `provider` when it names one, else the first provider it has a key - * for that applies the search's filters. A host that signs requests keeps - * the keys, so only a connection that signs for itself (`signsItself`) is - * asked to hold the key of the provider it names. + * for that applies the search's filters. */ function chosen( providers: SearchProvider[], @@ -142,14 +81,9 @@ function chosen( signsItself: boolean, search: SearchRequest, ): SearchProvider { - const name = config.provider; - if (name === undefined) { - const keyed = providers.filter((candidate) => hasKey(candidate, config)); - if (!keyed.length) - throw new Error( - `${NAME}: no search provider has a key. Set one of ${providers.map((candidate) => candidate.env).join(", ")}, or the connection's "provider" when the host keeps the keys.`, - ); - const able = keyed.find( + const provider = namedProvider(NAME, providers, config, signsItself); + if (!provider) { + const able = keyedProviders(NAME, "search", providers, config).find( (candidate) => !unapplied(candidate, search).length, ); if (able) return able; @@ -158,15 +92,6 @@ function chosen( `${NAME}: no provider with a key can filter by ${set.join(" and ")}. Search without one of them.`, ); } - const provider = providers.find((candidate) => candidate.name === name); - if (!provider) - throw new Error( - `${NAME}: the connection names the provider ${JSON.stringify(name)}. The providers are ${providers.map((candidate) => candidate.name).join(", ")}.`, - ); - if (signsItself && !hasKey(provider, config)) - throw new Error( - `${NAME}: no key for ${provider.name}, the connection's provider. Set ${provider.env}.`, - ); const refused = unapplied(provider, search); if (refused.length) throw new Error( @@ -223,8 +148,19 @@ function defined(params: Record): Record { export function websearch( providers: SearchProvider[] = PROVIDERS, ): PluginFunction { - const credential = credentialOf(providers); - const names = providers.map((provider) => provider.name); + // A target is the provider's address, the method a search uses and the headers it carries. + const credential = routerCredential( + "codemodeWebsearch", + providers, + ({ name, baseUrl, method, headers }, config) => ({ + [name]: { + baseUrl: typeof baseUrl === "function" ? baseUrl(config) : baseUrl, + methods: [method], + ...(headers ? { allowedHeaders: Object.keys(headers) } : {}), + timeoutMs: TIMEOUT_MS, + }, + }), + ); return function plugin(rl: CodemodePluginAPI): void { rl.setName(NAME); @@ -235,23 +171,9 @@ export function websearch( rl.setCredential(credential); rl.setConnectionSchema( t.Object({ - provider: t.Optional( - t.String({ - enum: names, - description: - "The provider every search goes to. The default is the first provider with a key that can apply the search's filters", - }), - ), - ...Object.fromEntries( - providers.map((provider) => [ - keyField(provider), - t.Optional( - t.String({ - env: provider.env, - description: `API key for ${provider.name}`, - }), - ), - ]), + ...routerConnectionFields( + providers, + "The provider every search goes to. The default is the first provider with a key that can apply the search's filters", ), ...Object.assign({}, ...providers.map((provider) => provider.fields)), }), diff --git a/packages/codemode-websearch/src/providers.ts b/packages/codemode-websearch/src/providers.ts index 07c8c1bc..9ec6c1ea 100644 --- a/packages/codemode-websearch/src/providers.ts +++ b/packages/codemode-websearch/src/providers.ts @@ -4,7 +4,7 @@ * pure functions; the plugin sends the request. */ -import { httpsBase } from "@shiftlabs/codemode"; +import { httpsBase, type RoutedProvider } from "@shiftlabs/codemode"; import * as t from "typebox"; import { BRAVE_COUNTRIES, @@ -54,13 +54,7 @@ export interface SearchResult { } /** A search API: where it is, where its key goes, and how a search reads to and from it. */ -export interface SearchProvider { - /** The name a connection gives as its `provider`, and the stem of the key's connection field. */ - name: string; - /** The environment variable that fills the key. */ - env: string; - /** Where the key goes in a request: a header, or a query parameter. */ - key: { header: string; prefix?: string } | { query: string }; +export interface SearchProvider extends RoutedProvider { /** * The HTTPS address the key may be sent beneath, ending in `/`: fixed, or * from the connection's config. diff --git a/packages/codemode/src/credentials/router.ts b/packages/codemode/src/credentials/router.ts new file mode 100644 index 00000000..000e42fa --- /dev/null +++ b/packages/codemode/src/credentials/router.ts @@ -0,0 +1,148 @@ +/** + * What a plugin that routes to one of several providers shares: one + * connection that holds a key per provider, each key sent to its own + * provider alone, and the connection's choice of which provider a request + * goes to. + */ + +import * as t from "typebox"; +import { staticCredential } from "./plugin.js"; +import type { CredentialDeclaration, CredentialTarget } from "./types.js"; + +/** A provider a plugin routes to: its name, and where its key comes from and goes. */ +export interface RoutedProvider { + /** The name a connection gives as its `provider`, and the stem of the key's connection field. */ + name: string; + /** The environment variable that fills the key. */ + env: string; + /** Where the key goes in a request: a header, or a query parameter. */ + key: { header: string; prefix?: string } | { query: string }; +} + +type Config = Readonly>; + +/** The connection field that holds a provider's key. */ +export function providerKeyField(provider: RoutedProvider): string { + return `${provider.name}ApiKey`; +} + +/** Whether the connection holds a key for the provider. */ +function hasKey(provider: RoutedProvider, config: Config): boolean { + return Boolean(config[providerKeyField(provider)]); +} + +/** + * One credential for every provider: a part per provider, each optional and + * each placed only on that provider's targets, so a connection holds the + * keys it has and a key is sent to its own provider alone. `targets` gives a + * provider's targets by name; the names are no other provider's and do not + * depend on the connection's config. + */ +export function routerCredential

( + id: string, + providers: readonly P[], + targets: (provider: P, config: Config) => Record, +): CredentialDeclaration { + const names = providers.map((provider) => provider.name); + return staticCredential({ + id, + auth: { + kind: "static", + parts: names, + optionalParts: names, + placements: providers.map((provider) => { + const { name, key } = provider; + const own = Object.keys(targets(provider, {})); + return "query" in key + ? { in: "query", part: name, name: key.query, targets: own } + : { + in: "header", + part: name, + name: key.header, + ...(key.prefix === undefined ? {} : { prefix: key.prefix }), + targets: own, + }; + }), + }, + local: Object.fromEntries( + providers.map((provider) => [provider.name, providerKeyField(provider)]), + ), + targets: (config) => + Object.assign({}, ...providers.map((one) => targets(one, config))), + }); +} + +/** + * The connection fields every routing plugin has: `provider`, described by + * `choice`, and an optional key per provider, filled from its environment + * variable. + */ +export function routerConnectionFields( + providers: readonly RoutedProvider[], + choice: string, +) { + return { + provider: t.Optional( + t.String({ + enum: providers.map((provider) => provider.name), + description: choice, + }), + ), + ...Object.fromEntries( + providers.map((provider) => [ + providerKeyField(provider), + t.Optional( + t.String({ + env: provider.env, + description: `API key for ${provider.name}`, + }), + ), + ]), + ), + }; +} + +/** + * The provider the connection names as its `provider`, or nothing when it + * names none. A host that signs requests keeps the keys, so only a + * connection that signs for itself (`signsItself`) is asked to hold the key + * of the provider it names. + */ +export function namedProvider

( + plugin: string, + providers: readonly P[], + config: Config, + signsItself: boolean, +): P | undefined { + const name = config.provider; + if (name === undefined) return undefined; + const provider = providers.find((candidate) => candidate.name === name); + if (!provider) + throw new Error( + `${plugin}: the connection names the provider ${JSON.stringify(name)}. The providers are ${providers.map((candidate) => candidate.name).join(", ")}.`, + ); + if (signsItself && !hasKey(provider, config)) + throw new Error( + `${plugin}: no key for ${provider.name}, the connection's provider. Set ${provider.env}.`, + ); + return provider; +} + +/** + * The providers the connection holds a key for, in the plugin's order: the + * candidates when the connection names no provider. `kind` says what the + * providers are in the error when there is none, such as `search`. + */ +export function keyedProviders

( + plugin: string, + kind: string, + providers: readonly P[], + config: Config, +): P[] { + const keyed = providers.filter((candidate) => hasKey(candidate, config)); + if (!keyed.length) + throw new Error( + `${plugin}: no ${kind} provider has a key. Set one of ${providers.map((candidate) => candidate.env).join(", ")}, or the connection's "provider" when the host keeps the keys.`, + ); + return keyed; +} diff --git a/packages/codemode/src/index.ts b/packages/codemode/src/index.ts index 950857e1..1c268d1e 100644 --- a/packages/codemode/src/index.ts +++ b/packages/codemode/src/index.ts @@ -137,6 +137,14 @@ export { staticSecretSchema, validateCredential, } from "./credentials/registry.js"; +export { + keyedProviders, + namedProvider, + providerKeyField, + type RoutedProvider, + routerConnectionFields, + routerCredential, +} from "./credentials/router.js"; export type { AuthenticatedRequest, CredentialBroker, @@ -332,6 +340,15 @@ export { shellRunAction, syncExec, } from "./utils/cli.js"; +export { + IMAGE_EXTENSIONS, + type ImageFacts, + imageBase64, + imageDataUrl, + imageFacts, + type LocalImage, + readLocalImage, +} from "./utils/image.js"; export { readLocalFile } from "./utils/local-file.js"; export { ACTION_MEMORY_BYTES, diff --git a/packages/codemode/src/plugin/schema.ts b/packages/codemode/src/plugin/schema.ts index 702c0455..a2fbe821 100644 --- a/packages/codemode/src/plugin/schema.ts +++ b/packages/codemode/src/plugin/schema.ts @@ -12,6 +12,8 @@ interface SchemaMetadata { type?: string; properties?: Record; items?: SchemaMetadata; + patternProperties?: Record; + additionalProperties?: boolean | SchemaMetadata; required?: string[]; anyOf?: SchemaMetadata[]; oneOf?: SchemaMetadata[]; @@ -161,7 +163,8 @@ function describeProperties( /** * Describe one input, following arrays into their item shape, objects - * into their properties, and unions into each branch. + * into their properties or the shape of their values, and unions into each + * branch. * * A parameter typed only as "array" tells an agent nothing about what to * put in it, so the shape has to be guessed and the first call is a coin @@ -185,9 +188,11 @@ function describeField( }; const branches = unionBranches(field); + const values = valuesOf(field); if (depth >= MAX_DESCRIBE_DEPTH) { // Only claim truncation where something was actually left unread. - if (field.items || field.properties || branches) described.truncated = true; + if (field.items || field.properties || values || branches) + described.truncated = true; return described; } @@ -198,6 +203,10 @@ function describeField( if (field.properties) { described.properties = describeProperties(field, depth + 1); } + if (values) { + // A value under a key the caller chooses is not "required" either. + described.values = describeField(values, false, depth + 1); + } if (branches) { described.variants = branches.map((branch) => describeField(branch, false, depth + 1), @@ -206,6 +215,24 @@ function describeField( return described; } +/** + * The schema every value has, for an object whose keys the caller chooses + * (a record): its one pattern's schema, or the schema of its additional + * properties. + */ +function valuesOf(schema: SchemaMetadata): SchemaMetadata | undefined { + const patterns = Object.values(schema.patternProperties ?? {}); + const additional = schema.additionalProperties; + const values = + patterns.length === 1 + ? patterns[0] + : additional !== null && typeof additional === "object" + ? additional + : undefined; + // A value that may be anything has no shape to describe. + return values && Object.keys(values).length ? values : undefined; +} + /** * The branches of a union worth describing individually. * @@ -227,6 +254,7 @@ function hasShape(schema: SchemaMetadata): boolean { return Boolean( schema.properties || schema.items || + valuesOf(schema) || branchesOf(schema) || schema.enum?.length || schema.description, diff --git a/packages/codemode/src/plugin/types.ts b/packages/codemode/src/plugin/types.ts index 4053e603..b96e3430 100644 --- a/packages/codemode/src/plugin/types.ts +++ b/packages/codemode/src/plugin/types.ts @@ -45,6 +45,8 @@ export interface HelpInput { items?: HelpInput; /** Nested field shapes, for object inputs. */ properties?: Record; + /** The shape of every value, for an object whose keys the caller chooses. */ + values?: HelpInput; /** * Branches of a union, where at least one carries shape the display * type cannot express. Absent for unions of literals or bare scalars. diff --git a/packages/codemode/src/tests/action-schema-ergonomics.test.ts b/packages/codemode/src/tests/action-schema-ergonomics.test.ts index d4575740..69d229a5 100644 --- a/packages/codemode/src/tests/action-schema-ergonomics.test.ts +++ b/packages/codemode/src/tests/action-schema-ergonomics.test.ts @@ -32,6 +32,47 @@ describe("action schema ergonomics", () => { assert.equal(items.properties?.multiline.required, false); }); + it("returns the shape of the values of an object whose keys the caller chooses", () => { + const schema = t.Object({ + questions: t.Record( + t.String(), + t.Object({ + type: t.String({ enum: ["yesNo", "choice"] }), + options: t.Optional(t.Array(t.Object({ value: t.String() }))), + }), + ), + anything: t.Record(t.String(), t.Unknown()), + counts: { type: "object", additionalProperties: { type: "number" } }, + }); + const fields = helpInputs(schema as never); + const values = fields.questions.values; + assert.ok(values, "a record must describe the shape of its values"); + assert.equal(values.required, false); + assert.deepEqual(values.properties?.type.enum, ["yesNo", "choice"]); + assert.deepEqual( + Object.keys(values.properties?.options.items?.properties ?? {}), + ["value"], + ); + assert.equal(fields.counts.values?.type, "number"); + assert.equal(fields.anything.values, undefined); + }); + + it("keeps the variants of a union one of whose branches is such an object", () => { + const schema = t.Object({ + input: t.Union([ + t.String(), + t.Record(t.String(), t.Object({ id: t.String() })), + ]), + evidence: t.Union([t.String(), t.Record(t.String(), t.Unknown())]), + }); + const fields = helpInputs(schema); + assert.deepEqual( + Object.keys(fields.input.variants?.[1].values?.properties ?? {}), + ["id"], + ); + assert.equal(fields.evidence.variants, undefined); + }); + it("returns nested properties for an object input", () => { const schema = t.Object({ filter: t.Object({ diff --git a/packages/codemode/src/tests/credential-router.test.ts b/packages/codemode/src/tests/credential-router.test.ts new file mode 100644 index 00000000..c5d65575 --- /dev/null +++ b/packages/codemode/src/tests/credential-router.test.ts @@ -0,0 +1,151 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { + keyedProviders, + namedProvider, + providerKeyField, + type RoutedProvider, + routerConnectionFields, + routerCredential, +} from "../credentials/router.js"; +import type { CredentialTarget } from "../credentials/types.js"; +import { connectionFields } from "../plugin/schema.js"; + +const acme: RoutedProvider = { + name: "acme", + env: "ACME_API_KEY", + key: { header: "Authorization", prefix: "Bearer " }, +}; +const globex: RoutedProvider = { + name: "globex", + env: "GLOBEX_API_KEY", + key: { query: "api_key" }, +}; +const PROVIDERS = [acme, globex]; +/** acme has two targets, globex one whose address comes from the connection. */ +const targets = ( + { name }: RoutedProvider, + config: Readonly>, +): Record => + name === "acme" + ? { + acme: { baseUrl: "https://api.acme.example/", methods: ["POST"] }, + acmeFiles: { baseUrl: "https://files.acme.example/", methods: ["GET"] }, + } + : { + globex: { + baseUrl: `https://${config.region ?? "us"}.globex.example/`, + methods: ["GET"], + }, + }; + +describe("routerCredential", () => { + const selection = routerCredential( + "acmeOrGlobex", + PROVIDERS, + targets, + )({ region: "eu" }); + const method = selection.type.methods[selection.method]; + + it("declares every provider's targets, each from the connection's config", () => { + assert.deepEqual( + Object.fromEntries( + Object.entries(method.targets).map(([name, target]) => [ + name, + target.baseUrl, + ]), + ), + { + acme: "https://api.acme.example/", + acmeFiles: "https://files.acme.example/", + globex: "https://eu.globex.example/", + }, + ); + }); + + it("makes every key optional, and places each on its own provider's targets alone", () => { + assert.deepEqual(method.authentication, { + kind: "static", + field: "credential", + parts: ["acme", "globex"], + optionalParts: ["acme", "globex"], + placements: [ + { + in: "header", + part: "acme", + name: "Authorization", + prefix: "Bearer ", + targets: ["acme", "acmeFiles"], + }, + { in: "query", part: "globex", name: "api_key", targets: ["globex"] }, + ], + }); + }); +}); + +describe("the connection of a plugin that routes", () => { + it("has a provider field and a key per provider, filled from its environment variable", () => { + const fields = connectionFields({ + type: "object", + properties: routerConnectionFields(PROVIDERS, "Which provider"), + } as never); + assert.deepEqual(Object.keys(fields), [ + "provider", + "acmeApiKey", + "globexApiKey", + ]); + assert.equal(fields.provider.description, "Which provider"); + assert.equal(fields.globexApiKey.env, "GLOBEX_API_KEY"); + assert.equal(fields.globexApiKey.required, false); + assert.equal(providerKeyField(globex), "globexApiKey"); + }); + + it("names its provider, which needs a key only where the connection signs for itself", () => { + assert.equal(namedProvider("p", PROVIDERS, {}, true), undefined); + assert.equal( + namedProvider("p", PROVIDERS, { provider: "globex" }, false), + globex, + ); + assert.equal( + namedProvider( + "p", + PROVIDERS, + { provider: "globex", globexApiKey: "g" }, + true, + ), + globex, + ); + assert.throws( + () => namedProvider("p", PROVIDERS, { provider: "globex" }, true), + { + message: + "p: no key for globex, the connection's provider. Set GLOBEX_API_KEY.", + }, + ); + assert.throws( + () => namedProvider("p", PROVIDERS, { provider: "initech" }, false), + { + message: + 'p: the connection names the provider "initech". The providers are acme, globex.', + }, + ); + }); + + it("offers the providers it holds a key for, in order, or says which keys to set", () => { + assert.deepEqual( + keyedProviders("p", "search", PROVIDERS, { + globexApiKey: "g", + acmeApiKey: "a", + }), + [acme, globex], + ); + assert.deepEqual( + keyedProviders("p", "search", PROVIDERS, { globexApiKey: "g" }), + [globex], + ); + assert.throws(() => keyedProviders("p", "search", PROVIDERS, {}), { + message: + 'p: no search provider has a key. Set one of ACME_API_KEY, GLOBEX_API_KEY, or the connection\'s "provider" when the host keeps the keys.', + }); + }); +}); diff --git a/packages/codemode/src/tests/helpers/image.ts b/packages/codemode/src/tests/helpers/image.ts new file mode 100644 index 00000000..44f3f409 --- /dev/null +++ b/packages/codemode/src/tests/helpers/image.ts @@ -0,0 +1,10 @@ +/** The first bytes of a PNG of this size: all that tells an image's type and size. */ +export function png(width: number, height: number): Buffer { + const bytes = Buffer.alloc(33); + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(bytes); + bytes.writeUInt32BE(13, 8); + bytes.write("IHDR", 12); + bytes.writeUInt32BE(width, 16); + bytes.writeUInt32BE(height, 20); + return bytes; +} diff --git a/packages/codemode/src/tests/image.test.ts b/packages/codemode/src/tests/image.test.ts new file mode 100644 index 00000000..b94cf71b --- /dev/null +++ b/packages/codemode/src/tests/image.test.ts @@ -0,0 +1,119 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, describe, it } from "node:test"; +import { + imageBase64, + imageDataUrl, + imageFacts, + readLocalImage, +} from "../utils/image.js"; +import { png } from "./helpers/image.js"; + +const dir = mkdtempSync(join(tmpdir(), "image-test-")); +after(() => rmSync(dir, { recursive: true, force: true })); + +describe("imageFacts", () => { + it("tells an image's type and size from its first bytes", () => { + assert.deepEqual(imageFacts(png(640, 480)), { + mimeType: "image/png", + width: 640, + height: 480, + }); + const gif = Buffer.alloc(16); + gif.write("GIF89a"); + gif.writeUInt16LE(320, 6); + gif.writeUInt16LE(200, 8); + assert.deepEqual(imageFacts(gif), { + mimeType: "image/gif", + width: 320, + height: 200, + }); + const jpeg = Buffer.from([ + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, 0xff, 0xc0, 0x00, 0x11, + 0x08, 0x01, 0xe0, 0x02, 0x80, 0x03, 0x00, 0x00, + ]); + assert.deepEqual(imageFacts(jpeg), { + mimeType: "image/jpeg", + width: 640, + height: 480, + }); + const webp = Buffer.alloc(30); + webp.write("RIFF"); + webp.write("WEBP", 8); + webp.write("VP8X", 12); + webp.writeUIntLE(799, 24, 3); + webp.writeUIntLE(599, 27, 3); + assert.deepEqual(imageFacts(webp), { + mimeType: "image/webp", + width: 800, + height: 600, + }); + assert.deepEqual( + imageFacts( + Buffer.from( + '\n', + ), + ), + { mimeType: "image/svg+xml" }, + ); + assert.equal(imageFacts(Buffer.from("plain text, long enough")), undefined); + }); +}); + +describe("an image's bytes for an API", () => { + it("are base64, or a data URL with the image's type", () => { + const image = { bytes: new Uint8Array([0]), mimeType: "image/png" }; + assert.equal(imageBase64(image), "AA=="); + assert.equal(imageDataUrl(image), "data:image/png;base64,AA=="); + }); +}); + +describe("readLocalImage", () => { + const options = { + subject: "example: photo", + maxBytes: 1024 * 1024, + types: ["image/png", "image/jpeg"], + }; + + it("reads an image with what its bytes say it is", async () => { + const file = join(dir, "photo.jpg"); + writeFileSync(file, png(640, 480)); + const image = await readLocalImage(file, options); + assert.deepEqual( + { ...image, bytes: image.bytes.byteLength }, + { + mimeType: "image/png", + width: 640, + height: 480, + bytes: 33, + fileName: "photo.jpg", + }, + ); + }); + + it("refuses a file that is none of the types, whatever its name, and one too large", async () => { + const text = join(dir, "notes.png"); + writeFileSync(text, "not an image"); + await assert.rejects(() => readLocalImage(text, options), { + message: "example: photo is not a PNG or JPEG image.", + }); + const svg = join(dir, "logo.svg"); + writeFileSync(svg, ''); + await assert.rejects( + () => + readLocalImage(svg, { + ...options, + types: ["image/png", "image/jpeg", "image/webp"], + }), + { message: "example: photo is not a PNG, JPEG or WebP image." }, + ); + const big = join(dir, "big.png"); + writeFileSync(big, Buffer.concat([png(10, 10), Buffer.alloc(40)])); + await assert.rejects( + () => readLocalImage(big, { ...options, maxBytes: 64 }), + { message: /^example: photo is larger than / }, + ); + }); +}); diff --git a/packages/codemode-imagegen/src/image.ts b/packages/codemode/src/utils/image.ts similarity index 62% rename from packages/codemode-imagegen/src/image.ts rename to packages/codemode/src/utils/image.ts index e677068d..525fa0b5 100644 --- a/packages/codemode-imagegen/src/image.ts +++ b/packages/codemode/src/utils/image.ts @@ -1,21 +1,11 @@ /** * What an image is, read from its first bytes: its type, and its size in - * pixels where the format states one. And the two forms an API takes an - * image's bytes in. + * pixels where the format states one. And an image file an action input + * names, read as what its bytes say it is. */ -/** An image's bytes in base64, for an API that takes them in JSON. */ -export function base64Of(image: { bytes: Uint8Array }): string { - return Buffer.from(image.bytes).toString("base64"); -} - -/** An image as a `data:` URL, for an API that takes a link or one of these. */ -export function dataUrlOf(image: { - bytes: Uint8Array; - mimeType: string; -}): string { - return `data:${image.mimeType};base64,${base64Of(image)}`; -} +import { basename } from "node:path"; +import { readLocalFile } from "./local-file.js"; export interface ImageFacts { mimeType: string; @@ -23,8 +13,8 @@ export interface ImageFacts { height?: number; } -/** The file extension of each type an image provider answers with. */ -export const EXTENSIONS: Readonly> = { +/** The file extension of each type of image `imageFacts` tells. */ +export const IMAGE_EXTENSIONS: Readonly> = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp", @@ -32,6 +22,28 @@ export const EXTENSIONS: Readonly> = { "image/svg+xml": ".svg", }; +/** What each type is called in an error. */ +const TYPE_NAMES: Readonly> = { + "image/png": "PNG", + "image/jpeg": "JPEG", + "image/webp": "WebP", + "image/gif": "GIF", + "image/svg+xml": "SVG", +}; + +/** An image's bytes in base64, for an API that takes them in JSON. */ +export function imageBase64(image: { bytes: Uint8Array }): string { + return Buffer.from(image.bytes).toString("base64"); +} + +/** An image as a `data:` URL, for an API that takes a link or one of these. */ +export function imageDataUrl(image: { + bytes: Uint8Array; + mimeType: string; +}): string { + return `data:${image.mimeType};base64,${imageBase64(image)}`; +} + function ascii(bytes: Uint8Array, start: number, length: number): string { return String.fromCharCode(...bytes.subarray(start, start + length)); } @@ -78,7 +90,7 @@ function webpSize( return undefined; } -/** The type and size of an image, or nothing when the bytes are no image this package writes. */ +/** The type and size of an image, or nothing when the bytes are none of the types in `IMAGE_EXTENSIONS`. */ export function imageFacts(bytes: Uint8Array): ImageFacts | undefined { if (bytes.length < 12) return undefined; const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); @@ -103,3 +115,34 @@ export function imageFacts(bytes: Uint8Array): ImageFacts | undefined { return { mimeType: "image/svg+xml" }; return undefined; } + +/** An image read from a file on the codemode host. */ +export interface LocalImage extends ImageFacts { + bytes: Buffer; + fileName: string; +} + +/** + * Read an image file an action input names. What it is, its bytes say, never + * its name: a file that is none of `types` is refused. `subject` is what + * errors call the file. + */ +export async function readLocalImage( + path: string, + options: { subject: string; maxBytes: number; types: readonly string[] }, +): Promise { + const { subject, maxBytes, types } = options; + const bytes = await readLocalFile(path, { + subject, + maxBytes, + oversize: `${subject} is larger than ${maxBytes / (1024 * 1024)} MiB`, + }); + const facts = imageFacts(bytes); + if (!facts || !types.includes(facts.mimeType)) { + const names = types.map((type) => TYPE_NAMES[type] ?? type); + throw new Error( + `${subject} is not a ${[names.slice(0, -1).join(", "), names.at(-1)].filter(Boolean).join(" or ")} image.`, + ); + } + return { ...facts, bytes, fileName: basename(path) }; +}