@github/copilot-sdk 1.0.15-preview.3 → 1.0.15-preview.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/types.d.ts CHANGED
@@ -4,14 +4,16 @@
4
4
  import type { Canvas } from "./canvas.js";
5
5
  import type { SessionFsProvider } from "./sessionFsProvider.js";
6
6
  import type { CopilotRequestHandler } from "./copilotRequestHandler.js";
7
+ import type { InstallationConfirmationHandler } from "./installationConfirmation.js";
8
+ export type { InstallationConfirmationHandler } from "./installationConfirmation.js";
7
9
  import type { AttachmentExtensionContext as GeneratedExtensionContextAttachment, AutoTier, PermissionRequest as GeneratedPermissionRequest, PermissionRequestedData as GeneratedPermissionRequestedData, PermissionRequestedEvent as GeneratedPermissionRequestedEvent, ReasoningSummary, SessionLimitsConfig, SessionEvent as GeneratedSessionEvent } from "./generated/session-events.js";
8
10
  import type { CopilotSession } from "./session.js";
9
- import type { FactoryJsonSchema, JsonValue } from "./factory.js";
11
+ import type { JsonValue } from "./workflow.js";
10
12
  import type { ExtensionLaunchProviderHandler as GeneratedExtensionLaunchProvider, GitHubTokenAcquireRequest, GitHubTokenAcquireResult, GitHubTelemetryNotification, ModelBillingTokenPrices, DiagnosticsConfiguration, OpenCanvasInstance, RemoteSessionMode, CurrentToolMetadata } from "./generated/rpc.js";
11
13
  import type { ToolSet } from "./toolSet.js";
12
14
  export type { RemoteSessionMode } from "./generated/rpc.js";
13
15
  export type { CurrentToolMetadata } from "./generated/rpc.js";
14
- export type { ConnectorAccountRequest, ConnectorAvailability, ConnectorCapabilities, ConnectorCatalogEntry, ConnectorCatalogResult, ConnectorCatalogStatus, ConnectorConnectRequest, ConnectorConnectResult, ConnectorContinueRequest, ConnectorDisconnectResult, ConnectorMcpStatus, ConnectorReconcileRequest, ConnectorRuntimeStatus, ConnectorStatus, ExtensionLaunchProfile, ExtensionLaunchProviderResolveRequest, ExtensionLaunchProviderResolveResult, GitHubTokenAcquireReason, GitHubTokenAcquireResult, GitHubTelemetryNotification, GitHubTelemetryEvent, GitHubTelemetryClientInfo, } from "./generated/rpc.js";
16
+ export type { ConnectorAccountRequest, ConnectorAvailability, ConnectorCapabilities, ConnectorCatalogEntry, ConnectorCatalogResult, ConnectorCatalogStatus, ConnectorConnectRequest, ConnectorConnectResult, ConnectorContinueRequest, ConnectorDisconnectResult, ConnectorMcpStatus, ConnectorReconcileRequest, ConnectorRuntimeStatus, ConnectorStatus, ExtensionLaunchProfile, ExtensionLaunchProviderResolveRequest, ExtensionLaunchProviderResolveResult, GitHubTokenAcquireReason, GitHubTokenAcquireResult, GitHubTelemetryNotification, GitHubTelemetryEvent, GitHubTelemetryClientInfo, InstallationConfirmationRequest, InstallationConfirmationResponse, InstallationDecision, InstallationReview, McpInstallationReview, } from "./generated/rpc.js";
15
17
  /**
16
18
  * Arguments passed to a session's {@link GitHubTokenProvider}.
17
19
  *
@@ -290,6 +292,12 @@ export interface CopilotClientOptions {
290
292
  * @experimental
291
293
  */
292
294
  extensionLaunchProvider?: ExtensionLaunchProvider;
295
+ /**
296
+ * Connection-global human review for experimental installation operations.
297
+ * Does not register or enable installation capabilities on the runtime.
298
+ * @experimental
299
+ */
300
+ installationConfirmationHandler?: InstallationConfirmationHandler;
293
301
  /**
294
302
  * Log level for the Copilot runtime. When omitted, the runtime uses its
295
303
  * own default (currently `"info"`).
@@ -1692,69 +1700,6 @@ export interface CanvasProviderIdentity {
1692
1700
  /** Optional display name surfaced as the canvas extension name. */
1693
1701
  name?: string;
1694
1702
  }
