An open-source, faster Devin alternative
TypeScript
feat(flue): add managed repository tools
Igor Zalutski7c89a84c1924
diff --git a/sdks/flue/README.md b/sdks/flue/README.mdindex 27494ebc..88d0b319 100644--- a/sdks/flue/README.md+++ b/sdks/flue/README.md@@ -12,6 +12,8 @@ package supplies the OpenComputer-specific wiring the app opts into. Deployments- **`route`** — the HTTP-transport opt-in every OC-hosted agent must export (`export { route }`).- **`ocSandbox(env)`** — optional, demand-driven Linux shell/files. Declaring it makes no networkrequest; the first actual sandbox operation resolves the persistent session sandbox.+- **`ocRepoTools(ctx)`** — managed repository discovery, exact-SHA checkout into the session+ sandbox, and OpenComputer-authored GitHub pull requests.- **`@opencomputer/flue/app`** — a default hosting app (`flue()` routes + `/health` + telemetry). Or`import '@opencomputer/flue/wire'` from your own `app.ts` for telemetry only.@@ -40,13 +42,50 @@ export { default } from "@opencomputer/flue/app";Then `flue build --target cloudflare` and `oc agent deploy`. See `oc-flue-starter` for a full example.-The current profile supports direct text sessions and optional demand-driven sandboxes. Channels,-workflows, repository sources, pull-request publishing, attachments, and arbitrary Worker egress are-not supported yet.+## Repository work++Give a hosted agent the standard repository tools beside its sandbox:++```ts+import { defineAgent, defineAgentProfile } from "@flue/runtime";+import {+ DEFAULT_MODEL,+ ocRepoTools,+ ocSandbox,+ route,+ useOcGateway,+} from "@opencomputer/flue";++export { route };++export default defineAgent((ctx) => {+ useOcGateway(ctx);+ return {+ profile: defineAgentProfile({+ instructions:+ "List working repositories, resolve an exact owner/repository, add it, edit and test only in the returned source path, then open a pull request.",+ }),+ model: DEFAULT_MODEL,+ sandbox: ocSandbox(ctx.env),+ tools: ocRepoTools(ctx),+ };+});+```++`list_working_repos` returns only repositories allowed by the agent's current+OpenComputer policy and GitHub App grant. `add_source` pins the selected ref to+an exact commit and returns its `/workspace/sources/...` path.+`github_publish_pull_request` publishes that source's inspected changes on an+`oc/...` branch. The tools do not default to the deployment repository, expose+credentials, or perform fuzzy repository selection.++Direct text sessions, managed Slack, workflows, and optional demand-driven+sandboxes continue to use ordinary Flue behavior.## Environment (set on the tenant script by the OC deploy)-`OC_GATEWAY` and `OC_SESSION_TOKEN` are always managed by OpenComputer. Agents that explicitly use-`ocSandbox` use the managed `OC_SANDBOX_API`. User variables come from `agent.toml [vars]`; write-only-secrets are set with `oc agent secret` and both take effect on the next deployment. Reserved-`OC_`/`FLUE_` prefixes are platform-managed.+`OC_GATEWAY`, `OC_SESSION_TOKEN`, and `OC_REPO_API` are managed by+OpenComputer. Agents that explicitly use `ocSandbox` use the managed+`OC_SANDBOX_API`. User variables come from `agent.toml [vars]`; write-only+secrets are set with `oc agent secret` and both take effect on the next+deployment. Reserved `OC_`/`FLUE_` prefixes are platform-managed.diff --git a/sdks/flue/package-lock.json b/sdks/flue/package-lock.jsonindex 62fd1eb2..2d834bb9 100644--- a/sdks/flue/package-lock.json+++ b/sdks/flue/package-lock.json@@ -1,16 +1,20 @@{"name": "@opencomputer/flue",- "version": "0.2.0",+ "version": "0.3.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/flue",- "version": "0.2.0",+ "version": "0.3.0","license": "Apache-2.0",+ "dependencies": {+ "valibot": "^1.4.2"+ },"devDependencies": {"@flue/runtime": "1.0.0-beta.9","@types/node": "^22.10.0",+ "esbuild": "^0.28.1","typescript": "^5.9.3","vitest": "^3.0.0"},@@ -4997,7 +5001,7 @@"version": "5.9.3","resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz","integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",- "dev": true,+ "devOptional": true,"license": "Apache-2.0","bin": {"tsc": "bin/tsc",@@ -5062,7 +5066,6 @@"version": "1.4.2","resolved": "https://registry.npmjs.org/valibot/-/valibot-1.4.2.tgz","integrity": "sha512-gjdCvJ6d3RyHAneqxMYMW9QMCwYMb3jpOO0IyHZV1bnRHFBHrX3VkIILt5XYR0WhwHiH7Mty8ovuPZ/O3gamrg==",- "dev": true,"license": "MIT","peerDependencies": {"typescript": ">=5"diff --git a/sdks/flue/package.json b/sdks/flue/package.jsonindex 8f44e009..e045f016 100644--- a/sdks/flue/package.json+++ b/sdks/flue/package.json@@ -1,7 +1,7 @@{"name": "@opencomputer/flue",- "version": "0.2.0",- "description": "Run a Flue app as an OpenComputer agent with managed models and optional demand-driven sandboxes.",+ "version": "0.3.0",+ "description": "Run a Flue app as an OpenComputer agent with managed models, repository tools, and demand-driven sandboxes.","keywords": ["agents","flue",@@ -48,7 +48,8 @@"build": "npm run clean && tsc -p tsconfig.json","typecheck": "tsc -p tsconfig.json --noEmit","test": "vitest run",- "prepublishOnly": "npm test && npm run build"+ "check:workerd": "node scripts/check-workerd.mjs",+ "prepublishOnly": "npm test && npm run build && npm run check:workerd"},"sideEffects": ["./dist/wire.js"@@ -59,9 +60,13 @@"publishConfig": {"access": "public"},+ "dependencies": {+ "valibot": "^1.4.2"+ },"devDependencies": {"@flue/runtime": "1.0.0-beta.9","@types/node": "^22.10.0",+ "esbuild": "^0.28.1","typescript": "^5.9.3","vitest": "^3.0.0"}diff --git a/sdks/flue/scripts/check-workerd.mjs b/sdks/flue/scripts/check-workerd.mjsnew file mode 100644index 00000000..aef56be7--- /dev/null+++ b/sdks/flue/scripts/check-workerd.mjs@@ -0,0 +1,12 @@+import { build } from "esbuild";++await build({+ entryPoints: ["src/index.ts"],+ bundle: true,+ write: false,+ format: "esm",+ platform: "browser",+ target: "es2022",+ external: ["@flue/runtime", "cloudflare:workers"],+ logLevel: "warning",+});diff --git a/sdks/flue/src/index.ts b/sdks/flue/src/index.tsindex 2f972c1c..a720f36d 100644--- a/sdks/flue/src/index.ts+++ b/sdks/flue/src/index.ts@@ -1,6 +1,7 @@// @opencomputer/flue — make a stock Flue agent OpenComputer-native (design 013 §4/§5).// - useOcGateway + route + DEFAULT_MODEL: point managed anthropic at the OC gateway; HTTP-transport opt-in.// - ocSandbox: optional, demand-driven durable shell/files as the agent's SandboxApi.+// - ocRepoTools: exact working-repository discovery, materialization, and pull-request publishing.// - installOcObserver: forward lifecycle/usage to OC_INGEST.// Default hosting app is at `@opencomputer/flue/app`; `@opencomputer/flue/wire` is the telemetry-only// side-effect for apps with their own app.ts.@@ -9,4 +10,15 @@ export { useOcGateway, route, DEFAULT_MODEL } from "./gateway.js";export type { OcEnv } from "./gateway.js";export { ocSandbox, WORKSPACE_CWD } from "./sandbox.js";export type { OcSandboxEnv } from "./sandbox.js";+export { ocRepoTools } from "./repo.js";+export type {+ AddSourceResult,+ ListWorkingReposResult,+ OcRepoEnv,+ OcRepoError,+ OcRepoErrorCode,+ OcRepoFailure,+ PublishPullRequestResult,+ WorkingRepository,+} from "./repo.js";export { installOcObserver } from "./observe.js";diff --git a/sdks/flue/src/repo.test.ts b/sdks/flue/src/repo.test.tsnew file mode 100644index 00000000..3e59ded9--- /dev/null+++ b/sdks/flue/src/repo.test.ts@@ -0,0 +1,498 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import * as v from "valibot";+import { ocRepoTools } from "./repo.js";+import type { OcRepoEnv } from "./repo.js";++type RunnableTool = {+ name: string;+ description: string;+ input: v.GenericSchema<Record<string, unknown>, unknown>;+ run(context: {+ input: Record<string, unknown>;+ signal?: AbortSignal;+ }): Promise<unknown>;+};++function tools(+ env: OcRepoEnv = {+ OC_REPO_API: "https://sessions.opencomputer.test/",+ OC_SESSION_TOKEN: "deploy-token",+ },+ id = "ses_1",+): RunnableTool[] {+ return ocRepoTools({ id, env }) as RunnableTool[];+}++function tool(+ name: string,+ env?: OcRepoEnv,+ id?: string,+): RunnableTool {+ const found = tools(env, id).find((candidate) => candidate.name === name);+ if (!found) throw new Error(`missing tool ${name}`);+ return found;+}++function json(value: unknown, status = 200): Response {+ return new Response(JSON.stringify(value), {+ status,+ headers: { "content-type": "application/json" },+ });+}++afterEach(() => vi.unstubAllGlobals());++describe("ocRepoTools contract", () => {+ it("returns exactly the three stable tools in workflow order", () => {+ expect(tools().map(({ name }) => name)).toEqual([+ "list_working_repos",+ "add_source",+ "github_publish_pull_request",+ ]);+ });++ it("keeps exact-target and safe-publish guidance in model context", () => {+ const [list, add, publish] = tools();+ expect(list?.description).toMatch(/exact owner\/repository/);+ expect(list?.description).toMatch(/Never assume the deployment source/);+ expect(list?.description).toMatch(/otherwise ask/);+ expect(add?.description).toMatch(/await this tool before filesystem work/);+ expect(add?.description).toMatch(/returned \/workspace\/sources/);+ expect(publish?.description).toMatch(/inspect and test the diff/);+ expect(publish?.description).toMatch(+ /exact repository, base branch, and intended diff/,+ );+ expect(publish?.description).toMatch(/pull-request URL/);+ });++ it("uses strict bounded input schemas", () => {+ const list = tool("list_working_repos");+ expect(v.safeParse(list.input, { q: "owner/repo" }).success).toBe(true);+ expect(v.safeParse(list.input, { q: "x".repeat(101) }).success).toBe(+ false,+ );+ expect(v.safeParse(list.input, { surprise: true }).success).toBe(false);++ const add = tool("add_source");+ expect(+ v.safeParse(add.input, {+ repository: "repo_1",+ ref: "main",+ name: "app",+ }).success,+ ).toBe(true);+ expect(+ v.safeParse(add.input, { repository: "", ref: "main" }).success,+ ).toBe(false);++ const publish = tool("github_publish_pull_request");+ expect(+ v.safeParse(publish.input, {+ source: "app",+ title: "Document setup",+ base: "main",+ }).success,+ ).toBe(true);+ expect(+ v.safeParse(publish.input, {+ source: "app",+ title: "Document setup",+ base: "main",+ idempotency_key: "model-controlled",+ }).success,+ ).toBe(false);+ });+});++describe("list_working_repos HTTP fixtures", () => {+ it("resolves request-time env and encodes the session and query", async () => {+ const env: OcRepoEnv = {};+ const list = tool("list_working_repos", env, "ses_/customer space");+ const fetchSpy = vi.fn(async () =>+ json({+ ok: true,+ repositories: [+ {+ id: "repo_1",+ full_name: "diggerhq/example app",+ default_branch: "main",+ },+ ],+ truncated: true,+ }),+ );+ vi.stubGlobal("fetch", fetchSpy);++ env.OC_REPO_API = "https://sessions.opencomputer.test///";+ env.OC_SESSION_TOKEN = "request-token";+ const result = await list.run({ input: { q: "diggerhq/example app" } });++ expect(result).toEqual({+ ok: true,+ repositories: [+ {+ id: "repo_1",+ full_name: "diggerhq/example app",+ default_branch: "main",+ },+ ],+ truncated: true,+ });+ expect(fetchSpy).toHaveBeenCalledOnce();+ const [url, init] = fetchSpy.mock.calls[0] ?? [];+ expect(url).toBe(+ "https://sessions.opencomputer.test/flue/sessions/ses_%2Fcustomer%20space/repositories?q=diggerhq%2Fexample+app",+ );+ expect(init).toMatchObject({+ method: "GET",+ headers: {+ accept: "application/json",+ authorization: "Bearer request-token",+ },+ });+ });++ it.each([+ ["github_not_connected", 409, false],+ ["github_unavailable", 503, true],+ ["github_permission_missing", 409, false],+ ["repository_scope_empty", 403, false],+ ["repository_not_allowed", 403, false],+ ["repository_not_granted", 403, false],+ ["repository_not_found", 404, false],+ ["repository_rate_limited", 429, true],+ ["source_name_taken", 409, false],+ ["source_unresolved", 422, true],+ ["source_materialization_failed", 503, true],+ ["source_not_ready", 409, true],+ ["publish_in_progress", 409, true],+ ["publish_failed", 502, false],+ ["stale_deployment_token", 409, false],+ ["deployment_updating", 503, true],+ ["deployment_unverified", 409, false],+ ] as const)(+ "returns the canonical %s product failure as tool data",+ async (code, status, retryable) => {+ const body = {+ ok: false as const,+ error: {+ code,+ message: `Safe recovery for ${code}`,+ retryable,+ ...(code === "repository_rate_limited"+ ? { retry_after_seconds: 17 }+ : {}),+ },+ };+ vi.stubGlobal("fetch", vi.fn(async () => json(body, status)));++ await expect(+ tool("list_working_repos").run({ input: {} }),+ ).resolves.toEqual(body);+ },+ );++ it("rejects status, retryability, and retry-after contract drift", async () => {+ const list = tool("list_working_repos");+ const fetchSpy = vi+ .fn()+ .mockResolvedValueOnce(+ json(+ {+ ok: false,+ error: {+ code: "repository_not_allowed",+ message: "Choose another repository.",+ retryable: false,+ },+ },+ 500,+ ),+ )+ .mockResolvedValueOnce(+ json(+ {+ ok: false,+ error: {+ code: "github_unavailable",+ message: "Retry later.",+ retryable: false,+ },+ },+ 503,+ ),+ )+ .mockResolvedValueOnce(+ json(+ {+ ok: false,+ error: {+ code: "repository_rate_limited",+ message: "Wait before retrying.",+ retryable: true,+ },+ },+ 429,+ ),+ );+ vi.stubGlobal("fetch", fetchSpy);++ for (let i = 0; i < 3; i++) {+ await expect(list.run({ input: {} })).rejects.toThrow(+ "repository API returned an invalid response",+ );+ }+ });++ it("throws secret-safe errors for malformed platform responses", async () => {+ const leaked = "ghs_should-never-appear";+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response(`provider said ${leaked}`, { status: 502 })),+ );++ let thrown: unknown;+ try {+ await tool("list_working_repos").run({ input: {} });+ } catch (error) {+ thrown = error;+ }+ expect(thrown).toBeInstanceOf(Error);+ expect((thrown as Error).message).toBe(+ "[oc-flue] repository API returned an invalid response (status 502).",+ );+ expect((thrown as Error).message).not.toContain(leaked);+ expect((thrown as Error).message).not.toContain("deploy-token");+ expect((thrown as Error).message).not.toContain(+ "sessions.opencomputer.test",+ );+ });++ it("preserves cancellation while reading a response body", async () => {+ const aborted = new DOMException("cancelled while reading", "AbortError");+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => {+ return {+ status: 200,+ json: async () => {+ throw aborted;+ },+ } as Response;+ }),+ );++ await expect(+ tool("list_working_repos").run({ input: {} }),+ ).rejects.toBe(aborted);+ });+});++describe("add_source HTTP fixture", () => {+ it("posts the exact target and returns a usable pinned source path", async () => {+ const fetchSpy = vi.fn(async () =>+ json({+ ok: true,+ name: "app",+ repository_id: "repo_1",+ full_name: "diggerhq/example-app",+ ref: "main",+ sha: "a".repeat(40),+ path: "/workspace/sources/app",+ }),+ );+ vi.stubGlobal("fetch", fetchSpy);++ const result = await tool("add_source").run({+ input: { repository: "repo_1", ref: "main", name: "app" },+ });++ expect(result).toEqual({+ ok: true,+ name: "app",+ repository_id: "repo_1",+ full_name: "diggerhq/example-app",+ ref: "main",+ sha: "a".repeat(40),+ path: "/workspace/sources/app",+ });+ const [url, init] = fetchSpy.mock.calls[0] ?? [];+ expect(url).toBe(+ "https://sessions.opencomputer.test/flue/sessions/ses_1/sources",+ );+ expect(init).toMatchObject({+ method: "POST",+ headers: {+ accept: "application/json",+ authorization: "Bearer deploy-token",+ "content-type": "application/json",+ },+ body: JSON.stringify({+ repository: "repo_1",+ ref: "main",+ name: "app",+ }),+ });+ });++ it("rejects a success response whose path is outside the managed source root", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ json({+ ok: true,+ name: "app",+ repository_id: "repo_1",+ full_name: "diggerhq/example-app",+ ref: "main",+ sha: "a".repeat(40),+ path: "/tmp/app",+ }),+ ),+ );++ await expect(+ tool("add_source").run({+ input: { repository: "repo_1", ref: "main", name: "app" },+ }),+ ).rejects.toThrow("repository API returned an invalid response");+ });+});++describe("github_publish_pull_request HTTP fixtures", () => {+ it("reuses one random idempotency key across an ambiguous transport retry", async () => {+ const bodies: Array<Record<string, unknown>> = [];+ const signals: Array<AbortSignal | null | undefined> = [];+ let calls = 0;+ vi.stubGlobal(+ "fetch",+ vi.fn(async (_url: string, init?: RequestInit) => {+ bodies.push(JSON.parse(String(init?.body)) as Record<string, unknown>);+ signals.push(init?.signal);+ calls++;+ if (calls === 1) throw new TypeError("network reset at secret host");+ return json({+ ok: true,+ no_changes: false,+ branch: "oc/ses_1/document-setup",+ commit: "d".repeat(40),+ pull_request: {+ number: 42,+ url: "https://github.com/diggerhq/example-app/pull/42",+ },+ });+ }),+ );+ const controller = new AbortController();++ const result = await tool("github_publish_pull_request").run({+ input: {+ source: "app",+ title: "Document setup",+ body: "Adds setup notes.",+ base: "main",+ draft: true,+ },+ signal: controller.signal,+ });++ expect(result).toMatchObject({+ ok: true,+ no_changes: false,+ pull_request: {+ number: 42,+ url: "https://github.com/diggerhq/example-app/pull/42",+ },+ });+ expect(bodies).toHaveLength(2);+ expect(bodies[0]).toEqual(bodies[1]);+ expect(bodies[0]).toMatchObject({+ source: "app",+ title: "Document setup",+ body: "Adds setup notes.",+ base: "main",+ draft: true,+ });+ expect(bodies[0]?.idempotency_key).toEqual(expect.any(String));+ expect(String(bodies[0]?.idempotency_key).length).toBeGreaterThanOrEqual(+ 32,+ );+ expect(signals).toEqual([controller.signal, controller.signal]);+ });++ it("returns no_changes as a successful terminal result", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => json({ ok: true, no_changes: true })),+ );+ await expect(+ tool("github_publish_pull_request").run({+ input: {+ source: "app",+ title: "Document setup",+ base: "main",+ },+ }),+ ).resolves.toEqual({ ok: true, no_changes: true });+ });++ it("propagates AbortSignal cancellation without retrying or wrapping it", async () => {+ const aborted = new DOMException("cancelled", "AbortError");+ const fetchSpy = vi.fn(async (_url: string, init?: RequestInit) => {+ expect(init?.signal?.aborted).toBe(true);+ throw aborted;+ });+ vi.stubGlobal("fetch", fetchSpy);+ const controller = new AbortController();+ controller.abort();++ await expect(+ tool("github_publish_pull_request").run({+ input: {+ source: "app",+ title: "Document setup",+ base: "main",+ },+ signal: controller.signal,+ }),+ ).rejects.toBe(aborted);+ expect(fetchSpy).toHaveBeenCalledOnce();+ });++ it("sanitizes exhausted transport errors", async () => {+ const fetchSpy = vi.fn(async () => {+ throw new TypeError(+ "request to https://secret.internal/?token=deploy-token failed",+ );+ });+ vi.stubGlobal("fetch", fetchSpy);++ await expect(+ tool("github_publish_pull_request").run({+ input: {+ source: "app",+ title: "Document setup",+ base: "main",+ },+ }),+ ).rejects.toThrow(+ "[oc-flue] repository API request failed before a response was received.",+ );+ expect(fetchSpy).toHaveBeenCalledTimes(2);+ });+});++describe("managed binding failures", () => {+ it("fails before fetch without printing missing or present binding values", async () => {+ const fetchSpy = vi.fn();+ vi.stubGlobal("fetch", fetchSpy);+ await expect(+ tool("list_working_repos", {+ OC_SESSION_TOKEN: "secret-token",+ }).run({ input: {} }),+ ).rejects.toThrow(+ "[oc-flue] ocRepoTools requires managed repository API bindings.",+ );+ expect(fetchSpy).not.toHaveBeenCalled();+ });+});diff --git a/sdks/flue/src/repo.ts b/sdks/flue/src/repo.tsnew file mode 100644index 00000000..09284b55--- /dev/null+++ b/sdks/flue/src/repo.ts@@ -0,0 +1,478 @@+import { defineTool } from "@flue/runtime";+import type {+ AgentInitializerContext,+ ToolDefinition,+} from "@flue/runtime";+import * as v from "valibot";+import { ocResolveEnv } from "./cf-env.js";+import type { OcEnv } from "./gateway.js";++export interface OcRepoEnv extends OcEnv {+ /** Managed repository API base injected by OpenComputer. */+ OC_REPO_API?: string;+}++const ERROR_CODES = [+ "github_not_connected",+ "github_unavailable",+ "github_permission_missing",+ "repository_scope_empty",+ "repository_not_allowed",+ "repository_not_granted",+ "repository_not_found",+ "repository_rate_limited",+ "source_name_taken",+ "source_unresolved",+ "source_materialization_failed",+ "source_not_ready",+ "publish_in_progress",+ "publish_failed",+ "stale_deployment_token",+ "deployment_updating",+ "deployment_unverified",+] as const;++export type OcRepoErrorCode = (typeof ERROR_CODES)[number];++export interface OcRepoError {+ code: OcRepoErrorCode;+ message: string;+ retryable: boolean;+ retry_after_seconds?: number;+}++export type OcRepoFailure = {+ ok: false;+ error: OcRepoError;+};++const RepoErrorSchema = v.strictObject({+ code: v.picklist(ERROR_CODES),+ message: v.pipe(v.string(), v.minLength(1), v.maxLength(500)),+ retryable: v.boolean(),+ retry_after_seconds: v.optional(+ v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(600)),+ ),+});++const RepoFailureSchema = v.strictObject({+ ok: v.literal(false),+ error: RepoErrorSchema,+});++const WorkingRepositorySchema = v.strictObject({+ id: v.pipe(v.string(), v.minLength(1)),+ full_name: v.pipe(v.string(), v.minLength(3)),+ default_branch: v.pipe(v.string(), v.minLength(1)),+});++export interface WorkingRepository {+ id: string;+ full_name: string;+ default_branch: string;+}++const ListWorkingReposSuccessSchema = v.strictObject({+ ok: v.literal(true),+ repositories: v.pipe(+ v.array(WorkingRepositorySchema),+ v.maxLength(50),+ ),+ truncated: v.boolean(),+});++const SourceNameSchema = v.pipe(+ v.string(),+ v.regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),+);++const AddSourceSuccessSchema = v.pipe(+ v.strictObject({+ ok: v.literal(true),+ name: SourceNameSchema,+ repository_id: v.pipe(v.string(), v.startsWith("repo_")),+ full_name: v.pipe(v.string(), v.minLength(3)),+ ref: v.pipe(v.string(), v.minLength(1)),+ sha: v.pipe(v.string(), v.regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i)),+ path: v.pipe(v.string(), v.startsWith("/workspace/sources/")),+ }),+ v.check(+ (result) => result.path === `/workspace/sources/${result.name}`,+ "source path does not match source name",+ ),+);++const PublishNoChangesSchema = v.strictObject({+ ok: v.literal(true),+ no_changes: v.literal(true),+});++const PublishPullRequestSuccessSchema = v.strictObject({+ ok: v.literal(true),+ no_changes: v.literal(false),+ branch: v.pipe(v.string(), v.minLength(1)),+ commit: v.pipe(+ v.string(),+ v.regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i),+ ),+ pull_request: v.strictObject({+ number: v.pipe(v.number(), v.integer(), v.minValue(1)),+ url: v.pipe(v.string(), v.url()),+ }),+});++const ListWorkingReposResultSchema = v.union([+ ListWorkingReposSuccessSchema,+ RepoFailureSchema,+]);+const AddSourceResultSchema = v.union([+ AddSourceSuccessSchema,+ RepoFailureSchema,+]);+const PublishPullRequestResultSchema = v.union([+ PublishNoChangesSchema,+ PublishPullRequestSuccessSchema,+ RepoFailureSchema,+]);++export type ListWorkingReposResult =+ | {+ ok: true;+ repositories: WorkingRepository[];+ truncated: boolean;+ }+ | OcRepoFailure;++export type AddSourceResult =+ | {+ ok: true;+ name: string;+ repository_id: string;+ full_name: string;+ ref: string;+ sha: string;+ path: string;+ }+ | OcRepoFailure;++export type PublishPullRequestResult =+ | { ok: true; no_changes: true }+ | {+ ok: true;+ no_changes: false;+ branch: string;+ commit: string;+ pull_request: { number: number; url: string };+ }+ | OcRepoFailure;++const ListWorkingReposInputSchema = v.strictObject({+ q: v.optional(+ v.pipe(+ v.string(),+ v.maxLength(100),+ v.description(+ "Optional case-insensitive owner/repository substring. Use the returned exact id or owner/repository; never guess from a bare name.",+ ),+ ),+ ),+});++const AddSourceInputSchema = v.strictObject({+ repository: v.pipe(+ v.string(),+ v.minLength(1),+ v.description(+ "An exact repo_… id returned by list_working_repos, or exact owner/repository coordinates from that list.",+ ),+ ),+ ref: v.pipe(+ v.string(),+ v.minLength(1),+ v.description("The branch, tag, or commit to pin."),+ ),+ name: v.optional(+ v.pipe(+ SourceNameSchema,+ v.description(+ "Optional stable source name used by later repository operations.",+ ),+ ),+ ),+});++const PublishPullRequestInputSchema = v.strictObject({+ source: v.pipe(+ v.string(),+ v.minLength(1),+ v.description(+ "The source name returned by add_source, not a path or repository guess.",+ ),+ ),+ title: v.pipe(v.string(), v.minLength(1)),+ body: v.optional(v.string()),+ base: v.pipe(+ v.string(),+ v.minLength(1),+ v.description("Exact target branch for the pull request."),+ ),+ draft: v.optional(v.boolean()),+});++type RepoResultSchema =+ | typeof ListWorkingReposResultSchema+ | typeof AddSourceResultSchema+ | typeof PublishPullRequestResultSchema;++const HTTP_BY_ERROR: Readonly<+ Record<OcRepoErrorCode, readonly number[]>+> = {+ github_not_connected: [409],+ github_unavailable: [503],+ github_permission_missing: [409],+ repository_scope_empty: [403],+ repository_not_allowed: [403],+ repository_not_granted: [403],+ repository_not_found: [404],+ repository_rate_limited: [429],+ source_name_taken: [409],+ source_unresolved: [422],+ source_materialization_failed: [502, 503],+ source_not_ready: [409],+ publish_in_progress: [409],+ publish_failed: [502, 503],+ stale_deployment_token: [409],+ deployment_updating: [503],+ deployment_unverified: [409],+};++const RETRYABLE_BY_ERROR: Readonly<+ Partial<Record<OcRepoErrorCode, boolean>>+> = {+ github_not_connected: false,+ github_unavailable: true,+ github_permission_missing: false,+ repository_scope_empty: false,+ repository_not_allowed: false,+ repository_not_granted: false,+ repository_not_found: false,+ repository_rate_limited: true,+ source_name_taken: false,+ source_not_ready: true,+ publish_in_progress: true,+ stale_deployment_token: false,+ deployment_updating: true,+ deployment_unverified: false,+};++function invalidResponse(status: number): Error {+ return new Error(+ `[oc-flue] repository API returned an invalid response (status ${status}).`,+ );+}++function validateResult<TSchema extends RepoResultSchema>(+ schema: TSchema,+ status: number,+ payload: unknown,+): v.InferOutput<TSchema> {+ const parsed = v.safeParse(schema, payload);+ if (!parsed.success) throw invalidResponse(status);++ const result = parsed.output;+ if (result.ok) {+ if (status < 200 || status >= 300) throw invalidResponse(status);+ return result;+ }++ if (!HTTP_BY_ERROR[result.error.code].includes(status)) {+ throw invalidResponse(status);+ }+ const expectedRetryable = RETRYABLE_BY_ERROR[result.error.code];+ if (+ expectedRetryable !== undefined &&+ result.error.retryable !== expectedRetryable+ ) {+ throw invalidResponse(status);+ }+ if (+ result.error.code === "repository_rate_limited" !==+ (result.error.retry_after_seconds !== undefined)+ ) {+ throw invalidResponse(status);+ }+ return result;+}++function endpoint(+ env: OcRepoEnv,+ sessionId: string,+ resource: string,+ query?: URLSearchParams,+): string {+ const base = env.OC_REPO_API?.replace(/\/+$/, "");+ if (!base || !env.OC_SESSION_TOKEN) {+ throw new Error(+ "[oc-flue] ocRepoTools requires managed repository API bindings.",+ );+ }+ const suffix = query && query.size > 0 ? `?${query.toString()}` : "";+ return `${base}/flue/sessions/${encodeURIComponent(sessionId)}/${resource}${suffix}`;+}++function isAbortError(error: unknown): boolean {+ return (+ typeof error === "object" &&+ error !== null &&+ "name" in error &&+ error.name === "AbortError"+ );+}++async function fetchWithOneTransportRetry(+ url: string,+ init: RequestInit,+): Promise<Response> {+ for (let attempt = 0; attempt < 2; attempt++) {+ try {+ return await fetch(url, init);+ } catch (error) {+ if (init.signal?.aborted || isAbortError(error)) {+ throw error;+ }+ if (attempt === 1) {+ throw new Error(+ "[oc-flue] repository API request failed before a response was received.",+ );+ }+ }+ }+ throw new Error("[oc-flue] repository API request failed.");+}++async function request<TSchema extends RepoResultSchema>(+ schema: TSchema,+ env: OcRepoEnv,+ sessionId: string,+ resource: string,+ options: {+ method?: "GET" | "POST";+ query?: URLSearchParams;+ body?: unknown;+ signal?: AbortSignal;+ },+): Promise<v.InferOutput<TSchema>> {+ const url = endpoint(env, sessionId, resource, options.query);+ const response = await fetchWithOneTransportRetry(url, {+ method: options.method ?? "GET",+ headers: {+ accept: "application/json",+ authorization: `Bearer ${env.OC_SESSION_TOKEN}`,+ ...(options.body === undefined+ ? {}+ : { "content-type": "application/json" }),+ },+ ...(options.body === undefined+ ? {}+ : { body: JSON.stringify(options.body) }),+ signal: options.signal,+ });++ let payload: unknown;+ try {+ payload = await response.json();+ } catch (error) {+ if (options.signal?.aborted || isAbortError(error)) throw error;+ throw invalidResponse(response.status);+ }+ return validateResult(schema, response.status, payload);+}++function randomIdempotencyKey(): string {+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();++ const bytes = new Uint8Array(16);+ globalThis.crypto?.getRandomValues(bytes);+ if (bytes.every((byte) => byte === 0)) {+ throw new Error(+ "[oc-flue] secure randomness is unavailable for pull-request publishing.",+ );+ }+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(+ "",+ );+}++/**+ * Standard hosted-repository tools for an OpenComputer Flue session.+ *+ * The initializer captures only the session id and environment reference.+ * Managed bindings are resolved inside each tool run because Cloudflare+ * secrets are request-scoped.+ */+export function ocRepoTools(+ ctx: AgentInitializerContext<OcRepoEnv>,+): ToolDefinition[] {+ const sessionId = ctx.id;+ const env = ctx.env;++ const listWorkingRepos = defineTool({+ name: "list_working_repos",+ description:+ "List repositories this agent may use. Call this before repository work. Match the user's exact owner/repository or returned repo_ id; a bare name may be selected only when this list has exactly one match, otherwise ask. Never assume the deployment source is the target. State the resolved owner/repository before adding it.",+ input: ListWorkingReposInputSchema,+ output: ListWorkingReposResultSchema,+ async run({ input, signal }) {+ const query = new URLSearchParams();+ if (input.q !== undefined) query.set("q", input.q);+ return request(+ ListWorkingReposResultSchema,+ ocResolveEnv<OcRepoEnv>(env),+ sessionId,+ "repositories",+ { query, signal },+ );+ },+ });++ const addSource = defineTool({+ name: "add_source",+ description:+ "Pin and materialize one exact repository source after list_working_repos resolved it. Tell the user the exact owner/repository first, await this tool before filesystem work, then use only the returned /workspace/sources/... path. On a product error, explain its stated recovery instead of guessing another target.",+ input: AddSourceInputSchema,+ output: AddSourceResultSchema,+ async run({ input, signal }) {+ return request(+ AddSourceResultSchema,+ ocResolveEnv<OcRepoEnv>(env),+ sessionId,+ "sources",+ { method: "POST", body: input, signal },+ );+ },+ });++ const publishPullRequest = defineTool({+ name: "github_publish_pull_request",+ description:+ "Publish the inspected changes from one added source as an OpenComputer-authored GitHub pull request. First inspect and test the diff, then restate the exact repository, base branch, and intended diff. Report the returned pull-request URL; if there are no changes or a product error, report that result and its recovery exactly.",+ input: PublishPullRequestInputSchema,+ output: PublishPullRequestResultSchema,+ async run({ input, signal }) {+ const idempotencyKey = randomIdempotencyKey();+ return request(+ PublishPullRequestResultSchema,+ ocResolveEnv<OcRepoEnv>(env),+ sessionId,+ "pull-requests",+ {+ method: "POST",+ body: { ...input, idempotency_key: idempotencyKey },+ signal,+ },+ );+ },+ });++ return [listWorkingRepos, addSource, publishPullRequest];+}