import { s as ReleasePolicy, t as registerResource } from "./resources-B6ZjmsZN.js"; import { g as Worktree, l as readWorktreeDiff, o as pushApprovedChange, p as ReadBranchState } from "./change-DqLNW9Dp.js"; import { z } from "zod"; import { LanguageModel, TextStreamPart, ToolSet, generateText } from "ai"; import { Options } from "@anthropic-ai/claude-agent-sdk"; import { CodexAppServerSettings } from "ai-sdk-provider-codex-cli"; //#region src/checks/check.d.ts /** * A check's outcome: a pass with an optional `detail`, or a failure with its repair. A repair * quotes each command to run in backticks. */ type CheckResult = { ok: true; detail?: string; } | { ok: false; reason: string; repair: string; }; //#endregion //#region src/workflow/factory.d.ts /** * Accept a Linear issue UUID or an uppercase team-and-number ticket identifier. * * @group Factory and workflows */ declare const ticketInputSchema: z.ZodUnion; /** Metadata supplied to every workflow run. */ type Injected = { triggerId: string; }; /** * Parsed workflow inputs with the trigger that started the run. * * @group Factory and workflows */ type WorkflowInputs = z.output & Injected; /** * Ticket references are ordinary inputs; resolve them explicitly in a step. * * @group Factory and workflows */ type TicketWorkflowInputs> = WorkflowInputs; /** * A workflow: its function, its input schema, and what a run needs before it * may start. * * @group Factory and workflows */ interface WorkflowDefinition { inputs: S; /** * What the workflow needs before a run can start: the agents it runs, the * integrations, bindings and API model sources it uses, and the names of the * environment variables its steps read as `secrets`. The service checks the * CLI of every agent's harness when it starts, and preflight checks * everything listed before every run. List only what the workflow uses. * * @remarks * A secret is set in the factory's environment and read in a step from the * process environment. The variables an agent's MCP servers name count as secrets * without being listed. Listing a secret does not pass it to agents. * * @example * Pass this value as `requires` when calling `defineWorkflow`. * ```ts * import { harnesses, type WorkflowDefinition } from "@jigs-ai/jigs"; * * const agents = { * builder: harnesses.claude({ model: "opus" }), * reviewer: harnesses.codex({ model: "gpt-5.6-sol" }), * }; * * const requires = { * agents, * integrations: ["linear", "github"], * bindings: ["app"], * secrets: ["SNOWFLAKE_TOKEN"], * } satisfies WorkflowDefinition["requires"]; * ``` */ requires?: WorkflowRequires; release?: ReleasePolicy; workflow: (inputs: WorkflowInputs) => Promise; } /** * Declare a workflow as the default export of its file. It returns the * definition unchanged; it exists so TypeScript checks the workflow's * parameter against the input schema. * * @example * ```ts * import { defineWorkflow, type WorkflowInputs } from "@jigs-ai/jigs"; * import { z } from "zod"; * * const inputs = z.object({ name: z.string() }); * * export async function hello(input: WorkflowInputs) { * "use workflow"; * return `Hello, ${input.name}!`; * } * * export default defineWorkflow({ inputs, workflow: hello }); * ``` * * @group Factory and workflows */ declare function defineWorkflow(definition: WorkflowDefinition): WorkflowDefinition; type AnyWorkflowDefinition = WorkflowDefinition; /** One recurring trigger: a workflow, when to fire it, and the inputs to * fire it with. * * @group Factory and workflows */ interface Schedule { /** An inactive schedule never fires. */ active: boolean; workflow: string; /** Five fields, evaluated in the service host's local time zone. */ cron: string; inputs: Record; } /** * What an event trigger watches: a source kind and the provider's own query * parameters for it. Plain data, so it can sit in `jigs.config.ts`; a source's * constructor builds it. * * @group Factory and workflows */ interface SourceDescriptor { kind: string; params: Record; } /** * A trigger that starts one run per occurrence its source reports, at most * once per occurrence. Each run gets the reference the source hands it, * merged over the fixed `inputs`. * * @remarks * A new trigger starts from the moment the service first runs it, with no * backfill. After the service was down, it starts runs only for occurrences * within `lookbackMinutes` and records older ones as skipped. * * @group Factory and workflows */ interface EventTrigger { /** An inactive trigger is not armed: its source's occurrences start no runs. */ active: boolean; workflow: string; source: SourceDescriptor; inputs?: Record; /** Runs of this trigger active at once. Defaults to 20; further occurrences wait, oldest first. */ maxActive?: number; /** How far back to catch up after the service was down. Defaults to 60. */ lookbackMinutes?: number; } /** * What a factory repo hands the service: its workflows, keyed by name, and * the schedules and event triggers that start them. A schedule is keyed by * its own name rather than nested under a workflow. The name is what runs, * status and `jigs doctor` refer to, and one workflow can carry several. * * @group Factory and workflows */ interface Factory { workflows: Record; schedules?: Record; triggers?: Record; } /** * Who the operator is on GitHub. * * @remarks * jigs acts on GitHub as the GitHub App the hub assigns this factory, so its pull requests come * from `[bot]` and the operator approves them with a review. * * @example * Use this value for `github` in `jigs.config.ts`. * ```ts * import type { GitHubDefinition } from "@jigs-ai/jigs"; * * const github = { * operator: "octocat", * coAuthor: "Octo Cat ", * } satisfies GitHubDefinition; * ``` * * @group Factory and workflows */ type GitHubDefinition = z.input; /** * Who a ticket run's Linear questions and notes mention. * * @remarks * `operator` is the email of the Linear user who runs the factory. With it, * every question and note a ticket run posts mentions the operator and the * ticket's assignee; without it, the ticket's creator and assignee. * `jigs doctor` fails when no Linear user has the email. Steps read it from * the built factory, so a change takes effect after a rebuild, which * `jigs up` does. * * @example * Use this value for `linear` in `jigs.config.ts`. * ```ts * import type { LinearDefinition } from "@jigs-ai/jigs"; * * const linear = { * operator: "salim@example.com", * } satisfies LinearDefinition; * ``` * * @group Factory and workflows */ type LinearDefinition = z.input; /** * A repository this factory works in: its remote, the GitHub installation * that reaches it, and how a worktree cut from it is provisioned. * * @remarks * `installationName` is the name an admin gave the GitHub App installation on * the hub. Pushes, pull requests and their events go through it. * * @example * Use this value for `bindings.api` in `jigs.config.ts`. * ```ts * import type { BindingDefinition } from "@jigs-ai/jigs"; * * const api = { * remote: "git@github.com:acme/api.git", * installationName: "github-acme", * postCreate: ["pnpm install"], * } satisfies BindingDefinition; * ``` * * @group Factory and workflows */ type BindingDefinition = z.input; /** * Settings for the agent harnesses this factory runs. * * @group Factory and workflows */ type AgentsDefinition = z.input; /** * Factory-wide defaults for the harnesses this factory's workflows build. * * @remarks * `claude.credential` is how every Claude harness that sets no `credential` of its own pays for * its calls. Leave it out for the claude.ai subscription login. Workflow code cannot read the * environment, but `jigs.config.ts` can, so each copy can choose its own: the subscription login * on a laptop and an API key on a server, from the same workflows. The service reads it when it * starts. * * @example * Use this value for `harnesses` in `jigs.config.ts`. * ```ts * import type { HarnessesDefinition } from "@jigs-ai/jigs"; * * const harnesses = { * claude: { credential: process.env.ANTHROPIC_API_KEY ? { kind: "api-key" } : undefined }, * } satisfies HarnessesDefinition; * ``` * * @group Factory and workflows */ type HarnessesDefinition = z.input; /** * Operating settings and deferred workflow modules declared by a factory. * * @group Factory and workflows */ type FactoryDefinition = z.input & { workflows: Record; }; /** * Check the declaration against what jigs accepts and preserve its inferred keys, without loading * its workflows. * * @group Factory and workflows */ declare function defineFactory(factory: T & Record, never>): T; //#endregion //#region src/workflow/factory-schema.d.ts declare const agentsSchema: z.ZodObject<{ env: z.ZodDefault>; }, z.core.$strict>; declare const harnessesSchema: z.ZodObject<{ claude: z.ZodPrefault; apiKeyEnv: z.ZodOptional; }, z.core.$strict>, z.ZodObject<{ kind: z.ZodLiteral<"bedrock">; }, z.core.$strict>], "kind">>; }, z.core.$strict>>; }, z.core.$strict>; /** * An installation's name, as an admin set it on the hub: lowercase letters, digits and hyphens, * starting with a letter. Use it for a workflow input that names an installation. * * @group Factory and workflows */ declare const installationNameSchema: z.ZodString; declare const bindingSchema: z.ZodObject<{ remote: z.ZodString; installationName: z.ZodString; copy: z.ZodDefault>; postCreate: z.ZodDefault>; preRemove: z.ZodDefault>; hookTimeoutMinutes: z.ZodDefault; }, z.core.$strict>; declare const githubSchema: z.ZodObject<{ operator: z.ZodOptional; coAuthor: z.ZodOptional; }, z.core.$strict>; /** * A factory's Linear settings: optionally the operator, the Linear user's * email that every question and note a ticket run posts mentions together * with the ticket's assignee. jigs acts on Linear as the Linear app the hub * assigns the factory. */ declare const linearSchema: z.ZodObject<{ operator: z.ZodOptional; }, z.core.$strict>; type WorkflowImport = () => Promise<{ default: WorkflowDefinition; }>; declare const factoryConfigSchema: z.ZodObject<{ bindings: z.ZodDefault>; postCreate: z.ZodDefault>; preRemove: z.ZodDefault>; hookTimeoutMinutes: z.ZodDefault; }, z.core.$strict>>>; hub: z.ZodOptional>; github: z.ZodPrefault; coAuthor: z.ZodOptional; }, z.core.$strict>>; linear: z.ZodPrefault; }, z.core.$strict>>; release: z.ZodOptional; onFailure: z.ZodEnum<{ keep: "keep"; release: "release"; }>; }, z.core.$strict>>; deployments: z.ZodPrefault; }, z.core.$strict>>; agents: z.ZodPrefault>; }, z.core.$strict>>; harnesses: z.ZodPrefault; apiKeyEnv: z.ZodOptional; }, z.core.$strict>, z.ZodObject<{ kind: z.ZodLiteral<"bedrock">; }, z.core.$strict>], "kind">>; }, z.core.$strict>>; }, z.core.$strict>>; workflows: z.ZodOptional>>; schedules: z.ZodOptional>>>; triggers: z.ZodOptional>>>; }, z.core.$strict>; type FactoryConfig = z.output; //#endregion //#region src/config/factory-context.d.ts interface FactoryContext { readonly root: string; /** Keys this factory's rows, service record and clones apart from other factories'. */ readonly slug: string; readonly config: FactoryConfig; /** The process environment's value. Empty is unset. */ env(name: string): string | undefined; } //#endregion //#region src/workflow/agents/harness-config.d.ts /** * A harmless MCP tool call used to prove that a configured server is available. * * @group Harnesses and models */ type McpToolProbe = { tool: string; arguments?: Record; }; /** * Configuration for an MCP server launched as a child process. * * @remarks * Credentials never appear in workflow code: each `env` value names an environment variable of * the service, read when the step starts the agent. A step whose named variable is not set fails * before the agent starts. * * @example * ```ts * import { harnesses } from "@jigs-ai/jigs"; * * // The server reads BRAVE_API_KEY; its value comes from the service's SEARCH_API_KEY. * const researcher = harnesses.claude({ * model: "opus", * mcpServers: { * search: { * command: "npx", * args: ["-y", "@brave/brave-search-mcp-server"], * env: { BRAVE_API_KEY: "SEARCH_API_KEY" }, * probe: { tool: "brave_web_search", arguments: { query: "jigs", count: 1 } }, * }, * }, * }); * ``` * * @group Harnesses and models */ type McpStdioServerConfig = { command: string; args?: string[]; /** Maps the server's variable names to the names of the service variables holding their values. */ env?: Record; /** Raw MCP tool names the model may not call. Pi takes its `tools` allowlist instead. */ disabledTools?: string[]; probe: McpToolProbe; }; /** * Configuration for an MCP server reached over HTTP. * * @remarks * Credentials never appear in workflow code: each `headers` value and `bearerTokenEnv` name an * environment variable of the service, read when the step starts the agent. A step whose named * variable is not set fails before the agent starts. * * @group Harnesses and models */ type McpHttpServerConfig = { url: string; /** Maps HTTP header names to the names of the service variables holding their values. */ headers?: Record; /** Names the service variable holding a token sent as `Authorization: Bearer `. */ bearerTokenEnv?: string; /** Raw MCP tool names the model may not call. Pi takes its `tools` allowlist instead. */ disabledTools?: string[]; probe: McpToolProbe; }; /** * An MCP server an agent harness can expose to the model. * * @group Harnesses and models */ type McpServerConfig = McpStdioServerConfig | McpHttpServerConfig; /** * A stdio MCP server Pi exposes through an explicit direct-tool allowlist. * * @group Harnesses and models */ type PiMcpStdioServerConfig = Omit & { /** Raw MCP tool names the model may call. This must include the probe tool. */ tools: string[]; }; /** * An HTTP MCP server Pi exposes through an explicit direct-tool allowlist. * * @group Harnesses and models */ type PiMcpHttpServerConfig = Omit & { /** Raw MCP tool names the model may call. This must include the probe tool. */ tools: string[]; } & ({ /** Use OAuth credentials already held by the adapter's secure store. */ auth: "oauth"; bearerTokenEnv?: never; } | { /** Disable OAuth auto-detection for this server. */ auth?: false; bearerTokenEnv?: never; } | { auth?: never; bearerTokenEnv: string; }); /** * An explicitly configured MCP server accepted by the Pi harness. * * @group Harnesses and models */ type PiMcpServerConfig = PiMcpStdioServerConfig | PiMcpHttpServerConfig; type IsData = unknown extends T ? true : Depth["length"] extends 6 ? true : T extends ((...args: never[]) => unknown) ? false : T extends readonly (infer E)[] ? IsData : T extends object ? false extends { [K in keyof T]-?: IsData, [...Depth, unknown]>; }[keyof T] ? false : true : true; /** * The keys of a settings type whose values are data, so they can cross into a step. * * @group Harnesses and models */ type JsonOnly = { [K in keyof T as false extends IsData> ? never : K]: T[K]; }; declare const claudePolicyKeys: readonly ["cwd", "env", "pathToClaudeCodeExecutable", "executable", "executableArgs", "permissionMode", "allowDangerouslySkipPermissions", "strictMcpConfig", "mcpServers", "settingSources", "resume", "continue", "sessionId", "forkSession", "persistSession", "resumeSessionAt", "resumeDropsTurn", "extraArgs", "outputFormat", "agents", "settings", "plugins", "projectConfigRoot", "skills"]; /** * A Claude Code option a descriptor cannot name, because jigs sets it itself or holds it as * policy. * * @remarks * jigs sets the working directory, environment, executable, session and output format for every * step, and holds permissions, setting sources and MCP servers as policy. `extraArgs` would * rewrite any of those. `agents`, `settings`, `plugins` and `projectConfigRoot` would bring in * unprobed MCP servers, environment, permissions and hooks from outside the worktree; they come * from the repository's project settings instead. jigs fills `plugins` itself to load the * descriptor's `skills`, which replace Claude Code's own `skills` option. * * @group Harnesses and models */ type ClaudePolicyKey = (typeof claudePolicyKeys)[number]; declare const codexPolicyKeys: readonly ["cwd", "env", "codexPath", "approvalPolicy", "sandboxPolicy", "autoApprove", "threadMode", "resume", "persistExtendedHistory", "configOverrides", "mcpServers"]; /** * A Codex setting a descriptor cannot name, because jigs sets it itself or holds it as policy. * * @remarks * jigs sets the working directory, environment, executable, thread and session for every step, * and holds the approval and sandbox policies and MCP servers. `configOverrides` would rewrite * the sandbox and MCP tables. * * @group Harnesses and models */ type CodexPolicyKey = (typeof codexPolicyKeys)[number]; /** * Names the installation, as an admin named it on the hub, an agent acts through. * * @remarks * On `github`, the agent gets a fresh token of that GitHub App installation in `GH_TOKEN`, so * `gh` works as the App's bot, and git reaches the installation account's repositories over * HTTPS with that token. Its commits are authored by the bot, while your own git configuration * stays the committer and signer. On `linear`, the workspace's token goes in * `JIGS_LINEAR_TOKEN`; on `pagerduty`, the account's token goes in `JIGS_PAGERDUTY_TOKEN`. * * @example * ```ts * import { harnesses } from "@jigs-ai/jigs"; * * const builder = harnesses.codex({ * model: "gpt-5.6-sol", * github: { installationName: "github-acme" }, * }); * ``` * * @group Harnesses and models */ type AgentInstallation = { installationName: string; }; /** * Skill folders an agent loads, each holding a `SKILL.md` and any files it refers to. * * @remarks * Each path is relative to the factory root, or absolute. jigs copies every folder into a private * place for each agent call, so the skills reach the agent whatever its working directory and * nothing the agent changes there reaches the factory. Each folder is copied under its own name, * so two folders cannot share one; keep it the same as the `name` in its `SKILL.md`. A run whose * folder is missing or has no `SKILL.md` fails its checks before the agent starts. Skills apply * when an agent runs in a directory, not to `askAgent`. * * @group Harnesses and models */ type HarnessSkills = { skills?: string[]; }; /** * Claude Code pays for its calls with an Anthropic API key, read from `apiKeyEnv` in the * factory's environment, or `ANTHROPIC_API_KEY` when that is left out. * * @group Harnesses and models */ type ClaudeApiKeyCredential = { kind: "api-key"; apiKeyEnv?: string; }; /** * Claude Code calls its models through Amazon Bedrock, with the AWS credentials and region the * factory's environment holds: static keys, a profile, or the credentials an ECS task, a Fargate * task or an EKS pod is given. * * @group Harnesses and models */ type ClaudeBedrockCredential = { kind: "bedrock"; }; /** * How Claude Code pays for its calls when not through a claude.ai subscription login. * * @remarks * A harness without one uses the factory's default, `harnesses.claude.credential` in * `jigs.config.ts`, and without that the account `claude auth login` signed in. Set the default * there to choose per copy from its environment, since workflow code cannot read it. Workflow * code never holds a key: `api-key` names the variable the step reads when the agent starts, and * `bedrock` passes the AWS variables the service has through to the agent. * * @example * ```ts * import { harnesses } from "@jigs-ai/jigs"; * * const hosted = harnesses.claude({ model: "opus", credential: { kind: "api-key" } }); * const onAws = harnesses.claude({ model: "opus", credential: { kind: "bedrock" } }); * ``` * * @group Harnesses and models */ type ClaudeCredential = ClaudeApiKeyCredential | ClaudeBedrockCredential; /** * A Claude Code harness descriptor: the Claude Agent SDK's own options that are data, minus each * {@link ClaudePolicyKey}, plus the model, jigs' MCP server shape, {@link HarnessSkills} and an * optional {@link ClaudeCredential}. * * @group Harnesses and models */ type ClaudeHarness = JsonOnly> & HarnessSkills & { kind: "claude"; model: string; /** An API key or Bedrock; left out, the factory's default or the subscription login. */ credential?: ClaudeCredential; mcpServers?: Record; /** Acts on GitHub as the factory's App, through this installation. */ github?: AgentInstallation; /** Acts on Linear as the factory's app, through this installation. */ linear?: AgentInstallation; /** Acts on PagerDuty as the factory's app, through this installation. */ pagerduty?: AgentInstallation; }; /** * A Codex harness descriptor: the provider's own settings that are data, minus each * {@link CodexPolicyKey}, plus the model, jigs' MCP server shape and {@link HarnessSkills}. * * @group Harnesses and models */ type CodexHarness = JsonOnly> & HarnessSkills & { kind: "codex"; model: string; mcpServers?: Record; /** Acts on GitHub as the factory's App, through this installation. */ github?: AgentInstallation; /** Acts on Linear as the factory's app, through this installation. */ linear?: AgentInstallation; /** Acts on PagerDuty as the factory's app, through this installation. */ pagerduty?: AgentInstallation; }; type SharedPiHarness = HarnessSkills & { kind: "pi"; thinking?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"; tools?: string[]; mcpServers?: Record; /** Acts on GitHub as the factory's App, through this installation. */ github?: AgentInstallation; /** Acts on Linear as the factory's app, through this installation. */ linear?: AgentInstallation; /** Acts on PagerDuty as the factory's app, through this installation. */ pagerduty?: AgentInstallation; }; /** * An OpenRouter API model source. * * @group Harnesses and models */ type OpenrouterSource = { kind: "openrouter"; model: string; apiKeyEnv: string; }; /** * Pi-specific compatibility hints for an OpenAI-compatible model. * * @group Harnesses and models */ type PiOpenaiCompatibleOptions = { supportsDeveloperRole: boolean; supportsReasoningEffort: boolean; }; /** * An OpenAI-compatible API model source. * * @group Harnesses and models */ type OpenaiCompatibleSource = { kind: "openai-compatible"; name: string; baseUrl: string; model: string; apiKeyEnv?: string; }; /** * The Codex subscription model source used only by the Pi harness. * * @group Harnesses and models */ type OpenaiCodexSource = { kind: "openai-codex"; model: string; }; /** * Any configured source from which a model can answer. * * @group Harnesses and models */ type ModelSource = OpenrouterSource | OpenaiCompatibleSource | OpenaiCodexSource; /** * A model source accepted by a direct model call. * * @group Harnesses and models */ type AskableModelSource = Exclude; /** * The stable name of a model source. * * @group Harnesses and models */ type ModelKind = ModelSource["kind"]; /** * A Pi harness descriptor backed by an OpenAI-compatible source, with its compatibility hints. * * @group Harnesses and models */ type PiOpenaiCompatibleHarness = SharedPiHarness & { model: OpenaiCompatibleSource; compat: PiOpenaiCompatibleOptions; }; /** * A Pi harness descriptor backed by any source other than an OpenAI-compatible one. * * @group Harnesses and models */ type PiOtherHarness = SharedPiHarness & { model: Exclude; compat?: never; }; /** * A Pi harness descriptor backed by a nested model source. * * @group Harnesses and models */ type PiHarness = PiOpenaiCompatibleHarness | PiOtherHarness; /** * A serializable agent-program descriptor. * * @group Harnesses and models */ type Harness = ClaudeHarness | CodexHarness | PiHarness; /** * Marks a descriptor that names no tools, MCP servers or provider access. * * @group Harnesses and models */ type ToolFree = { tools?: never; mcpServers?: never; github?: never; linear?: never; pagerduty?: never; }; /** * A harness `askAgent` can run with no tools: Claude Code or Pi, without MCP * servers, provider access or a Pi tool allowlist. Codex has no mode without tools. * * @group Harnesses and models */ type AskableHarness = (ClaudeHarness & ToolFree) | (PiHarness & ToolFree); /** * The stable name of an agent harness. * * @group Harnesses and models */ type HarnessKind = Harness["kind"]; /** * Constructors for model-source descriptors. * * @group Harnesses and models */ declare const models: { /** * Build an OpenRouter source. Its key is read from `OPENROUTER_API_KEY` * unless `apiKeyEnv` names another variable. */ readonly openrouter: (model: string, options?: { apiKeyEnv?: string; }) => OpenrouterSource; /** Build a source for an OpenAI-compatible server. */ readonly openaiCompatible: (options: { name: string; baseUrl: string; model: string; apiKeyEnv?: string; }) => OpenaiCompatibleSource; /** * Build a source that runs through the Codex subscription Pi is logged in * to. Only `harnesses.pi` accepts it. */ readonly openaiCodex: (model: string) => OpenaiCodexSource; }; /** * Options for `harnesses.pi`. `compat` applies only to an OpenAI-compatible * model source. * * @group Harnesses and models */ type PiHarnessOptions = Pick & { compat?: Partial; }; /** * The one argument `harnesses.claude` takes: the model and any Claude Code settings. * * @group Harnesses and models */ type ClaudeHarnessSettings = Omit; /** * The one argument `harnesses.codex` takes: the model and any Codex settings. * * @group Harnesses and models */ type CodexHarnessSettings = Omit; type Exactly = O & { [K in Exclude]: never; }; /** * The descriptor a harness constructor returns for its options. It is also * {@link ToolFree}, so `askAgent` accepts it, when the options name no tools, * MCP servers or provider access. * * @group Harnesses and models */ type HarnessForOptions = [Extract] extends [never] ? H & ToolFree : H; /** * Build a Pi harness around a model source. `compat` applies only to an * OpenAI-compatible source; each hint omitted from it defaults to `false`. * Without `tools` or `mcpServers` the harness also works with `askAgent`. An * MCP server Pi cannot run throws here, when the workflow module loads. */ declare function piHarness>(model: OpenaiCompatibleSource, options?: O): HarnessForOptions; declare function piHarness = Record>(model: Exclude, options?: O): HarnessForOptions; declare function piHarness & { compat?: OpenaiCompatibleSource extends M ? Partial : never; } = Record>(model: M, options?: O): HarnessForOptions; /** * Build a Claude Code harness from the model and any Claude Code settings. Without `tools` or * `mcpServers` it also works with `askAgent`. A `credential` the drivers cannot forward throws * here, when the workflow module loads. * * @example * ```ts * import { harnesses } from "@jigs-ai/jigs"; * * const builder = harnesses.claude({ model: "opus", effort: "high", maxTurns: 40 }); * ``` * * @example * `credential` pays with an Anthropic API key or through Amazon Bedrock instead of the * subscription login. * ```ts * import { harnesses } from "@jigs-ai/jigs"; * * const hosted = harnesses.claude({ model: "opus", credential: { kind: "api-key" } }); * ``` * * @example * `skills` names skill folders relative to the factory root. On Claude Code they join the * repository's own `.claude/skills` under the `jigs-skills:` prefix. * ```ts * import { harnesses } from "@jigs-ai/jigs"; * * const analyst = harnesses.claude({ model: "opus", skills: ["skills/snowflake"] }); * ``` */ declare function claudeHarness(settings: Exactly): HarnessForOptions; /** * Build a Codex harness from the model and any Codex settings. Only `runAgent` accepts it: Codex * has no mode without tools. * * @example * ```ts * import { harnesses } from "@jigs-ai/jigs"; * * const builder = harnesses.codex({ model: "gpt-5.6-sol", personality: "pragmatic" }); * ``` */ declare function codexHarness(settings: Exactly): CodexHarness; /** * Constructors for agent-harness descriptors. * * @group Harnesses and models */ declare const harnesses: { readonly claude: typeof claudeHarness; readonly codex: typeof codexHarness; readonly pi: typeof piHarness; }; /** * Every harness kind this release of jigs can build, taken from the keys of * `harnesses`. Use it for a workflow input that names a harness, so a new kind * appears without editing the input. * * @example * ```ts * import { harnessKinds } from "@jigs-ai/jigs"; * import { z } from "zod"; * * const inputs = z.object({ harness: z.enum(harnessKinds) }); * ``` * * @group Harnesses and models */ declare const harnessKinds: [HarnessKind, ...HarnessKind[]]; //#endregion //#region src/workflow/agents/conversation.d.ts /** One message a person sent into a conversation. `uuid` is the caller's own id for it, a UUID. */ type ConversationMessage = { uuid: string; author: string; text: string; }; /** * One turn of a conversation with a harness: the messages that open it, in the worktree the * harness works in. * * @remarks * `conversation` names the conversation. It keys the live turn that accepts more messages while * the turn runs, and every turn with the same name continues the same harness session. That * session lives with the worktree, so a conversation keeps one `cwd` for its whole life. * `messages` holds at least one message. `instructions` lead the first message when the session * starts fresh, and are ignored once it exists. */ type TurnRequest = { harness: Harness; cwd: string; conversation: string; messages: ConversationMessage[]; instructions?: string; }; /** * How a turn ended, with each answer the harness gave and `consumed`, every message it took, in * order: one not listed was never delivered. `finished` means it answered every message the turn * accepted. `stopped` means the turn was stopped and messages still queued were dropped. `failed` * means a turn ended in an error, which `error` describes; the messages after it were dropped. */ type TurnResult = { outcome: "finished" | "stopped"; replies: string[]; consumed: string[]; } | { outcome: "failed"; error: string; replies: string[]; consumed: string[]; }; /** What the turn step returns: the turn's result, or the just-in-time checks that failed. */ type TurnStepResult = TurnResult | { jitFailure: FailedCheck[]; }; //#endregion //#region src/workflow/agents/jev.d.ts /** * A calibrated yes-or-no question. * * @group Decision models */ type YesNoQuestion = { type: "yes-no"; instructions: string; }; /** * A question answered with one named option. * * @group Decision models */ type ChoiceQuestion = Record> = { type: "choice"; instructions: string; options: OPTIONS; }; /** * A question scored over ordered levels, from lowest to highest. * * @group Decision models */ type ScoreQuestion = { type: "score"; instructions: string; levels: string[]; }; /** * Any question accepted by `askJev`. * * @group Decision models */ type JevQuestion = YesNoQuestion | ChoiceQuestion | ScoreQuestion; /** * Named decision questions evaluated against one shared state. * * @group Decision models */ type JevQuestions = Record; type JevJsonValue = null | boolean | number | string | JevJsonValue[] | JevJsonObject; type JevJsonObject = { [key: string]: JevJsonValue; }; /** * JSON-compatible evidence evaluated by a decision model. * * @group Decision models */ type JevState = string | JevJsonObject | JevJsonValue[]; /** * The calibrated answer shape selected by one question descriptor. * * @group Decision models */ type JevAnswer = QUESTION extends ChoiceQuestion ? { choice: Extract; probabilities: { [OPTION in keyof OPTIONS]: number; }; confidence: number; } : QUESTION extends ScoreQuestion ? { /** The probability-weighted expected value over the ordered levels. */ score: number; probabilities: Record; legend: Record; confidence: number; } : { probability: number; }; /** * Answers narrowed independently for every named question. * * @group Decision models */ type JevAnswers = { [KEY in keyof QUESTIONS]: JevAnswer; }; /** * A decision request in workflow and durable wire form. * * @group Decision models */ type AskJevOptions = { model: OpenrouterSource; state: JevState; questions: QUESTIONS; }; /** * A typed decision result. * * @group Decision models */ type JevResult = { answers: JevAnswers; }; /** * The factory's durable wrapper around the decision step. * * @group Factory plumbing */ type ExecuteJevStep = (request: AskJevOptions) => Promise>; /** * Build a calibrated yes-or-no question. * * @group Decision models */ declare function yesNo(instructions: string): YesNoQuestion; /** * Build a question answered with one named option. It throws unless every option has a * description. * * @group Decision models */ declare function choice>(instructions: string, options: OPTIONS): ChoiceQuestion; /** * Build a question scored over ordered levels, from lowest to highest. It throws unless there * are at least two levels, each described. * * @group Decision models */ declare function score(instructions: string, levels: string[]): ScoreQuestion; //#endregion //#region src/workflow/agents/output-schema.d.ts /** * The serializable JSON Schema sent across the workflow-step boundary. * * @group Agent and model requests/results */ type OutputJsonSchema = Record; //#endregion //#region src/workflow/agents/result.d.ts /** * A session reference: the small piece of data that lets a later `runAgent` call resume the same * harness session. Pass it back as `resume`. * * @group Agent and model requests/results */ type AgentSessionRef = { harness: Harness["kind"]; id: string; /** The harness descriptor the session was recorded on, as {@link describeHarness} renders it. */ descriptor: string; }; /** * A harness descriptor as a string that ignores field order: two descriptors that list the same * settings in another order render the same. * * @group Agent and model requests/results */ declare function describeHarness(harness: Harness): string; /** * Text and structured output returned by a model call. * * @group Agent and model requests/results */ type ModelResult = { text: string; output: T; }; /** * A model result with the session reference an agent harness returned, when it returned one. * * @group Agent and model requests/results */ type AgentResult = ModelResult & { session?: AgentSessionRef; }; //#endregion //#region src/workflow/agents/plan.d.ts /** * Options for an agent that works inside a directory. * * @group Agent and model requests/results */ type RunAgentOptions = { harness: Harness; cwd: string; prompt: string; /** The session reference of an earlier run to continue. */ resume?: AgentSessionRef | undefined; output?: z.ZodType | undefined; }; /** * Options for one harness turn without tools or a worktree. * * @group Agent and model requests/results */ type AskAgentOptions = { harness: AskableHarness; prompt: string; system?: string | undefined; output?: z.ZodType | undefined; }; /** * Options for one API model call. * * @group Agent and model requests/results */ type AskModelOptions = { model: AskableModelSource; prompt: string; system?: string | undefined; output?: z.ZodType | undefined; }; /** * Serializable agent request passed to a durable step. * * @group Factory plumbing */ type AgentRequest = (Omit & { outputSchema?: OutputJsonSchema; }) | (Omit & { cwd?: never; resume?: never; outputSchema?: OutputJsonSchema; }); /** * Serializable API model request passed to a durable step. * * @group Factory plumbing */ type ModelRequest = Omit & { outputSchema?: OutputJsonSchema; }; //#endregion //#region src/steps/agents/shared/step-stream.d.ts /** The SDK event fields the step stream reads; other event types are ignored. */ type AgentSourcePart

