@microsoft/copilot-sdk 0.0.0-stage → 2.0.0-preview.0

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.
Files changed (91) hide show
  1. package/README.md +2531 -2
  2. package/dist/canvas.d.ts +135 -0
  3. package/dist/canvas.js +51 -0
  4. package/dist/cjs/canvas.js +77 -0
  5. package/dist/cjs/cliVersion.js +31 -0
  6. package/dist/cjs/client.js +3941 -0
  7. package/dist/cjs/copilotRequestHandler.js +815 -0
  8. package/dist/cjs/decisions.js +139 -0
  9. package/dist/cjs/entra.js +83 -0
  10. package/dist/cjs/extension.js +79 -0
  11. package/dist/cjs/ffiRuntimeHost.js +400 -0
  12. package/dist/cjs/generated/lifecycle-diagnostics.js +16 -0
  13. package/dist/cjs/generated/rpc.js +5883 -0
  14. package/dist/cjs/generated/session-events.js +16 -0
  15. package/dist/cjs/host.js +83 -0
  16. package/dist/cjs/index.js +100 -0
  17. package/dist/cjs/installationConfirmation.js +98 -0
  18. package/dist/cjs/jsonrpcTypes.js +41 -0
  19. package/dist/cjs/localModelJson.js +103 -0
  20. package/dist/cjs/package.json +1 -0
  21. package/dist/cjs/providerConfiguration.js +39 -0
  22. package/dist/cjs/rpcCancellation.js +49 -0
  23. package/dist/cjs/runtimeArtifacts.js +255 -0
  24. package/dist/cjs/schema.js +40 -0
  25. package/dist/cjs/sdkProtocolVersion.js +33 -0
  26. package/dist/cjs/session.js +2764 -0
  27. package/dist/cjs/sessionFsProvider.js +283 -0
  28. package/dist/cjs/taskAnalyticsJson.js +47 -0
  29. package/dist/cjs/telemetry.js +35 -0
  30. package/dist/cjs/toolSet.js +107 -0
  31. package/dist/cjs/types.js +204 -0
  32. package/dist/cjs/workflow.js +278 -0
  33. package/dist/cliVersion.d.ts +2 -0
  34. package/dist/cliVersion.js +6 -0
  35. package/dist/client.d.ts +576 -0
  36. package/dist/client.js +3924 -0
  37. package/dist/copilotRequestHandler.d.ts +91 -0
  38. package/dist/copilotRequestHandler.js +787 -0
  39. package/dist/decisions.d.ts +65 -0
  40. package/dist/decisions.js +113 -0
  41. package/dist/entra.d.ts +3 -0
  42. package/dist/entra.js +59 -0
  43. package/dist/extension.d.ts +69 -0
  44. package/dist/extension.js +59 -0
  45. package/dist/ffiRuntimeHost.d.ts +44 -0
  46. package/dist/ffiRuntimeHost.js +366 -0
  47. package/dist/generated/lifecycle-diagnostics.d.ts +232 -0
  48. package/dist/generated/lifecycle-diagnostics.js +0 -0
  49. package/dist/generated/rpc.d.ts +47706 -0
  50. package/dist/generated/rpc.js +5854 -0
  51. package/dist/generated/session-events.d.ts +17349 -0
  52. package/dist/generated/session-events.js +0 -0
  53. package/dist/host.d.ts +143 -0
  54. package/dist/host.js +59 -0
  55. package/dist/index.d.ts +23 -0
  56. package/dist/index.js +74 -0
  57. package/dist/installationConfirmation.d.ts +19 -0
  58. package/dist/installationConfirmation.js +74 -0
  59. package/dist/jsonrpcTypes.d.ts +16 -0
  60. package/dist/jsonrpcTypes.js +17 -0
  61. package/dist/localModelJson.d.ts +1 -0
  62. package/dist/localModelJson.js +69 -0
  63. package/dist/providerConfiguration.d.ts +3 -0
  64. package/dist/providerConfiguration.js +15 -0
  65. package/dist/rpcCancellation.d.ts +3 -0
  66. package/dist/rpcCancellation.js +25 -0
  67. package/dist/runtimeArtifacts.d.ts +18 -0
  68. package/dist/runtimeArtifacts.js +233 -0
  69. package/dist/schema.d.ts +4 -0
  70. package/dist/schema.js +14 -0
  71. package/dist/sdkProtocolVersion.d.ts +10 -0
  72. package/dist/sdkProtocolVersion.js +8 -0
  73. package/dist/session.d.ts +524 -0
  74. package/dist/session.js +2751 -0
  75. package/dist/sessionFsProvider.d.ts +130 -0
  76. package/dist/sessionFsProvider.js +257 -0
  77. package/dist/taskAnalyticsJson.d.ts +8 -0
  78. package/dist/taskAnalyticsJson.js +12 -0
  79. package/dist/telemetry.d.ts +14 -0
  80. package/dist/telemetry.js +11 -0
  81. package/dist/toolSet.d.ts +75 -0
  82. package/dist/toolSet.js +82 -0
  83. package/dist/types.d.ts +3864 -0
  84. package/dist/types.js +169 -0
  85. package/dist/workflow.d.ts +413 -0
  86. package/dist/workflow.js +248 -0
  87. package/docs/agent-author.md +372 -0
  88. package/docs/examples.md +747 -0
  89. package/docs/extensions.md +121 -0
  90. package/docs/workflows.md +303 -0
  91. package/package.json +135 -5