1695
- /**
1696
- * Static resource ceilings declared by a factory before it runs.
1697
- *
1698
- * @experimental Part of the experimental Agent Factories surface and may
1699
- * change or be removed in future SDK or CLI releases.
1700
- */
1701
- export interface FactoryLimits {
1702
- /** Maximum number of factory subagents that may run concurrently. Must be positive when present. */
1703
- maxConcurrentSubagents?: number;
1704
- /** Maximum total number of factory subagents that may be spawned. Must be positive when present. */
1705
- maxTotalSubagents?: number;
1706
- /** Maximum AI credits consumed by factory subagents and descendants. This post-paid ceiling is soft. */
1707
- maxAiCredits?: number;
1708
- /**
1709
- * Maximum accumulated active-execution time, in seconds. Active execution includes the entire extension body,
1710
- * subprocess waits, queued-agent waits, and sleeps. The limit is armed from the remaining headroom when a run
1711
- * resumes; time between attempts is not counted. Must be finite and positive when present.
1712
- */
1713
- timeoutSeconds?: number;
1714
- }
1715
- /**
1716
- * Registration metadata for an extension-authored factory.
1717
- *
1718
- * @experimental Part of the experimental Agent Factories surface and may
1719
- * change or be removed in future SDK or CLI releases.
1720
- */
1721
- export interface FactoryMeta {
1722
- /** Stable factory name used for invocation. */
1723
- name: string;
1724
- /** Human-readable factory description. */
1725
- description: string;
1726
- /** Display metadata for the progress phases the factory may report. */
1727
- phases: Array<{
1728
- title: string;
1729
- detail?: string;
1730
- }>;
1731
- /**
1732
- * Optional declared shape of the arguments this factory expects as `ctx.args`.
1733
- *
1734
- * Declaring one is strongly recommended for any factory that reads `ctx.args`.
1735
- * When the model invokes the factory through the `run_factory` tool, the CLI
1736
- * validates `args` against this declaration **before** the run starts, so a
1737
- * malformed call is rejected with a correction hint and retried without ever
1738
- * creating a run row, prompting the user for permission, or spending credits. A
1739
- * factory that declares nothing is never validated: a malformed call starts,
1740
- * takes an approval, spends credits, and then fails inside the factory body.
1741
- * `factories_manage` with `operation: "inspect"` reports the declared shape so an
1742
- * agent can read it before invoking.
1743
- *
1744
- * This covers the model's `run_factory` path only. `session.factory.run(...)` is
1745
- * not validated against the declaration, so a factory should still check
1746
- * `ctx.args` rather than assume the declared shape held.
1747
- *
1748
- * Enforcement covers structure — types, required properties, and enum/const
1749
- * values. Finer constraints such as `minLength`, `pattern`, and
1750
- * `additionalProperties` are recorded in the declaration but not enforced. See
1751
- * {@link FactoryJsonSchema} for the accepted subset. A declaration outside that
1752
- * subset is rejected at registration.
1753
- */
1754
- argsSchema?: FactoryJsonSchema;
1755
- /** Optional resource ceilings presented to the user before execution. */
1756
- limits?: FactoryLimits;
1757
- }
1758
1703
  /**
1759
1704
  * Provider-scoped options for the Copilot API (CAPI).
1760
1705
  *
@@ -1,8 +1,11 @@
1
1
  import type { WorkflowGetRunProgressRequest, WorkflowListRunsRequest, WorkflowListRunsResult, WorkflowProgressPage, WorkflowRunDetail, WorkflowRunResult, WorkflowRunStatus, WorkflowRunSummary } from "./generated/rpc.js";
2
2
  import type { ContextTier } from "./generated/session-events.js";
3
3
  import type { CopilotSession } from "./session.js";
4
- import type { JsonValue } from "./factory.js";
5
4
  export type { WorkflowRunResult };
5
+ /** A value that can be represented losslessly on the SDK JSON wire. */
6
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
7
+ [key: string]: JsonValue;
8
+ };
6
9
  export type { WorkflowAgentSummary, WorkflowPhaseStatus, WorkflowPhaseObservation, WorkflowProgressLine, WorkflowProgressPage, WorkflowRunDetail, WorkflowRunStatus, WorkflowRunSummary, } from "./generated/rpc.js";
