happy-imou-cloud 2.1.49 → 2.1.51

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 (55) hide show
  1. package/dist/AcpBackend-CqO3D07V.mjs +2619 -0
  2. package/dist/AcpBackend-XPiTd6ph.cjs +2621 -0
  3. package/dist/{BaseReasoningProcessor-Dn9NcoHz.cjs → BaseReasoningProcessor-BD9tiwep.cjs} +1 -144
  4. package/dist/{BaseReasoningProcessor-CAVeOdyo.mjs → BaseReasoningProcessor-CjlayL2f.mjs} +2 -144
  5. package/dist/ConversationHistory-Bl2doTA-.cjs +780 -0
  6. package/dist/ConversationHistory-CI5bBfuA.mjs +771 -0
  7. package/dist/{ProviderSelectionHandler-BJJc7qOR.cjs → ProviderSelectionHandler-C7GE5QjX.cjs} +6 -6
  8. package/dist/{ProviderSelectionHandler-DIYidT13.mjs → ProviderSelectionHandler-uQ8jzdzr.mjs} +2 -2
  9. package/dist/RuntimeShell-BDt42io_.mjs +252 -0
  10. package/dist/RuntimeShell-D_Te12wq.cjs +258 -0
  11. package/dist/bootstrapManagedProviderSession-Bln-TwyB.cjs +147 -0
  12. package/dist/bootstrapManagedProviderSession-D2Z6YU3n.mjs +145 -0
  13. package/dist/claude-BKNT-2fG.cjs +1080 -0
  14. package/dist/claude-CnN5WCWj.mjs +1073 -0
  15. package/dist/codex-DLGP8WF6.mjs +577 -0
  16. package/dist/codex-Fv2eali8.cjs +582 -0
  17. package/dist/{command-VcH4hbhi.cjs → command-BWPlJyCN.cjs} +16 -8
  18. package/dist/{command-CzfRRhVe.mjs → command-CELwsYoG.mjs} +15 -7
  19. package/dist/config-CFL0Gkqt.cjs +184 -0
  20. package/dist/config-ChSPe7p9.mjs +174 -0
  21. package/dist/createDefaultRuntimeShell-BXu3vCvT.cjs +33 -0
  22. package/dist/createDefaultRuntimeShell-DOg6g3-G.mjs +31 -0
  23. package/dist/cursor-Blq1cHdr.cjs +91 -0
  24. package/dist/cursor-CwPNSy_A.mjs +88 -0
  25. package/dist/future-Dq4Ha1Dn.cjs +24 -0
  26. package/dist/future-xRdLl3vf.mjs +22 -0
  27. package/dist/{index-xa1kwZoj.cjs → index-B_JYgMUS.cjs} +189 -5352
  28. package/dist/{index-7Z93BoVn.mjs → index-CX-F_fuk.mjs} +177 -5331
  29. package/dist/index.cjs +2 -2
  30. package/dist/index.mjs +2 -2
  31. package/dist/installFatalProcessHandlers-0vaw9MAz.mjs +55 -0
  32. package/dist/installFatalProcessHandlers-CyURn5Bp.cjs +57 -0
  33. package/dist/launch-BoCCEd5p.mjs +63 -0
  34. package/dist/launch-wZA5BcvS.cjs +66 -0
  35. package/dist/lib.cjs +2 -3
  36. package/dist/lib.d.cts +20 -17
  37. package/dist/lib.d.mts +20 -17
  38. package/dist/lib.mjs +1 -2
  39. package/dist/resolveCommand-B3BGyBE2.mjs +189 -0
  40. package/dist/resolveCommand-DYMd9PNC.cjs +193 -0
  41. package/dist/{runClaude-zCwRhpOw.mjs → runClaude-Be0myF9k.mjs} +8 -5
  42. package/dist/{runClaude-BBGNmGj6.cjs → runClaude-DZJt5er7.cjs} +46 -43
  43. package/dist/{runCodex-BbgLVjb9.mjs → runCodex-BSnyN4m7.mjs} +226 -117
  44. package/dist/{runCodex-jUU6U2tZ.cjs → runCodex-DTCcGRue.cjs} +269 -160
  45. package/dist/runCursor-Bn1PuwJy.cjs +506 -0
  46. package/dist/runCursor-M6dQ6bGF.mjs +504 -0
  47. package/dist/{runGemini-DcwNsudA.mjs → runGemini-BNm4vYKA.mjs} +279 -5
  48. package/dist/{runGemini-C0NT8MHK.cjs → runGemini-Bn3lFhz6.cjs} +309 -35
  49. package/dist/{registerKillSessionHandler-DLDg2EES.mjs → sessionControl-1bT_7OI6.mjs} +1643 -2405
  50. package/dist/{registerKillSessionHandler-CfCya6si.cjs → sessionControl-flKnQrx0.cjs} +1647 -2417
  51. package/dist/{api-DnqaNvyV.mjs → types-B5vtxa38.mjs} +55 -5
  52. package/dist/{api-D7nAeZi7.cjs → types-CttABk32.cjs} +55 -4
  53. package/package.json +2 -2
  54. package/dist/types-CiliQpqS.mjs +0 -52
  55. package/dist/types-DVk3crez.cjs +0 -54
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var persistence = require('./api-D7nAeZi7.cjs');
4
- var registerKillSessionHandler = require('./registerKillSessionHandler-CfCya6si.cjs');
3
+ var persistence = require('./types-CttABk32.cjs');
4
+ var sessionControl = require('./sessionControl-flKnQrx0.cjs');
5
5
 
