Skip to content
Myr

Merge build/1007

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents f155a0c, f38c8dd · Browse files · 14 files+741 added−75 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

14 files+741 added−75 removed

  • tests:+440 added−2 removed
  • other:+301 added−73 removed

14 files+741 added−75 removed

modified:apps/platform/src/auth/provider.ts+6 added-6 removed
13 unmodified lines
14 */15import { OAuthAuthorizationServer } from "@cloudflare/workers-oauth-provider";16import { D1Client } from "@effect/sql-d1";17import { Context, Layer, Option, Redacted } from "effect";18import { HttpRouter } from "effect/http";1819import { AccountsD1 } from "../adapters/accounts-d1.ts";20import { WorkerFetch } from "../adapters/fetch.ts";21import { IdentitiesD1 } from "../adapters/identities-d1.ts";22import type { TokenReader } from "../adapters/sessions-oauth.ts";23import type { PlatformConfig } from "../platform.ts";24import { buildHandler } from "../router-build.ts";25import { SignInAttemptsBinding } from "./attempts/binding.ts";26import { GOOGLE_ACCOUNTS, GoogleClient, googleRoutes } from "./google.ts";27import type { GoogleServices } from "./google.ts";28import { OAuthStore } from "./oauth-store.ts";
45 unmodified lines
74) => Promise<Response>;7576/**77 * The Worker's fetch: OAuth and sign-in in front of `platformFetch`. The78 * sign-in routes are built once from `services` (a failure to build them79 * answers 500 on those paths only); each origin's authorization server is78 * sign-in routes are built once from `services`, now, awaiting nothing79 * (`router-build.ts`; a failure to build them answers 500 on those paths80 * only); each origin's authorization server is81 * made on its first request and kept for the isolate's life (a Worker is82 * reached only on its own hostnames).83 */84export const oauthProvider = <E>(85 services: Layer.Layer<GoogleServices, E>,86 platformFetch: PlatformFetch87) => {87 const { dispose, handler } = HttpRouter.toWebHandler(88 Layer.mergeAll(signInRoutes, googleRoutes).pipe(Layer.provide(services)),89 { disableLogger: true }88 const { dispose, handler } = buildHandler(89 Layer.mergeAll(signInRoutes, googleRoutes).pipe(Layer.provide(services))90 );9192 const servers = new Map<string, OAuthAuthorizationServer<OAuthEnv>>();93
110 unmodified lines
added:apps/platform/src/router-build.ts+129 added
1/**2 * A router's fetch handler, built before it answers anything.3 *4 * effect's `HttpRouter.toWebHandler` starts the layer's build when the5 * handler is made and has every request await that one build. On Workers6 * a request whose client goes away is cancelled where it stands, its7 * fibers never resumed: had the build awaited I/O a request started, every8 * later request would wait on it for the isolate's life (the 1101 hang9 * the code cache once had). Here the build runs at once, synchronously, so10 * it cannot await anything: a layer that awaits a promise or a timer while11 * it is built throws where the handler is made, which at module load stops12 * the Worker from starting (and a deploy from going out). Such work belongs13 * in the request path, per request. A build that fails otherwise (an env14 * that did not decode) fails every request with its error, as effect's does.15 *16 * Only the build's own fiber is run to its end here: a fiber the build forks17 * (a layer built beside others) that outlasts its turn and yields is18 * refused as if it had awaited. Both real compositions are built in19 * `test/router-build.test.ts`, so such a build fails `verify`, never a20 * deploy.21 */22import {23 Cause,24 Context,25 Data,26 Effect,27 Exit,28 Layer,29 Scheduler,30 Scope,31} from "effect";32import type { HttpServerRequest } from "effect/http";33import { HttpEffect, HttpRouter } from "effect/http";3435/** A router's build awaited a promise or a timer; nothing was served. */36export class RouterBuildAwaited extends Data.TaggedError("RouterBuildAwaited")<{37 readonly message: string;38}> {}3940/** What a request needs beyond itself: the services `R`'s routes require of it. */41type RequestNeeds<A, R> = Exclude<42 | HttpRouter.Request.Only<"Requires", R>43 | HttpRouter.Request.Only<"GlobalRequires", R>,44 A | Scope.Scope | HttpServerRequest.HttpServerRequest45>;4647/**48 * `appLayer`'s routes as a fetch handler, its layer built now; a request49 * that needs services of its own (`RequestNeeds`) is given them as its50 * context. `dispose` closes what the build opened.51 */52export const buildHandler = <53 A,54 E,55 R extends56 | HttpRouter.HttpRouter57 | HttpRouter.Request<"Requires", unknown>58 | HttpRouter.Request<"GlobalRequires", unknown>59 | HttpRouter.Request<"Error", unknown>60 | HttpRouter.Request<"GlobalError", unknown>,61>(62 appLayer: Layer.Layer<A, E, R>63) => {64 const scope = Scope.makeUnsafe();6566 // SAFETY: what `R` adds to `HttpRouter` are `HttpRouter.Request` markers,67 // which name what each request is given (its context) or may fail with,68 // never a service the build needs; effect's `toWebHandler` drops them the69 // same way.70 /* oxlint-disable typescript/no-unsafe-type-assertion -- the markers are phantom types with no service behind them; see SAFETY. */71 // @effect-diagnostics-next-line unsafeEffectTypeAssertion:off -- the markers are phantom types with no service behind them; see SAFETY.72 const routed = Layer.provideMerge(appLayer, HttpRouter.layer) as Layer.Layer<73 A | HttpRouter.HttpRouter,74 E75 >;76 /* oxlint-enable typescript/no-unsafe-type-assertion */7778 // `runSyncExit` runs its fiber on a scheduler of its own, which yields79 // through microtasks and would ride along in any context a layer captures80 // while it is built (`authenticated` verifies every credential in the81 // one it captured). The build runs on the scheduler a fiber has by default82 // instead; `runSyncExit` still drains what it schedules before it returns.83 const built = Effect.runSyncExit(84 Layer.buildWithScope(routed, scope).pipe(85 Effect.provideService(86 Scheduler.Scheduler,87 Scheduler.Scheduler.defaultValue()88 )89 )90 );9192 const awaited =93 Exit.isFailure(built) &&94 built.cause.reasons.some(95 (reason) =>96 Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)97 );9899 if (awaited) {100 throw new RouterBuildAwaited({101 message:102 "The router's build awaited a promise or a timer: move that work into the request path.",103 });104 }105106 const serveRequest = Exit.match(built, {107 onFailure: (cause) => () => Effect.runPromise(Effect.failCause(cause)),108 onSuccess: (context) =>109 HttpEffect.toWebHandlerWith<110 A | HttpRouter.HttpRouter,111 HttpServerRequest.HttpServerRequest | Scope.Scope,112 never113 >(context)(114 // @effect-diagnostics-next-line anyUnknownInErrorContext:off -- the router's own effect fails with whatever a route left unhandled, which `toWebHandlerWith` turns into a response (404 for no route), as effect's `toWebHandler` does with the same effect.115 Context.get(context, HttpRouter.HttpRouter).asHttpEffect()116 ),117 });118119 /** One request, given `context` beside it: what `R`'s routes require of it. */120 const handler = (121 request: Request,122 context?: Context.Context<RequestNeeds<A, R>>123 ): Promise<Response> => serveRequest(request, context);124125 return {126 dispose: () => Effect.runPromise(Scope.close(scope, Exit.void)),127 handler,128 };129};
modified:apps/platform/src/surfaces.ts+14 added-16 removed
1import { commandDocs } from "@repo/agent-kit/command-doc";2import { platformSkill } from "@repo/agent-kit/platform";2import { platformSkillParts } from "@repo/agent-kit/platform";3import { RepoHost } from "@repo/artifacts/repo-host";4import { Brand } from "@repo/brand";5import { Upstream } from "@repo/git/upstream";6import { CodeStore } from "@repo/project/code-store";
3 unmodified lines
10import { authenticated, bearerToken } from "@repo/protocol/authenticate";11import { Client, Contracts, surfaced } from "@repo/protocol/contracts";12import { ProjectName } from "@repo/protocol/ids";13import { toToolkit } from "@repo/protocol/mcp";14import {15 briefResources,16 skillIn,17 skillPrompt,18} from "@repo/protocol/mcp-extras";14import { briefResources, skillPrompt } from "@repo/protocol/mcp-extras";15import { Authenticated } from "@repo/protocol/principal";16import type { Person } from "@repo/protocol/principal";17import { Context, Effect, Layer, Option, Schema } from "effect";18import { McpProtocol, McpServer } from "effect/ai";
18 unmodified lines
37import { LayerGate } from "./layer-gate.ts";38import { rawResponse } from "./raw.ts";39import { releaseRoutes } from "./releases.ts";40import type { ReleaseStore } from "./releases.ts";41import { buildHandler } from "./router-build.ts";42import { Sessions } from "./sessions.ts";43import { isFramed } from "./watch.ts";44import { agentSkillRoutes } from "./well-known.ts";45
239 unmodified lines
285286/**287 * The platform's skill as the prompt `contribute`, made when the server288 * starts from agent-kit's command list, the one the CLI's prompt and the292 * web's `llms.txt` read, so they say the same.289 * web's `llms.txt` read, so they say the same. Made from the skill's parts,290 * not its `SKILL.md`, whose hash is a promise the router's build may not291 * await (`router-build.ts`).292 */294const contribute = Layer.unwrap(295 Effect.map(296 skillIn(platformSkill({ commands: commandDocs(Contracts) })),297 skillPrompt298 )293const contribute = skillPrompt(294 platformSkillParts({ commands: commandDocs(Contracts) })295);296297/**298 * The MCP-surfaced contracts as tools at `/mcp`, beside each ask's brief
165 unmodified lines
464 }465 })466);467472/** The platform's fetch handler over `services`. */468/**469 * The platform's fetch handler over `services`, its router built now,470 * before any request, awaiting nothing (`router-build.ts`).471 */472export const serve = <E>(services: Layer.Layer<Services, E>) =>474 HttpRouter.toWebHandler(473 buildHandler(474 Layer.mergeAll(475 home,476 health,477 discovery,
3 unmodified lines
481 rpc,482 releaseRoutes,483 agentSkillRoutes,484 identifyCaller486 ).pipe(Layer.provide(services)),487 { disableLogger: true }485 ).pipe(Layer.provide(services))486 );
modified:apps/platform/src/worker.ts+5 added-2 removed
added:apps/platform/test/router-build.test.ts+176 added
1/**2 * The router's handlers are built at module load, before any request, and3 * the build awaits nothing. Workers cancels a request whose client4 * left without interrupting its fibers, so a build that awaited a request's5 * I/O would leave every later request waiting on it. `buildHandler` builds6 * the router's layer at once or refuses: a layer that awaits a promise or7 * a timer while it is built throws where the handler is made, so the8 * Worker cannot start with one.9 */10import { describe, expect, it } from "@effect/vitest";11import { untouchable } from "@repo/testkit/untouchable";12import { env } from "cloudflare:workers";13import { Effect, Layer, Scheduler, Schema } from "effect";14import { HttpRouter, HttpServerResponse } from "effect/http";1516import { oauthProvider, signInServices } from "../src/auth/provider.ts";17import { decodeEnv, platformOf } from "../src/platform.ts";18import { buildHandler } from "../src/router-build.ts";19import { serve } from "../src/surfaces.ts";20import { callsTo, fakeEnv } from "./fake-env.ts";21import { origin } from "./harness.ts";2223/** A Worker's context, which nothing here needs. */24const context = untouchable<ExecutionContext>("ExecutionContext");2526/** One route, `GET /ping`, answering `pong`. */27const ping = HttpRouter.use((router) =>28 router.add("GET", "/ping", Effect.succeed(HttpServerResponse.text("pong")))29);3031/** `ping`, beside a layer that counts each time it is built. */32const counted = () => {33 const builds: number[] = [];3435 const layer = Layer.merge(36 ping,37 Layer.effectDiscard(Effect.sync(() => builds.push(builds.length + 1)))38 );3940 return { builds, layer };41};4243/** `ping`, beside a layer that awaits a promise while it is built. */44const awaiting = Layer.merge(45 ping,46 Layer.effectDiscard(Effect.promise(() => Promise.resolve()))47);4849/**50 * `GET /scheduler`, answering the execution mode of the scheduler its51 * effect runs on, in the context its layer captured while it was built (as52 * `authenticated` does for each credential it verifies).53 */54const capturing = Layer.unwrap(55 Effect.map(Effect.context(), (built) =>56 HttpRouter.use((router) =>57 router.add(58 "GET",59 "/scheduler",60 Scheduler.Scheduler.useSync(({ executionMode }) =>61 HttpServerResponse.text(executionMode)62 ).pipe(Effect.provideContext(built))63 )64 )65 )66);6768const pinged = (handler: (request: Request) => Promise<Response>) =>69 Effect.promise(() => handler(new Request(`${origin}/ping`))).pipe(70 Effect.flatMap((response) => Effect.promise(() => response.text()))71 );7273describe("the router's build", () => {74 it.effect(75 "is done when the handler is made, and no request builds it again",76 () =>77 Effect.gen(function* () {78 const { builds, layer } = counted();7980 const { dispose, handler } = buildHandler(layer);8182 expect(builds).toStrictEqual([1]);8384 const answers = yield* Effect.all([85 pinged(handler),86 pinged(handler),87 pinged(handler),88 ]);8990 expect(answers).toStrictEqual(["pong", "pong", "pong"]);91 expect(builds).toStrictEqual([1]);9293 yield* Effect.promise(dispose);94 })95 );9697 it("refuses a layer that awaits a promise while it is built, where the handler is made", () => {98 expect(() => buildHandler(awaiting)).toThrow(/awaited/u);99 });100101 it.effect(102 "leaves a request that runs in a context captured at build on the default scheduler",103 () =>104 Effect.gen(function* () {105 const { dispose, handler } = buildHandler(capturing);106107 const mode = yield* Effect.promise(() =>108 handler(new Request(`${origin}/scheduler`))109 ).pipe(110 Effect.flatMap((response) => Effect.promise(() => response.text()))111 );112113 expect(mode).toBe("async");114115 yield* Effect.promise(dispose);116 })117 );118});119120/** What `/health` answers. */121const Health = Schema.fromJsonString(122 Schema.Struct({ ok: Schema.Boolean, stage: Schema.String })123);124125describe("the Worker's two handlers", () => {126 it.effect(127 "are built when the Worker module has loaded, before any request",128 () =>129 Effect.gen(function* () {130 const before = callsTo(env.PROJECT).length;131132 // Loading runs `serve` and `oauthProvider`, each of which throws if133 // its build awaited anything: a module that loads has both built.134 const worker = yield* Effect.promise(() => import("../src/worker.ts"));135136 expect(Object.keys(worker.default)).toStrictEqual(["fetch"]);137 expect(callsTo(env.PROJECT)).toHaveLength(before);138 })139 );140141 it.effect(142 "build at once from the decoded env, touching no binding, and answer the first request",143 () =>144 Effect.gen(function* () {145 const shim = fakeEnv();146147 const config = yield* decodeEnv(shim).pipe(Effect.orDie);148149 // As `worker.ts` composes them: each would throw here if its build150 // awaited anything, and `fakeEnv`'s bindings throw when touched.151 const platform = serve(platformOf(config));152153 const { handler } = oauthProvider(signInServices(config), (request) =>154 platform.handler(request)155 );156157 expect(callsTo(shim.PROJECT)).toStrictEqual([]);158159 const health = yield* Effect.promise(() =>160 Promise.resolve(161 handler.fetch(new Request(`${origin}/health`), env, context)162 )163 );164165 expect(health.status).toBe(200);166 expect(167 yield* Effect.promise(() => health.text()).pipe(168 Effect.flatMap(Schema.decodeEffect(Health)),169 Effect.orDie170 )171 ).toStrictEqual({ ok: true, stage: "local" });172173 yield* Effect.promise(platform.dispose);174 })175 );176});
modified:packages/agent-kit/src/platform.ts+13 added-6 removed
97 unmodified lines
98 ...refusalSection(),99 ...unfencedSection(),100 ]);101102/**103 * The platform's skill as the prompt `contribute` serves it: its name, its104 * description and its Markdown, made at once. The platform builds the105 * prompt where nothing may be awaited (its router, at module load), and106 * `SKILL.md`'s frontmatter hashes the body through WebCrypto, a promise.107 */108export const platformSkillParts = (input: PlatformInput) => ({109 body: platformBody(input),110 description,111 name: Brand.slug,112});113114const skillFile = (input: PlatformInput) =>103 frontmatter({104 body: platformBody(input),105 description,106 landed: Option.none(),107 name: Brand.slug,108 });115 frontmatter({ ...platformSkillParts(input), landed: Option.none() });116117/** `skills/<slug>/SKILL.md`: the platform's skill, which comes from no landing. */118export const platformSkill = (119 input: PlatformInput
107 unmodified lines
modified:packages/agent-kit/test/generate.test.ts+31 added-2 removed
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Effect, Schema } from "effect";4import { Effect, Option, Schema } from "effect";56import { agentsBlock, upsertAgentsBlock } from "../src/agents-block.ts";7import { contentHash } from "../src/generated-file.ts";7import {8 contentHash,9 describedIn,10 readManaged,11} from "../src/generated-file.ts";12import type { GeneratedFile } from "../src/generated-file.ts";13import type { HookEvent } from "../src/hook-events.ts";14import { claudeEventOf } from "../src/hook-events.ts";15import {16 agentPluginsBundle,17 claudePlugin,18 platformSkill,19 platformSkillParts,20} from "../src/platform.ts";21import { projectSkill } from "../src/project-skill.ts";22import { wellKnownSkills } from "../src/well-known.ts";23import { commands, landed, platformUrl, policy, project } from "./fixtures.ts";24import { expectGolden, transcript } from "./golden.ts";2526const plugin = `plugins/${Brand.slug}`;2728/** The `name:` line of a file's frontmatter; none without one. */29const frontmatterName = (content: string) =>30 Option.fromNullishOr(/^name: (?<name>.+)$/mu.exec(content)?.groups?.name);3132const skill = `${project}-contribute`;3334/** `sha256("hello\n")`, as every tool that hashes prints it. */35const helloDigest =
258 unmodified lines
294 })295 );296});297298describe("the platform's skill as the prompt contribute serves it", () => {299 it.effect("has the name, description and body its SKILL.md gives", () =>300 Effect.gen(function* () {301 const [own] = yield* platformSkill({ commands, platformUrl });302 const content = own?.content ?? "";303 const parts = platformSkillParts({ commands, platformUrl });304305 expect({306 body: Option.map(readManaged(content), ({ body }) => body),307 description: describedIn(content),308 name: frontmatterName(content),309 }).toStrictEqual({310 body: Option.some(parts.body),311 description: Option.some(parts.description),312 name: Option.some(parts.name),313 });314 })315 );316});317318describe("the Claude Code plugin's hooks", () => {319 it.effect(320 "send PreToolUse on edits, Stop and SessionStart to the CLI's hook command",321 () =>
134 unmodified lines
modified:packages/config/test/smoke-loop.test.ts+176 added
203 unmodified lines
204 layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),205 };206});207208/**209 * A platform scripted at the process boundary: `status` names the decider,210 * `projects` lists `listed`, git does what it is asked, and `init` makes211 * the project on the platform and then fails (as a push that answered 500212 * after the project was made did on a dev stage). What was spawned is kept, git by213 * its subcommand and the CLI by its command.214 */215const scripted = (listed: readonly string[]) =>216 Effect.gen(function* () {217 const asked = yield* Ref.make<readonly string[]>([]);218219 // Each CLI command's `--json` envelope, as the CLI prints it.220 const replies = new Map([221 [222 "status",223 {224 code: 0,225 stdout: JSON.stringify({226 command: "status",227 data: { handle: decider },228 ok: true,229 v: 1,230 }),231 },232 ],233 [234 "projects",235 {236 code: 0,237 stdout: JSON.stringify({238 command: "projects",239 data: {240 projects: listed.map((project) => ({241 openAsks: 0,242 posture: "open",243 project,244 })),245 },246 ok: true,247 v: 1,248 }),249 },250 ],251 ["init", { code: 1, stdout: "" }],252 ]);253254 const spawner = ChildProcessSpawner.make((command) =>255 Effect.gen(function* () {256 const [program, args] = ChildProcess.isStandardCommand(command)257 ? [command.command, command.args]258 : ["a pipe", []];259260 // The CLI runs as `bun <entry> <command> … --json`.261 const said =262 program === "bun" ? (args[1] ?? "") : `${program} ${args[0] ?? ""}`;263264 yield* Ref.update(asked, (all) => [...all, said]);265266 const reply = replies.get(said) ?? { code: 0, stdout: "" };267268 return ChildProcessSpawner.makeHandle({269 all: Stream.empty,270 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(reply.code)),271 getInputFd: () => Sink.drain,272 getOutputFd: () => Stream.empty,273 isRunning: Effect.succeed(false),274 kill: () => Effect.void,275 pid: ChildProcessSpawner.ProcessId(1),276 stderr: Stream.empty,277 stdin: Sink.drain,278 stdout: Stream.make(new TextEncoder().encode(reply.stdout)),279 unref: Effect.succeed(Effect.void),280 });281 })282 );283284 return {285 asked: Ref.get(asked),286 layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),287 };288 });289290/**291 * The loop for run `r1` on the scripted platform, with the ledger in a file292 * of its own: how it ended, the CLI commands it ran, and the ledger's lines.293 */294const loopOnScripted = (listed: readonly string[]) =>295 Effect.gen(function* () {296 const fs = yield* FileSystem.FileSystem;297 const path = yield* Path.Path;298 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "smoke-ledger-" });299 const ledger = path.join(dir, "created.jsonl");300 const platform = yield* scripted(listed);301302 const failure = yield* smokeLoop({303 answerer: tokens.answerer,304 decider: tokens.decider,305 origin: "https://platform-dev.example.workers.dev",306 run: "r1",307 stage: "dev-example",308 }).pipe(309 Effect.catchTag("DemoStageRefused", Effect.die),310 Effect.flip,311 Effect.provide(platform.layer),312 Effect.provideService(LedgerFile, ledger)313 );314315 const lines = yield* readLedger.pipe(316 Effect.provideService(LedgerFile, ledger)317 );318319 return {320 cli: (yield* platform.asked).filter((said) => !said.startsWith("git ")),321 failure,322 ledger: lines.map(({ by, kind, name, stage }) => ({323 by,324 kind,325 name,326 stage,327 })),328 };329 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));330331describe("smoke --loop's throwaway ledger", () => {332 it.live(333 "writes the project and its repo before init, so an init that made the project and then failed leaves them in the ledger",334 () =>335 Effect.gen(function* () {336 const { cli, failure, ledger } = yield* loopOnScripted([]);337338 expect({ cli, ledger, step: failure.step }).toStrictEqual({339 cli: ["status", "status", "projects", "init"],340 ledger: [341 {342 by: "smoke",343 kind: "project",344 name: "smoke-r1",345 stage: "dev-example",346 },347 {348 by: "smoke",349 kind: "repo",350 name: "smoke-r1",351 stage: "dev-example",352 },353 ],354 step: "init",355 });356 })357 );358359 it.live(360 "stops before init on a name the platform already lists, and writes nothing",361 () =>362 Effect.gen(function* () {363 const { cli, failure, ledger } = yield* loopOnScripted([364 "datekit",365 "smoke-r1",366 ]);367368 expect({369 cli,370 ledger,371 reason: failure.reason,372 step: failure.step,373 }).toStrictEqual({374 cli: ["status", "status", "projects"],375 ledger: [],376 reason:377 "smoke-r1 is on the platform already, so nothing was made or recorded: a run a second later takes another name",378 step: "init",379 });380 })381 );382});383384describe("smoke --loop on demo", () => {385 it.live(386 "is refused with DemoStageRefused before any request or process: a throwaway project would show on demo's front page",387 () =>
143 unmodified lines
modified:packages/drafting/src/drafter/binding.ts+53 added-8 removed
27 unmodified lines
28 readonly role: "system" | "user";29}3031/**32 * How hard a reasoning model thinks before it answers, in the key a Workers33 * AI chat call takes it (glm-5.3: max, high or low; gpt-oss-120b: low,34 * medium or high; `@cloudflare/workers-types` 5.20261006.1).35 */36export interface ReasoningInputs {37 readonly reasoning_effort: "low";38}3940/**41 * What the drafter sends: the messages, the JSON Schema the reply must33 * match, and the sampling it asks for. A type alias, not an interface, so34 * it fits the binding's open `Record` of inputs.42 * match, the sampling it asks for, and the model's own settings43 * (`modelSettings`). A type alias, not an interface, so it fits the44 * binding's open `Record` of inputs.45 */36// oxlint-disable-next-line typescript/consistent-type-definitions -- an interface has no implicit index signature, so it would not fit the generated Ai's `Record<string, unknown>` inputs37export type ChatInputs = {46export type ChatInputs = Partial<ReasoningInputs> & {47 readonly max_completion_tokens: number;48 readonly messages: readonly ChatMessage[];49 readonly response_format: {50 readonly json_schema: JsonSchema.JsonSchema;
2 unmodified lines
53 readonly seed: number;54 readonly temperature: number;55};5657/** What a model is asked with beyond the prompt: its output cap, and how hard it reasons. */58export interface ModelSettings {59 readonly max_completion_tokens: number;60 /** The model's own reasoning input, sent as it stands; none sends nothing. */61 readonly reasoning?: ReasoningInputs;62}6364/** What a model not in `MODEL_SETTINGS` is asked with: `DRAFT_MODEL`'s settings. */65const DEFAULT_SETTINGS: ModelSettings = { max_completion_tokens: 12_000 };6667/**68 * The fallback models reason before they answer, and spent 12,000 tokens69 * doing so on the drafting prompt before the JSON was done. Each70 * gets more room and a low effort, in the key its Workers AI input schema71 * takes for a chat call (`ReasoningInputs`).72 */73const FALLBACK_SETTINGS: ModelSettings = {74 max_completion_tokens: 32_000,75 reasoning: { reasoning_effort: "low" },76};7778/** Settings by Workers AI model id; `DRAFT_MODEL` (kimi-k2.7-code) takes the defaults. */79const MODEL_SETTINGS: ReadonlyMap<string, ModelSettings> = new Map([80 ["@cf/moonshotai/kimi-k2.7-code", DEFAULT_SETTINGS],81 ["@cf/zai-org/glm-5.3", FALLBACK_SETTINGS],82 ["@cf/openai/gpt-oss-120b", FALLBACK_SETTINGS],83]);8485/** What `model` is asked with beyond the prompt; the defaults for a model not listed. */86export const modelSettings = (model: string): ModelSettings =>87 MODEL_SETTINGS.get(model) ?? DEFAULT_SETTINGS;8889/** `DraftedAsk` as JSON Schema, for `response_format`: an object root, no `$ref`. */90const responseSchema = (() => {91 const { definitions, schema } = Schema.toJsonSchemaDocument(DraftedAsk);92
67 unmodified lines
160 `${input.context.project}:${input.context.at}:${input.attempt}:${input.want}`161 )162 );163123/** The drafter over `ai`, asking `model` (the platform's `DRAFT_MODEL`). */164/** The drafter over `ai`, asking `model` (the platform's `DRAFT_MODEL`) with its settings. */165export const DrafterWorkersAi = (166 ai: AiLike,167 model: string127): Layer.Layer<Drafter> =>128 Layer.succeed(168): Layer.Layer<Drafter> => {169 const settings = modelSettings(model);170171 return Layer.succeed(172 Drafter,173 Drafter.of({174 draft: (input) =>175 Effect.gen(function* () {
8 unmodified lines
184 )185 ),186 try: () =>187 ai.run(model, {145 max_completion_tokens: 12_000,188 ...settings.reasoning,189 max_completion_tokens: settings.max_completion_tokens,190 messages: [191 {192 content: systemPrompt(input.context.policy),193 role: "system",
16 unmodified lines
210 );211 }),212 })213 );214};
modified:packages/drafting/test/binding.test.ts+44 added
113 unmodified lines
114 expect(call.inputs.seed).toBe((yield* callOf).inputs.seed);115 })116 );117118 it.effect(119 "gives each model its own room: the fallbacks more tokens and low reasoning, anything else the defaults",120 () =>121 Effect.gen(function* () {122 const asked = yield* Effect.forEach(123 [124 "@cf/moonshotai/kimi-k2.7-code",125 "@cf/zai-org/glm-5.3",126 "@cf/openai/gpt-oss-120b",127 model,128 ],129 (name) =>130 Effect.gen(function* () {131 const { ai, calls } = fakeAi(chat(json));132133 yield* Drafter.use(({ draft }) => draft(input)).pipe(134 Effect.provide(DrafterWorkersAi(ai, name))135 );136137 const call = yield* Effect.fromNullishOr(calls[0]);138139 return {140 max: call.inputs.max_completion_tokens,141 model: call.model,142 reasoning: Object.hasOwn(call.inputs, "reasoning_effort")143 ? call.inputs.reasoning_effort144 : "none sent",145 };146 })147 );148149 expect(asked).toStrictEqual([150 {151 max: 12_000,152 model: "@cf/moonshotai/kimi-k2.7-code",153 reasoning: "none sent",154 },155 { max: 32_000, model: "@cf/zai-org/glm-5.3", reasoning: "low" },156 { max: 32_000, model: "@cf/openai/gpt-oss-120b", reasoning: "low" },157 { max: 12_000, model, reasoning: "none sent" },158 ]);159 })160 );161162 it.effect("asks for JSON Schema with no null and no Infinity in it", () =>163 Effect.gen(function* () {164 const { response_format: format } = (yield* callOf).inputs;165 const text = JSON.stringify(format.json_schema);
122 unmodified lines
modified:packages/visibility/src/vault/webcrypto.ts+26 added-14 removed
76 unmodified lines
77 ? Option.some(bytes.subarray(0, end))78 : Option.none();79};8081/** The master key as an AES-KW key that can only wrap and unwrap. */82const importMasterKey = (masterKey: Redacted.Redacted) =>81/** The master key's 32 bytes, decoded from its hex; a defect for any other form. */82const masterKeyBytes = (masterKey: Redacted.Redacted) =>83 Schema.decodeEffect(Schema.Uint8ArrayFromHex)(Redacted.value(masterKey)).pipe(84 Effect.mapError(() => new MasterKeyUnusable()),85 Effect.filterOrFail(86 (bytes) => bytes.length === KEY_BYTES,87 () => new MasterKeyUnusable()88 ),89 Effect.flatMap((bytes) =>90 Effect.promise(() =>91 crypto.subtle.importKey("raw", owned(bytes), "AES-KW", false, [92 "wrapKey",93 "unwrapKey",94 ])95 )96 ),89 Effect.map(owned),90 Effect.orDie91 );9293/**94 * The master key as an AES-KW key that can only wrap and unwrap, imported95 * for each call: WebCrypto's import is a promise, and the layer is built96 * where nothing may be awaited (the platform's router, at module load).97 */98const importMasterKey = (bytes: Uint8Array<ArrayBuffer>) =>99 Effect.promise(() =>100 crypto.subtle.importKey("raw", bytes, "AES-KW", false, [101 "wrapKey",102 "unwrapKey",103 ])104 );105106/** A fresh data key, from WebCrypto's random bytes, extractable only to be wrapped. */107const freshDataKey = Effect.sync(() =>108 crypto.getRandomValues(new Uint8Array(KEY_BYTES))109).pipe(
105 unmodified lines
215 masterKey: Redacted.Redacted216): Layer.Layer<WriteOnlyValues> =>217 Layer.effect(218 WriteOnlyValues,213 importMasterKey(masterKey).pipe(214 Effect.map((master) =>219 masterKeyBytes(masterKey).pipe(220 Effect.map((bytes) =>221 WriteOnlyValues.of({216 open: (sealed) => unseal(master, sealed),217 put: (input) => seal(master, input),222 open: (sealed) =>223 Effect.flatMap(importMasterKey(bytes), (master) =>224 unseal(master, sealed)225 ),226 put: (input) =>227 Effect.flatMap(importMasterKey(bytes), (master) =>228 seal(master, input)229 ),230 })231 )232 )233 );
modified:packages/visibility/test/vault.test.ts+13 added
4 unmodified lines
5import {6 Cause,7 Effect,8 Exit,9 Layer,10 Option,11 Predicate,12 Redacted,13 Result,
131 unmodified lines
145 ]);146 })147 );148149 it("is built at once, awaiting nothing: the master key is imported per call", () => {150 // The platform builds its router at module load and refuses a build151 // that awaits (`router-build.ts`), so the vault's layer must build synchronously.152 const built = Effect.runSyncExit(153 Layer.build(masterKey).pipe(Effect.scoped)154 );155156 expect(Exit.isFailure(built) ? Cause.pretty(built.cause) : "built").toBe(157 "built"158 );159 });160161 it.effect("does not open a value under another master key", () =>162 Effect.gen(function* () {163 const sealed = yield* put(token).pipe(Effect.provide(masterKey));164
152 unmodified lines
modified:scripts/lib/smoke/core-loop.ts+29 added-2 removed
19 unmodified lines
20import { Decision, DecisionSubject } from "@repo/protocol/domain/decision";21import { Outcome } from "@repo/protocol/domain/outcome";22import { DraftState, Proposal } from "@repo/protocol/domain/proposal";23import { Envelope } from "@repo/protocol/envelope";24import {25 AskId,26 CommitSha,27 Handle,28 LandedSha,29 ProjectName,24import { AskId, CommitSha, Handle, LandedSha } from "@repo/protocol/ids";25import type { ProjectName, ProposalId } from "@repo/protocol/ids";30} from "@repo/protocol/ids";31import type { ProposalId } from "@repo/protocol/ids";32import { explain } from "@repo/protocol/render";33import {34 Array,35 Config,
423 unmodified lines
459 yield* gitOk(step, person, cwd, ["rev-parse", "HEAD"])460 );461 });462463const Listed = Schema.Struct({464 projects: Schema.Array(Schema.Struct({ project: ProjectName })),465});466467/**468 * Whether `project` is free on the platform, as `person` lists every469 * project (`<cli> projects`): a taken name fails the step, before470 * anything is made.471 */472export const projectIsFree = (person: LoopPerson, project: ProjectName) =>473 Effect.flatMap(cli("init", person, ["projects"], Listed), ({ projects }) =>474 projects.some((listed) => listed.project === project)475 ? Effect.fail(476 failed(477 "init",478 `${project} is on the platform already, so nothing was made or recorded: a run a second later takes another name`479 )480 )481 : Effect.void482 );483484const Inited = Schema.Struct({485 pushed: Schema.Boolean,486 remote: Schema.NonEmptyString,487});
544 unmodified lines
modified:scripts/lib/smoke/loop.ts+26 added-19 removed
2 unmodified lines
3 * the CLI and git, as its people would take it (`core-loop.ts` holds the4 * steps):5 *6 * 1. `people`: who the decider's and the answerer's tokens name;7 * 2. `init`: the decider makes a throwaway project, `smoke-<run>`, and8 * pushes its first commit;7 * 2. `init`: the decider checks `smoke-<run>` is free, records it, then8 * makes it a throwaway project and pushes its first commit;9 * 3. `open-ask`: the decider opens an ask, red twice on main first;10 * 4. `claim`: the answerer claims it, and gets a fork;11 * 5. `out-of-scope`: an answer that reaches outside the ask's territory is12 * refused, `OutOfScope` in git's own output;
11 unmodified lines
24 * that opened its ask discloses the drafter (`Assisted-by:`) and25 * credits the answerer as its asker.26 *27 * Each step is timed and printed as it passes; the first that fails ends28 * the run. The throwaway project, its repo and the claim's fork are written29 * to the throwaway ledger (`infra/created.ts`, by `smoke`) as soon as each30 * exists. It never runs on `demo`: a throwaway project would show on the31 * front page the user records.28 * the run. Every throwaway is written to the throwaway ledger29 * (`infra/created.ts`, by `smoke`): the project and its repo before `init`30 * makes them, once the platform's list of projects shows the name free (a31 * taken name stops the run, recording nothing), so an `init` that fails32 * after making the project still leaves it recorded; the claim's fork just33 * after the claim, since its name is known only then. It never runs on34 * `demo`: a throwaway project would show on the front page the user35 * records.36 */37import { Brand } from "@repo/brand";38import { ProjectName } from "@repo/protocol/ids";39import type { LandedSha } from "@repo/protocol/ids";
20 unmodified lines
60 initProject,61 LoopFailed,62 openAsk,63 personAt,64 projectIsFree,65 proposeDraft,66 pushAnswer,67 pushOutOfScope,68 readLanding,
182 unmodified lines
251 }),252 })253 );254255 // The name is checked free, then recorded, then made: an init that256 // makes the project and then fails still leaves it in the ledger, and257 // a name someone else holds never enters teardown's plan.258 const [, init] = yield* timed(259 stage,260 "init"261 )(254 initProject({255 answerer: answerer.handle,256 decider,257 dir: `${dir}/start`,258 project,259 }).pipe(260 Effect.tap(() =>261 Effect.andThen(262 recordThrowaway(stage, "project", project),263 recordThrowaway(stage, "repo", project)264 )265 )266 )262 Effect.gen(function* () {263 yield* projectIsFree(decider, project);264 yield* recordThrowaway(stage, "project", project);265 yield* recordThrowaway(stage, "repo", project);266267 return yield* initProject({268 answerer: answerer.handle,269 decider,270 dir: `${dir}/start`,271 project,272 });273 })274 );275276 const [, opened] = yield* timed(277 stage,
149 unmodified lines