7
10
  /**
8
11
  * Options for paging durable workflow runs.
@@ -311,7 +314,7 @@ export interface SessionWorkflowApi {
311
314
  * snapshot: resuming the same durable run can later change the envelope
312
315
  * returned by {@link SessionWorkflowApi.getRun}.
313
316
  *
314
- * This watches the runtime's `factory.run_updated` compatibility event and
317
+ * This watches the runtime's `workflow.run_updated` event and
315
318
  * periodically re-reads the durable envelope so a missed event cannot
316
319
  * leave the wait hanging. Pass a `signal` to stop waiting; aborting rejects
317
320
  * and has no effect on the run itself, which keeps executing. Use
@@ -78,5 +78,4 @@ An approved extension can pass a granted value to anything it starts, so ask onl
78
78
 
79
79
  - `examples.md` — Practical code examples for tools, hooks, events, and complete extensions
80
80
  - `workflows.md` — Authoring, running, resuming, and observing Dynamic Workflows
81
- - `factories.md`: Authoring, running, resuming, and observing Agent Factories
82
81
  - `agent-author.md` — Step-by-step workflow for agents authoring extensions programmatically
package/docs/workflows.md CHANGED
@@ -2,8 +2,6 @@
2
2
 
3
3
  Dynamic Workflows are extension-authored, session-scoped workflows that coordinate subagents and durable steps. The API is experimental.
4
4
 
5
- Use Dynamic Workflows for new extension-authored orchestration. Existing Agent Factory extensions remain supported during the transition, but one `joinSession` call must register either `workflows` or `factories`, never both.
6
-
7
5
  ## Define and register a workflow
8
6
 
9
7
  Use `defineWorkflow` and pass the returned handle to `joinSession`:
@@ -242,7 +240,7 @@ if (settled.status === "completed") {
242
240
  }
243
241
  ```
244
242
 
245
- It watches the runtime's `factory.run_updated` compatibility event and re-reads the durable envelope on each invalidation, collapsing a burst of events into a single in-flight read. A low-frequency periodic re-read runs alongside the subscription, so a dropped or missing invalidation degrades into a slightly late resolution rather than an unbounded wait. Pass a `signal` to stop waiting:
243
+ It watches `workflow.run_updated` and re-reads the durable envelope on each invalidation, collapsing a burst of events into a single in-flight read. A low-frequency periodic re-read runs alongside the subscription, so a dropped or missing invalidation degrades into a slightly late resolution rather than an unbounded wait. Pass a `signal` to stop waiting:
246
244
 
247
245
  ```ts
248
246
  const controller = new AbortController();
@@ -252,6 +250,6 @@ const settled = await session.workflow.waitForRun(runId, { signal: controller.si
252
250
 
253
251
  Aborting rejects the wait and has no effect on the run, which keeps executing—use `pause(runId)` or `cancel(runId)` to stop it. The resolved object is a snapshot of that settled attempt. If its status is `paused`, a later resume updates the durable envelope under the same run ID. Call `getRun(runId)` to read the latest envelope. `isWorkflowRunTerminal(status)` exposes the same current-attempt settlement test for callers driving their own loop.
254
252
 
255
- Listen for the ephemeral `factory.run_updated` compatibility event. Its `{ runId, revision }` payload is an invalidation signal. Re-read the desired API when a newer monotonic revision arrives.
253
+ Listen for the ephemeral `workflow.run_updated` event. Its `{ runId, revision }` payload is an invalidation signal. Re-read the desired API when a newer monotonic revision arrives.
256
254
 
257
255
  Revisions cover durable lifecycle, accounting, phase, agent, and progress changes. Continuous read-time fields can change without a new revision. These include `observedAt`, active-time calculations, live counts, and a live agent's status or prompt-safe activity text. Workflow prompts are never exposed by these APIs. A run is visible only through the session that owns it.
package/package.json CHANGED
@@ -4,8 +4,8 @@
4
4
  "type": "git",
5
5
  "url": "https://github.com/github/copilot-sdk.git"
6
6
  },
7
- "version": "1.0.15-preview.3",
8
- "copilotCliVersion": "1.0.89-3",
7
+ "version": "1.0.15-preview.4",
8
+ "copilotCliVersion": "1.0.89-7",
9
9
  "description": "TypeScript SDK for programmatic control of GitHub Copilot CLI via JSON-RPC",
10
10
  "main": "./dist/cjs/index.js",
11
11
  "types": "./dist/index.d.ts",
@@ -101,13 +101,13 @@
101
101
  "README.md"
102
102
  ],
103
103
  "optionalDependencies": {
104
- "@github/copilot-sdk-darwin-arm64": "1.0.15-preview.3",
105
- "@github/copilot-sdk-darwin-x64": "1.0.15-preview.3",
106
- "@github/copilot-sdk-linux-arm64": "1.0.15-preview.3",
107
- "@github/copilot-sdk-linux-x64": "1.0.15-preview.3",
108
- "@github/copilot-sdk-linuxmusl-arm64": "1.0.15-preview.3",
109
- "@github/copilot-sdk-linuxmusl-x64": "1.0.15-preview.3",
110
- "@github/copilot-sdk-win32-arm64": "1.0.15-preview.3",
111
- "@github/copilot-sdk-win32-x64": "1.0.15-preview.3"
104
+ "@github/copilot-sdk-darwin-arm64": "1.0.15-preview.4",
105
+ "@github/copilot-sdk-darwin-x64": "1.0.15-preview.4",
106
+ "@github/copilot-sdk-linux-arm64": "1.0.15-preview.4",
107
+ "@github/copilot-sdk-linux-x64": "1.0.15-preview.4",
108
+ "@github/copilot-sdk-linuxmusl-arm64": "1.0.15-preview.4",
109
+ "@github/copilot-sdk-linuxmusl-x64": "1.0.15-preview.4",
110
+ "@github/copilot-sdk-win32-arm64": "1.0.15-preview.4",
111
+ "@github/copilot-sdk-win32-x64": "1.0.15-preview.4"
112
112
  }
113
113
  }
@@ -1,134 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var factory_exports = {};
20
- __export(factory_exports, {
21
- FACTORY_AGENT_OPTION_KEYS: () => FACTORY_AGENT_OPTION_KEYS,
22
- FactoryResumeError: () => FactoryResumeError,
23
- defineFactory: () => defineFactory,
24
- getFactoryDefinition: () => getFactoryDefinition,
25
- isFactoryRunTerminal: () => isFactoryRunTerminal
26
- });
27
- module.exports = __toCommonJS(factory_exports);
28
- const FACTORY_TERMINAL_STATUSES = /* @__PURE__ */ new Set([
29
- "completed",
30
- "halted",
31
- "paused",
32
- "cancelled",
33
- "error"
34
- ]);
35
- function isFactoryRunTerminal(status) {
36
- return FACTORY_TERMINAL_STATUSES.has(status);
37
- }
38
- const FACTORY_AGENT_OPTION_KEYS = [
39
- "label",
40
- "schema",
41
- "model",
42
- "reasoningEffort",
43
- "contextTier",
44
- "agent"
45
- ];
46
- class FactoryResumeError extends Error {
47
- constructor(code, message) {
48
- super(message);
49
- this.code = code;
50
- this.name = "FactoryResumeError";
51
- }
52
- code;
53
- }
54
- const factoryHandles = /* @__PURE__ */ new WeakMap();
55
- const MAX_FACTORY_TIMEOUT_SECONDS = 2147483647e-3;
56
- const NANO_AIU_PER_AIU = 1e9;
57
- function deepFreeze(value) {
58
- if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
59
- Object.freeze(value);
60
- for (const nested of Object.values(value)) {
61
- deepFreeze(nested);
62
- }
63
- }
64
- return value;
65
- }
66
- function validateLimits(meta) {
67
- const limits = meta.limits;
68
- if (!limits) {
69
- return;
70
- }
71
- for (const field of ["maxConcurrentSubagents", "maxTotalSubagents"]) {
72
- const value = limits[field];
73
- if (value !== void 0 && (!Number.isInteger(value) || value <= 0)) {
74
- throw new Error(`Factory limit "${field}" must be a positive integer`);
75
- }
76
- }
77
- if (limits.timeoutSeconds !== void 0 && (!Number.isFinite(limits.timeoutSeconds) || limits.timeoutSeconds <= 0)) {
78
- throw new Error(
79
- 'Factory limit "timeoutSeconds" must be a positive, finite number of seconds'
80
- );
81
- }
82
- if (limits.timeoutSeconds !== void 0 && limits.timeoutSeconds > MAX_FACTORY_TIMEOUT_SECONDS) {
83
- throw new Error(
84
- `Factory limit "timeoutSeconds" must not exceed ${MAX_FACTORY_TIMEOUT_SECONDS} seconds`
85
- );
86
- }
87
- if (limits.maxAiCredits !== void 0) {
88
- const maxNanoAiu = Math.round(limits.maxAiCredits * NANO_AIU_PER_AIU);
89
- if (!Number.isFinite(limits.maxAiCredits) || limits.maxAiCredits <= 0 || !Number.isSafeInteger(maxNanoAiu) || maxNanoAiu < 1) {
90
- throw new Error(
91
- 'Factory limit "maxAiCredits" must be a positive, finite number that rounds to a safe positive integer nano-AIU ceiling'
92
- );
93
- }
94
- }
95
- }
96
- function validatePhases(meta) {
97
- const titles = /* @__PURE__ */ new Set();
98
- for (const phase of meta.phases) {
99
- if (phase.title.trim().length === 0) {
100
- throw new Error("Factory phase titles must not be empty");
101
- }
102
- if (titles.has(phase.title)) {
103
- throw new Error(`Factory phase title "${phase.title}" is declared more than once`);
104
- }
105
- titles.add(phase.title);
106
- }
107
- }
108
- function defineFactory(definition) {
109
- const meta = deepFreeze(structuredClone(definition.meta));
110
- validateLimits(meta);
111
- validatePhases(meta);
112
- const stored = {
113
- meta,
114
- run: definition.run
115
- };
116
- const handle = Object.freeze({ meta });
117
- factoryHandles.set(handle, stored);
118
- return handle;
119
- }
120
- function getFactoryDefinition(handle) {
121
- const definition = factoryHandles.get(handle);
122
- if (!definition) {
123
- throw new Error("Invalid factory handle");
124
- }
125
- return definition;
126
- }
127
- // Annotate the CommonJS export names for ESM import in node:
128
- 0 && (module.exports = {
129
- FACTORY_AGENT_OPTION_KEYS,
130
- FactoryResumeError,
131
- defineFactory,
132
- getFactoryDefinition,
133
- isFactoryRunTerminal
134
- });
package/dist/factory.d.ts DELETED
@@ -1,327 +0,0 @@
1
- import type { FactoryGetRunProgressRequest, FactoryListRunsRequest, FactoryListRunsResult, FactoryProgressPage, FactoryRunDetail, FactoryRunResult, FactoryRunStatus, FactoryRunSummary } from "./generated/rpc.js";
2
- import type { ContextTier } from "./generated/session-events.js";
3
- import type { CopilotSession } from "./session.js";
4
- import type { FactoryMeta } from "./types.js";
5
- export type { FactoryRunResult };
6
- export type { FactoryAgentSummary, FactoryPhaseStatus, FactoryPhaseObservation, FactoryProgressLine, FactoryProgressPage, FactoryRunDetail, FactoryRunStatus, FactoryRunSummary, } from "./generated/rpc.js";
7
- /**
8
- * Options for paging durable factory runs.
9
- *
10
- * @experimental Part of the experimental Agent Factories surface and may
11
- * change or be removed in future SDK or CLI releases.
12
- */
13
- export type FactoryListRunsOptions = FactoryListRunsRequest;
14
- /**
15
- * A page of durable factory runs and its paging metadata.
16
- *
17
- * @experimental Part of the experimental Agent Factories surface and may
18
- * change or be removed in future SDK or CLI releases.
19
- */
20
- export type FactoryRunsPage = FactoryListRunsResult;
21
- /**
22
- * Whether a factory run status is terminal.
23
- *
24
- * @experimental Part of the experimental Agent Factories surface and may
25
- * change or be removed in future SDK or CLI releases.
26
- */
27
- export declare function isFactoryRunTerminal(status: FactoryRunStatus): boolean;
28
- declare const factoryHandleBrand: unique symbol;
29
- /** A value that can be represented losslessly on the SDK JSON wire. */
30
- export type JsonValue = null | boolean | number | string | JsonValue[] | {
31
- [key: string]: JsonValue;
32
- };
33
- /**
34
- * Conservative JSON shape language accepted by the Agent Factories surface, for
35
- * both structured factory agent output and a factory's declared `argsSchema`.
36
- *
37
- * This is a best-effort structural guard — used to decide whether a subagent's
38
- * structured output should be accepted or retried, and whether a caller's
39
- * factory `args` match the declared shape — **not** a full JSON Schema
40
- * validator. Only these keywords are honored: `type`, `required`, `enum`,
41
- * `const`, recursive `properties`/`items`, and `anyOf`/`oneOf`/`allOf`. A `type`
42
- * is one of `null`, `boolean`, `integer`, `number`, `string`, `array`, or
43
- * `object`, or a non-empty array of those (for example `["object", "null"]`).
44
- *
45
- * Everything else is **ignored, not enforced**. In particular, string
46
- * constraints (`pattern`, `minLength`, `maxLength`, `format`), numeric ranges
47
- * (`minimum`, `maximum`), `additionalProperties`, and boolean (`true`/`false`)
48
- * schemas do not reject non-conforming output. `oneOf` is treated like `anyOf`
49
- * (at least one branch must match) rather than strict exactly-one. Author
50
- * schemas within this subset; do not rely on unsupported constraints for
51
- * correctness.
52
- *
53
- * @experimental Part of the experimental Agent Factories surface and may
54
- * change or be removed in future SDK or CLI releases.
55
- */
56
- export type FactoryJsonSchema = {
57
- [key: string]: JsonValue;
58
- };
59
- /**
60
- * Options for one factory-scoped subagent call.
61
- *
62
- * @experimental Part of the experimental Agent Factories surface and may
63
- * change or be removed in future SDK or CLI releases.
64
- */
65
- export interface FactoryAgentOptions {
66
- label?: string;
67
- schema?: FactoryJsonSchema;
68
- model?: string;
69
- reasoningEffort?: string;
70
- contextTier?: ContextTier;
71
- agent?: string;
72
- }
73
- export declare const FACTORY_AGENT_OPTION_KEYS: readonly ["label", "schema", "model", "reasoningEffort", "contextTier", "agent"];
74
- /**
75
- * Options for a durable factory step.
76
- *
77
- * @experimental Part of the experimental Agent Factories surface and may
78
- * change or be removed in future SDK or CLI releases.
79
- */
80
- export interface FactoryStepOptions {
81
- /** Skip the journal and always invoke the producer. */
82
- volatile?: boolean;
83
- }
84
- /**
85
- * Per-invocation factory resource ceiling overrides.
86
- *
87
- * An omitted field preserves the existing/default ceiling, a number replaces
88
- * it, and `null` explicitly makes that dimension unlimited.
89
- *
90
- * @experimental Part of the experimental Agent Factories surface and may
91
- * change or be removed in future SDK or CLI releases.
92
- */
93
- export interface FactoryLimitOverrides {
94
- maxConcurrentSubagents?: number | null;
95
- maxTotalSubagents?: number | null;
96
- maxAiCredits?: number | null;
97
- timeoutSeconds?: number | null;
98
- }
99
- /**
100
- * One stage in a per-item factory pipeline.
101
- *
102
- * @experimental Part of the experimental Agent Factories surface and may
103
- * change or be removed in future SDK or CLI releases.
104
- */
105
- export type FactoryPipelineStage<TInput = unknown, TResult = unknown> = (previous: TInput, item: unknown, index: number) => Promise<TResult> | TResult;
106
- /**
107
- * Context passed to an extension-authored factory body.
108
- *
109
- * @experimental Part of the experimental Agent Factories surface and may
110
- * change or be removed in future SDK or CLI releases.
111
- */
112
- export interface FactoryContext<TArgs extends JsonValue = JsonValue> {
113
- /** Stable identifier for the current factory run. */
114
- readonly runId: string;
115
- /** Spawn and await one factory-scoped subagent. */
116
- agent(prompt: string, options?: FactoryAgentOptions): Promise<unknown>;
117
- /** Memoize an arbitrary producer under a stable author-supplied key. */
118
- step(key: string, producer: () => Promise<JsonValue> | JsonValue, options?: FactoryStepOptions): Promise<JsonValue>;
119
- /**
120
- * Pause this run at a durable, one-shot checkpoint.
121
- *
122
- * The first attempt to reach a key pauses and aborts cooperatively. A
123
- * resumed attempt returns from the same key and continues.
124
- */
125
- pause(key: string): Promise<void>;
126
- /**
127
- * Run thunks concurrently and await all of them.
128
- *
129
- * A thunk that throws becomes `null` in the result array, so one failed
130
- * item does not lose the rest. Cancellation and hard runtime failures
131
- * (`ResponseError`, `ConnectionError`) are the exception: those propagate
132
- * and reject the whole call, because they mean the run itself is in
133
- * trouble rather than one item having failed.
134
- */
135
- parallel<TResult>(thunks: Array<() => Promise<TResult> | TResult>): Promise<Array<TResult | null>>;
136
- /**
137
- * Run each item through every stage without barriers between stages.
138
- *
139
- * A stage that throws drops that item to `null` and skips its remaining
140
- * stages. As with {@link FactoryContext.parallel}, cancellation and hard
141
- * runtime failures propagate instead of being recorded per item.
142
- */
143
- pipeline(items: unknown[], ...stages: FactoryPipelineStage[]): Promise<unknown[]>;
144
- /** Start a named factory progress phase. */
145
- phase(title: string): void;
146
- /** Emit a factory progress line. */
147
- log(message: string): void;
148
- /** Reject because nested factories are not supported. */
149
- factory(name: string, args?: JsonValue): Promise<JsonValue | void>;
150
- /** Caller-supplied input, forwarded verbatim. */
151
- args: TArgs;
152
- /**
153
- * The session instance returned by `joinSession`. It refuses calls that
154
- * start, resume, or pause a factory run.
155
- */
156
- session: CopilotSession;
157
- /** Cooperative cancellation signal for the current factory run. */
158
- signal: AbortSignal;
159
- }
160
- /**
161
- * Definition accepted by {@link defineFactory}.
162
- *
163
- * @experimental Part of the experimental Agent Factories surface and may
164
- * change or be removed in future SDK or CLI releases.
165
- */
166
- export interface FactoryDefinition<TArgs extends JsonValue = JsonValue, TResult extends JsonValue | void = JsonValue | void> {
167
- meta: FactoryMeta;
168
- run(context: FactoryContext<TArgs>): Promise<TResult>;
169
- }
170
- /**
171
- * A deeply immutable view of a value.
172
- *
173
- * `defineFactory` deep-freezes the metadata it stores, so the handle's view of
174
- * it has to be readonly all the way down or `handle.meta.name = "..."` and
175
- * `handle.meta.phases.push(...)` would compile and then throw at runtime.
176
- */
177
- type DeepReadonly<T> = T extends (infer U)[] ? readonly DeepReadonly<U>[] : T extends object ? {
178
- readonly [K in keyof T]: DeepReadonly<T[K]>;
179
- } : T;
180
- /**
181
- * Opaque reusable reference to a defined factory.
182
- *
183
- * @experimental Part of the experimental Agent Factories surface and may
184
- * change or be removed in future SDK or CLI releases.
185
- */
186
- export interface FactoryHandle<TArgs extends JsonValue = JsonValue, TResult extends JsonValue | void = JsonValue | void> {
187
- readonly meta: DeepReadonly<FactoryMeta>;
188
- readonly [factoryHandleBrand]: {
189
- readonly args: TArgs;
190
- readonly result: TResult;
191
- };
192
- }
193
- /**
194
- * Options for invoking a factory.
195
- *
196
- * @experimental Part of the experimental Agent Factories surface and may
197
- * change or be removed in future SDK or CLI releases.
198
- */
199
- export interface RunOptions<TArgs extends JsonValue = JsonValue> {
200
- /** Input surfaced as `context.args`. */
201
- args?: TArgs;
202
- /** Optional per-invocation resource ceiling overrides. */
203
- limits?: FactoryLimitOverrides;
204
- /** Whether to notify the originating session when the factory completes. */
205
- notifyOnComplete?: boolean;
206
- /** Whether to emit factory phase names to the session transcript. */
207
- logPhaseNames?: boolean;
208
- /**
209
- * Prior run whose persisted identity, arguments, journal, and accounting should be resumed.
210
- *
211
- * @deprecated Use {@link SessionFactoryApi.resume} instead.
212
- */
213
- resumeFromRunId?: string;
214
- }
215
- /**
216
- * Options for resuming a factory run by ID.
217
- *
218
- * @experimental Part of the experimental Agent Factories surface and may
219
- * change or be removed in future SDK or CLI releases.
220
- */
221
- export interface ResumeOptions {
222
- /** Optional per-invocation resource ceiling overrides. */
223
- limits?: FactoryLimitOverrides;
224
- /** Whether to notify the originating session when the factory completes. */
225
- notifyOnComplete?: boolean;
226
- /** Whether to emit factory phase names to the session transcript. */
227
- logPhaseNames?: boolean;
228
- }
229
- /**
230
- * Machine-readable pre-execution factory resume failure.
231
- *
232
- * @experimental Part of the experimental Agent Factories surface and may
233
- * change or be removed in future SDK or CLI releases.
234
- */
235
- export type FactoryResumeErrorCode = "not_found" | "non_resumable" | "already_active" | "factory_already_running" | "factory_limits_invalid" | "factory_session_disposed" | "factory_storage_unavailable" | "factory_storage_corrupt";
236
- /**
237
- * Friendly factory API exposed on a session.
238
- *
239
- * @experimental Part of the experimental Agent Factories surface and may
240
- * change or be removed in future SDK or CLI releases.
241
- */
242
- export interface SessionFactoryApi {
243
- /**
244
- * Run a registered factory and resolve with its run envelope.
245
- *
246
- * The envelope is returned for every outcome, including `error`, `halted`,
247
- * `paused`, and `cancelled` — inspect `status` and read `result` only when
248
- * the run completed. `paused` settles the current attempt, but the same
249
- * durable run can later resume under its existing run ID. SDK-initiated
250
- * runs do not request permission, so they have no declined outcome. The
251
- * model's `run_factory` tool requests permission before a durable row
252
- * exists; declining it creates no run row. Failures that occur before a run
253
- * exists (such as an unknown factory or attempting to start a run while the
254
- * session is at its active top-level run limit) still reject.
255
- */
256
- run(name: string, options?: RunOptions): Promise<FactoryRunResult>;
257
- run<TArgs extends JsonValue>(factory: FactoryHandle<TArgs, JsonValue | void>, options?: RunOptions<TArgs>): Promise<FactoryRunResult>;
258
- /**
259
- * Resume a run from its persisted factory name, arguments, journal, and accounting.
260
- *
261
- * Resolves with the run envelope like {@link SessionFactoryApi.run}.
262
- * SDK-initiated resumes do not request permission. A pre-execution failure
263
- * with a documented resume code rejects with {@link FactoryResumeError}.
264
- */
265
- resume(runId: string, options?: ResumeOptions): Promise<FactoryRunResult>;
266
- /** Read the latest durable envelope for a factory run. */
267
- getRun(runId: string): Promise<FactoryRunResult>;
268
- /**
269
- * Wait for the current attempt to settle and resolve with its envelope.
270
- *
271
- * Resolves as soon as the run reaches `completed`, `error`, `halted`,
272
- * `paused`, or `cancelled`, and resolves immediately when the current
273
- * attempt has already settled. A `paused` envelope is an attempt-level
274
- * snapshot: resuming the same durable run can later change the envelope
275
- * returned by {@link SessionFactoryApi.getRun}.
276
- *
277
- * This watches the run's `factory.run_updated` invalidation events and
278
- * periodically re-reads the durable envelope so a missed event cannot
279
- * leave the wait hanging. Pass a `signal` to stop waiting; aborting rejects
280
- * and has no effect on the run itself, which keeps executing. Use
281
- * {@link SessionFactoryApi.cancel} to actually stop it.
282
- */
283
- waitForRun(runId: string, options?: {
284
- signal?: AbortSignal;
285
- }): Promise<FactoryRunResult>;
286
- /**
287
- * List the newest default page of this session's durable factory runs.
288
- *
289
- * This backwards-compatible overload returns only the runs array. Pass
290
- * paging options to receive the full page, including its cursors and
291
- * truncation metadata.
292
- */
293
- listRuns(): Promise<FactoryRunSummary[]>;
294
- /**
295
- * Page this session's durable factory runs.
296
- *
297
- * `afterSeq` and `beforeSeq` are exclusive cursors. The result includes
298
- * `oldestSeq`, `newestSeq`, `hasMoreNewer`, and `omittedOlder` so callers
299
- * can continue paging without using the raw RPC client.
300
- */
301
- listRuns(options: FactoryListRunsOptions): Promise<FactoryRunsPage>;
302
- /** Read durable phases, direct agents, and the latest progress tail for a run. */
303
- getRunDetail(runId: string): Promise<FactoryRunDetail>;
304
- /** Page durable progress forward, backward, or from the latest tail. */
305
- getRunProgress(runId: string, options?: Omit<FactoryGetRunProgressRequest, "runId">): Promise<FactoryProgressPage>;
306
- /** Pause a running factory attempt and return its `paused` envelope. */
307
- pause(runId: string): Promise<FactoryRunResult>;
308
- /** Cancel a factory run and return its terminal envelope. */
309
- cancel(runId: string): Promise<FactoryRunResult>;
310
- }
311
- /**
312
- * Error thrown when a factory cannot be resumed before execution begins.
313
- *
314
- * @experimental Part of the experimental Agent Factories surface and may
315
- * change or be removed in future SDK or CLI releases.
316
- */
317
- export declare class FactoryResumeError extends Error {
318
- readonly code: FactoryResumeErrorCode;
319
- constructor(code: FactoryResumeErrorCode, message: string);
320
- }
321
- /**
322
- * Defines an extension-authored factory and returns an opaque registration handle.
323
- *
324
- * @experimental Part of the experimental Agent Factories surface and may
325
- * change or be removed in future SDK or CLI releases.
326
- */
327
- export declare function defineFactory<TArgs extends JsonValue = JsonValue, TResult extends JsonValue | void = JsonValue | void>(definition: FactoryDefinition<TArgs, TResult>): FactoryHandle<TArgs, TResult>;