= TextStreamPart> = P extends { type: "text-delta" | "reasoning-delta"; } ? Pick : P extends { type: "tool-call"; } ? Pick : P extends { type: "tool-result"; } ? Pick : P extends { type: "tool-error"; } ? Pick : P extends { type: "finish"; } ? Pick : P extends { type: "error"; } ? Pick : Pick; //#endregion //#region src/steps/agents/shared/types.d.ts /** * What a conversation turn reports while it runs: that it started, each piece of agent activity, * and each answer as Claude gives it. */ type TurnEvent = { type: "start"; resume: boolean; } | { type: "part"; part: AgentSourcePart; } | { type: "reply"; text: string; }; /** Watches a conversation turn. Best effort: a failure here never fails the turn. */ type TurnObserver = (event: TurnEvent) => void | Promise; //#endregion //#region src/workflow/providers.d.ts /** The outside services a factory reads from and writes to. */ type Provider = "github" | "linear" | "slack" | "pagerduty"; //#endregion //#region src/checks/index.d.ts interface WorkflowRequires { agents?: Record; integrations?: Provider[]; bindings?: string[]; models?: AskableModelSource[]; aws?: true; secrets?: string[]; } //#endregion //#region src/checks/catalog.d.ts /** `unanswered` marks a failure the check did not give: it threw, or did not answer in time. */ type CheckOutcome = { id: string; label: string; unanswered?: true; } & CheckResult; type FailedCheck = Extract; //#endregion //#region src/workflow/agents/agent.d.ts /** * A failed just-in-time tool check, with repair details for each failure. * * @group Errors and utilities */ declare class JitCheckError extends Error { readonly failures: FailedCheck[]; constructor(failures: FailedCheck[]); } /** * The factory's `"use step"` wrapper around `executeAgent`. * * @group Factory plumbing */ type ExecuteAgentStep = (wire: AgentRequest) => Promise; /** * Convert returned execution failure markers into errors the workflow throws. * * @group Agent and model requests/results */ declare function unwrapAgentStep(result: Awaited>): AgentResult; //#endregion //#region src/workflow/agents/github-mcp.d.ts /** * Options for {@link githubMcp} on a Pi harness. * * @group Harnesses and models */ type GithubMcpOptions = { /** Raw MCP tool names the model may call. jigs adds the probe tool, `search_repositories`. */ tools: string[]; }; /** * An MCP server that gives an agent GitHub's own tools, acting as the factory's GitHub App. * * @remarks * It runs `github-mcp-server`, which must be installed on the machine, with the token of an * agent whose harness sets `github`; a harness without `github` cannot use it. Tools that need a * user, such as `get_me`, are left out, since an App's token cannot answer them. Pi needs the * list of tools the model may call. * * @example * ```ts * import { githubMcp, harnesses } from "@jigs-ai/jigs"; * * const builder = harnesses.claude({ * model: "opus", * github: { installationName: "github-acme" }, * mcpServers: { github: githubMcp() }, * }); * ``` * * @group Harnesses and models */ declare function githubMcp(): McpStdioServerConfig; declare function githubMcp(options: GithubMcpOptions): PiMcpStdioServerConfig; //#endregion //#region src/workflow/agents/linear-mcp.d.ts /** * Options for {@link linearMcp} on a Pi harness. * * @group Harnesses and models */ type LinearMcpOptions = { /** Raw MCP tool names the model may call. jigs adds the probe tool, `list_teams`. */ tools: string[]; }; /** * An MCP server that gives an agent Linear's own tools, acting as the factory on Linear. * * @remarks * It reaches Linear's hosted server at `https://mcp.linear.app/mcp` with the token of an agent * whose harness sets `linear`; a harness without `linear` cannot use it. In app mode the agent * acts as the factory's Linear app, in key mode as the API key's user. Pi needs the list of * tools the model may call. The result is plain data, so spread it to change a field, such as * `url` to `https://mcp.linear.app/mcp/readonly` for read tools only. * * @example * ```ts * import { harnesses, linearMcp } from "@jigs-ai/jigs"; * * const triager = harnesses.claude({ * model: "opus", * linear: { installationName: "linear-acme" }, * mcpServers: { linear: linearMcp() }, * }); * ``` * * @group Harnesses and models */ declare function linearMcp(): McpHttpServerConfig; declare function linearMcp(options: LinearMcpOptions): PiMcpHttpServerConfig; //#endregion //#region src/workflow/agents/pagerduty-mcp.d.ts /** * Options for {@link pagerdutyMcp} on a Pi harness. * * @group Harnesses and models */ type PagerdutyMcpOptions = { /** Raw MCP tool names the model may call. jigs adds the probe tool, `list_incidents`. */ tools: string[]; }; /** * An MCP server that gives an agent PagerDuty's own tools, acting as the factory's PagerDuty app. * * @remarks * It reaches PagerDuty's hosted server with the token of an agent whose harness sets * `pagerduty`; a harness without `pagerduty` cannot use it. The token carries the scopes jigs * itself uses, so the agent can read and update incidents and read users; other tools fail for * lack of a scope. The token belongs to an app, not a user, so `get_user_data` is disabled and * `list_incidents` cannot filter by the `assigned` or `teams` request scope. Pi needs the list of * tools the model may call; leave `get_user_data` out of it. The result is plain data: for an * account in the EU service region, spread it with `url: "https://mcp.eu.pagerduty.com/mcp"`. * * @example * ```ts * import { harnesses, pagerdutyMcp } from "@jigs-ai/jigs"; * * const triager = harnesses.claude({ * model: "opus", * pagerduty: { installationName: "pagerduty-acme" }, * mcpServers: { pagerduty: pagerdutyMcp() }, * }); * ``` * * @group Harnesses and models */ declare function pagerdutyMcp(): McpHttpServerConfig; declare function pagerdutyMcp(options: PagerdutyMcpOptions): PiMcpHttpServerConfig; //#endregion //#region src/workflow/delivery/answers.d.ts declare const reviewFinding: z.ZodObject<{ summary: z.ZodString; blocking: z.ZodBoolean; }, z.core.$strict>; declare const findingResponse: z.ZodObject<{ finding: z.ZodString; changed: z.ZodBoolean; detail: z.ZodString; }, z.core.$strict>; /** * One finding from a review of the change. * * @group Pull request delivery */ type ReviewFinding = z.output; /** * The builder's answer to one finding: what it changed, or why it changed nothing. * * @group Pull request delivery */ type FindingResponse = z.output; /** * One build and the review of what it committed. * * @group Pull request delivery */ interface ReviewRound { round: number; /** The builder's answers to the previous round's findings; empty on the first round. */ responses: FindingResponse[]; /** `changes-requested` when any finding is blocking. */ verdict: "approved" | "changes-requested"; findings: ReviewFinding[]; } //#endregion //#region src/workflow/pull-requests/policy.d.ts /** * Which commits an approving review covers, chosen in workflow code. * * @remarks * `latest-commit`, the default, counts an approval only on the commit it names, so a push * withdraws it. `any-commit` keeps a person's approval counting through later pushes until a * later review requests changes or the approval is dismissed; approvals by a bot, such as an * agent acting as the factory's GitHub App, never count. */ type ApprovalCoverage = "latest-commit" | "any-commit"; /** * Whose consent a merge needs, chosen in workflow code for each merge. * * @remarks * `operator`, the default, needs a person's approving review. `workflow` lets the * workflow's own checks stand in for it, for a workflow that judges a pull request itself, such as * one that tests a dependency update before merging it. Every other merge requirement still holds, * and a review requesting changes still stops the merge. */ type MergeConsent = "operator" | "workflow"; //#endregion //#region src/workflow/pull-requests/pull-request.d.ts /** * Identifies a repository, and the GitHub installation jigs reaches it through. * * @group Pull requests */ type RepositoryRef = { /** The name of the GitHub App installation, as named on the hub, that jigs acts through. */ installationName: string; /** The GitHub organization or account that owns the repository. */ owner: string; /** The repository name. */ repo: string; }; /** * Identifies a pull request by its repository, the installation jigs reaches it through, and its number. * * @group Pull requests */ type PullRequestRef = RepositoryRef & { /** The repository-local pull request number. */ number: number; }; type FetchPrState = (pr: PullRequestRef, options?: PullRequestReadOptions) => Promise; /** * How workflow code asks for a pull request's approval to be read. * * @group Pull requests */ interface PullRequestReadOptions { /** Which commits an approving review covers. Default `"latest-commit"`. */ approvalCovers?: ApprovalCoverage; } /** * How workflow code asks for a pull request to be merged. * * @group Pull requests */ interface MergeOptions extends PullRequestReadOptions { /** Whose consent the merge needs. Default `"operator"`. */ consent?: MergeConsent; } //#endregion //#region src/workflow/pull-requests/snapshot.d.ts /** * A submitted GitHub review of a pull request. * * @group Pull requests */ interface PullRequestReview { id: number; state: string; body: string; user: string; submittedAt: string; commitSha?: string; } /** * A comment anchored to a file in a pull request review. * * @group Pull requests */ interface ReviewComment { id: number; rootId: number; body: string; user: string; path: string; line: number | null; createdAt: string; updatedAt: string; } /** * A pull request review conversation, with its optional file location. * * @group Pull requests */ interface ReviewThread { rootId: number; path: string; line: number | null; comments: ReviewComment[]; origin?: "conversation"; } /** * A comment on the pull request conversation, which hangs off no thread. * * @group Pull requests */ interface PullRequestComment { id: number; body: string; user: string; userType: string; createdAt: string; updatedAt: string; } /** * A check or commit status reported on a pull request head. * * @group Pull requests */ interface CheckRun { name: string; conclusion: string | null; url: string; } /** * GitHub facts about a pull request, without a judgment about outstanding work. * * @group Pull requests */ interface PullRequestSnapshot { state: "open" | "closed"; merged: boolean; draft: boolean; headSha: string; /** * GitHub's own verdict on whether the pull request can merge right now, * folding in conflicts, required checks and required reviews. `"clean"` is * the only value that permits a merge; `"unknown"` means GitHub has not * finished computing it, so the answer is "not yet, ask again". */ mergeState: string; /** Label names on the pull request. */ labels: string[]; /** The merge commit, once GitHub has made one. */ mergeCommitSha: string | null; reviews: PullRequestReview[]; reviewThreads: ReviewThread[]; conversationComments: PullRequestComment[]; /** `none`: no check or status has reported on this head yet. It is never green. */ ci: "red" | "green" | "pending" | "none"; failingChecks: CheckRun[]; /** The operator's consent: how the people's approving reviews read on this head. */ approval: ApprovalState; /** * The login of the factory's GitHub App, `[bot]`: the account jigs posts as, and so do * agents whose harness sets `github`. */ appBot: string; } /** * How the operator's consent reads right now. `stale` is an approval that * named an earlier commit. This differs from a pull * request nobody has approved. * * @group Pull requests */ type ApprovalState = "approved" | "changes-requested" | "stale" | "none"; /** * A comparison key for the facts in a pull request snapshot. * * @remarks * Collection ordering and incidental fields do not change the key. Compare keys for equality; * the key format is opaque and is not a durable identifier. * * @group Pull requests */ declare function pullRequestSnapshotKey(snapshot: PullRequestSnapshot): string; //#endregion //#region src/providers/github.d.ts interface PullRequestReviewRequest { event: "comment" | "approve" | "request-changes"; body: string; comments?: Array<{ path: string; line: number; body: string; }>; } //#endregion //#region src/workflow/pull-requests/merge-ready.d.ts /** Why a merge did not happen, and whether a later wake could change it. */ interface MergeRefusal { /** A human-readable explanation of the state that prevented the merge. */ reason: string; /** * Whether the same head could still merge. A transient refusal is a state * jigs is waiting out — a check still running, a merge state GitHub has not * finished computing, an approval waiting to be granted again — so the * commit stays merge-ready and the next wake asks again. A terminal one is * the pull request as it stands refusing the merge, so the commit is stood * down until a new commit or a change to the repository moves it. */ transient: boolean; } /** * Whether current GitHub facts satisfy the configured approval and merge requirements. * * @group Pull requests */ declare function isPullRequestMergeReady(snapshot: PullRequestSnapshot): boolean; /** * The note to leave on a pull request that is approved and green but that GitHub * blocks from merging, or `null` when that is not why it waits. * * @remarks * GitHub does not say which branch rule blocks the merge, so without a note * jigs would wait in silence. * * @group Pull requests */ declare function blockedMergeNote(snapshot: PullRequestSnapshot): string | null; //#endregion //#region src/steps/pull-requests/pr.d.ts /** * A newly opened or adopted pull request and its browser URL. * * @group Open/update */ type OpenedPullRequest = PullRequestRef & { /** The pull request's browser URL. */ url: string; }; /** * Create a pull request from the worktree's branch into its repository's default branch. * * The lookup comes first because this is one step: a create that succeeded * before the assignment failed, or whose response was lost, leaves a pull * request GitHub will refuse to open twice. The retry adopts that pull request * and re-attempts only what did not finish. * * @group Open/update */ declare function createPullRequest(request: { worktree: Worktree; title: string; body: string; draft?: boolean | undefined; }): Promise; /** * Mark a draft pull request ready and return its freshly read state. * * @group Open/update */ declare function markPullRequestReady(pr: PullRequestRef): Promise; /** * Reply to a review thread and return the posted comment id. * * @group Discuss/review */ declare function replyToPullRequestReviewThread(pr: PullRequestRef, rootId: number, body: string): Promise<{ /** The posted comment id. */ id: number; }>; /** * Post a comment on the pull request conversation and return its id. * * @group Discuss/review */ declare function commentOnPullRequest(pr: PullRequestRef, body: string): Promise<{ /** The posted comment id. */ id: number; }>; /** * Post a pull request review and return its id. GitHub refuses an approval from * the pull request's own author with 422 Unprocessable Entity; Jigs lets * GitHub's GitHubApiError surface unchanged. * * @group Discuss/review */ declare function reviewPullRequest(pr: PullRequestRef, review: PullRequestReviewRequest): Promise<{ /** The posted review id. */ id: number; }>; /** * What GitHub did, why it declined, and whether asking again could * change the answer, which is what decides between standing the commit down * and leaving it merge-ready. * * @group Merge */ type MergeOutcome = { /** Confirms that GitHub reports the pull request merged. */ merged: true; /** The merge commit, or `null` when GitHub has not reported it yet. */ mergeCommitSha: string | null; } | ({ /** Indicates that the merge did not happen. */ merged: false; } & MergeRefusal); /** * Merge the pull request, pinned to the head the caller judged ready. * * The method is the first one the repository allows of squash, merge commit * and rebase, read from GitHub at each merge. * * The title is re-read here rather than carried in from `describePullRequest`: * a reviewer who corrects it, usually to satisfy a conventional-commit check * on the target repo, does so between the pull request opening and this * merge, and a title captured at open time would ship the one they corrected * away. After any ambiguous answer the pull request is read again, and this * reports `merged` only if GitHub says so. * * @group Merge */ declare function mergePullRequest(pr: PullRequestRef, expectedHeadSha: string, options?: MergeOptions): Promise; //#endregion //#region src/workflow/agents/agent-session.d.ts /** Run an agent through the factory's bound step wrapper. */ type RunAgentFn = (config: RunAgentOptions) => Promise>; /** * The two ways to state one turn of an agent session. * * @group Agent and model requests/results */ interface AgentSessionTurn { /** * Sent to an agent that already holds the earlier turns: only what is new. A function is called * only when the resume is taken. */ resume: string | (() => Promise); /** * Sent to an agent starting from nothing: everything it needs. A function is called only when * the session starts fresh, so gathering its context costs nothing on a resume. */ fresh: string | (() => Promise); } /** * One agent across several turns of a workflow. * * @remarks * `run` resumes the harness session the agent session holds. When that session is gone, or it was * recorded on a different harness descriptor, `run` starts fresh with the `fresh` prompt instead. * * @group Agent and model requests/results */ interface AgentSession { readonly harness: Harness; /** * With `output`, the answer is validated against it and returned parsed. An invalid answer is * asked for once more with the reasons, as `runAgent` does, and never sends the turn back to * `fresh`; a second invalid answer throws its `ZodError`. */ run(turn: AgentSessionTurn & { output: z.ZodType; }): Promise; run(turn: AgentSessionTurn): Promise; } /** What an agent session is started with. */ interface AgentSessionOptions { /** Names the session in log lines. */ name: string; harness: Harness; cwd: string; } /** * Build `agentSession` around the factory's bound `runAgent`. * * @group Factory plumbing */ declare function bindAgentSession(runAgent: RunAgentFn): (options: AgentSessionOptions) => AgentSession; //#endregion //#region src/workflow/delivery/delivery.d.ts /** * One piece of work taken to a pull request: what to build, where, and the agents that build, * review and describe it. * * @remarks * `work` is yours: only your prompts read it. Give each delivery its own agent session objects: a * session holds its agent's conversation, and its name only labels log lines. `writer` describes * the pull request and defaults to `builder`. Each routine reads only some of these fields, so a * full delivery can be passed to all of them. * * @group Pull request delivery */ interface Delivery { work: W; /** One key per pull request: it scopes the hidden markers on that pull request's notes. */ key: string; worktree: Worktree; prompts: DeliveryPrompts; builder: AgentSession; reviewer: AgentSession; writer?: AgentSession | undefined; } /** * The prompts a delivery sends, written by the workflow. jigs adds only the line that tells each * agent the shape of its answer. * * @remarks * A turn with two forms goes to an agent session: `resume` is sent to an agent that holds the * earlier turns, so it says only what is new, and `fresh` to one starting from nothing, so it * says everything. `describe` is sent either way. * * @group Pull request delivery */ interface DeliveryPrompts { build: { fresh: (facts: BuildFacts) => string; resume: (facts: { findings: ReviewFinding[]; }) => string; }; review: { fresh: (facts: ReviewFacts) => string; resume: (facts: { headSha: string; diff: string; responses: FindingResponse[]; }) => string; }; describe: (facts: { work: W; worktree: Worktree; diff: string; }) => string; maintain: { fresh: (facts: MaintainFacts & { work: W; worktree: Worktree; diff: string; }) => string; resume: (facts: MaintainFacts) => string; }; } /** * What a fresh build prompt is given: the open findings and the diff so far. * * @group Pull request delivery */ interface BuildFacts { work: W; worktree: Worktree; findings: ReviewFinding[]; /** Empty before the first commit. */ diff: string; } /** * What a fresh review prompt is given: the commit under review and every earlier round. * * @group Pull request delivery */ interface ReviewFacts { work: W; worktree: Worktree; headSha: string; diff: string; ledger: ReviewRound[]; } /** * What a maintenance prompt is given: the pull request as GitHub reports it, and any local work * the builder has to recover first. * * @group Pull request delivery */ interface MaintainFacts { pr: PullRequestRef; snapshot: PullRequestSnapshot; /** * The wake facts in `snapshot` the builder has not been shown, as the wake rule wrote them. * Empty when the turn only recovers local work. */ news: string[]; recovery?: UnpublishedWork | undefined; } /** * Local work the pull request has never had: uncommitted changes, or a local commit that was not * pushed. It holds back a merge until it is published. * * @group Pull request delivery */ interface UnpublishedWork { dirty: boolean; localHead: string; pullRequestHead: string; } /** * The durable steps the delivery routines run. * * @group Factory plumbing */ interface DeliverySteps { readBranchState: ReadBranchState; readWorktreeDiff: typeof readWorktreeDiff; pushApprovedChange: typeof pushApprovedChange; createPullRequest: typeof createPullRequest; registerResource: typeof registerResource; fetchPullRequestState: FetchPrState; mergePullRequest: typeof mergePullRequest; } //#endregion //#region src/workflow/delivery/build-and-review.d.ts /** * The parts of a delivery `buildAndReview` reads. * * @group Pull request delivery */ type BuildDelivery = Pick, "work" | "worktree" | "builder" | "reviewer"> & { prompts: Pick, "build" | "review">; }; /** * What `buildAndReview` needs besides the delivery. * * @group Pull request delivery */ interface BuildAndReviewOptions { /** One round is one build plus one review of what it committed. */ rounds: number; } /** * A change the reviewer approved. * * @group Pull request delivery */ interface BuildApproved { outcome: "approved"; /** The commit the reviewer approved. Publish exactly this one. */ reviewedCommit: string; /** The non-blocking findings of the approving round, for a person to read. */ notes: string[]; ledger: ReviewRound[]; } /** * Why `buildAndReview` stopped without an approved change. Nothing is pushed: committed work stays * in the worktree for the workflow to push or leave. * * @remarks * `rounds-exhausted` carries the blocking findings still open. `uncommitted` and `no-commits` mean * the builder left uncommitted changes, or committed nothing new, so there was nothing to review. * * @group Pull request delivery */ interface BuildStopped { outcome: "stopped"; reason: "rounds-exhausted" | "uncommitted" | "no-commits"; findings: string[]; /** The round it stopped in; for `rounds-exhausted`, the last round. */ round: number; } /** * What `buildAndReview` returns: an approved change, or a stop. * * @group Pull request delivery */ type BuildResult = BuildApproved | BuildStopped; //#endregion //#region src/workflow/delivery/describe.d.ts /** * The parts of a delivery `describePullRequest` reads. * * @group Pull request delivery */ type DescribeDelivery = Pick, "work" | "worktree" | "builder" | "writer"> & { prompts: Pick, "describe">; }; /** * A pull request title and body. * * @group Pull request delivery */ interface Described { title: string; body: string; } /** * What `describePullRequest` needs besides the delivery. * * @group Pull request delivery */ interface DescribeOptions { /** * The problems with a title and body, such as a title that breaks your naming convention; none * means they are fine. The writer is sent back once with the problems, and problems in its * second answer throw. */ check?: ((described: Described) => string[]) | undefined; } //#endregion //#region src/workflow/delivery/follow.d.ts /** * The parts of a delivery `followPullRequestToOutcome` reads. * * @group Pull request delivery */ type FollowDelivery = Pick, "work" | "key" | "worktree" | "builder"> & { prompts: Pick, "maintain">; }; /** * Why a pull request needs a person, as facts for the workflow to word and send. * * @remarks * - `builder-asked`: the builder said it needs a person; `detail` is its summary. * - `attempts-exhausted`: the builder's attempts for one pull request update ran out with local * work still unpublished; `detail` is its last summary. * - `merge-refused`: GitHub refused the merge; `detail` is the last refusal and `tries` how * often jigs tried. A transient refusal is retried up to ten times before it is reported. * - `merge-blocked`: GitHub blocks an approved, green pull request from merging, usually because * of a branch rule; `detail` says so in a sentence. Sent once per head. Mark a note posted * about it with `headSha` and the delivery's scope, so it does not wake the builder and a later * run does not post it again. * * `unpublished` is set when local work the pull request has never had holds back the merge. * The local worktree path never appears in `detail`. * * @group Pull request delivery */ type NeedsHuman = { reason: "builder-asked" | "attempts-exhausted"; detail: string; unpublished?: UnpublishedWork | undefined; } | { reason: "merge-refused"; detail: string; tries: number; } | { reason: "merge-blocked"; detail: string; headSha: string; }; /** * What `followPullRequestToOutcome` needs besides the delivery and the pull request. * * @group Pull request delivery */ interface FollowOptions { /** Builder turns allowed for each change to the pull request, including recovery. */ attemptsPerUpdate: number; /** * The facts in a snapshot that wake the builder, one string each; it is woken for one it has * not been shown. `scope` is the delivery's marker scope. Pass `builderWakeFacts` for the * default rules, or your own function, for example to ignore another bot's comments. */ wake: (snapshot: PullRequestSnapshot, scope: string) => string[]; /** * Whether you consent to merging this snapshot now. jigs still merges only when GitHub reports * the pull request approved, green and clean, so this can only make merging stricter. Return * `false` to leave every merge to a person, or check the snapshot, such as for a label. */ mergeWhen: (snapshot: PullRequestSnapshot) => boolean; /** Which commits a person's approving review covers. */ approvalCovers: ApprovalCoverage; /** * Tell a person the pull request needs them. Watching goes on: the next change to the pull * request picks the work back up. The same facts are never sent twice in a row. */ onNeedsHuman: (facts: NeedsHuman) => Promise; } /** * How `followPullRequestToOutcome` ended: the pull request merged, or closed unmerged. * * @group Pull request delivery */ type FollowResult = { outcome: "merged"; } | { outcome: "closed"; }; //#endregion //#region src/workflow/delivery/publish.d.ts /** * The parts of a delivery `publishPullRequest` reads. * * @group Pull request delivery */ type PublishDelivery = Pick, "worktree">; /** * What `publishPullRequest` needs besides the delivery. * * @group Pull request delivery */ interface PublishOptions { /** The commit to publish. It must be the worktree's HEAD, with nothing uncommitted. */ commit: string; title: string; body: string; draft?: boolean | undefined; } //#endregion //#region src/workflow/delivery/wake.d.ts /** * The default wake rule for `followPullRequestToOutcome`: the facts in a snapshot a builder can * act on, one string each. * * @remarks * A review with a body or one requesting changes, a new comment or a person's edit of one, a * check failing on the current head, and a conflict with the base each wake the builder. Checks * that queue, run or pass, a bare approval, label changes, a bot editing its own comment, the App * bot's unmarked comments (the builder's own replies) and notes marked with the delivery's * `scope` wake nothing. To change the rules, wrap it or pass your own function as `wake`. * * @example * ```ts * import { builderWakeFacts, type PullRequestSnapshot } from "@jigs-ai/jigs"; * * // Also ignore a coverage bot's comments. * const wake = (snapshot: PullRequestSnapshot, scope: string) => * builderWakeFacts( * { * ...snapshot, * conversationComments: snapshot.conversationComments.filter( * (comment) => comment.user !== "codecov[bot]", * ), * }, * scope, * ); * ``` * * @group Pull request delivery */ declare function builderWakeFacts(snapshot: PullRequestSnapshot, scope: string): string[]; //#endregion //#region src/workflow/errors.d.ts /** * An operator-readable failure that is safe to construct inside a workflow. * * @group Errors and utilities */ declare class JigsError extends Error { /** * What the reader can do about it. Quote each command to run in backticks, as in * ``stop the service first: `pnpm exec jigs service stop` ``: the CLI prints it on its own line. */ readonly hint?: string; constructor(message: string, hint?: string); } //#endregion //#region src/workflow/github/source.d.ts declare const gitHubPushesParamsSchema: z.ZodObject<{ installationName: z.ZodString; repositories: z.ZodOptional>; branches: z.ZodOptional>; }, z.core.$strict>; /** * Which pushes a `github.pushes` source starts runs for. Each list matches * any of its values; leaving one out does not filter on it. * * - `installationName`: the GitHub App installation, as named on the hub, * whose repositories it watches. * - `repositories`: `owner/repo` names, such as `acme/api`, in any case. * - `branches`: branch names, such as `main`. * * @group Factory and workflows */ type GitHubPushesParams = z.input; /** * The inputs a `github.pushes` source hands each run it starts. * * @group Factory and workflows */ type GitHubPushInputs = RepositoryRef & { /** The branch pushed to, such as `main`. */ branch: string; /** The commit the branch pointed at before the push, all zeros for a new branch. */ before: string; /** The commit the branch points at after the push. */ after: string; }; declare const gitHubPullRequestsParamsSchema: z.ZodObject<{ installationName: z.ZodString; repositories: z.ZodOptional>; authors: z.ZodOptional>; labels: z.ZodOptional>; baseBranches: z.ZodOptional>; }, z.core.$strict>; /** * Which pull requests a `github.pullRequests` source starts runs for. Each * list matches any of its values; leaving one out does not filter on it. * * - `installationName`: the GitHub App installation, as named on the hub, * whose repositories it watches. * - `repositories`: `owner/repo` names, such as `acme/api`, in any case. * - `authors`: GitHub logins of who opened the pull request, such as * `dependabot[bot]`. * - `labels`: label names; a pull request with any of them matches. * - `baseBranches`: the branches the pull request merges into, such as `main`. * * @group Factory and workflows */ type GitHubPullRequestsParams = z.input; declare const gitHubIssuesParamsSchema: z.ZodObject<{ installationName: z.ZodString; repositories: z.ZodOptional>; authors: z.ZodOptional>; labels: z.ZodOptional>; }, z.core.$strict>; /** * Which issues a `github.issues` source starts runs for. Each list matches * any of its values; leaving one out does not filter on it. * * - `installationName`: the GitHub App installation, as named on the hub, * whose repositories it watches. * - `repositories`: `owner/repo` names, such as `acme/api`, in any case. * - `authors`: GitHub logins of who opened the issue. * - `labels`: label names; an issue with any of them matches. * * @group Factory and workflows */ type GitHubIssuesParams = z.input; /** * The inputs a `github.issues` source hands each run it starts. * * @group Factory and workflows */ type GitHubIssueInputs = RepositoryRef & { /** The repository-local issue number. */ number: number; }; declare const gitHubReleasesParamsSchema: z.ZodObject<{ installationName: z.ZodString; repositories: z.ZodOptional>; }, z.core.$strict>; /** * Which releases a `github.releases` source starts runs for. * * - `installationName`: the GitHub App installation, as named on the hub, * whose repositories it watches. * - `repositories`: `owner/repo` names, such as `acme/api`, in any case; * leaving it out watches them all. * * @group Factory and workflows */ type GitHubReleasesParams = z.input; /** * The inputs a `github.releases` source hands each run it starts. * * @group Factory and workflows */ type GitHubReleaseInputs = RepositoryRef & { /** The release's tag, such as `v1.2.0`. */ tag: string; }; /** * Event-trigger sources on GitHub. * * @group Factory and workflows */ declare const github: { /** * Start a run for each push to a branch, with {@link GitHubPushInputs} as * its inputs. Each push starts at most one run, ever. Tag pushes and * branch deletions start none. A push the factory's own GitHub App made, * such as merging a person's pull request, starts runs like any other. * * @remarks * The GitHub App must subscribe to the **Push** event. * * @example * ```ts * import { github } from "@jigs-ai/jigs"; * * const source = github.pushes({ * installationName: "github-acme", * repositories: ["acme/api"], * branches: ["main"], * }); * ``` */ readonly pushes: (params: GitHubPushesParams) => SourceDescriptor; /** * Start a run for each pull request, with its {@link PullRequestRef} as * the inputs. A pull request starts at most one run, ever: the first time * any of its events shows it open, not a draft and matching the filters, * such as when it is opened, labeled or marked ready for review. A pull * request reopened after its run ended starts no new one; rerun it with * `jigs run`. * * @remarks * Events the factory's own GitHub App caused start no run, so a pull * request the App opens starts one only once a person acts on it, such as * by adding a label the trigger filters on. * * @example * ```ts * import { github } from "@jigs-ai/jigs"; * * const source = github.pullRequests({ * installationName: "github-acme", * repositories: ["acme/api"], * authors: ["dependabot[bot]"], * }); * ``` */ readonly pullRequests: (params: GitHubPullRequestsParams) => SourceDescriptor; /** * Start a run for each issue, with {@link GitHubIssueInputs} as its inputs. * An issue starts at most one run, ever: the first time any of its events * shows it open and matching the filters, such as when it is opened or * labeled. An issue reopened after its run ended starts no new one; rerun * it with `jigs run`. * * @remarks * The GitHub App must subscribe to the **Issues** event. Events the * factory's own GitHub App caused start no run, so an issue the App opens * starts one only once a person acts on it, such as by adding a label the * trigger filters on. * * @example * ```ts * import { github } from "@jigs-ai/jigs"; * * const source = github.issues({ * installationName: "github-acme", * repositories: ["acme/api"], * labels: ["agent"], * }); * ``` */ readonly issues: (params: GitHubIssuesParams) => SourceDescriptor; /** * Start a run for each published release, with {@link GitHubReleaseInputs} * as its inputs. A release starts at most one run, ever, once it is * published and not a prerelease: a prerelease starts its run when it * becomes a release. Drafts start none. * * @remarks * The GitHub App must subscribe to the **Release** event and needs * **Contents: read**. * * @example * ```ts * import { github } from "@jigs-ai/jigs"; * * const source = github.releases({ * installationName: "github-acme", * repositories: ["acme/api"], * }); * ``` */ readonly releases: (params: GitHubReleasesParams) => SourceDescriptor; }; //#endregion //#region src/workflow/human/questions.d.ts /** * A value that can be serialized as JSON and embedded in a prompt or comment. * * @group Human input */ type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue; }; /** * Validates an answer choice with a nonempty label and an optional recommendation marker. * * @group Human input */ declare const haltOptionSchema: z.ZodObject<{ label: z.ZodString; recommended: z.ZodOptional; }, z.core.$strict>; /** * Validates a question with nonempty text, optional context and optional suggested answers. * * @group Human input */ declare const haltQuestionSchema: z.ZodObject<{ question: z.ZodString; context: z.ZodOptional; options: z.ZodOptional; }, z.core.$strict>>>; }, z.core.$strict>; /** * One answer choice for a question shown to a human. * * @group Human input */ type HaltOption = z.infer; /** * A question shown to a human while a run waits for their reply. * * @group Human input */ type HaltQuestion = z.infer; //#endregion //#region src/workflow/interpolate.d.ts /** * Replace named `{{ placeholders }}` once, leaving unknown names unchanged. * * @group Errors and utilities */ declare function interpolate(template: string, values: Record): string; //#endregion //#region src/workflow/linear/agent-session.d.ts /** * What the factory's app posts into a Linear agent session. A `thought` or an `action` shows * progress; an `elicitation` asks the person for input; a `response` or an `error` ends the * app's turn, and Linear waits for the person. * * @group Linear agent sessions */ type LinearAgentActivityContent = { type: "thought"; body: string; } | { type: "action"; action: string; parameter: string; result?: string; } | { type: "elicitation"; body: string; } | { type: "response"; body: string; } | { type: "error"; body: string; }; /** * One message a person sent into a Linear agent session, oldest first when listed. * * @remarks * `signal` is null for a plain reply and `"stop"` when the person pressed stop; Linear also names * `continue`, `auth` and `select`. `sourceCommentId` is the comment the reply was written as, and * is null for a stop. * * @group Linear agent sessions */ type LinearAgentPrompt = { id: string; createdAt: string; body: string; signal: string | null; author: { id: string; name: string; }; sourceCommentId: string | null; }; /** * One turn of a conversation in a Linear agent session: the harness and worktree it runs in, the * mention that opened the session until a turn takes it, and `consumed`, the ids of the messages * earlier turns took. The turn takes every newer reply in the session. */ type LinearAgentTurnRequest = { installationName: string; sessionId: string; harness: Harness; cwd: string; instructions?: string; opening?: ConversationMessage; consumed: string[]; }; //#endregion //#region src/workflow/linear/source.d.ts declare const linearAgentSessionsParamsSchema: z.ZodObject<{ installationName: z.ZodString; teams: z.ZodOptional>; projects: z.ZodOptional>; labels: z.ZodOptional>; creators: z.ZodOptional>; }, z.core.$strict>; /** * Which Linear agent sessions a `linear.delegations` or `linear.mentions` * source starts runs for. Each list matches any of its values; leaving one out * does not filter on it. * * - `installationName`: the Linear installation, as named on the hub, whose * sessions it watches. * - `teams`: team keys, such as `ENG`, or team ids. * - `projects`: project ids, or the id at the end of a project's URL. * - `labels`: label names, as Linear shows them. * - `creators`: emails of the people who delegated the issue or mentioned the * app, in any case. * * @group Factory and workflows */ type LinearAgentSessionsParams = z.input; /** * The inputs a `linear.delegations` source hands each run it starts. * * @group Factory and workflows */ interface LinearDelegationInputs { /** The Linear agent session's id. */ session: string; /** The Linear installation, as named on the hub, the session is in. */ installationName: string; issue: { id: string; identifier: string; title: string; url: string; }; /** * Linear's formatted context for the session: the issue, its description and the comments * around it, or null if Linear sent none. */ promptContext: string | null; /** The person who delegated the issue, or mentioned the app. */ creator: { id: string; name: string; email: string; }; } /** * The inputs a `linear.mentions` source hands each run it starts. * * @group Factory and workflows */ interface LinearMentionInputs extends LinearDelegationInputs { /** The body of the comment that mentioned the app. */ comment: string; } /** * Event-trigger sources on Linear. * * @remarks * Delegating an issue to the factory's Linear app, or mentioning the app in a * comment, opens a Linear agent session. Each session starts at most one run * per trigger, ever. The hub posts the session's first reply, so Linear shows * the app at work while the run starts. That reply appears even when no * trigger matches, so make the filters match what the app is for. Every * factory assigned the app hears every session, and each matching trigger * starts its own run. Sessions not on an issue, and sessions the app opened * itself, start no run. * * @group Factory and workflows */ declare const linear: { /** * Start a run whenever someone delegates an issue to the factory's Linear * app, with {@link LinearDelegationInputs} as its inputs. * * @example * ```ts * import { linear } from "@jigs-ai/jigs"; * * const source = linear.delegations({ installationName: "acme", teams: ["ENG"] }); * ``` */ readonly delegations: (params: LinearAgentSessionsParams) => SourceDescriptor; /** * Start a run whenever someone mentions the factory's Linear app in a * comment on an issue, with {@link LinearMentionInputs} as its inputs. * * @example * ```ts * import { linear } from "@jigs-ai/jigs"; * * const source = linear.mentions({ installationName: "acme", labels: ["agent"] }); * ``` */ readonly mentions: (params: LinearAgentSessionsParams) => SourceDescriptor; }; //#endregion //#region src/workflow/linear/agent-conversation.d.ts type SessionRef = { installationName: string; sessionId: string; }; /** * The durable steps a Linear agent conversation runs. * * @group Factory plumbing */ interface LinearAgentConversationSteps { executeLinearAgentTurn(request: LinearAgentTurnRequest): Promise; listLinearAgentSessionPrompts(session: SessionRef): Promise; postLinearAgentActivity(request: SessionRef & { content: LinearAgentActivityContent; once?: string; }): Promise; setLinearAgentSessionUrls(request: SessionRef & { urls: Array<{ label: string; url: string; }>; }): Promise; } /** * How a Linear agent conversation runs: the Claude harness and the worktree it works in. * * @remarks * `instructions` lead the first message Claude reads, which carries Linear's context for the * session when Linear sends one. The conversation ends once no one has replied for `idleFor`, a duration such * as `"30m"` or milliseconds; four hours by default. * * @group Linear agent sessions */ interface LinearAgentConversationOptions { harness: Harness; cwd: string; instructions?: string; idleFor?: `${number}${"s" | "m" | "h" | "d"}` | number; } /** * How a Linear agent conversation ended, and how many turns it ran. * * @group Linear agent sessions */ type LinearAgentConversationResult = { outcome: "idle" | "stopped"; turns: number; } | { outcome: "failed"; turns: number; error: string; }; /** * Hold a conversation with Claude in the Linear agent session that started this run, until no * one replies for `idleFor`, someone presses stop, or a turn fails. * * @remarks * Claude answers the delegation or mention that opened the session, then each reply, in the same session and * worktree. A reply sent while Claude works joins its turn. Linear shows a live status line while * Claude works, each answer as a response, a failure as an error, and a link to the run. A stop * ends the conversation with "Stopped.". Provision the worktree before calling this: the workflow * keeps the worktree, the issue and anything it delivers, and runs on once this returns. Each * matching trigger starts one run for the session. The first to call this holds the session for * the whole conversation; any other run that calls it throws `ClaimConflictError`. * * @group Linear agent sessions */ declare function linearAgentConversation(session: LinearDelegationInputs | LinearMentionInputs, options: LinearAgentConversationOptions, steps: LinearAgentConversationSteps): Promise; //#endregion //#region src/workflow/linear/claim.d.ts /** * A ticket-claim failure that identifies the run already holding the ticket. * * @group Errors and utilities */ declare class ClaimConflictError extends Error { readonly resource: string; readonly owningRunId: string; constructor(resource: string, owningRunId: string); } /** * A ticket held exclusively by the current workflow run, with the Linear agent session the run * talks to people in. * * @group Linear tickets */ interface TicketClaim { /** The Linear installation, as named on the hub, the ticket is reached through. */ installationName: string; issueId: string; identifier: string; token: string; /** The Linear agent session this run asks its questions and posts its notes in. */ sessionId: string; /** The messages in the session this run has already read. A later question skips them. */ consumedPromptIds: string[]; } //#endregion //#region src/workflow/linear/halt-for-human.d.ts /** * What the question says, in the words a stranger to the repo reads. * `headline` is one plain sentence naming what paused and why, `where` * names the routine it paused in so the footer can say so, `about` restates the * ticket itself, `notes` are plain bullet lines, and `onReply` decides what * the question asks the human to do: choose between the questions ("continue") * or repair something and let the step run again ("retry"). `mention` adds * people, by Linear email, to the operator (or the creator) and the assignee * the question already mentions; an email no Linear user has is skipped. * * @group Human input */ type Halt = { headline: string; where: string; about?: string | undefined; questions?: HaltQuestion[] | undefined; notes?: string[] | undefined; onReply: "continue" | "retry"; mention?: string[] | undefined; }; /** * What people answered in the run's Linear agent session. * * @remarks * Every message sent since the run last read the session counts, including any sent before the * question. `body` holds every message oldest first, each after its author's name; `author` and * `createdAt` are the newest message's. * * @group Human input */ interface HumanReply { body: string; author: { id: string; name: string; }; createdAt: string; } /** Durable step contract for asking a question in the run's Linear agent session. */ type PostTicketHumanInputRequest = (request: { installationName: string; issueId: string; sessionId: string; halt: Halt; }) => Promise; /** Durable operations required to ask and resume a human halt. */ type HaltForHumanDependencies = Pick & { postTicketHumanInputRequest: PostTicketHumanInputRequest; }; /** {@link haltForHuman} with its steps already bound, as a workflow calls it. */ type HaltForHumanFn = (claim: TicketClaim, halt: Halt) => Promise; //#endregion //#region src/workflow/linear/review.d.ts /** * Structured verdict returned by the agent that reviews a ticket before work starts. * * @group Linear tickets */ declare const ticketReviewVerdictSchema: z.ZodObject<{ verdict: z.ZodEnum<{ "needs-human": "needs-human"; proceed: "proceed"; }>; brief: z.ZodString; about: z.ZodString; questions: z.ZodArray; options: z.ZodOptional; }, z.core.$strict>>>; }, z.core.$strict>>; assumptions: z.ZodArray; }, z.core.$strict>; /** * A note a ticket run posts in its Linear agent session that asks for nothing * and suspends nothing. It carries its own words, the way a halt does, so the * renderer owns the layout and every caller owns what it says. * * @remarks * Linear marks a session stale after about 30 minutes with no activity, and a * stale session hides its Stop button. Before a long quiet wait on people, such * as a pull request waiting for review, post a note with `run: "waiting"`. * * @group Linear tickets */ type TicketNote = { /** One plain sentence naming what jigs is about to do, or has stopped doing. */ headline: string; /** The bullet lines under it. */ notes: string[]; /** What the reader should do with it. */ closing: string; /** * More people to mention, by Linear email, beyond the operator (or the * creator) and the assignee. Each person is named once; an email no Linear * user has is skipped with a warning. */ mention?: string[] | undefined; /** * What the run does after this note; omitted, it keeps working. * * @remarks * `"ended"` is the run's final message, success or not; Linear shows the * session as finished. Set it on every way out of the run. `"waiting"` shows the session as awaiting input, which never goes * stale but shows no Stop button. The run does not read replies to a waiting * note, so say in it where people act and how to stop the run. */ run?: "waiting" | "ended" | undefined; }; /** * Posting a note in the run's Linear agent session. Declared here rather than * written as `typeof postTicketNote` for the same reason the halt's step * contract is: the routine that calls the step owns the contract. */ type PostTicketNote = (request: { installationName: string; issueId: string; sessionId: string; note: TicketNote; }) => Promise; //#endregion //#region src/providers/http.d.ts /** Where a provider call's credential comes from. */ interface ProviderAuth { bearer(): Promise; /** Forget `stale` if it is still cached, so the next `bearer()` asks the hub for a fresh one. */ invalidate(stale: string): void; } interface ProviderApiErrorInit { provider: Provider; status: number; /** The call, as `METHOD /path` or a method name, without its query. */ request: string; body: string; code?: string; /** Replaces the body in the message. */ detail?: string; /** Replaces the whole message. */ message?: string; } /** * A provider answered a call with a failure: an error status, or a refusal in its body. * * @group Errors */ declare class ProviderApiError extends JigsError { readonly provider: Provider; readonly status: number; readonly code?: string; readonly body: string; constructor(init: ProviderApiErrorInit); } //#endregion //#region src/providers/linear-auth.d.ts /** The user Linear made for the factory's app in a workspace: who jigs is there. */ interface LinearAppUser { id: string; name: string; } interface LinearAuth extends ProviderAuth { /** The bearer token, asked of the hub again when less than `minLifetimeMs` of it is left. */ bearer(minLifetimeMs?: number): Promise; /** The app's own user in the workspace. */ user(): Promise; } //#endregion //#region src/providers/linear.d.ts interface LinearUser { id: string; name: string; } /** A Linear user with their profile link, which mentions them when written into Linear text. */ interface LinearProfile extends LinearUser { url: string; } interface LinearComment { id: string; body: string; createdAt: string; user: LinearUser | null; } interface LinearClientDeps { /** The Linear installation, as named on the hub, the client acts through. */ installationName: string; auth?: LinearAuth; fetch?: typeof fetch; sleep?: (ms: number) => Promise; /** The factory it acts for. Defaults to the process's own, resolved on each call. */ context?: FactoryContext; } interface LinearIssueRef { id: string; identifier: string; } interface LinearIssueState { id: string; name: string; type: string; position: number; } interface LinearIssueFiling { project: { id: string; slugId: string; } | null; labels: string[]; } interface LinearIssueStates { state: { id: string; name: string; }; team: { name: string; states: { nodes: LinearIssueState[]; }; }; } interface RawIssueRef { id: string; identifier: string; title: string; } interface RawIssueSnapshot { id: string; identifier: string; title: string; description: string | null; url: string; branchName: string; state: { name: string; }; labels: { nodes: Array<{ name: string; }>; }; comments: { nodes: LinearComment[]; }; attachments: { nodes: Array<{ title: string; url: string; }>; }; children: { nodes: RawIssueRef[]; }; relations: { nodes: Array<{ type: string; relatedIssue: RawIssueRef; }>; }; inverseRelations: { nodes: Array<{ type: string; issue: RawIssueRef; }>; }; } /** * Where a Linear ticket lives: a team (key such as `ENG`, name or id), a project (id or the slug * its URL ends in), or both. Without a team, the project's first team. * * @group Create and update */ type IssuePlace = { team: string; project?: string; } | { team?: string; project: string; }; /** * A new Linear ticket. `status` is a workflow status name such as `Triage`; without one, Linear * picks the team's default. `labels` are names from the team or the whole workspace. * * @group Create and update */ type CreateIssueInput = IssuePlace & { status?: string; labels?: string[]; title: string; description: string; }; /** * A search for the newest ticket whose title starts with `titlePrefix`. * * @group Resolve and read */ type FindIssueInput = IssuePlace & { titlePrefix: string; }; /** * A matching Linear ticket returned by a project title search. * * @group Resolve and read */ interface LinearIssueMatch { id: string; identifier: string; url: string; title: string; description: string; state: string; } declare function createLinearClient(deps: LinearClientDeps): { graphql: (query: string, variables: Record) => Promise; appUser: () => Promise; findUserByEmail: (email: string) => Promise; fetchIssueFiling: (issueId: string) => Promise; fetchIssueStates: (issueId: string) => Promise; updateIssueState: (issueId: string, stateId: string) => Promise; resolveIssueRef: (ticket: string) => Promise; getIssueParticipants: (issueId: string) => Promise<{ creator: LinearProfile | null; assignee: LinearProfile | null; }>; fetchIssueSnapshot: (issueId: string) => Promise; createComment: (issueId: string, body: string, id?: string) => Promise<{ id: string; createdAt: string; }>; createIssue: (input: CreateIssueInput) => Promise<{ id: string; identifier: string; url: string; }>; findIssue: (input: FindIssueInput) => Promise; }; type LinearClient = ReturnType; //#endregion //#region src/workflow/linear/snapshot.d.ts /** * A compact reference to a related Linear ticket. * * @group Linear tickets */ type TicketRef = { id: string; identifier: string; title: string; }; /** * A Linear ticket comment captured in a workflow snapshot. * * @group Linear tickets */ type TicketComment = { id: string; body: string; createdAt: string; author: string | null; }; /** * A named external link attached to a Linear ticket. * * @group Linear tickets */ type TicketLink = { title: string; url: string; }; /** * The fixed ticket state shared by every step in one workflow activation. * * @group Linear tickets */ type TicketSnapshot = { fetchedAt: string; id: string; identifier: string; title: string; description: string; url: string; branchName: string; state: string; labels: string[]; comments: TicketComment[]; blockedBy: TicketRef[]; blocks: TicketRef[]; links: TicketLink[]; subIssues: TicketRef[]; }; /** * Render a ticket snapshot as Markdown for an agent prompt. * * @group Linear tickets */ declare function renderTicketSnapshot(snapshot: TicketSnapshot): string; //#endregion //#region src/workflow/linear/ticket-review.prompt.d.ts /** * The rendered ticket supplied to a ticket-review prompt. * * @group Linear tickets */ type TicketReviewPromptInput = { ticket: string; }; /** * Renders instructions for an agent to turn a ticket into an actionable handoff. * * @group Linear tickets */ type TicketReviewPrompt = (input: TicketReviewPromptInput) => string; /** * The default prompt for reviewing a Linear ticket before implementation begins. * * @group Linear tickets */ declare const ticketReviewPrompt: TicketReviewPrompt; //#endregion //#region src/workflow/pagerduty/snapshot.d.ts /** * A PagerDuty object an incident points at, such as its service or an assignee. * * @group PagerDuty incidents */ type IncidentRef = { id: string; name: string; url: string | null; }; /** * The incident as one workflow activation read it. * * @group PagerDuty incidents */ type IncidentSnapshot = { fetchedAt: string; id: string; number: number; title: string; status: "triggered" | "acknowledged" | "resolved"; urgency: "high" | "low"; createdAt: string; url: string; service: IncidentRef; assignees: IncidentRef[]; escalationPolicy: IncidentRef; }; //#endregion //#region src/workflow/pagerduty/source.d.ts declare const pagerDutyIncidentsParamsSchema: z.ZodObject<{ installationName: z.ZodString; services: z.ZodOptional>; teams: z.ZodOptional>; urgencies: z.ZodOptional>>; }, z.core.$strict>; /** * Which incidents a `pagerduty.incidents` source starts runs for. Each list * matches any of its values; leaving one out does not filter on it. * * - `installationName`: the PagerDuty installation, as named on the hub, * whose incidents it watches. * - `services`: PagerDuty service IDs, such as `P48FPG2`. * - `teams`: PagerDuty team IDs. * - `urgencies`: `high`, `low` or both. * * @group Factory and workflows */ type PagerDutyIncidentsParams = z.input; /** * Event-trigger sources on PagerDuty. * * @group Factory and workflows */ declare const pagerduty: { /** * Watch for new incidents. Every new incident starts at most one run, ever, * with `{ installationName, incident: "" }` as its inputs, even one acknowledged or * resolved before the service saw it; the workflow can check the status and * skip one that is already handled. The run starts as soon as the hub * passes on PagerDuty's `incident.triggered` event. * * @example * ```ts * import { pagerduty } from "@jigs-ai/jigs"; * * const source = pagerduty.incidents({ * installationName: "acme", * services: ["P48FPG2"], * urgencies: ["high"], * }); * ``` */ readonly incidents: (params: PagerDutyIncidentsParams) => SourceDescriptor; }; //#endregion //#region src/workflow/pull-requests/marker.d.ts /** The work recorded by a hidden marker in a pull request comment. */ type MarkerKind = "reply" | "status"; /** * Label a status note as a merge refusal, CI failure or temporary merge refusal. * Distinct reasons keep notes for the same commit independent. They do not * change merge readiness or schedule more work. * * @group Pull requests */ type StatusReason = "merge" | "ci" | "merge-retry"; /** * Hidden progress metadata stored in a pull request comment. * * @group Pull requests */ interface PullRequestMarker { /** * Names this workflow's work on the pull request. Keep it stable across * replacement runs to recognize earlier notes and replies. */ scope: string; /** The run that wrote it. Provenance for a reader; never matched on. */ run: string; /** * `reply` answers the thing named by `source`, and `status` is a note about a * commit, such as a stand-down * after a refused merge, a CI failure jigs could not repair, or a merge * refused for a state that will pass. */ kind: MarkerKind; /** Required on a `status` marker, meaningless on any other. */ reason?: StatusReason; /** What this answers: a comment as `id@updatedAt`, or a commit sha. */ source?: string; } /** * Every marker in one comment body, in the order they appear. * * @group Pull requests */ declare function parseMarkers(body: string): PullRequestMarker[]; //#endregion //#region src/workflow/pull-requests/answers.d.ts /** Inputs for posting one commit-scoped pull request status note. */ interface PostPullRequestNoteOptions { /** Factory-owned step used to read what the pull request already records. */ fetchPullRequestState: FetchPrState; /** Factory-owned step used to post on the pull request conversation. */ commentOnPullRequest: typeof commentOnPullRequest; /** The pull request receiving the note. */ pr: PullRequestRef; /** The continuation identity that owns the note. */ scope: string; /** The commit the note is about: a red head, or a head it could not merge. */ headSha: string; /** Labels the update so CI and merge notes for the same commit stay independent. */ reason: StatusReason; /** The Markdown note body. */ body: string; } /** * Post a status note once per scope, commit and reason. * * @remarks * Reads current pull request comments and skips a note whose marker is already present. * A posting failure is logged and returns without throwing. The workflow decides whether * and when to try again; the note does not change merge readiness or schedule another action. */ declare function postPullRequestNote(options: PostPullRequestNoteOptions): Promise; /** * Render failed checks as a Markdown list for a pull request note. * * @group Pull requests */ declare function renderChecks(failing: CheckRun[]): string; //#endregion //#region src/workflow/pull-requests/writer.d.ts /** * The scope a caller gets when it names none: this workflow's function name * and the subject it was given: a ticket key or the pull request itself. * Pass an explicit scope to continue another workflow's work, or to review a * pull request independently of the run delivering it. * * @group Pull requests */ declare function defaultPullRequestScope(subject: string): string; //#endregion //#region src/workflow/slack/snapshot.d.ts /** * Someone who posted in Slack. * * @remarks * `id` is the Slack user ID, or the bot ID for an integration that posts * without a user. `email` is missing for bots. `isOwnBot` marks the factory's * own bot, which is what posts every message jigs sends. * * @group Slack messages */ interface SlackAuthor { id: string; name: string; email?: string | undefined; bot: boolean; isOwnBot: boolean; } /** * One Slack message: its timestamp, which is also its ID in the channel, its * `mrkdwn` text and who wrote it. * * @group Slack messages */ interface SlackPost { ts: string; text: string; author: SlackAuthor; } /** * A Slack message and its thread, as `fetchSlackMessage` read them, or `gone` * when the message was deleted. * * @remarks * `replies` are the thread's replies, oldest first, without the message * itself. * * @group Slack messages */ type SlackMessageSnapshot = { gone: true; channel: string; ts: string; } | (SlackPost & { gone: false; channel: string; permalink: string; replies: SlackPost[]; }); //#endregion //#region src/workflow/slack/sources.d.ts /** * Event-trigger sources for Slack, one per trigger in `jigs.config.ts`. * * @remarks * Both read top-level messages in the listed channels of one Slack * installation, named as on the hub, whose bot must be a member of them, and * start one run per message with the inputs `{ installationName, channel, ts }`. Posts from people, other bots and apps count, including * posts with files. The factory's own posts never count, and neither do * thread replies, edits, deletes, joins or other channel events. Direct * messages are never read. Channels are listed by ID, such as `C0123ABCD`, * not by name. * * @example * Start a run for every message that mentions the bot in one channel. * ```ts * import { slack } from "@jigs-ai/jigs"; * * const triggers = { * "answer-questions": { * active: process.env.ANSWER_QUESTIONS_ACTIVE === "true", * workflow: "answer", * source: slack.mentions({ installationName: "acme", channels: ["C0123ABCD"] }), * }, * }; * ``` * * @group Factory and workflows */ declare const slack: { /** Every top-level message in the channels. */ messages: ({ installationName, channels }: { installationName: string; channels: string[]; }) => SourceDescriptor; /** Only the top-level messages that mention the factory's bot. */ mentions: ({ installationName, channels }: { installationName: string; channels: string[]; }) => SourceDescriptor; }; //#endregion //#region src/steps/slack/fetch-message.d.ts /** * Read a Slack message, its permalink and its thread's replies, with each * author's name and email, through the Slack installation `installationName` names. * * @remarks * `ts` must be a top-level message. A reply's ts fails the step without a * retry, naming the top-level message's ts. * * @group Read */ declare function fetchSlackMessage({ installationName, channel, ts }: { installationName: string; channel: string; ts: string; }): Promise; //#endregion //#region src/workflow/slack/wait-for-reply.d.ts /** * The durable Slack read a thread-reply wait needs. * * @group Factory plumbing */ interface SlackReplySteps { fetchSlackMessage: typeof fetchSlackMessage; } /** * The thread a wait reads, named by the ts of its top-level message (never a * reply's). `lastRead` is the ts of the newest post the workflow has read, * never its own question; only human replies after it count. `until`, an * ISO 8601 timestamp, is when to stop waiting. * * @group Slack messages */ interface SlackQuestion { /** The Slack installation, as named on the hub, the thread is read through; only its events wake the wait. */ installationName: string; channel: string; threadTs: string; lastRead: string; until?: string; } /** * How `waitForSlackReply` ended: `replied` with the new human replies (oldest first, never * empty), `timed-out` at `until`, or `gone` when the thread's top-level message was deleted. * * @group Slack messages */ type SlackReplyResult = { outcome: "replied"; replies: SlackPost[]; } | { outcome: "timed-out"; } | { outcome: "gone"; }; /** * Wait for a human to reply in a Slack thread after `lastRead`, and return * every such reply. Ends `timed-out` once `until` passes, and `gone` when the * thread's top-level message is deleted. * * @remarks * Without `until`, waits until a reply or `jigs cancel`. With it, the thread is * read at least once, so a reply already there wins even when `until` has * passed; after that the wait ends `timed-out` at `until`, and a later * reply wakes nothing. A reply heard through the hub and `jigs poke` each make * it read the thread again. Replies from bots, including the factory's * own, never count. `threadTs` must be the thread's top-level message: a * reply's ts fails the wait, naming the top-level message's ts. A reply * already in the thread returns at once, and may not answer the question the * workflow just asked. When a human reply is already in the thread, every run * waiting on it returns them; a second run that has to park while another waits * on the thread fails with the Workflow SDK's `HookConflictError`. * * @group Slack messages */ declare function waitForSlackReply(question: SlackQuestion, steps: SlackReplySteps): Promise; //#endregion //#region src/workflow/unreachable.d.ts /** * Fail an exhaustive branch if an unexpected value reaches it at runtime. * * @group Errors and utilities */ declare function unreachable(value: never): never; //#endregion export { LinearDelegationInputs as $, choice as $n, SourceDescriptor as $r, replyToPullRequestReviewThread as $t, CreateIssueInput as A, Provider as An, PiHarness as Ar, BuildAndReviewOptions as At, ticketReviewVerdictSchema as B, describeHarness as Bn, harnesses as Br, ReviewFacts as Bt, TicketReviewPromptInput as C, LinearMcpOptions as Cn, McpStdioServerConfig as Cr, FollowDelivery as Ct, TicketRef as D, ExecuteAgentStep as Dn, OpenaiCodexSource as Dr, DescribeDelivery as Dt, TicketLink as E, githubMcp as En, ModelSource as Er, NeedsHuman as Et, LinearIssueRef as F, ModelRequest as Fn, PiOpenaiCompatibleHarness as Fr, BuildFacts as Ft, PostTicketHumanInputRequest as G, JevAnswer as Gn, BindingDefinition as Gr, RunAgentFn as Gt, HaltForHumanDependencies as H, AskJevOptions as Hn, FactoryContext as Hr, AgentSession as Ht, LinearProfile as I, RunAgentOptions as In, PiOpenaiCompatibleOptions as Ir, Delivery as It, LinearAgentConversationOptions as J, JevQuestions as Jn, FactoryDefinition as Jr, OpenedPullRequest as Jt, ClaimConflictError as K, JevAnswers as Kn, EventTrigger as Kr, bindAgentSession as Kt, ProviderApiError as L, AgentResult as Ln, PiOtherHarness as Lr, DeliveryPrompts as Lt, IssuePlace as M, AgentRequest as Mn, PiMcpHttpServerConfig as Mr, BuildDelivery as Mt, LinearClient as N, AskAgentOptions as Nn, PiMcpServerConfig as Nr, BuildResult as Nt, TicketSnapshot as O, JitCheckError as On, OpenaiCompatibleSource as Or, DescribeOptions as Ot, LinearIssueMatch as P, AskModelOptions as Pn, PiMcpStdioServerConfig as Pr, BuildStopped as Pt, LinearAgentSessionsParams as Q, YesNoQuestion as Qn, Schedule as Qr, mergePullRequest as Qt, PostTicketNote as R, AgentSessionRef as Rn, ToolFree as Rr, DeliverySteps as Rt, TicketReviewPrompt as S, pagerdutyMcp as Sn, McpServerConfig as Sr, PublishOptions as St, TicketComment as T, GithubMcpOptions as Tn, ModelKind as Tr, FollowResult as Tt, HaltForHumanFn as U, ChoiceQuestion as Un, installationNameSchema as Ur, AgentSessionOptions as Ut, Halt as V, OutputJsonSchema as Vn, models as Vr, UnpublishedWork as Vt, HumanReply as W, ExecuteJevStep as Wn, AgentsDefinition as Wr, AgentSessionTurn as Wt, LinearAgentConversationSteps as X, JevState as Xn, HarnessesDefinition as Xr, createPullRequest as Xt, LinearAgentConversationResult as Y, JevResult as Yn, GitHubDefinition as Yr, commentOnPullRequest as Yt, linearAgentConversation as Z, ScoreQuestion as Zn, LinearDefinition as Zr, markPullRequestReady as Zt, parseMarkers as _, MergeConsent as _n, HarnessForOptions as _r, GitHubReleasesParams as _t, waitForSlackReply as a, ticketInputSchema as ai, PullRequestComment as an, AskableHarness as ar, interpolate as at, IncidentRef as b, ReviewRound as bn, JsonOnly as br, builderWakeFacts as bt, SlackAuthor as c, ReviewComment as cn, ClaudeBedrockCredential as cr, JsonValue as ct, defaultPullRequestScope as d, FetchPrState as dn, ClaudeHarnessSettings as dr, GitHubIssueInputs as dt, TicketWorkflowInputs as ei, reviewPullRequest as en, score as er, LinearMentionInputs as et, PostPullRequestNoteOptions as f, MergeOptions as fn, ClaudePolicyKey as fr, GitHubIssuesParams as ft, StatusReason as g, ApprovalCoverage as gn, Harness as gr, GitHubReleaseInputs as gt, PullRequestMarker as h, RepositoryRef as hn, CodexPolicyKey as hr, GitHubPushesParams as ht, SlackReplySteps as i, defineWorkflow as ii, CheckRun as in, AgentInstallation as ir, LinearAgentTurnRequest as it, FindIssueInput as j, TurnObserver as jn, PiHarnessOptions as jr, BuildApproved as jt, renderTicketSnapshot as k, unwrapAgentStep as kn, OpenrouterSource as kr, Described as kt, SlackMessageSnapshot as l, ReviewThread as ln, ClaudeCredential as lr, haltOptionSchema as lt, renderChecks as m, PullRequestRef as mn, CodexHarnessSettings as mr, GitHubPushInputs as mt, SlackQuestion as n, WorkflowInputs as ni, isPullRequestMergeReady as nn, TurnRequest as nr, LinearAgentActivityContent as nt, fetchSlackMessage as o, PullRequestReview as on, AskableModelSource as or, HaltOption as ot, postPullRequestNote as p, PullRequestReadOptions as pn, CodexHarness as pr, GitHubPullRequestsParams as pt, TicketClaim as q, JevQuestion as qn, Factory as qr, MergeOutcome as qt, SlackReplyResult as r, defineFactory as ri, ApprovalState as rn, TurnStepResult as rr, LinearAgentPrompt as rt, slack as s, PullRequestSnapshot as sn, ClaudeApiKeyCredential as sr, HaltQuestion as st, unreachable as t, WorkflowDefinition as ti, blockedMergeNote as tn, yesNo as tr, linear as tt, SlackPost as u, pullRequestSnapshotKey as un, ClaudeHarness as ur, haltQuestionSchema as ut, PagerDutyIncidentsParams as v, FindingResponse as vn, HarnessKind as vr, github as vt, ticketReviewPrompt as w, linearMcp as wn, McpToolProbe as wr, FollowOptions as wt, IncidentSnapshot as x, PagerdutyMcpOptions as xn, McpHttpServerConfig as xr, PublishDelivery as xt, pagerduty as y, ReviewFinding as yn, HarnessSkills as yr, JigsError as yt, TicketNote as z, ModelResult as zn, harnessKinds as zr, MaintainFacts as zt };