@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,139 @@
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 decisions_exports = {};
20
+ __export(decisions_exports, {
21
+ CopilotDecisions: () => CopilotDecisions,
22
+ decisionErrorData: () => decisionErrorData,
23
+ decisionErrorKind: () => decisionErrorKind
24
+ });
25
+ module.exports = __toCommonJS(decisions_exports);
26
+ var import_node = require("vscode-jsonrpc/node");
27
+ class CopilotDecisions {
28
+ constructor(rpc) {
29
+ this.rpc = rpc;
30
+ }
31
+ rpc;
32
+ /**
33
+ * The decision models the account can call: `models.list`'s `decisionModels`,
34
+ * or an empty list when the runtime does not report them (the feature is off).
35
+ */
36
+ async listModels(request, options) {
37
+ const list = await withAbort(() => this.rpc().models.list(request ?? {}), options?.signal);
38
+ return list.decisionModels ?? [];
39
+ }
40
+ /** Asks every question in `request` and returns the answers, also indexed by name. */
41
+ async ask(request, options) {
42
+ const result = await withAbort(() => this.rpc().decisions.ask(request), options?.signal);
43
+ return {
44
+ ...result,
45
+ byName: Object.fromEntries(result.answers.map((answer) => [answer.name, answer]))
46
+ };
47
+ }
48
+ /** Asks one yes/no question about `context`, which may be plain text or a structured context. */
49
+ async yesNo(question, context, options) {
50
+ const threshold = options?.threshold ?? 0.5;
51
+ const result = await this.ask(
52
+ {
53
+ context: typeof context === "string" ? { kind: "text", text: context } : context,
54
+ questions: [{ kind: "boolean", name: "answer", instructions: question }],
55
+ ...options?.selectionId !== void 0 ? { selectionId: options.selectionId } : {},
56
+ ...options?.gitHubToken !== void 0 ? { gitHubToken: options.gitHubToken } : {},
57
+ ...options?.model !== void 0 ? { model: options.model } : {},
58
+ ...options?.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
59
+ ...options?.purpose !== void 0 ? { purpose: options.purpose } : {}
60
+ },
61
+ options
62
+ );
63
+ const answer = result.answers[0];
64
+ if (answer?.kind !== "boolean") {
65
+ return { refused: true };
66
+ }
67
+ return {
68
+ refused: false,
69
+ yes: answer.probability >= threshold,
70
+ probability: answer.probability
71
+ };
72
+ }
73
+ }
74
+ function decisionErrorData(error) {
75
+ if (!(error instanceof import_node.ResponseError)) {
76
+ return void 0;
77
+ }
78
+ const data = error.data;
79
+ if (typeof data !== "object" || data === null) {
80
+ return void 0;
81
+ }
82
+ const kind = data.kind;
83
+ if (typeof kind !== "string" || !DECISION_ERROR_KINDS.has(kind)) {
84
+ return void 0;
85
+ }
86
+ return data;
87
+ }
88
+ const DECISION_ERROR_KINDS = /* @__PURE__ */ new Set([
89
+ "notEnabled",
90
+ "noModel",
91
+ "unauthenticated",
92
+ "invalidRequest",
93
+ "tooLarge",
94
+ "upstreamProtocol",
95
+ "rateLimited",
96
+ "timeout",
97
+ "unavailable",
98
+ "overloaded"
99
+ ]);
100
+ function decisionErrorKind(error) {
101
+ return decisionErrorData(error)?.kind;
102
+ }
103
+ function abortError(signal) {
104
+ const reason = signal.reason;
105
+ if (reason instanceof Error && reason.name === "AbortError") {
106
+ return reason;
107
+ }
108
+ const error = new Error("The decisions call was aborted");
109
+ error.name = "AbortError";
110
+ return error;
111
+ }
112
+ function withAbort(call, signal) {
113
+ if (!signal) {
114
+ return call();
115
+ }
116
+ if (signal.aborted) {
117
+ return Promise.reject(abortError(signal));
118
+ }
119
+ return new Promise((resolve, reject) => {
120
+ const onAbort = () => reject(abortError(signal));
121
+ signal.addEventListener("abort", onAbort, { once: true });
122
+ call().then(
123
+ (value) => {
124
+ signal.removeEventListener("abort", onAbort);
125
+ resolve(value);
126
+ },
127
+ (error) => {
128
+ signal.removeEventListener("abort", onAbort);
129
+ reject(error);
130
+ }
131
+ );
132
+ });
133
+ }
134
+ // Annotate the CommonJS export names for ESM import in node:
135
+ 0 && (module.exports = {
136
+ CopilotDecisions,
137
+ decisionErrorData,
138
+ decisionErrorKind
139
+ });
@@ -0,0 +1,83 @@
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 entra_exports = {};
20
+ __export(entra_exports, {
21
+ registerEntraTokenProvider: () => registerEntraTokenProvider
22
+ });
23
+ module.exports = __toCommonJS(entra_exports);
24
+ var import_node = require("vscode-jsonrpc/node");
25
+ function registerEntraTokenProvider(connection, provider) {
26
+ const closed = new import_node.CancellationTokenSource();
27
+ const connectionClosed = closed.token;
28
+ const close = connection.onClose(() => closed.cancel());
29
+ const dispose = connection.onDispose(() => {
30
+ closed.cancel();
31
+ closed.dispose();
32
+ close.dispose();
33
+ dispose.dispose();
34
+ });
35
+ connection.onRequest(
36
+ "entraToken.getToken",
37
+ async ({ request }, token) => {
38
+ const combined = new import_node.CancellationTokenSource();
39
+ const subscriptions = [];
40
+ const checkCancellation = () => {
41
+ if (connectionClosed.isCancellationRequested || token.isCancellationRequested) {
42
+ combined.cancel();
43
+ throw new import_node.ResponseError(-32800, "Entra token acquisition cancelled");
44
+ }
45
+ };
46
+ try {
47
+ const cancelled = new Promise((_resolve, reject) => {
48
+ const cancel = () => {
49
+ combined.cancel();
50
+ reject(new import_node.ResponseError(-32800, "Entra token acquisition cancelled"));
51
+ };
52
+ subscriptions.push(
53
+ token.onCancellationRequested(cancel),
54
+ connectionClosed.onCancellationRequested(cancel)
55
+ );
56
+ });
57
+ checkCancellation();
58
+ const result = await Promise.race([
59
+ Promise.resolve().then(() => {
60
+ checkCancellation();
61
+ return provider(request, combined.token);
62
+ }),
63
+ cancelled
64
+ ]);
65
+ checkCancellation();
66
+ if (result === void 0 || result === null) {
67
+ throw new import_node.ResponseError(-32603, "Entra token provider failed");
68
+ }
69
+ return result;
70
+ } catch {
71
+ checkCancellation();
72
+ throw new import_node.ResponseError(-32603, "Entra token provider failed");
73
+ } finally {
74
+ for (const subscription of subscriptions) subscription.dispose();
75
+ combined.dispose();
76
+ }
77
+ }
78
+ );
79
+ }
80
+ // Annotate the CommonJS export names for ESM import in node:
81
+ 0 && (module.exports = {
82
+ registerEntraTokenProvider
83
+ });
@@ -0,0 +1,79 @@
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 extension_exports = {};
20
+ __export(extension_exports, {
21
+ Canvas: () => import_canvas.Canvas,
22
+ CanvasError: () => import_canvas.CanvasError,
23
+ WorkflowResumeError: () => import_workflow.WorkflowResumeError,
24
+ createCanvas: () => import_canvas.createCanvas,
25
+ defineWorkflow: () => import_workflow.defineWorkflow,
26
+ isWorkflowRunTerminal: () => import_workflow.isWorkflowRunTerminal,
27
+ joinSession: () => joinSession
28
+ });
29
+ module.exports = __toCommonJS(extension_exports);
30
+ var import_client = require("./client.js");
31
+ var import_types = require("./types.js");
32
+ var import_canvas = require("./canvas.js");
33
+ var import_workflow = require("./workflow.js");
34
+ async function joinSession(config = {}) {
35
+ const sessionId = process.env.SESSION_ID;
36
+ if (!sessionId) {
37
+ throw new Error(
38
+ "joinSession() is intended for extensions running as child processes of the Copilot CLI."
39
+ );
40
+ }
41
+ const client = new import_client.CopilotClient({
42
+ mode: "coding-agent",
43
+ _internalConnection: { kind: "parent-process" }
44
+ });
45
+ const {
46
+ extensionSdkPath: _stripped,
47
+ skillProvider: _strippedSkillProvider,
48
+ imageGeneration: _strippedImageGeneration,
49
+ workflows,
50
+ requestedEnvironmentVariables,
51
+ ...rest
52
+ } = config;
53
+ void _stripped;
54
+ void _strippedSkillProvider;
55
+ void _strippedImageGeneration;
56
+ const session = await client.resumeSessionForExtension(
57
+ sessionId,
58
+ {
59
+ ...rest,
60
+ onPermissionRequest: config.onPermissionRequest ?? import_types.defaultJoinSessionPermissionHandler,
61
+ suppressResumeEvent: config.suppressResumeEvent ?? true
62
+ },
63
+ { workflows },
64
+ requestedEnvironmentVariables?.length ? { requestedEnvironmentVariables } : void 0
65
+ );
66
+ return Object.defineProperty(session, "fetch", {
67
+ get: () => client.rpc.fetch
68
+ });
69
+ }
70
+ // Annotate the CommonJS export names for ESM import in node:
71
+ 0 && (module.exports = {
72
+ Canvas,
73
+ CanvasError,
74
+ WorkflowResumeError,
75
+ createCanvas,
76
+ defineWorkflow,
77
+ isWorkflowRunTerminal,
78
+ joinSession
79
+ });
@@ -0,0 +1,400 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var ffiRuntimeHost_exports = {};
30
+ __export(ffiRuntimeHost_exports, {
31
+ FfiRuntimeHost: () => FfiRuntimeHost
32
+ });
33
+ module.exports = __toCommonJS(ffiRuntimeHost_exports);
34
+ var import_node_fs = require("node:fs");
35
+ var import_koffi = __toESM(require("koffi"), 1);
36
+ var import_node_path = require("node:path");
37
+ var import_node_stream = require("node:stream");
38
+ const SYMBOL_PREFIX = "copilot_runtime_";
39
+ const KEEP_ALIVE_INTERVAL_MS = 1 << 30;
40
+ const CLEANUP_RETRY_INTERVAL_MS = 100;
41
+ let loadedLibraryPath;
42
+ let loadedLibrary;
43
+ function loadLibrary(libraryPath) {
44
+ if (loadedLibrary) {
45
+ if (loadedLibraryPath !== libraryPath) {
46
+ throw new Error(
47
+ `An in-process FFI runtime library is already loaded from '${loadedLibraryPath}'; loading a different library from '${libraryPath}' in the same process is not supported.`
48
+ );
49
+ }
50
+ return loadedLibrary;
51
+ }
52
+ const lib = import_koffi.default.load(libraryPath);
53
+ const outboundCallbackType = import_koffi.default.pointer(
54
+ import_koffi.default.proto(
55
+ `void ${SYMBOL_PREFIX}outbound(void *userData, uint8 *bytesPtr, size_t bytesLen)`
56
+ )
57
+ );
58
+ loadedLibrary = {
59
+ hostStart: lib.func(`${SYMBOL_PREFIX}host_start`, "uint32", [
60
+ "uint8*",
61
+ "size_t",
62
+ "uint8*",
63
+ "size_t"
64
+ ]),
65
+ hostShutdown: lib.func(`${SYMBOL_PREFIX}host_shutdown`, "bool", ["uint32"]),
66
+ connectionOpen: lib.func(`${SYMBOL_PREFIX}connection_open`, "uint32", [
67
+ "uint32",
68
+ outboundCallbackType,
69
+ "void*",
70
+ "uint8*",
71
+ "size_t",
72
+ "uint8*",
73
+ "size_t",
74
+ "uint8*",
75
+ "size_t"
76
+ ]),
77
+ connectionWrite: lib.func(`${SYMBOL_PREFIX}connection_write`, "bool", [
78
+ "uint32",
79
+ "uint8*",
80
+ "size_t"
81
+ ]),
82
+ connectionClose: lib.func(`${SYMBOL_PREFIX}connection_close`, "bool", ["uint32"]),
83
+ connectionSetUiThreadHandler: lib.func(
84
+ `${SYMBOL_PREFIX}connection_set_ui_thread_handler`,
85
+ "bool",
86
+ ["uint32", "bool"]
87
+ ),
88
+ connectionRunUiAction: lib.func(`${SYMBOL_PREFIX}connection_run_ui_action`, "bool", [
89
+ "uint32",
90
+ "uint32"
91
+ ]),
92
+ outboundCallbackType
93
+ };
94
+ loadedLibraryPath = libraryPath;
95
+ return loadedLibrary;
96
+ }
97
+ function buildArgvJson(cliEntrypoint, args) {
98
+ const argv = cliEntrypoint ? cliEntrypoint.toLowerCase().endsWith(".js") ? ["node", cliEntrypoint, "--embedded-host", "--no-auto-update"] : [cliEntrypoint, "--embedded-host", "--no-auto-update"] : [];
99
+ argv.push(...args);
100
+ return Buffer.from(JSON.stringify(argv), "utf8");
101
+ }
102
+ function buildEnvJson(environment) {
103
+ if (!environment) {
104
+ return null;
105
+ }
106
+ const obj = {};
107
+ for (const [key, value] of Object.entries(environment)) {
108
+ if (value !== void 0) {
109
+ obj[key] = value;
110
+ }
111
+ }
112
+ if (Object.keys(obj).length === 0) {
113
+ return null;
114
+ }
115
+ return Buffer.from(JSON.stringify(obj), "utf8");
116
+ }
117
+ class FfiRuntimeHost {
118
+ constructor(libraryPath, cliEntrypoint, environment, args) {
119
+ this.libraryPath = libraryPath;
120
+ this.cliEntrypoint = cliEntrypoint;
121
+ this.environment = environment;
122
+ this.args = args;
123
+ this.lib = loadLibrary(libraryPath);
124
+ this.receiveStream = new import_node_stream.PassThrough();
125
+ this.sendStream = new import_node_stream.Writable({
126
+ // connection_write enqueues the frame into the runtime's inbound channel and
127
+ // returns immediately, so a synchronous FFI call is sufficient here.
128
+ write: (chunk, _encoding, callback) => {
129
+ try {
130
+ this.writeFrame(chunk);
131
+ callback();
132
+ } catch (error) {
133
+ callback(error);
134
+ }
135
+ }
136
+ });
137
+ }
138
+ libraryPath;
139
+ cliEntrypoint;
140
+ environment;
141
+ args;
142
+ static quarantinedHosts = /* @__PURE__ */ new Set();
143
+ lib;
144
+ serverId = 0;
145
+ connectionId = 0;
146
+ disposed = false;
147
+ starting = false;
148
+ outboundCallback;
149
+ keepAliveTimer;
150
+ cleanupRetryTimer;
151
+ cleanupInProgress = false;
152
+ /** The stream JSON-RPC reads server→client frames from. */
153
+ receiveStream;
154
+ /** The stream JSON-RPC writes client→server frames to. */
155
+ sendStream;
156
+ /**
157
+ * Loads the runtime cdylib at the given path and prepares the FFI host.
158
+ */
159
+ static create(libraryPath, cliEntrypoint, environment, args) {
160
+ const fullLibraryPath = (0, import_node_path.resolve)(libraryPath);
161
+ if (!(0, import_node_fs.existsSync)(fullLibraryPath)) {
162
+ throw new Error(`FFI runtime library not found at '${fullLibraryPath}'.`);
163
+ }
164
+ return new FfiRuntimeHost(
165
+ fullLibraryPath,
166
+ cliEntrypoint ? (0, import_node_path.resolve)(cliEntrypoint) : void 0,
167
+ environment,
168
+ args
169
+ );
170
+ }
171
+ /** Starts the in-process Rust runtime and opens the FFI JSON-RPC connection. */
172
+ async start() {
173
+ if (this.disposed) {
174
+ throw new Error("The in-process runtime host is disposed.");
175
+ }
176
+ this.starting = true;
177
+ const argvJson = buildArgvJson(this.cliEntrypoint, this.args);
178
+ const envJson = buildEnvJson(this.environment);
179
+ try {
180
+ this.serverId = await new Promise((resolvePromise, rejectPromise) => {
181
+ this.lib.hostStart.async(
182
+ argvJson,
183
+ argvJson.length,
184
+ envJson,
185
+ envJson ? envJson.length : 0,
186
+ (error, result) => {
187
+ if (error) {
188
+ rejectPromise(error);
189
+ } else {
190
+ resolvePromise(result);
191
+ }
192
+ }
193
+ );
194
+ });
195
+ if (!this.serverId) {
196
+ throw new Error(
197
+ `copilot_runtime_host_start failed (library '${this.libraryPath}').`
198
+ );
199
+ }
200
+ if (this.disposed) {
201
+ throw new Error("The in-process runtime host was disposed during startup.");
202
+ }
203
+ this.outboundCallback = import_koffi.default.register(
204
+ (_userData, bytesPtr, bytesLen) => this.feedInbound(bytesPtr, bytesLen),
205
+ this.lib.outboundCallbackType
206
+ );
207
+ this.connectionId = this.lib.connectionOpen(
208
+ this.serverId,
209
+ this.outboundCallback,
210
+ null,
211
+ null,
212
+ 0,
213
+ null,
214
+ 0,
215
+ null,
216
+ 0
217
+ );
218
+ if (!this.connectionId) {
219
+ this.unregisterCallback();
220
+ await this.shutdownHost();
221
+ this.serverId = 0;
222
+ throw new Error("copilot_runtime_connection_open failed.");
223
+ }
224
+ this.keepAliveTimer = setInterval(() => {
225
+ }, KEEP_ALIVE_INTERVAL_MS);
226
+ } finally {
227
+ this.starting = false;
228
+ if (this.disposed) {
229
+ await this.tryFinalizeCleanup();
230
+ }
231
+ }
232
+ }
233
+ writeFrame(frame) {
234
+ if (this.disposed || !this.connectionId) {
235
+ throw new Error("The in-process runtime connection is closed.");
236
+ }
237
+ const ok = this.lib.connectionWrite(this.connectionId, frame, frame.length);
238
+ if (!ok) {
239
+ throw new Error("Failed to write a frame to the in-process runtime connection.");
240
+ }
241
+ }
242
+ configureUiThread(enabled) {
243
+ if (this.disposed || !this.lib.connectionSetUiThreadHandler(this.connectionId, enabled)) {
244
+ throw new Error("Failed to configure the in-process UI dispatcher.");
245
+ }
246
+ }
247
+ runUiAction(actionId) {
248
+ if (!Number.isInteger(actionId) || actionId < 0 || actionId > 4294967295) {
249
+ throw new RangeError("UI action ID must be an unsigned 32-bit integer.");
250
+ }
251
+ if (this.disposed || !this.lib.connectionRunUiAction(this.connectionId, actionId)) {
252
+ throw new Error(
253
+ "Native UI action is retired, already executed, or not running on the process main thread."
254
+ );
255
+ }
256
+ }
257
+ /**
258
+ * Native outbound (server→client) callback. koffi delivers it on the JS event loop
259
+ * via a threadsafe function, so the frame is decoded and written straight to
260
+ * {@link receiveStream}. The native pointer is only valid for this call, so the
261
+ * bytes are copied out before returning.
262
+ */
263
+ feedInbound(bytesPtr, bytesLen) {
264
+ try {
265
+ if (this.disposed || this.receiveStream.writableEnded) {
266
+ return;
267
+ }
268
+ const length = Number(bytesLen);
269
+ if (!bytesPtr || length <= 0) {
270
+ return;
271
+ }
272
+ const bytes = import_koffi.default.decode(
273
+ bytesPtr,
274
+ import_koffi.default.array("uint8", length, "Typed")
275
+ );
276
+ this.receiveStream.write(Buffer.from(bytes));
277
+ } catch (error) {
278
+ console.error(
279
+ `In-process FFI inbound callback failed: ${error instanceof Error ? error.stack ?? error.message : String(error)}`
280
+ );
281
+ }
282
+ }
283
+ shutdownHost() {
284
+ return new Promise((resolvePromise, rejectPromise) => {
285
+ this.lib.hostShutdown.async(this.serverId, (error, result) => {
286
+ if (error) {
287
+ rejectPromise(error);
288
+ } else {
289
+ resolvePromise(result);
290
+ }
291
+ });
292
+ });
293
+ }
294
+ unregisterCallback() {
295
+ if (this.outboundCallback === void 0) {
296
+ return true;
297
+ }
298
+ const callback = this.outboundCallback;
299
+ try {
300
+ import_koffi.default.unregister(callback);
301
+ this.outboundCallback = void 0;
302
+ return true;
303
+ } catch (error) {
304
+ console.error(
305
+ `Failed to unregister in-process FFI callback: ${error instanceof Error ? error.stack ?? error.message : String(error)}`
306
+ );
307
+ FfiRuntimeHost.quarantinedHosts.add(this);
308
+ return false;
309
+ }
310
+ }
311
+ scheduleCleanupRetry() {
312
+ if (this.cleanupRetryTimer !== void 0) {
313
+ return;
314
+ }
315
+ this.cleanupRetryTimer = setTimeout(() => {
316
+ this.cleanupRetryTimer = void 0;
317
+ void this.tryFinalizeCleanup();
318
+ }, CLEANUP_RETRY_INTERVAL_MS);
319
+ }
320
+ async tryFinalizeCleanup() {
321
+ if (this.cleanupInProgress) {
322
+ this.scheduleCleanupRetry();
323
+ return;
324
+ }
325
+ this.cleanupInProgress = true;
326
+ try {
327
+ if (this.connectionId) {
328
+ let closed = false;
329
+ try {
330
+ closed = await new Promise((resolvePromise, rejectPromise) => {
331
+ this.lib.connectionClose.async(
332
+ this.connectionId,
333
+ (error, result) => {
334
+ if (error) {
335
+ rejectPromise(error);
336
+ } else {
337
+ resolvePromise(result);
338
+ }
339
+ }
340
+ );
341
+ });
342
+ } catch (error) {
343
+ console.error(
344
+ `Failed to close in-process FFI connection: ${error instanceof Error ? error.stack ?? error.message : String(error)}`
345
+ );
346
+ FfiRuntimeHost.quarantinedHosts.add(this);
347
+ if (this.keepAliveTimer !== void 0) {
348
+ clearInterval(this.keepAliveTimer);
349
+ this.keepAliveTimer = void 0;
350
+ }
351
+ return;
352
+ }
353
+ if (!closed) {
354
+ this.scheduleCleanupRetry();
355
+ return;
356
+ }
357
+ this.connectionId = 0;
358
+ }
359
+ const callbackUnregistered = this.unregisterCallback();
360
+ if (this.keepAliveTimer !== void 0) {
361
+ clearInterval(this.keepAliveTimer);
362
+ this.keepAliveTimer = void 0;
363
+ }
364
+ if (this.serverId) {
365
+ try {
366
+ if (!await this.shutdownHost()) {
367
+ console.error(
368
+ `In-process FFI host shutdown did not recognize server ${this.serverId}.`
369
+ );
370
+ }
371
+ } catch (error) {
372
+ console.error(
373
+ `Failed to shut down in-process FFI host: ${error instanceof Error ? error.stack ?? error.message : String(error)}`
374
+ );
375
+ }
376
+ this.serverId = 0;
377
+ }
378
+ if (callbackUnregistered) {
379
+ FfiRuntimeHost.quarantinedHosts.delete(this);
380
+ }
381
+ } finally {
382
+ this.cleanupInProgress = false;
383
+ }
384
+ }
385
+ /** Awaits the initial cleanup attempt; a non-quiescent close is retried in the background. */
386
+ async dispose() {
387
+ if (this.disposed) {
388
+ return;
389
+ }
390
+ this.disposed = true;
391
+ this.receiveStream.end();
392
+ if (!this.starting) {
393
+ await this.tryFinalizeCleanup();
394
+ }
395
+ }
396
+ }
397
+ // Annotate the CommonJS export names for ESM import in node:
398
+ 0 && (module.exports = {
399
+ FfiRuntimeHost
400
+ });