happy-imou-cloud 2.0.21 → 2.0.23

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 (29) hide show
  1. package/dist/{BaseReasoningProcessor-0nj-PMFc.cjs → BaseReasoningProcessor-BzbDRBqp.cjs} +3 -3
  2. package/dist/{BaseReasoningProcessor-DnVC7liC.mjs → BaseReasoningProcessor-DH3BCCTf.mjs} +3 -3
  3. package/dist/ProviderSelectionHandler-CbkbtIRC.mjs +673 -0
  4. package/dist/ProviderSelectionHandler-meVvz9NZ.cjs +680 -0
  5. package/dist/{api-MGlKcEf3.cjs → api-C4bF6GEA.cjs} +35 -3
  6. package/dist/{api-DJe9WP9M.mjs → api-DX7Vg4Hz.mjs} +35 -4
  7. package/dist/{command-DAlFmWmr.cjs → command-CF6Wi_v2.cjs} +3 -3
  8. package/dist/{command-CfyFnMv2.mjs → command-DicPZ-Up.mjs} +3 -3
  9. package/dist/{index-CgVjDJpt.cjs → index-BybqdOf2.cjs} +63 -15
  10. package/dist/{index-CHXCgpwi.mjs → index-CEJmASSW.mjs} +60 -12
  11. package/dist/index.cjs +3 -3
  12. package/dist/index.mjs +3 -3
  13. package/dist/lib.cjs +1 -1
  14. package/dist/lib.d.cts +108 -105
  15. package/dist/lib.d.mts +108 -105
  16. package/dist/lib.mjs +1 -1
  17. package/dist/{persistence-DLFUNI9q.cjs → persistence-CdqBfAwo.cjs} +1 -1
  18. package/dist/{persistence-CkP90vEt.mjs → persistence-xypxp7ei.mjs} +1 -1
  19. package/dist/{registerKillSessionHandler-Cs_INk4A.cjs → registerKillSessionHandler-BK3fZIch.cjs} +14 -364
  20. package/dist/{registerKillSessionHandler-DsHTZDsU.mjs → registerKillSessionHandler-BNN-_qNu.mjs} +15 -362
  21. package/dist/{runClaude-DAQAEmHe.mjs → runClaude-B-ex_tr3.mjs} +8 -6
  22. package/dist/{runClaude-BGSgcyUp.cjs → runClaude-CT3jCZjH.cjs} +11 -9
  23. package/dist/{runCodex-B2UpSn82.mjs → runCodex-DhbvUtJC.mjs} +9 -7
  24. package/dist/{runCodex-earICaxw.cjs → runCodex-DodH9jhh.cjs} +12 -10
  25. package/dist/{runGemini-BBUmH1Qh.mjs → runGemini-BsFR5Pd3.mjs} +12 -74
  26. package/dist/{runGemini-D5RAIaR0.cjs → runGemini-CeHCZ1l4.cjs} +12 -74
  27. package/package.json +1 -1
  28. package/dist/ProviderSelectionHandler-Bafuy28L.cjs +0 -265
  29. package/dist/ProviderSelectionHandler-R-2r7ItM.mjs +0 -261