6
6
  async function runModeLoop(opts) {
7
7
  let currentMode = opts.startingMode;
@@ -75,7 +75,7 @@ class ProviderSelectionHandler {
75
75
  };
76
76
  pending.timeoutHandle = setTimeout(() => {
77
77
  this.handleSelectionTimeout(request.id, pending);
78
- }, registerKillSessionHandler.getPendingInteractionTimeoutMs());
78
+ }, sessionControl.getPendingInteractionTimeoutMs());
79
79
  this.pendingRequests.set(request.id, pending);
80
80
  this.session.updateAgentState((currentState) => ({
81
81
  ...currentState,
@@ -111,7 +111,7 @@ class ProviderSelectionHandler {
111
111
  hasPendingRequests() {
112
112
  return this.pendingRequests.size > 0;
113
113
  }
114
- supersedePendingRequests(reason = registerKillSessionHandler.INTERACTION_SUPERSEDED_ERROR) {
114
+ supersedePendingRequests(reason = sessionControl.INTERACTION_SUPERSEDED_ERROR) {
115
115
  const pendingSnapshot = Array.from(this.pendingRequests.entries());
116
116
  if (pendingSnapshot.length === 0) {
117
117
  return 0;
@@ -223,7 +223,7 @@ class ProviderSelectionHandler {
223
223
  }
224
224
  this.pendingRequests.delete(requestId);
225
225
  this.clearPendingRequestTimeout(active);
226
- active.reject(new Error(registerKillSessionHandler.INTERACTION_TIMED_OUT_ERROR));
226
+ active.reject(new Error(sessionControl.INTERACTION_TIMED_OUT_ERROR));
227
227
  this.session.updateAgentState((currentState) => {
228
228
  const request = currentState.requests?.[requestId] || {
229
229
  tool: "AskUserQuestion",
@@ -246,7 +246,7 @@ class ProviderSelectionHandler {
246
246
  ...request,
247
247
  completedAt: Date.now(),
248
248
  status: "canceled",
249
- reason: registerKillSessionHandler.INTERACTION_TIMED_OUT_ERROR,
249
+ reason: sessionControl.INTERACTION_TIMED_OUT_ERROR,
250
250
  requestKind: "selection"
251
251
  }
252
252
  }
@@ -1,5 +1,5 @@
1
- import { l as logger } from './api-DnqaNvyV.mjs';
2
- import { g as getPendingInteractionTimeoutMs, I as INTERACTION_SUPERSEDED_ERROR, a as INTERACTION_TIMED_OUT_ERROR } from './registerKillSessionHandler-DLDg2EES.mjs';
1
+ import { l as logger } from './types-B5vtxa38.mjs';
2
+ import { g as getPendingInteractionTimeoutMs, I as INTERACTION_SUPERSEDED_ERROR, a as INTERACTION_TIMED_OUT_ERROR } from './sessionControl-1bT_7OI6.mjs';
3
3
 
4
4
  async function runModeLoop(opts) {
5
5
  let currentMode = opts.startingMode;
@@ -0,0 +1,252 @@
1
+ import 'cross-spawn';
2
+ import '@agentclientprotocol/sdk';
3
+ import 'node:crypto';
4
+ import './types-B5vtxa38.mjs';
5
+ import './index-CX-F_fuk.mjs';
6
+ import 'ps-list';
7
+ import 'fs';
8
+ import 'path';
9
+ import 'os';
10
+ import 'child_process';
11
+ import 'node:fs';
12
+ import 'node:path';
13
+ import 'node:os';
14
+ import 'node:child_process';
15
+ import 'node:readline';
16
+
17
+ class AgentRegistry {
18
+ factories = /* @__PURE__ */ new Map();
19
+ /**
20
+ * Register a factory function for an agent type.
21
+ *
22
+ * @param id - The agent identifier
23
+ * @param factory - Factory function to create the backend
24
+ */
25
+ register(id, factory) {
26
+ this.factories.set(id, factory);
27
+ }
28
+ /**
29
+ * Check if an agent type is registered.
30
+ *
31
+ * @param id - The agent identifier to check
32
+ * @returns true if the agent is registered
33
+ */
34
+ has(id) {
35
+ return this.factories.has(id);
36
+ }
37
+ /**
38
+ * Get the list of registered agent identifiers.
39
+ *
40
+ * @returns Array of registered agent IDs
41
+ */
42
+ list() {
43
+ return Array.from(this.factories.keys());
44
+ }
45
+ /**
46
+ * Create an agent backend instance.
47
+ *
48
+ * @param id - The agent identifier
49
+ * @param opts - Options for creating the backend
50
+ * @returns The created agent backend
51
+ * @throws Error if the agent type is not registered
52
+ */
53
+ create(id, opts) {
54
+ const factory = this.factories.get(id);
55
+ if (!factory) {
56
+ const available = this.list().join(", ") || "none";
57
+ throw new Error(`Unknown agent: ${id}. Available agents: ${available}`);
58
+ }
59
+ return factory(opts);
60
+ }
61
+ }
62
+ const agentRegistry = new AgentRegistry();
63
+
64
+ const PREFERRED_MESSAGE_FIELDS = ["stderr", "error", "message", "detail", "stdout", "text", "reason"];
65
+ function safeSerializeDisplayValue(value) {
66
+ const seen = /* @__PURE__ */ new WeakSet();
67
+ try {
68
+ const serialized = JSON.stringify(value, (_key, currentValue) => {
69
+ if (typeof currentValue === "bigint") {
70
+ return currentValue.toString();
71
+ }
72
+ if (currentValue instanceof Error) {
73
+ return {
74
+ name: currentValue.name,
75
+ message: currentValue.message,
76
+ stack: currentValue.stack
77
+ };
78
+ }
79
+ if (typeof currentValue === "object" && currentValue !== null) {
80
+ if (seen.has(currentValue)) {
81
+ return "[Circular]";
82
+ }
83
+ seen.add(currentValue);
84
+ }
85
+ return currentValue;
86
+ });
87
+ return serialized ?? String(value);
88
+ } catch {
89
+ return String(value);
90
+ }
91
+ }
92
+ function formatDisplayMessage(value, seen = /* @__PURE__ */ new WeakSet()) {
93
+ if (typeof value === "string") {
94
+ return value;
95
+ }
96
+ if (value instanceof Error) {
97
+ return value.message || String(value);
98
+ }
99
+ if (value === null || value === void 0) {
100
+ return "";
101
+ }
102
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(value)) {
103
+ return value.toString("utf8");
104
+ }
105
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
106
+ return String(value);
107
+ }
108
+ if (typeof value === "object") {
109
+ if (seen.has(value)) {
110
+ return "[Circular]";
111
+ }
112
+ seen.add(value);
113
+ const record = value;
114
+ for (const field of PREFERRED_MESSAGE_FIELDS) {
115
+ if (!(field in record)) {
116
+ continue;
117
+ }
118
+ const formattedField = formatDisplayMessage(record[field], seen).trim();
119
+ if (formattedField.length > 0) {
120
+ return formattedField;
121
+ }
122
+ }
123
+ return safeSerializeDisplayValue(value);
124
+ }
125
+ return String(value);
126
+ }
127
+ function truncateDisplayMessage(value, maxLength) {
128
+ const formatted = formatDisplayMessage(value);
129
+ if (formatted.length <= maxLength) {
130
+ return formatted;
131
+ }
132
+ return `${formatted.substring(0, maxLength)}...`;
133
+ }
134
+
135
+ function isRecord(value) {
136
+ return !!value && typeof value === "object" && !Array.isArray(value);
137
+ }
138
+ function hasOnlyAllowedKeys(record, allowedKeys) {
139
+ return Object.keys(record).every((key) => allowedKeys.includes(key));
140
+ }
141
+ function isTerminalReferenceItem(value) {
142
+ if (!isRecord(value)) {
143
+ return false;
144
+ }
145
+ const hasTerminalId = typeof value.terminalId === "string" && value.terminalId.length > 0 || typeof value.terminal_id === "string" && value.terminal_id.length > 0;
146
+ return hasTerminalId && value.type === "terminal" && hasOnlyAllowedKeys(value, ["terminalId", "terminal_id", "type", "id"]);
147
+ }
148
+ function isTerminalReferenceOnlyPayload(value) {
149
+ if (Array.isArray(value)) {
150
+ return value.length > 0 && value.every((entry) => isTerminalReferenceOnlyPayload(entry));
151
+ }
152
+ if (!isRecord(value)) {
153
+ return false;
154
+ }
155
+ if (isTerminalReferenceItem(value)) {
156
+ return true;
157
+ }
158
+ const items = Array.isArray(value.items) ? value.items : null;
159
+ if (items && items.length > 0 && items.every((entry) => isTerminalReferenceOnlyPayload(entry)) && hasOnlyAllowedKeys(value, ["items", "type"])) {
160
+ return true;
161
+ }
162
+ const content = "content" in value ? value.content : void 0;
163
+ if (content !== void 0 && isTerminalReferenceOnlyPayload(content) && hasOnlyAllowedKeys(value, ["content", "type"])) {
164
+ return true;
165
+ }
166
+ return false;
167
+ }
168
+
169
+ class InMemoryRuntimeEventBuffer {
170
+ events = [];
171
+ maxEvents;
172
+ constructor(maxEvents = 64) {
173
+ this.maxEvents = Math.max(1, maxEvents);
174
+ }
175
+ push(event) {
176
+ this.events.push(event);
177
+ while (this.events.length > this.maxEvents) {
178
+ this.events.shift();
179
+ }
180
+ }
181
+ drain() {
182
+ return this.events.splice(0, this.events.length);
183
+ }
184
+ }
185
+ class RuntimeShell {
186
+ registry;
187
+ constructor(registry = agentRegistry) {
188
+ this.registry = registry;
189
+ }
190
+ supports(provider) {
191
+ return this.registry.has(provider);
192
+ }
193
+ async launch(opts) {
194
+ if (!opts.createBackend && !this.registry.has(opts.provider)) {
195
+ throw new Error(`Runtime provider "${opts.provider}" is not registered`);
196
+ }
197
+ const backendFactory = opts.createBackend ?? ((factoryOpts) => this.registry.create(opts.provider, factoryOpts));
198
+ const backend = backendFactory({
199
+ cwd: opts.cwd,
200
+ env: opts.env
201
+ });
202
+ const handlers = /* @__PURE__ */ new Set();
203
+ const eventBuffer = new InMemoryRuntimeEventBuffer();
204
+ const fanout = (message) => {
205
+ if (handlers.size === 0) {
206
+ eventBuffer.push(message);
207
+ }
208
+ for (const handler of handlers) {
209
+ handler(message);
210
+ }
211
+ };
212
+ backend.onMessage(fanout);
213
+ const started = await backend.startSession(opts.initialPrompt);
214
+ return {
215
+ provider: opts.provider,
216
+ backend,
217
+ sessionId: started.sessionId,
218
+ sendPrompt: async (prompt) => {
219
+ await backend.sendPrompt(started.sessionId, prompt);
220
+ },
221
+ cancel: async () => {
222
+ await backend.cancel(started.sessionId);
223
+ },
224
+ respondToPermission: async (requestId, approved) => {
225
+ if (!backend.respondToPermission) {
226
+ throw new Error(`Runtime provider "${opts.provider}" does not support permission responses`);
227
+ }
228
+ await backend.respondToPermission(requestId, approved);
229
+ },
230
+ waitForResponseComplete: async (timeoutMs) => {
231
+ if (!backend.waitForResponseComplete) {
232
+ return;
233
+ }
234
+ await backend.waitForResponseComplete(timeoutMs);
235
+ },
236
+ dispose: async () => {
237
+ await backend.dispose();
238
+ },
239
+ onMessage: (handler) => {
240
+ for (const buffered of eventBuffer.drain()) {
241
+ handler(buffered);
242
+ }
243
+ handlers.add(handler);
244
+ return () => {
245
+ handlers.delete(handler);
246
+ };
247
+ }
248
+ };
249
+ }
250
+ }
251
+
252
+ export { RuntimeShell as R, agentRegistry as a, formatDisplayMessage as f, isTerminalReferenceOnlyPayload as i, truncateDisplayMessage as t };
@@ -0,0 +1,258 @@
1
+ 'use strict';
2
+
3
+ require('cross-spawn');
4
+ require('@agentclientprotocol/sdk');
5
+ require('node:crypto');
6
+ require('./types-CttABk32.cjs');
7
+ require('./index-B_JYgMUS.cjs');
8
+ require('ps-list');
9
+ require('fs');
10
+ require('path');
11
+ require('os');
12
+ require('child_process');
13
+ require('node:fs');
14
+ require('node:path');
15
+ require('node:os');
16
+ require('node:child_process');
17
+ require('node:readline');
18
+
19
+ class AgentRegistry {
20
+ factories = /* @__PURE__ */ new Map();
21
+ /**
22
+ * Register a factory function for an agent type.
23
+ *
24
+ * @param id - The agent identifier
25
+ * @param factory - Factory function to create the backend
26
+ */
27
+ register(id, factory) {
28
+ this.factories.set(id, factory);
29
+ }
30
+ /**
31
+ * Check if an agent type is registered.
32
+ *
33
+ * @param id - The agent identifier to check
34
+ * @returns true if the agent is registered
35
+ */
36
+ has(id) {
37
+ return this.factories.has(id);
38
+ }
39
+ /**
40
+ * Get the list of registered agent identifiers.
41
+ *
42
+ * @returns Array of registered agent IDs
43
+ */
44
+ list() {
45
+ return Array.from(this.factories.keys());
46
+ }
47
+ /**
48
+ * Create an agent backend instance.
49
+ *
50
+ * @param id - The agent identifier
51
+ * @param opts - Options for creating the backend
52
+ * @returns The created agent backend
53
+ * @throws Error if the agent type is not registered
54
+ */
55
+ create(id, opts) {
56
+ const factory = this.factories.get(id);
57
+ if (!factory) {
58
+ const available = this.list().join(", ") || "none";
59
+ throw new Error(`Unknown agent: ${id}. Available agents: ${available}`);
60
+ }
61
+ return factory(opts);
62
+ }
63
+ }
64
+ const agentRegistry = new AgentRegistry();
65
+
66
+ const PREFERRED_MESSAGE_FIELDS = ["stderr", "error", "message", "detail", "stdout", "text", "reason"];
67
+ function safeSerializeDisplayValue(value) {
68
+ const seen = /* @__PURE__ */ new WeakSet();
69
+ try {
70
+ const serialized = JSON.stringify(value, (_key, currentValue) => {
71
+ if (typeof currentValue === "bigint") {
72
+ return currentValue.toString();
73
+ }
74
+ if (currentValue instanceof Error) {
75
+ return {
76
+ name: currentValue.name,
77
+ message: currentValue.message,
78
+ stack: currentValue.stack
79
+ };
80
+ }
81
+ if (typeof currentValue === "object" && currentValue !== null) {
82
+ if (seen.has(currentValue)) {
83
+ return "[Circular]";
84
+ }
85
+ seen.add(currentValue);
86
+ }
87
+ return currentValue;
88
+ });
89
+ return serialized ?? String(value);
90
+ } catch {
91
+ return String(value);
92
+ }
93
+ }
94
+ function formatDisplayMessage(value, seen = /* @__PURE__ */ new WeakSet()) {
95
+ if (typeof value === "string") {
96
+ return value;
97
+ }
98
+ if (value instanceof Error) {
99
+ return value.message || String(value);
100
+ }
101
+ if (value === null || value === void 0) {
102
+ return "";
103
+ }
104
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(value)) {
105
+ return value.toString("utf8");
106
+ }
107
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
108
+ return String(value);
109
+ }
110
+ if (typeof value === "object") {
111
+ if (seen.has(value)) {
112
+ return "[Circular]";
113
+ }
114
+ seen.add(value);
115
+ const record = value;
116
+ for (const field of PREFERRED_MESSAGE_FIELDS) {
117
+ if (!(field in record)) {
118
+ continue;
119
+ }
120
+ const formattedField = formatDisplayMessage(record[field], seen).trim();
121
+ if (formattedField.length > 0) {
122
+ return formattedField;
123
+ }
124
+ }
125
+ return safeSerializeDisplayValue(value);
126
+ }
127
+ return String(value);
128
+ }
129
+ function truncateDisplayMessage(value, maxLength) {
130
+ const formatted = formatDisplayMessage(value);
131
+ if (formatted.length <= maxLength) {
132
+ return formatted;
133
+ }
134
+ return `${formatted.substring(0, maxLength)}...`;
135
+ }
136
+
137
+ function isRecord(value) {
138
+ return !!value && typeof value === "object" && !Array.isArray(value);
139
+ }
140
+ function hasOnlyAllowedKeys(record, allowedKeys) {
141
+ return Object.keys(record).every((key) => allowedKeys.includes(key));
142
+ }
143
+ function isTerminalReferenceItem(value) {
144
+ if (!isRecord(value)) {
145
+ return false;
146
+ }
147
+ const hasTerminalId = typeof value.terminalId === "string" && value.terminalId.length > 0 || typeof value.terminal_id === "string" && value.terminal_id.length > 0;
148
+ return hasTerminalId && value.type === "terminal" && hasOnlyAllowedKeys(value, ["terminalId", "terminal_id", "type", "id"]);
149
+ }
150
+ function isTerminalReferenceOnlyPayload(value) {
151
+ if (Array.isArray(value)) {
152
+ return value.length > 0 && value.every((entry) => isTerminalReferenceOnlyPayload(entry));
153
+ }
154
+ if (!isRecord(value)) {
155
+ return false;
156
+ }
157
+ if (isTerminalReferenceItem(value)) {
158
+ return true;
159
+ }
160
+ const items = Array.isArray(value.items) ? value.items : null;
161
+ if (items && items.length > 0 && items.every((entry) => isTerminalReferenceOnlyPayload(entry)) && hasOnlyAllowedKeys(value, ["items", "type"])) {
162
+ return true;
163
+ }
164
+ const content = "content" in value ? value.content : void 0;
165
+ if (content !== void 0 && isTerminalReferenceOnlyPayload(content) && hasOnlyAllowedKeys(value, ["content", "type"])) {
166
+ return true;
167
+ }
168
+ return false;
169
+ }
170
+
171
+ class InMemoryRuntimeEventBuffer {
172
+ events = [];
173
+ maxEvents;
174
+ constructor(maxEvents = 64) {
175
+ this.maxEvents = Math.max(1, maxEvents);
176
+ }
177
+ push(event) {
178
+ this.events.push(event);
179
+ while (this.events.length > this.maxEvents) {
180
+ this.events.shift();
181
+ }
182
+ }
183
+ drain() {
184
+ return this.events.splice(0, this.events.length);
185
+ }
186
+ }
187
+ class RuntimeShell {
188
+ registry;
189
+ constructor(registry = agentRegistry) {
190
+ this.registry = registry;
191
+ }
192
+ supports(provider) {
193
+ return this.registry.has(provider);
194
+ }
195
+ async launch(opts) {
196
+ if (!opts.createBackend && !this.registry.has(opts.provider)) {
197
+ throw new Error(`Runtime provider "${opts.provider}" is not registered`);
198
+ }
199
+ const backendFactory = opts.createBackend ?? ((factoryOpts) => this.registry.create(opts.provider, factoryOpts));
200
+ const backend = backendFactory({
201
+ cwd: opts.cwd,
202
+ env: opts.env
203
+ });
204
+ const handlers = /* @__PURE__ */ new Set();
205
+ const eventBuffer = new InMemoryRuntimeEventBuffer();
206
+ const fanout = (message) => {
207
+ if (handlers.size === 0) {
208
+ eventBuffer.push(message);
209
+ }
210
+ for (const handler of handlers) {
211
+ handler(message);
212
+ }
213
+ };
214
+ backend.onMessage(fanout);
215
+ const started = await backend.startSession(opts.initialPrompt);
216
+ return {
217
+ provider: opts.provider,
218
+ backend,
219
+ sessionId: started.sessionId,
220
+ sendPrompt: async (prompt) => {
221
+ await backend.sendPrompt(started.sessionId, prompt);
222
+ },
223
+ cancel: async () => {
224
+ await backend.cancel(started.sessionId);
225
+ },
226
+ respondToPermission: async (requestId, approved) => {
227
+ if (!backend.respondToPermission) {
228
+ throw new Error(`Runtime provider "${opts.provider}" does not support permission responses`);
229
+ }
230
+ await backend.respondToPermission(requestId, approved);
231
+ },
232
+ waitForResponseComplete: async (timeoutMs) => {
233
+ if (!backend.waitForResponseComplete) {
234
+ return;
235
+ }
236
+ await backend.waitForResponseComplete(timeoutMs);
237
+ },
238
+ dispose: async () => {
239
+ await backend.dispose();
240
+ },
241
+ onMessage: (handler) => {
242
+ for (const buffered of eventBuffer.drain()) {
243
+ handler(buffered);
244
+ }
245
+ handlers.add(handler);
246
+ return () => {
247
+ handlers.delete(handler);
248
+ };
249
+ }
250
+ };
251
+ }
252
+ }
253
+
254
+ exports.RuntimeShell = RuntimeShell;
255
+ exports.agentRegistry = agentRegistry;
256
+ exports.formatDisplayMessage = formatDisplayMessage;
257
+ exports.isTerminalReferenceOnlyPayload = isTerminalReferenceOnlyPayload;
258
+ exports.truncateDisplayMessage = truncateDisplayMessage;
@@ -0,0 +1,147 @@
1
+ 'use strict';
2
+
3
+ var index = require('./index-B_JYgMUS.cjs');
4
+ var persistence = require('./types-CttABk32.cjs');
5
+ var node_events = require('node:events');
6
+
7
+ function createOfflineSessionStub(sessionTag) {
8
+ const emitter = new node_events.EventEmitter();
9
+ let metadata = null;
10
+ let agentState = null;
11
+ const stub = {
12
+ sessionId: `offline-${sessionTag}`,
13
+ sendCodexMessage: () => {
14
+ },
15
+ sendAgentMessage: () => {
16
+ },
17
+ sendClaudeSessionMessage: () => {
18
+ },
19
+ keepAlive: () => {
20
+ },
21
+ sendSessionEvent: () => {
22
+ },
23
+ sendSessionDeath: () => {
24
+ },
25
+ updateLifecycleState: () => {
26
+ },
27
+ requestControlTransfer: async () => {
28
+ },
29
+ flush: async () => {
30
+ },
31
+ close: async () => {
32
+ },
33
+ updateMetadata: (handler) => {
34
+ metadata = handler(metadata || {});
35
+ emitter.emit("metadata-updated", metadata);
36
+ },
37
+ updateAgentState: (handler) => {
38
+ agentState = handler(agentState || {});
39
+ emitter.emit("agent-state-updated", agentState);
40
+ },
41
+ getMetadataSnapshot: () => metadata,
42
+ getAgentStateSnapshot: () => agentState,
43
+ waitForMetadataUpdate: async () => metadata,
44
+ onUserMessage: () => {
45
+ },
46
+ onSessionMessage: () => {
47
+ },
48
+ configureProtocolV3Sync: () => {
49
+ },
50
+ rpcHandlerManager: {
51
+ registerHandler: () => {
52
+ }
53
+ },
54
+ on: emitter.on.bind(emitter),
55
+ once: emitter.once.bind(emitter),
56
+ off: emitter.off.bind(emitter),
57
+ emit: emitter.emit.bind(emitter)
58
+ };
59
+ return stub;
60
+ }
61
+
62
+ function setupOfflineReconnection(opts) {
63
+ const { api, sessionTag, metadata, state, response, onSessionSwap } = opts;
64
+ let session;
65
+ let reconnectionHandle = null;
66
+ if (!response) {
67
+ session = createOfflineSessionStub(sessionTag);
68
+ reconnectionHandle = persistence.startOfflineReconnection({
69
+ serverUrl: persistence.configuration.serverUrl,
70
+ onReconnected: async () => {
71
+ const resp = await api.getOrCreateSession({ tag: sessionTag, metadata, state });
72
+ if (!resp) throw new Error("Server unavailable");
73
+ const realSession = api.sessionSyncClient(resp);
74
+ onSessionSwap(realSession);
75
+ return realSession;
76
+ },
77
+ onNotify: (msg) => {
78
+ console.log(msg);
79
+ }
80
+ });
81
+ return { session, reconnectionHandle, isOffline: true };
82
+ } else {
83
+ session = api.sessionSyncClient(response);
84
+ return { session, reconnectionHandle: null, isOffline: false };
85
+ }
86
+ }
87
+
88
+ async function bootstrapManagedProviderSession(opts) {
89
+ const { state, metadata, happyOrgStartupBinding } = index.createSessionMetadata({
90
+ flavor: opts.flavor,
91
+ machineId: opts.machineId,
92
+ startedBy: opts.startedBy,
93
+ managedSessionTag: opts.startedBy === "daemon" && (opts.flavor === "codex" || opts.flavor === "cursor") ? opts.sessionTag : void 0
94
+ });
95
+ const reconcileAttachedSessionMetadata = (session2) => {
96
+ if (!opts.reconcileMetadataOnAttach) {
97
+ return;
98
+ }
99
+ try {
100
+ session2.updateMetadata(() => metadata);
101
+ } catch (error) {
102
+ persistence.logger.debug(`[managed-session] Failed to reconcile metadata for ${opts.flavor} session`, error);
103
+ }
104
+ };
105
+ let response = null;
106
+ try {
107
+ response = await opts.api.getOrCreateSession({
108
+ tag: opts.sessionTag,
109
+ metadata,
110
+ state,
111
+ stableDataKeyPath: ["managed-session-tag", opts.sessionTag]
112
+ });
113
+ } catch (error) {
114
+ if (!persistence.isAuthenticationRequiredError(error)) {
115
+ throw error;
116
+ }
117
+ persistence.logger.debug(opts.authFallbackLogMessage);
118
+ }
119
+ const { session, reconnectionHandle } = setupOfflineReconnection({
120
+ api: opts.api,
121
+ sessionTag: opts.sessionTag,
122
+ metadata,
123
+ state,
124
+ response,
125
+ onSessionSwap: (newSession) => {
126
+ opts.onSessionSwap?.(newSession, metadata);
127
+ reconcileAttachedSessionMetadata(newSession);
128
+ void index.publishSessionRegistration(newSession.sessionId, metadata);
129
+ }
130
+ });
131
+ if (response) {
132
+ reconcileAttachedSessionMetadata(session);
133
+ }
134
+ if (response) {
135
+ await index.publishSessionRegistration(response.id, metadata);
136
+ }
137
+ return {
138
+ state,
139
+ metadata,
140
+ happyOrgStartupBinding,
141
+ response,
142
+ session,
143
+ reconnectionHandle
144
+ };
145
+ }
146
+
147
+ exports.bootstrapManagedProviderSession = bootstrapManagedProviderSession;