@@ -0,0 +1,65 @@
1
+ import type { DecisionAnswer, DecisionContext, DecisionErrorData, DecisionErrorKind, DecisionModelInfo, DecisionsAskRequest, DecisionsAskResult, ModelsListRequest, createServerRpc } from "./generated/rpc.js";
2
+ type ServerRpc = ReturnType<typeof createServerRpc>;
3
+ /** Options shared by the decision helpers. */
4
+ export interface DecisionCallOptions {
5
+ /**
6
+ * Rejects the call with an `AbortError` as soon as the signal aborts. The
7
+ * runtime does not observe the abort: the request still finishes, or hits
8
+ * its `timeoutMs` deadline, on the runtime side.
9
+ */
10
+ signal?: AbortSignal;
11
+ }
12
+ /** Options for {@link CopilotDecisions.yesNo}. */
13
+ export interface YesNoOptions extends DecisionCallOptions {
14
+ /** Account to ask as; see `DecisionsAskRequest.selectionId`. */
15
+ selectionId?: string;
16
+ /** GitHub token to ask as; see `DecisionsAskRequest.gitHubToken`. */
17
+ gitHubToken?: string;
18
+ /** Decision model id; the runtime default when omitted. */
19
+ model?: string;
20
+ /** Probability at or above which the answer counts as yes. Defaults to 0.5. */
21
+ threshold?: number;
22
+ /** Deadline in milliseconds; see `DecisionsAskRequest.timeoutMs`. */
23
+ timeoutMs?: number;
24
+ /** Static telemetry identifier of the calling feature. */
25
+ purpose?: string;
26
+ }
27
+ /** Result of {@link CopilotDecisions.yesNo}. A refusal is never reported as "no". */
28
+ export type YesNoResult = {
29
+ refused: false;
30
+ yes: boolean;
31
+ probability: number;
32
+ } | {
33
+ refused: true;
34
+ };
35
+ /** A decisions result with its answers also indexed by question name. */
36
+ export type DecisionsAskResultWithNames = DecisionsAskResult & {
37
+ byName: Readonly<Record<string, DecisionAnswer>>;
38
+ };
39
+ /**
40
+ * Convenience wrapper over the `decisions.*` RPCs: one-off yes/no, pick-one and
41
+ * rating questions answered by Copilot decision models.
42
+ *
43
+ * @experimental
44
+ */
45
+ export declare class CopilotDecisions {
46
+ private readonly rpc;
47
+ constructor(rpc: () => ServerRpc);
48
+ /**
49
+ * The decision models the account can call: `models.list`'s `decisionModels`,
50
+ * or an empty list when the runtime does not report them (the feature is off).
51
+ */
52
+ listModels(request?: ModelsListRequest, options?: DecisionCallOptions): Promise<DecisionModelInfo[]>;
53
+ /** Asks every question in `request` and returns the answers, also indexed by name. */
54
+ ask(request: DecisionsAskRequest, options?: DecisionCallOptions): Promise<DecisionsAskResultWithNames>;
55
+ /** Asks one yes/no question about `context`, which may be plain text or a structured context. */
56
+ yesNo(question: string, context: string | DecisionContext, options?: YesNoOptions): Promise<YesNoResult>;
57
+ }
58
+ /**
59
+ * The typed failure behind a rejected `decisions.*` call, or `undefined` when
60
+ * the error did not come from one (for example an `AbortError`).
61
+ */
62
+ export declare function decisionErrorData(error: unknown): DecisionErrorData | undefined;
63
+ /** Shorthand for `decisionErrorData(error)?.kind`. */
64
+ export declare function decisionErrorKind(error: unknown): DecisionErrorKind | undefined;
65
+ export {};
@@ -0,0 +1,113 @@
1
+ import { ResponseError } from "vscode-jsonrpc/node";
2
+ class CopilotDecisions {
3
+ constructor(rpc) {
4
+ this.rpc = rpc;
5
+ }
6
+ rpc;
7
+ /**
8
+ * The decision models the account can call: `models.list`'s `decisionModels`,
9
+ * or an empty list when the runtime does not report them (the feature is off).
10
+ */
11
+ async listModels(request, options) {
12
+ const list = await withAbort(() => this.rpc().models.list(request ?? {}), options?.signal);
13
+ return list.decisionModels ?? [];
14
+ }
15
+ /** Asks every question in `request` and returns the answers, also indexed by name. */
16
+ async ask(request, options) {
17
+ const result = await withAbort(() => this.rpc().decisions.ask(request), options?.signal);
18
+ return {
19
+ ...result,
20
+ byName: Object.fromEntries(result.answers.map((answer) => [answer.name, answer]))
21
+ };
22
+ }
23
+ /** Asks one yes/no question about `context`, which may be plain text or a structured context. */
24
+ async yesNo(question, context, options) {
25
+ const threshold = options?.threshold ?? 0.5;
26
+ const result = await this.ask(
27
+ {
28
+ context: typeof context === "string" ? { kind: "text", text: context } : context,
29
+ questions: [{ kind: "boolean", name: "answer", instructions: question }],
30
+ ...options?.selectionId !== void 0 ? { selectionId: options.selectionId } : {},
31
+ ...options?.gitHubToken !== void 0 ? { gitHubToken: options.gitHubToken } : {},
32
+ ...options?.model !== void 0 ? { model: options.model } : {},
33
+ ...options?.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
34
+ ...options?.purpose !== void 0 ? { purpose: options.purpose } : {}
35
+ },
36
+ options
37
+ );
38
+ const answer = result.answers[0];
39
+ if (answer?.kind !== "boolean") {
40
+ return { refused: true };
41
+ }
42
+ return {
43
+ refused: false,
44
+ yes: answer.probability >= threshold,
45
+ probability: answer.probability
46
+ };
47
+ }
48
+ }
49
+ function decisionErrorData(error) {
50
+ if (!(error instanceof ResponseError)) {
51
+ return void 0;
52
+ }
53
+ const data = error.data;
54
+ if (typeof data !== "object" || data === null) {
55
+ return void 0;
56
+ }
57
+ const kind = data.kind;
58
+ if (typeof kind !== "string" || !DECISION_ERROR_KINDS.has(kind)) {
59
+ return void 0;
60
+ }
61
+ return data;
62
+ }
63
+ const DECISION_ERROR_KINDS = /* @__PURE__ */ new Set([
64
+ "notEnabled",
65
+ "noModel",
66
+ "unauthenticated",
67
+ "invalidRequest",
68
+ "tooLarge",
69
+ "upstreamProtocol",
70
+ "rateLimited",
71
+ "timeout",
72
+ "unavailable",
73
+ "overloaded"
74
+ ]);
75
+ function decisionErrorKind(error) {
76
+ return decisionErrorData(error)?.kind;
77
+ }
78
+ function abortError(signal) {
79
+ const reason = signal.reason;
80
+ if (reason instanceof Error && reason.name === "AbortError") {
81
+ return reason;
82
+ }
83
+ const error = new Error("The decisions call was aborted");
84
+ error.name = "AbortError";
85
+ return error;
86
+ }
87
+ function withAbort(call, signal) {
88
+ if (!signal) {
89
+ return call();
90
+ }
91
+ if (signal.aborted) {
92
+ return Promise.reject(abortError(signal));
93
+ }
94
+ return new Promise((resolve, reject) => {
95
+ const onAbort = () => reject(abortError(signal));
96
+ signal.addEventListener("abort", onAbort, { once: true });
97
+ call().then(
98
+ (value) => {
99
+ signal.removeEventListener("abort", onAbort);
100
+ resolve(value);
101
+ },
102
+ (error) => {
103
+ signal.removeEventListener("abort", onAbort);
104
+ reject(error);
105
+ }
106
+ );
107
+ });
108
+ }
109
+ export {
110
+ CopilotDecisions,
111
+ decisionErrorData,
112
+ decisionErrorKind
113
+ };
@@ -0,0 +1,3 @@
1
+ import type { MessageConnection } from "./jsonrpcTypes.js";
2
+ import type { EntraTokenProvider } from "./types.js";
3
+ export declare function registerEntraTokenProvider(connection: MessageConnection, provider: EntraTokenProvider): void;
package/dist/entra.js ADDED
@@ -0,0 +1,59 @@
1
+ import { CancellationTokenSource, ResponseError } from "vscode-jsonrpc/node";
2
+ function registerEntraTokenProvider(connection, provider) {
3
+ const closed = new CancellationTokenSource();
4
+ const connectionClosed = closed.token;
5
+ const close = connection.onClose(() => closed.cancel());
6
+ const dispose = connection.onDispose(() => {
7
+ closed.cancel();
8
+ closed.dispose();
9
+ close.dispose();
10
+ dispose.dispose();
11
+ });
12
+ connection.onRequest(
13
+ "entraToken.getToken",
14
+ async ({ request }, token) => {
15
+ const combined = new CancellationTokenSource();
16
+ const subscriptions = [];
17
+ const checkCancellation = () => {
18
+ if (connectionClosed.isCancellationRequested || token.isCancellationRequested) {
19
+ combined.cancel();
20
+ throw new ResponseError(-32800, "Entra token acquisition cancelled");
21
+ }
22
+ };
23
+ try {
24
+ const cancelled = new Promise((_resolve, reject) => {
25
+ const cancel = () => {
26
+ combined.cancel();
27
+ reject(new ResponseError(-32800, "Entra token acquisition cancelled"));
28
+ };
29
+ subscriptions.push(
30
+ token.onCancellationRequested(cancel),
31
+ connectionClosed.onCancellationRequested(cancel)
32
+ );
33
+ });
34
+ checkCancellation();
35
+ const result = await Promise.race([
36
+ Promise.resolve().then(() => {
37
+ checkCancellation();
38
+ return provider(request, combined.token);
39
+ }),
40
+ cancelled
41
+ ]);
42
+ checkCancellation();
43
+ if (result === void 0 || result === null) {
44
+ throw new ResponseError(-32603, "Entra token provider failed");
45
+ }
46
+ return result;
47
+ } catch {
48
+ checkCancellation();
49
+ throw new ResponseError(-32603, "Entra token provider failed");
50
+ } finally {
51
+ for (const subscription of subscriptions) subscription.dispose();
52
+ combined.dispose();
53
+ }
54
+ }
55
+ );
56
+ }
57
+ export {
58
+ registerEntraTokenProvider
59
+ };
@@ -0,0 +1,69 @@
1
+ import { CopilotClient } from "./client.js";
2
+ import type { CopilotSession } from "./session.js";
3
+ import { type PermissionHandler, type ResumeSessionConfig } from "./types.js";
4
+ import type { WorkflowHandle } from "./workflow.js";
5
+ export { Canvas, CanvasError, createCanvas, type CanvasAction, type CanvasDeclaration, type CanvasHostContext, type CanvasJsonSchema, type CanvasOptions, } from "./canvas.js";
6
+ export type JoinSessionConfig = Omit<ResumeSessionConfig, "onPermissionRequest" | "extensionSdkPath" | "skillProvider" | "imageGeneration"> & {
7
+ onPermissionRequest?: PermissionHandler;
8
+ /**
9
+ * Names of sensitive environment variables this extension needs, such as
10
+ * `"GITHUB_TOKEN"`.
11
+ *
12
+ * The Copilot CLI strips sensitive variables from every extension process
13
+ * before it starts, so an extension that needs one must ask for it by name.
14
+ * The CLI prompts the user with the extension's name and the exact list of
15
+ * variables requested. On approval the granted values are written into this
16
+ * process's `process.env` before {@link joinSession} resolves, so they are
17
+ * readable afterwards. On denial the join rejects and the extension does not
18
+ * load, so its tools never reach the model.
19
+ *
20
+ * An approval is remembered against the exact set of names the user saw, so
21
+ * asking for an additional variable later prompts again. Names that are unset
22
+ * or that the CLI does not filter from extensions are not prompted for. An
23
+ * empty list means the same as omitting the option: nothing is requested.
24
+ *
25
+ * Requires a Copilot CLI that supports extension environment access; older
26
+ * CLIs ignore the request and grant nothing.
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * const session = await joinSession({
31
+ * requestedEnvironmentVariables: ["GITHUB_TOKEN"],
32
+ * });
33
+ * const token = process.env.GITHUB_TOKEN;
34
+ * ```
35
+ */
36
+ requestedEnvironmentVariables?: string[];
37
+ /**
38
+ * Workflow handles to register when the extension joins the session.
39
+ *
40
+ * @experimental Part of the experimental Dynamic Workflows surface and may
41
+ * change or be removed in future SDK or CLI releases.
42
+ */
43
+ workflows?: WorkflowHandle[];
44
+ };
45
+ export type { ExtensionInfo } from "./types.js";
46
+ /** A joined session with HTTP transport owned by the extension's connection. */
47
+ export interface JoinedSession extends CopilotSession {
48
+ /**
49
+ * Create, send, read, and cancel HTTP requests through the shared runtime transport.
50
+ *
51
+ * @experimental These methods may change or be removed in future SDK or CLI releases.
52
+ */
53
+ readonly fetch: CopilotClient["rpc"]["fetch"];
54
+ }
55
+ export { defineWorkflow, WorkflowResumeError, isWorkflowRunTerminal, type WorkflowRunOptions, type WorkflowResumeOptions, type WorkflowLimitOverrides, type WorkflowResumeErrorCode, type SessionWorkflowApi, type WorkflowAgentOptions, type WorkflowContext, type WorkflowDefinition, type WorkflowHandle, type WorkflowAgentReference, type JsonValue, type WorkflowJsonSchema, type WorkflowLimits, type WorkflowMeta, type WorkflowPipelineStage, type WorkflowStepOptions, type WorkflowRunResult, type WorkflowRunStatus, type WorkflowRunSummary, type WorkflowListRunsOptions, type WorkflowRunsPage, type WorkflowRunDetail, type WorkflowProgressPage, type WorkflowProgressLine, type WorkflowPhaseObservation, type WorkflowPhaseStatus, type WorkflowAgentContextObservation, type WorkflowAgentModelObservation, type WorkflowAgentReasoningEffortObservation, type WorkflowAgentSummary, } from "./workflow.js";
56
+ /**
57
+ * Joins the current foreground session.
58
+ *
59
+ * @param config - Configuration to add to the session
60
+ * @returns A promise that resolves with the joined session
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * import { joinSession } from "@microsoft/copilot-sdk/extension";
65
+ *
66
+ * const session = await joinSession({ tools: [myTool] });
67
+ * ```
68
+ */
69
+ export declare function joinSession(config?: JoinSessionConfig): Promise<JoinedSession>;
@@ -0,0 +1,59 @@
1
+ import { CopilotClient } from "./client.js";
2
+ import {
3
+ defaultJoinSessionPermissionHandler
4
+ } from "./types.js";
5
+ import {
6
+ Canvas,
7
+ CanvasError,
8
+ createCanvas
9
+ } from "./canvas.js";
10
+ import {
11
+ defineWorkflow,
12
+ WorkflowResumeError,
13
+ isWorkflowRunTerminal
14
+ } from "./workflow.js";
15
+ async function joinSession(config = {}) {
16
+ const sessionId = process.env.SESSION_ID;
17
+ if (!sessionId) {
18
+ throw new Error(
19
+ "joinSession() is intended for extensions running as child processes of the Copilot CLI."
20
+ );
21
+ }
22
+ const client = new CopilotClient({
23
+ mode: "coding-agent",
24
+ _internalConnection: { kind: "parent-process" }
25
+ });
26
+ const {
27
+ extensionSdkPath: _stripped,
28
+ skillProvider: _strippedSkillProvider,
29
+ imageGeneration: _strippedImageGeneration,
30
+ workflows,
31
+ requestedEnvironmentVariables,
32
+ ...rest
33
+ } = config;
34
+ void _stripped;
35
+ void _strippedSkillProvider;
36
+ void _strippedImageGeneration;
37
+ const session = await client.resumeSessionForExtension(
38
+ sessionId,
39
+ {
40
+ ...rest,
41
+ onPermissionRequest: config.onPermissionRequest ?? defaultJoinSessionPermissionHandler,
42
+ suppressResumeEvent: config.suppressResumeEvent ?? true
43
+ },
44
+ { workflows },
45
+ requestedEnvironmentVariables?.length ? { requestedEnvironmentVariables } : void 0
46
+ );
47
+ return Object.defineProperty(session, "fetch", {
48
+ get: () => client.rpc.fetch
49
+ });
50
+ }
51
+ export {
52
+ Canvas,
53
+ CanvasError,
54
+ WorkflowResumeError,
55
+ createCanvas,
56
+ defineWorkflow,
57
+ isWorkflowRunTerminal,
58
+ joinSession
59
+ };
@@ -0,0 +1,44 @@
1
+ import { PassThrough, Writable } from "node:stream";
2
+ export declare class FfiRuntimeHost {
3
+ private readonly libraryPath;
4
+ private readonly cliEntrypoint;
5
+ private readonly environment;
6
+ private readonly args;
7
+ private static readonly quarantinedHosts;
8
+ private readonly lib;
9
+ private serverId;
10
+ private connectionId;
11
+ private disposed;
12
+ private starting;
13
+ private outboundCallback;
14
+ private keepAliveTimer;
15
+ private cleanupRetryTimer;
16
+ private cleanupInProgress;
17
+ /** The stream JSON-RPC reads server→client frames from. */
18
+ readonly receiveStream: PassThrough;
19
+ /** The stream JSON-RPC writes client→server frames to. */
20
+ readonly sendStream: Writable;
21
+ private constructor();
22
+ /**
23
+ * Loads the runtime cdylib at the given path and prepares the FFI host.
24
+ */
25
+ static create(libraryPath: string, cliEntrypoint: string | undefined, environment: Record<string, string | undefined> | undefined, args: readonly string[]): FfiRuntimeHost;
26
+ /** Starts the in-process Rust runtime and opens the FFI JSON-RPC connection. */
27
+ start(): Promise<void>;
28
+ private writeFrame;
29
+ configureUiThread(enabled: boolean): void;
30
+ runUiAction(actionId: number): void;
31
+ /**
32
+ * Native outbound (server→client) callback. koffi delivers it on the JS event loop
33
+ * via a threadsafe function, so the frame is decoded and written straight to
34
+ * {@link receiveStream}. The native pointer is only valid for this call, so the
35
+ * bytes are copied out before returning.
36
+ */
37
+ private feedInbound;
38
+ private shutdownHost;
39
+ private unregisterCallback;
40
+ private scheduleCleanupRetry;
41
+ private tryFinalizeCleanup;
42
+ /** Awaits the initial cleanup attempt; a non-quiescent close is retried in the background. */
43
+ dispose(): Promise<void>;
44
+ }