@@ -0,0 +1,680 @@
1
+ 'use strict';
2
+
3
+ var api = require('./api-C4bF6GEA.cjs');
4
+ var registerKillSessionHandler = require('./registerKillSessionHandler-BK3fZIch.cjs');
5
+
6
+ async function runModeLoop(opts) {
7
+ let currentMode = opts.startingMode;
8
+ if (opts.notifyInitialMode) {
9
+ await opts.onModeChange?.(currentMode);
10
+ }
11
+ while (true) {
12
+ opts.onIteration?.(currentMode);
13
+ const result = await opts.launchers[currentMode]();
14
+ if (result.type === "exit") {
15
+ return result.value;
16
+ }
17
+ currentMode = result.mode;
18
+ await opts.onModeChange?.(currentMode);
19
+ }
20
+ }
21
+
22
+ function createKeepAliveController(opts) {
23
+ let thinking = opts.initialThinking ?? false;
24
+ let mode = opts.initialMode;
25
+ let disposed = false;
26
+ const sync = () => {
27
+ if (disposed) {
28
+ return;
29
+ }
30
+ opts.send(thinking, mode);
31
+ };
32
+ sync();
33
+ const intervalId = setInterval(sync, opts.intervalMs ?? 2e3);
34
+ return {
35
+ dispose: () => {
36
+ if (disposed) {
37
+ return;
38
+ }
39
+ disposed = true;
40
+ clearInterval(intervalId);
41
+ },
42
+ getMode: () => mode,
43
+ getThinking: () => thinking,
44
+ setMode: (nextMode) => {
45
+ mode = nextMode;
46
+ sync();
47
+ },
48
+ setThinking: (nextThinking) => {
49
+ thinking = nextThinking;
50
+ sync();
51
+ },
52
+ sync
53
+ };
54
+ }
55
+
56
+ function normalizeOptionalText(value) {
57
+ if (typeof value !== "string") {
58
+ return null;
59
+ }
60
+ const trimmed = value.trim();
61
+ return trimmed.length > 0 ? trimmed : null;
62
+ }
63
+ function normalizeSummaryText(value) {
64
+ const normalized = normalizeOptionalText(value);
65
+ return normalized ? normalized.replace(/\s+/g, " ").slice(0, api.HAPPY_ORG_SUMMARY_MAX_LENGTH) : null;
66
+ }
67
+ function cloneHappyOrgMetadata(happyOrg) {
68
+ return {
69
+ taskContext: happyOrg?.taskContext ? { ...happyOrg.taskContext } : void 0,
70
+ runtime: happyOrg?.runtime ? { ...happyOrg.runtime } : void 0,
71
+ activeOwner: happyOrg?.activeOwner ? { ...happyOrg.activeOwner } : null,
72
+ repeat: happyOrg?.repeat ? {
73
+ threshold: happyOrg.repeat.threshold,
74
+ fingerprints: Object.fromEntries(
75
+ Object.entries(happyOrg.repeat.fingerprints ?? {}).map(([fingerprint, entry]) => [
76
+ fingerprint,
77
+ { ...entry }
78
+ ])
79
+ )
80
+ } : void 0,
81
+ lastTurnReport: happyOrg?.lastTurnReport ? { ...happyOrg.lastTurnReport } : void 0
82
+ };
83
+ }
84
+ function normalizeHappyOrgMetadata(metadata) {
85
+ const happyOrg = cloneHappyOrgMetadata(metadata?.happyOrg);
86
+ return {
87
+ ...happyOrg,
88
+ runtime: happyOrg.runtime ?? {
89
+ status: "active",
90
+ reason: null
91
+ },
92
+ repeat: happyOrg.repeat ?? {
93
+ threshold: api.HAPPY_ORG_REPEAT_THRESHOLD,
94
+ fingerprints: {}
95
+ }
96
+ };
97
+ }
98
+ function withHappyOrgMetadata(metadata, happyOrg) {
99
+ return {
100
+ ...metadata,
101
+ happyOrg
102
+ };
103
+ }
104
+ function resetHappyOrgRuntimeForTask(taskContext) {
105
+ return {
106
+ taskContext,
107
+ runtime: {
108
+ status: "active",
109
+ reason: null
110
+ },
111
+ activeOwner: null,
112
+ repeat: {
113
+ threshold: api.HAPPY_ORG_REPEAT_THRESHOLD,
114
+ fingerprints: {}
115
+ }
116
+ };
117
+ }
118
+ function buildTerminatedStatusMessage(taskId) {
119
+ return `Task ${taskId} is terminated. Reopen it with new context, a new decision, or a new resource before continuing.`;
120
+ }
121
+ function buildMemberBusyStatusMessage(memberAgentId, activeTaskId, nextTaskId) {
122
+ return `Member ${memberAgentId} is already busy with active task ${activeTaskId}. Reject task ${nextTaskId} without continuing token usage.`;
123
+ }
124
+ function buildOwnerConflictStatusMessage(taskId, ownerAgentId) {
125
+ return `Task ${taskId} is already active under owner ${ownerAgentId}. This turn must exit without continuing token usage.`;
126
+ }
127
+ function inferDraftTurnStatus(draft) {
128
+ if (draft?.turnStatus === "turn_update" || draft?.turnStatus === "task_complete") {
129
+ return draft.turnStatus;
130
+ }
131
+ return null;
132
+ }
133
+ function inferInterventionType(draft) {
134
+ if (draft?.interventionType === "none" || draft?.interventionType === "review_needed" || draft?.interventionType === "blocker" || draft?.interventionType === "decision_needed") {
135
+ return draft.interventionType;
136
+ }
137
+ if (normalizeOptionalText(draft?.decisionNeeded)) {
138
+ return "decision_needed";
139
+ }
140
+ if (normalizeOptionalText(draft?.blockerCode)) {
141
+ return "blocker";
142
+ }
143
+ return "none";
144
+ }
145
+ function buildFallbackSummary(text, turnStatus) {
146
+ const trimmed = text.trim();
147
+ if (trimmed) {
148
+ return trimmed.replace(/\s+/g, " ").slice(0, api.HAPPY_ORG_SUMMARY_MAX_LENGTH);
149
+ }
150
+ return turnStatus === "turn_aborted" ? "Turn aborted before completion." : "Turn completed without a textual summary.";
151
+ }
152
+ function normalizeTurnReportDraft(draft) {
153
+ return {
154
+ turnStatus: inferDraftTurnStatus(draft),
155
+ summary: normalizeSummaryText(draft?.summary),
156
+ interventionType: inferInterventionType(draft),
157
+ blockerCode: normalizeOptionalText(draft?.blockerCode),
158
+ decisionNeeded: normalizeOptionalText(draft?.decisionNeeded),
159
+ targetArtifact: normalizeOptionalText(draft?.targetArtifact)
160
+ };
161
+ }
162
+ function stripCodeFence(text) {
163
+ return text.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "").trim();
164
+ }
165
+ function extractTaggedTurnReport(text) {
166
+ const matcher = new RegExp(
167
+ `<${api.HAPPY_ORG_TURN_REPORT_TAG}>\\s*([\\s\\S]*?)\\s*</${api.HAPPY_ORG_TURN_REPORT_TAG}>`,
168
+ "gi"
169
+ );
170
+ let lastMatch = null;
171
+ for (let match = matcher.exec(text); match; match = matcher.exec(text)) {
172
+ lastMatch = match;
173
+ }
174
+ if (!lastMatch) {
175
+ return {
176
+ cleanedText: text.trim(),
177
+ draft: null
178
+ };
179
+ }
180
+ const rawBlock = stripCodeFence(lastMatch[1] ?? "");
181
+ let draft = null;
182
+ try {
183
+ const parsed = JSON.parse(rawBlock);
184
+ draft = {
185
+ turnStatus: normalizeOptionalText(parsed.turnStatus),
186
+ summary: normalizeSummaryText(parsed.summary),
187
+ interventionType: normalizeOptionalText(parsed.interventionType),
188
+ blockerCode: normalizeOptionalText(parsed.blockerCode),
189
+ decisionNeeded: normalizeOptionalText(parsed.decisionNeeded),
190
+ targetArtifact: normalizeOptionalText(parsed.targetArtifact)
191
+ };
192
+ } catch {
193
+ draft = null;
194
+ }
195
+ const cleanedText = `${text.slice(0, lastMatch.index)}${text.slice(lastMatch.index + lastMatch[0].length)}`.replace(/\n{3,}/g, "\n\n").trim();
196
+ return {
197
+ cleanedText,
198
+ draft
199
+ };
200
+ }
201
+ function buildRepeatFingerprint(context, blockerCode, targetArtifact) {
202
+ if (!blockerCode) {
203
+ return null;
204
+ }
205
+ return [
206
+ context.taskId,
207
+ context.memberAgentId,
208
+ blockerCode,
209
+ targetArtifact ?? ""
210
+ ].join("::");
211
+ }
212
+ function resolveReportedTurnStatus(transportTurnStatus, draft) {
213
+ if (transportTurnStatus === "turn_aborted") {
214
+ return "turn_aborted";
215
+ }
216
+ return draft.turnStatus === "task_complete" ? "task_complete" : "turn_update";
217
+ }
218
+ function buildRuntimeStateAfterTurn(report) {
219
+ if (report.turnStatus === "task_complete") {
220
+ return {
221
+ status: "waiting_close",
222
+ reason: "awaiting_ceo_close"
223
+ };
224
+ }
225
+ switch (report.interventionType) {
226
+ case "decision_needed":
227
+ return {
228
+ status: "waiting_decision",
229
+ reason: "awaiting_user_decision"
230
+ };
231
+ case "review_needed":
232
+ return {
233
+ status: "waiting_review",
234
+ reason: "awaiting_ceo_review"
235
+ };
236
+ case "blocker":
237
+ return {
238
+ status: "waiting_review",
239
+ reason: "awaiting_ceo_context"
240
+ };
241
+ default:
242
+ return {
243
+ status: "active",
244
+ reason: null
245
+ };
246
+ }
247
+ }
248
+ function buildHappyOrgTurnPrompt(prompt, turn) {
249
+ const reopenLines = turn.reopenContext ? [
250
+ "",
251
+ "This task was explicitly reopened for this turn with the following new inputs:",
252
+ turn.reopenContext.newContext ? `- newContext: ${turn.reopenContext.newContext}` : null,
253
+ turn.reopenContext.newDecision ? `- newDecision: ${turn.reopenContext.newDecision}` : null,
254
+ turn.reopenContext.newResource ? `- newResource: ${turn.reopenContext.newResource}` : null
255
+ ].filter(Boolean) : [];
256
+ const header = [
257
+ "[HAPPY_ORG_TASK_CONTEXT]",
258
+ `taskId=${turn.context.taskId}`,
259
+ `organizationId=${turn.context.organizationId}`,
260
+ `memberAgentId=${turn.context.memberAgentId}`,
261
+ `supervisorAgentId=${turn.context.supervisorAgentId}`,
262
+ "Stay on this exact task for the whole turn.",
263
+ "End your response with exactly one raw JSON block inside these tags and do not wrap it in a markdown code fence:",
264
+ `<${api.HAPPY_ORG_TURN_REPORT_TAG}>{"turnStatus":"turn_update","summary":"short task-board summary","interventionType":"none","blockerCode":null,"decisionNeeded":null,"targetArtifact":null}</${api.HAPPY_ORG_TURN_REPORT_TAG}>`,
265
+ "Allowed turnStatus values in the JSON block: turn_update, task_complete.",
266
+ "Allowed interventionType values: none, review_needed, blocker, decision_needed.",
267
+ "Use turnStatus=task_complete only when you believe the assigned task is finished and ready for CEO acceptance.",
268
+ "If turnStatus=task_complete, the task will wait for CEO close; do not treat it as automatically closed.",
269
+ "If turnStatus=task_complete, interventionType must be review_needed.",
270
+ `summary must fit on a one-line CEO card or task-board card: short, actionable, no long process logs, max ${api.HAPPY_ORG_SUMMARY_MAX_LENGTH} characters.`,
271
+ "Use blocker only for problems the organization may still solve internally.",
272
+ "Use decision_needed only when a CEO or user decision is required.",
273
+ "Use review_needed when supervisor review is needed but the work is not blocked.",
274
+ ...reopenLines,
275
+ "[/HAPPY_ORG_TASK_CONTEXT]",
276
+ "",
277
+ prompt
278
+ ];
279
+ return header.join("\n");
280
+ }
281
+ function resolveHappyOrgQueuedTurn(opts) {
282
+ const metadata = opts.metadata ?? null;
283
+ if (!metadata) {
284
+ return {
285
+ nextMetadata: null,
286
+ queuedTurn: null,
287
+ blocked: false
288
+ };
289
+ }
290
+ const currentHappyOrg = normalizeHappyOrgMetadata(metadata);
291
+ let nextHappyOrg = cloneHappyOrgMetadata(currentHappyOrg);
292
+ const messageHappyOrg = opts.message.meta?.happyOrg;
293
+ const now = opts.now?.() ?? Date.now();
294
+ const createRunId = opts.createRunId ?? ((taskContext2, currentNow) => `${taskContext2.taskId}:${taskContext2.memberAgentId}:${currentNow}`);
295
+ if (messageHappyOrg?.taskContext) {
296
+ const currentTaskId = currentHappyOrg.taskContext?.taskId ?? null;
297
+ if (currentTaskId !== messageHappyOrg.taskContext.taskId) {
298
+ if (currentHappyOrg.taskContext && currentHappyOrg.runtime?.status === "active") {
299
+ return {
300
+ nextMetadata: withHappyOrgMetadata(metadata, nextHappyOrg),
301
+ queuedTurn: null,
302
+ blocked: true,
303
+ statusMessage: buildMemberBusyStatusMessage(
304
+ currentHappyOrg.taskContext.memberAgentId,
305
+ currentHappyOrg.taskContext.taskId,
306
+ messageHappyOrg.taskContext.taskId
307
+ )
308
+ };
309
+ }
310
+ nextHappyOrg = resetHappyOrgRuntimeForTask(messageHappyOrg.taskContext);
311
+ } else {
312
+ nextHappyOrg.taskContext = { ...messageHappyOrg.taskContext };
313
+ }
314
+ }
315
+ const taskContext = nextHappyOrg.taskContext ?? null;
316
+ if (!taskContext) {
317
+ return {
318
+ nextMetadata: metadata,
319
+ queuedTurn: null,
320
+ blocked: false
321
+ };
322
+ }
323
+ const control = messageHappyOrg?.control;
324
+ if (control?.action === "terminate") {
325
+ nextHappyOrg.runtime = {
326
+ status: "terminated",
327
+ reason: normalizeOptionalText(control.reason) ?? "terminated_by_supervisor",
328
+ terminatedAt: now
329
+ };
330
+ nextHappyOrg.activeOwner = null;
331
+ return {
332
+ nextMetadata: withHappyOrgMetadata(metadata, nextHappyOrg),
333
+ queuedTurn: null,
334
+ blocked: true,
335
+ statusMessage: buildTerminatedStatusMessage(taskContext.taskId)
336
+ };
337
+ }
338
+ const hasReopenInputs = Boolean(
339
+ normalizeOptionalText(control?.newContext) || normalizeOptionalText(control?.newDecision) || normalizeOptionalText(control?.newResource)
340
+ );
341
+ if (nextHappyOrg.runtime?.status === "terminated") {
342
+ if (control?.action !== "reopen") {
343
+ return {
344
+ nextMetadata: withHappyOrgMetadata(metadata, nextHappyOrg),
345
+ queuedTurn: null,
346
+ blocked: true,
347
+ statusMessage: buildTerminatedStatusMessage(taskContext.taskId)
348
+ };
349
+ }
350
+ if (!hasReopenInputs) {
351
+ return {
352
+ nextMetadata: withHappyOrgMetadata(metadata, nextHappyOrg),
353
+ queuedTurn: null,
354
+ blocked: true,
355
+ statusMessage: `Task ${taskContext.taskId} can only reopen with new context, a new decision, or a new resource.`
356
+ };
357
+ }
358
+ }
359
+ const reopenContext = control?.action === "reopen" && hasReopenInputs ? {
360
+ newContext: normalizeOptionalText(control.newContext),
361
+ newDecision: normalizeOptionalText(control.newDecision),
362
+ newResource: normalizeOptionalText(control.newResource)
363
+ } : void 0;
364
+ if (reopenContext) {
365
+ nextHappyOrg.runtime = {
366
+ status: "active",
367
+ reason: null,
368
+ reopenedAt: now
369
+ };
370
+ } else if (!nextHappyOrg.runtime || nextHappyOrg.runtime.status !== "active") {
371
+ nextHappyOrg.runtime = {
372
+ status: "active",
373
+ reason: null
374
+ };
375
+ }
376
+ if (!nextHappyOrg.activeOwner) {
377
+ nextHappyOrg.activeOwner = {
378
+ ownerAgentId: taskContext.memberAgentId,
379
+ ownerRunId: createRunId(taskContext, now),
380
+ claimedAt: now
381
+ };
382
+ } else if (nextHappyOrg.activeOwner.ownerAgentId !== taskContext.memberAgentId) {
383
+ return {
384
+ nextMetadata: withHappyOrgMetadata(metadata, nextHappyOrg),
385
+ queuedTurn: null,
386
+ blocked: true,
387
+ statusMessage: buildOwnerConflictStatusMessage(
388
+ taskContext.taskId,
389
+ nextHappyOrg.activeOwner.ownerAgentId
390
+ )
391
+ };
392
+ }
393
+ return {
394
+ nextMetadata: withHappyOrgMetadata(metadata, nextHappyOrg),
395
+ queuedTurn: {
396
+ context: taskContext,
397
+ ...reopenContext ? { reopenContext } : {}
398
+ },
399
+ blocked: false
400
+ };
401
+ }
402
+ function finalizeHappyOrgTurn(opts) {
403
+ const metadata = opts.metadata ?? null;
404
+ const queuedTurn = opts.queuedTurn ?? null;
405
+ const { cleanedText, draft } = extractTaggedTurnReport(opts.responseText);
406
+ if (!metadata || !queuedTurn) {
407
+ return {
408
+ cleanedText,
409
+ report: null,
410
+ nextMetadata: metadata
411
+ };
412
+ }
413
+ const now = opts.now?.() ?? Date.now();
414
+ const normalizedDraft = normalizeTurnReportDraft(draft);
415
+ const reportTurnStatus = resolveReportedTurnStatus(opts.turnStatus, normalizedDraft);
416
+ const report = {
417
+ ...queuedTurn.context,
418
+ turnStatus: reportTurnStatus,
419
+ interventionType: reportTurnStatus === "task_complete" ? "review_needed" : normalizedDraft.interventionType ?? "none",
420
+ summary: normalizedDraft.summary ?? buildFallbackSummary(cleanedText, reportTurnStatus),
421
+ blockerCode: normalizedDraft.blockerCode ?? null,
422
+ decisionNeeded: normalizedDraft.decisionNeeded ?? null,
423
+ targetArtifact: normalizedDraft.targetArtifact ?? null,
424
+ repeatFingerprint: buildRepeatFingerprint(
425
+ queuedTurn.context,
426
+ normalizedDraft.blockerCode ?? null,
427
+ normalizedDraft.targetArtifact ?? null
428
+ )
429
+ };
430
+ const nextHappyOrg = normalizeHappyOrgMetadata(metadata);
431
+ nextHappyOrg.taskContext = { ...queuedTurn.context };
432
+ nextHappyOrg.lastTurnReport = report;
433
+ nextHappyOrg.activeOwner = null;
434
+ nextHappyOrg.repeat = nextHappyOrg.repeat ?? {
435
+ threshold: api.HAPPY_ORG_REPEAT_THRESHOLD,
436
+ fingerprints: {}
437
+ };
438
+ let terminateMessage;
439
+ if (report.repeatFingerprint) {
440
+ const currentEntry = nextHappyOrg.repeat.fingerprints[report.repeatFingerprint] ?? {
441
+ count: 0};
442
+ const nextCount = currentEntry.count + 1;
443
+ nextHappyOrg.repeat.fingerprints[report.repeatFingerprint] = {
444
+ count: nextCount,
445
+ lastSeenAt: now
446
+ };
447
+ if (nextCount >= nextHappyOrg.repeat.threshold) {
448
+ nextHappyOrg.runtime = {
449
+ status: "terminated",
450
+ reason: `repeat_fingerprint:${report.repeatFingerprint}`,
451
+ terminatedAt: now
452
+ };
453
+ terminateMessage = `Task ${queuedTurn.context.taskId} hit repeat threshold for ${report.repeatFingerprint} and is now terminated until reopen.`;
454
+ } else if (!nextHappyOrg.runtime || nextHappyOrg.runtime.status !== "terminated") {
455
+ nextHappyOrg.runtime = buildRuntimeStateAfterTurn(report);
456
+ }
457
+ } else if (!nextHappyOrg.runtime || nextHappyOrg.runtime.status !== "terminated") {
458
+ nextHappyOrg.runtime = buildRuntimeStateAfterTurn(report);
459
+ }
460
+ return {
461
+ cleanedText,
462
+ report,
463
+ nextMetadata: withHappyOrgMetadata(metadata, nextHappyOrg),
464
+ terminateMessage
465
+ };
466
+ }
467
+
468
+ class ProviderSelectionHandler {
469
+ pendingRequests = /* @__PURE__ */ new Map();
470
+ session;
471
+ providerLabel;
472
+ constructor(session, providerLabel) {
473
+ this.session = session;
474
+ this.providerLabel = providerLabel;
475
+ this.setupRpcHandler();
476
+ }
477
+ updateSession(newSession) {
478
+ this.session = newSession;
479
+ this.setupRpcHandler();
480
+ }
481
+ async requestSelection(request) {
482
+ return new Promise((resolve, reject) => {
483
+ const pending = {
484
+ resolve,
485
+ reject,
486
+ request
487
+ };
488
+ pending.timeoutHandle = setTimeout(() => {
489
+ this.handleSelectionTimeout(request.id, pending);
490
+ }, registerKillSessionHandler.getPendingInteractionTimeoutMs());
491
+ this.pendingRequests.set(request.id, pending);
492
+ this.session.updateAgentState((currentState) => ({
493
+ ...currentState,
494
+ requests: {
495
+ ...currentState.requests,
496
+ [request.id]: {
497
+ tool: "AskUserQuestion",
498
+ arguments: {
499
+ requestKind: "selection",
500
+ questions: [
501
+ {
502
+ header: this.providerLabel,
503
+ question: request.message,
504
+ multiSelect: false,
505
+ options: request.options.map((option) => ({
506
+ label: option.label,
507
+ description: option.description || option.optionId,
508
+ optionId: option.optionId
509
+ }))
510
+ }
511
+ ]
512
+ },
513
+ createdAt: Date.now(),
514
+ requestKind: "selection",
515
+ options: request.options,
516
+ defaultOptionId: request.defaultOptionId
517
+ }
518
+ }
519
+ }));
520
+ api.logger.debug(`[${this.providerLabel}] Selection request sent (${request.id}) with ${request.options.length} options`);
521
+ });
522
+ }
523
+ hasPendingRequests() {
524
+ return this.pendingRequests.size > 0;
525
+ }
526
+ supersedePendingRequests(reason = registerKillSessionHandler.INTERACTION_SUPERSEDED_ERROR) {
527
+ const pendingSnapshot = Array.from(this.pendingRequests.entries());
528
+ if (pendingSnapshot.length === 0) {
529
+ return 0;
530
+ }
531
+ this.pendingRequests.clear();
532
+ const completedAt = Date.now();
533
+ for (const [, pending] of pendingSnapshot) {
534
+ this.clearPendingRequestTimeout(pending);
535
+ pending.reject(new Error(reason));
536
+ }
537
+ this.session.updateAgentState((currentState) => {
538
+ const requests = { ...currentState.requests || {} };
539
+ const completedRequests = { ...currentState.completedRequests || {} };
540
+ for (const [id, request] of Object.entries(requests)) {
541
+ if (request.requestKind !== "selection") {
542
+ continue;
543
+ }
544
+ completedRequests[id] = {
545
+ ...request,
546
+ completedAt,
547
+ status: "canceled",
548
+ reason,
549
+ requestKind: "selection"
550
+ };
551
+ delete requests[id];
552
+ }
553
+ return {
554
+ ...currentState,
555
+ requests,
556
+ completedRequests
557
+ };
558
+ });
559
+ api.logger.debug(`[${this.providerLabel}] Superseded ${pendingSnapshot.length} pending selection request(s)`);
560
+ return pendingSnapshot.length;
561
+ }
562
+ reset(reason = "Session reset") {
563
+ const pendingSnapshot = Array.from(this.pendingRequests.entries());
564
+ this.pendingRequests.clear();
565
+ for (const [, pending] of pendingSnapshot) {
566
+ this.clearPendingRequestTimeout(pending);
567
+ pending.reject(new Error(reason));
568
+ }
569
+ this.session.updateAgentState((currentState) => {
570
+ const requests = { ...currentState.requests || {} };
571
+ const completedRequests = { ...currentState.completedRequests || {} };
572
+ for (const [id, request] of Object.entries(requests)) {
573
+ if (request.requestKind !== "selection") {
574
+ continue;
575
+ }
576
+ completedRequests[id] = {
577
+ ...request,
578
+ completedAt: Date.now(),
579
+ status: "canceled",
580
+ reason,
581
+ requestKind: "selection"
582
+ };
583
+ delete requests[id];
584
+ }
585
+ return {
586
+ ...currentState,
587
+ requests,
588
+ completedRequests
589
+ };
590
+ });
591
+ }
592
+ setupRpcHandler() {
593
+ this.session.rpcHandlerManager.registerHandler("selection", async (response) => {
594
+ const pending = this.pendingRequests.get(response.id);
595
+ if (!pending) {
596
+ api.logger.debug(`[${this.providerLabel}] Selection request not found or already resolved`);
597
+ return;
598
+ }
599
+ this.pendingRequests.delete(response.id);
600
+ this.clearPendingRequestTimeout(pending);
601
+ pending.resolve(response);
602
+ this.session.updateAgentState((currentState) => {
603
+ const request = currentState.requests?.[response.id];
604
+ if (!request) {
605
+ return currentState;
606
+ }
607
+ const { [response.id]: _, ...remainingRequests } = currentState.requests || {};
608
+ return {
609
+ ...currentState,
610
+ requests: remainingRequests,
611
+ completedRequests: {
612
+ ...currentState.completedRequests,
613
+ [response.id]: {
614
+ ...request,
615
+ completedAt: Date.now(),
616
+ status: "approved",
617
+ requestKind: "selection",
618
+ selectedOptionId: response.optionId
619
+ }
620
+ }
621
+ };
622
+ });
623
+ });
624
+ }
625
+ clearPendingRequestTimeout(pending) {
626
+ if (pending?.timeoutHandle) {
627
+ clearTimeout(pending.timeoutHandle);
628
+ pending.timeoutHandle = void 0;
629
+ }
630
+ }
631
+ handleSelectionTimeout(requestId, pending) {
632
+ const active = this.pendingRequests.get(requestId);
633
+ if (!active || active !== pending) {
634
+ return;
635
+ }
636
+ this.pendingRequests.delete(requestId);
637
+ this.clearPendingRequestTimeout(active);
638
+ active.reject(new Error(registerKillSessionHandler.INTERACTION_TIMED_OUT_ERROR));
639
+ this.session.updateAgentState((currentState) => {
640
+ const request = currentState.requests?.[requestId] || {
641
+ tool: "AskUserQuestion",
642
+ arguments: {
643
+ requestKind: "selection",
644
+ questions: []
645
+ },
646
+ createdAt: Date.now(),
647
+ requestKind: "selection",
648
+ options: active.request.options,
649
+ defaultOptionId: active.request.defaultOptionId
650
+ };
651
+ const { [requestId]: _, ...remainingRequests } = currentState.requests || {};
652
+ return {
653
+ ...currentState,
654
+ requests: remainingRequests,
655
+ completedRequests: {
656
+ ...currentState.completedRequests,
657
+ [requestId]: {
658
+ ...request,
659
+ completedAt: Date.now(),
660
+ status: "canceled",
661
+ reason: registerKillSessionHandler.INTERACTION_TIMED_OUT_ERROR,
662
+ requestKind: "selection"
663
+ }
664
+ }
665
+ };
666
+ });
667
+ this.session.sendSessionEvent({
668
+ type: "message",
669
+ message: "Pending interaction timed out waiting for a response. Send a new message to continue."
670
+ });
671
+ api.logger.debug(`[${this.providerLabel}] Selection request timed out (${requestId})`);
672
+ }
673
+ }
674
+
675
+ exports.ProviderSelectionHandler = ProviderSelectionHandler;
676
+ exports.buildHappyOrgTurnPrompt = buildHappyOrgTurnPrompt;
677
+ exports.createKeepAliveController = createKeepAliveController;
678
+ exports.finalizeHappyOrgTurn = finalizeHappyOrgTurn;
679
+ exports.resolveHappyOrgQueuedTurn = resolveHappyOrgQueuedTurn;
680
+ exports.runModeLoop = runModeLoop;