happy-imou-cloud 2.0.13 → 2.0.14

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 (30) hide show
  1. package/dist/BaseReasoningProcessor-CB7luAdI.mjs +320 -0
  2. package/dist/BaseReasoningProcessor-Cwhs4PwS.cjs +323 -0
  3. package/dist/ProviderSelectionHandler-CmDe9yDh.cjs +265 -0
  4. package/dist/ProviderSelectionHandler-DnnCwXqU.mjs +261 -0
  5. package/dist/{api-D1meoL-9.mjs → api-Bad69WzY.mjs} +2 -2
  6. package/dist/{api-DH5-IqeM.cjs → api-CaqY_2x_.cjs} +2 -2
  7. package/dist/{command-CMvWClny.mjs → command-D9ZaQZQN.mjs} +4 -3
  8. package/dist/{command-Ch8Dgidj.cjs → command-DkVbAV9p.cjs} +4 -3
  9. package/dist/{index-Cxrx9m5D.mjs → index-naa51zV7.mjs} +1102 -50
  10. package/dist/{index-CryJfCh5.cjs → index-oxTpdQx2.cjs} +1106 -50
  11. package/dist/index.cjs +5 -4
  12. package/dist/index.mjs +5 -4
  13. package/dist/lib.cjs +1 -1
  14. package/dist/lib.mjs +1 -1
  15. package/dist/{persistence-9Iu0wGNM.mjs → persistence-4BmGePWc.mjs} +1 -1
  16. package/dist/{persistence-Bl3FYvwd.cjs → persistence-Byr0hWCR.cjs} +1 -1
  17. package/dist/{registerKillSessionHandler-BjkY-oUn.cjs → registerKillSessionHandler-CodtiIoq.cjs} +549 -4
  18. package/dist/{registerKillSessionHandler-BElGmD1E.mjs → registerKillSessionHandler-HO4ql8g-.mjs} +541 -5
  19. package/dist/{runClaude-CDZxAF3l.cjs → runClaude-C3UNcGqk.cjs} +583 -747
  20. package/dist/{runClaude-D7dF4RDM.mjs → runClaude-Ev-A-kLN.mjs} +575 -738
  21. package/dist/{runCodex-DnGz1XES.mjs → runCodex-BwFOTxMW.mjs} +9 -215
  22. package/dist/{runCodex-Cik8VzFs.cjs → runCodex-CNM6wz69.cjs} +20 -226
  23. package/dist/{runGemini-B8tXMHeL.mjs → runGemini-CXctVflO.mjs} +8 -7
  24. package/dist/{runGemini-BM2BQ4I7.cjs → runGemini-DqfqSBsP.cjs} +16 -15
  25. package/package.json +1 -1
  26. package/scripts/release-smoke.mjs +6 -5
  27. package/dist/ConversationHistory-V3VLmjJf.cjs +0 -868
  28. package/dist/ConversationHistory-_ciJNIgH.mjs +0 -856
  29. package/dist/createKeepAliveController-C5cQlDRr.mjs +0 -51
  30. package/dist/createKeepAliveController-DO8H6d5E.cjs +0 -54
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
3
  require('chalk');
4
- require('./api-DH5-IqeM.cjs');
5
- require('./persistence-Bl3FYvwd.cjs');
4
+ require('./api-CaqY_2x_.cjs');
5
+ require('./persistence-Byr0hWCR.cjs');
6
6
  require('zod');
7
- require('./index-CryJfCh5.cjs');
7
+ require('./index-oxTpdQx2.cjs');
8
8
  require('node:child_process');
9
9
  require('node:fs');
10
10
  require('cross-spawn');
@@ -17,6 +17,7 @@ require('os');
17
17
  require('child_process');
18
18
  require('node:path');
19
19
  require('node:os');
20
+ require('node:readline');
20
21
  require('node:fs/promises');
21
22
  require('fs/promises');
22
23
  require('crypto');
@@ -34,7 +35,7 @@ require('ink');
34
35
  require('url');
35
36
  require('fastify');
36
37
  require('fastify-type-provider-zod');
37
- require('node:readline');
38
38
  require('http');
39
39
  require('util');
40
+ require('node:url');
40
41
 
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  import 'chalk';
2
- import './api-D1meoL-9.mjs';
3
- import './persistence-9Iu0wGNM.mjs';
2
+ import './api-Bad69WzY.mjs';
3
+ import './persistence-4BmGePWc.mjs';
4
4
  import 'zod';
5
- import './index-Cxrx9m5D.mjs';
5
+ import './index-naa51zV7.mjs';
6
6
  import 'node:child_process';
7
7
  import 'node:fs';
8
8
  import 'cross-spawn';
@@ -15,6 +15,7 @@ import 'os';
15
15
  import 'child_process';
16
16
  import 'node:path';
17
17
  import 'node:os';
18
+ import 'node:readline';
18
19
  import 'node:fs/promises';
19
20
  import 'fs/promises';
20
21
  import 'crypto';
@@ -32,6 +33,6 @@ import 'ink';
32
33
  import 'url';
33
34
  import 'fastify';
34
35
  import 'fastify-type-provider-zod';
35
- import 'node:readline';
36
36
  import 'http';
37
37
  import 'util';
38
+ import 'node:url';
package/dist/lib.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var api = require('./api-DH5-IqeM.cjs');
3
+ var api = require('./api-CaqY_2x_.cjs');
4
4
  var types = require('./types-DVk3crez.cjs');
5
5
  require('axios');
6
6
  require('chalk');
package/dist/lib.mjs CHANGED
@@ -1,4 +1,4 @@
1
- export { A as ApiClient, a as ApiSessionClient, c as configuration, l as logger } from './api-D1meoL-9.mjs';
1
+ export { A as ApiClient, a as ApiSessionClient, c as configuration, l as logger } from './api-Bad69WzY.mjs';
2
2
  export { R as RawJSONLinesSchema } from './types-CiliQpqS.mjs';
3
3
  import 'axios';
4
4
  import 'chalk';
@@ -1,7 +1,7 @@
1
1
  import { unlink, readFile, mkdir, open, stat, writeFile, rename } from 'node:fs/promises';
2
2
  import { existsSync, unlinkSync, readdirSync, constants, writeFileSync, readFileSync } from 'node:fs';
3
3
  import { join, dirname } from 'node:path';
4
- import { c as configuration, l as logger, e as encodeBase64 } from './api-D1meoL-9.mjs';
4
+ import { c as configuration, l as logger, e as encodeBase64 } from './api-Bad69WzY.mjs';
5
5
  import * as z from 'zod';
6
6
  import 'axios';
7
7
  import 'chalk';
@@ -3,7 +3,7 @@
3
3
  var promises = require('node:fs/promises');
4
4
  var fs = require('node:fs');
5
5
  var path = require('node:path');
6
- var api = require('./api-DH5-IqeM.cjs');
6
+ var api = require('./api-CaqY_2x_.cjs');
7
7
  var z = require('zod');
8
8
  require('axios');
9
9
  require('chalk');
@@ -1,15 +1,15 @@
1
1
  'use strict';
2
2
 
3
- var index = require('./index-CryJfCh5.cjs');
4
- var persistence = require('./persistence-Bl3FYvwd.cjs');
3
+ var index = require('./index-oxTpdQx2.cjs');
4
+ var persistence = require('./persistence-Byr0hWCR.cjs');
5
5
  var os = require('node:os');
6
6
  var path = require('node:path');
7
- var api = require('./api-DH5-IqeM.cjs');
7
+ var api = require('./api-CaqY_2x_.cjs');
8
+ var node_crypto = require('node:crypto');
8
9
  var crypto = require('crypto');
9
10
  require('axios');
10
11
  require('node:events');
11
12
  require('socket.io-client');
12
- require('node:crypto');
13
13
  require('tweetnacl');
14
14
  require('fs/promises');
15
15
  require('path');
@@ -61,6 +61,199 @@ function createSessionMetadata(opts) {
61
61
  return { state, metadata };
62
62
  }
63
63
 
64
+ async function launchRuntimeHandleWithFactoryResult(opts) {
65
+ const shell = opts.shell ?? new index.RuntimeShell();
66
+ let factoryResult;
67
+ const session = await shell.launch({
68
+ provider: opts.provider,
69
+ cwd: opts.cwd,
70
+ env: opts.env,
71
+ createBackend: (factoryOpts) => {
72
+ factoryResult = opts.createBackendResult(factoryOpts);
73
+ return factoryResult.backend;
74
+ }
75
+ });
76
+ if (factoryResult === void 0) {
77
+ throw new Error(`Runtime provider "${opts.provider}" did not create a backend result`);
78
+ }
79
+ return {
80
+ session,
81
+ factoryResult
82
+ };
83
+ }
84
+
85
+ function inferToolResultError(result) {
86
+ if (!result || typeof result !== "object") {
87
+ return false;
88
+ }
89
+ const record = result;
90
+ if (record.isError === true || record.is_error === true) {
91
+ return true;
92
+ }
93
+ if (typeof record.error === "string" && record.error.trim().length > 0) {
94
+ return true;
95
+ }
96
+ if (record.success === false) {
97
+ return true;
98
+ }
99
+ const status = typeof record.status === "string" ? record.status.toLowerCase() : "";
100
+ return status === "failed" || status === "cancelled" || status === "error" || status === "denied" || status === "aborted";
101
+ }
102
+
103
+ function buildToolHappierMetaV2(input) {
104
+ return {
105
+ ...input,
106
+ v: 2
107
+ };
108
+ }
109
+ function attachToolHappierMetaV2(value, meta) {
110
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
111
+ return value;
112
+ }
113
+ return {
114
+ ...value,
115
+ _happier: buildToolHappierMetaV2(meta)
116
+ };
117
+ }
118
+
119
+ function getDefaultExecToolName(provider) {
120
+ switch (provider) {
121
+ case "claude":
122
+ return "ClaudeBash";
123
+ case "codex":
124
+ return "CodexBash";
125
+ case "gemini":
126
+ return "GeminiBash";
127
+ }
128
+ }
129
+ function getDefaultPatchToolName(provider) {
130
+ switch (provider) {
131
+ case "claude":
132
+ return "ClaudePatch";
133
+ case "codex":
134
+ return "CodexPatch";
135
+ case "gemini":
136
+ return "GeminiPatch";
137
+ }
138
+ }
139
+ function attachToolMeta(provider, rawToolName, value) {
140
+ const canonicalToolName = index.resolveCanonicalToolNameV2(rawToolName);
141
+ return attachToolHappierMetaV2(value, {
142
+ v: 2,
143
+ protocol: "acp",
144
+ provider,
145
+ rawToolName,
146
+ canonicalToolName
147
+ });
148
+ }
149
+ function forwardAgentMessageToProviderSession(msg, options) {
150
+ const createId = options.createId ?? node_crypto.randomUUID;
151
+ const toolResultType = options.toolResultType ?? "tool-result";
152
+ switch (msg.type) {
153
+ case "tool-call": {
154
+ options.send({
155
+ type: "tool-call",
156
+ name: index.resolveCanonicalToolNameV2(msg.toolName),
157
+ callId: msg.callId,
158
+ input: attachToolMeta(options.provider, msg.toolName, msg.args),
159
+ id: createId()
160
+ });
161
+ return true;
162
+ }
163
+ case "tool-result": {
164
+ options.send({
165
+ type: toolResultType,
166
+ callId: msg.callId,
167
+ output: attachToolMeta(options.provider, msg.toolName, msg.result),
168
+ id: createId(),
169
+ isError: inferToolResultError(msg.result)
170
+ });
171
+ return true;
172
+ }
173
+ case "fs-edit": {
174
+ options.send({
175
+ type: "file-edit",
176
+ description: msg.description,
177
+ diff: msg.diff,
178
+ filePath: msg.path || "unknown",
179
+ id: createId()
180
+ });
181
+ return true;
182
+ }
183
+ case "terminal-output": {
184
+ options.send({
185
+ type: "terminal-output",
186
+ data: msg.data,
187
+ callId: msg.callId ?? createId()
188
+ });
189
+ return true;
190
+ }
191
+ case "permission-request": {
192
+ const payload = msg.payload && typeof msg.payload === "object" ? msg.payload : {};
193
+ options.send({
194
+ type: "permission-request",
195
+ permissionId: msg.id,
196
+ toolName: typeof payload.toolName === "string" ? payload.toolName : msg.reason || "unknown",
197
+ description: msg.reason || (typeof payload.toolName === "string" ? payload.toolName : ""),
198
+ options: payload
199
+ });
200
+ return true;
201
+ }
202
+ case "exec-approval-request": {
203
+ const rawToolName = options.execToolName ?? getDefaultExecToolName(options.provider);
204
+ const { call_id, type: _type, ...inputs } = msg;
205
+ options.send({
206
+ type: "tool-call",
207
+ name: index.resolveCanonicalToolNameV2(rawToolName),
208
+ callId: call_id,
209
+ input: attachToolMeta(options.provider, rawToolName, inputs),
210
+ id: createId()
211
+ });
212
+ return true;
213
+ }
214
+ case "patch-apply-begin": {
215
+ const rawToolName = options.patchToolName ?? getDefaultPatchToolName(options.provider);
216
+ options.send({
217
+ type: "tool-call",
218
+ name: index.resolveCanonicalToolNameV2(rawToolName),
219
+ callId: msg.call_id,
220
+ input: attachToolMeta(options.provider, rawToolName, {
221
+ auto_approved: msg.auto_approved,
222
+ changes: msg.changes
223
+ }),
224
+ id: createId()
225
+ });
226
+ return true;
227
+ }
228
+ case "patch-apply-end": {
229
+ const rawToolName = options.patchToolName ?? getDefaultPatchToolName(options.provider);
230
+ options.send({
231
+ type: toolResultType,
232
+ callId: msg.call_id,
233
+ output: attachToolMeta(options.provider, rawToolName, {
234
+ stdout: msg.stdout,
235
+ stderr: msg.stderr,
236
+ success: msg.success
237
+ }),
238
+ id: createId(),
239
+ isError: !msg.success
240
+ });
241
+ return true;
242
+ }
243
+ case "token-count": {
244
+ const { type: _type, ...payload } = msg;
245
+ options.send({
246
+ type: "token_count",
247
+ ...payload,
248
+ id: createId()
249
+ });
250
+ return true;
251
+ }
252
+ default:
253
+ return false;
254
+ }
255
+ }
256
+
64
257
  async function closeProviderSession(session, opts = {}) {
65
258
  let firstError;
66
259
  const captureError = (error) => {
@@ -101,6 +294,27 @@ async function closeProviderSession(session, opts = {}) {
101
294
  }
102
295
  }
103
296
 
297
+ function createAbortError() {
298
+ const error = new Error("Operation aborted");
299
+ error.name = "AbortError";
300
+ return error;
301
+ }
302
+ async function waitForResponseCompleteWithAbort(backend, signal, timeoutMs = 12e4) {
303
+ if (!backend.waitForResponseComplete) {
304
+ return;
305
+ }
306
+ if (signal.aborted) {
307
+ throw createAbortError();
308
+ }
309
+ await new Promise((resolve, reject) => {
310
+ const onAbort = () => reject(createAbortError());
311
+ signal.addEventListener("abort", onAbort, { once: true });
312
+ backend.waitForResponseComplete(timeoutMs).then(resolve).catch(reject).finally(() => {
313
+ signal.removeEventListener("abort", onAbort);
314
+ });
315
+ });
316
+ }
317
+
104
318
  function supportsAgentStateUpdateEvents(sessionClient) {
105
319
  return typeof sessionClient.once === "function" && typeof sessionClient.off === "function";
106
320
  }
@@ -296,6 +510,328 @@ class MessageBuffer {
296
510
  }
297
511
  }
298
512
 
513
+ let ConversationHistory$1 = class ConversationHistory {
514
+ messages = [];
515
+ maxMessages;
516
+ maxCharacters;
517
+ constructor(options = {}) {
518
+ this.maxMessages = options.maxMessages ?? 20;
519
+ this.maxCharacters = options.maxCharacters ?? 5e4;
520
+ }
521
+ isDuplicate(role, content) {
522
+ if (this.messages.length === 0) {
523
+ return false;
524
+ }
525
+ for (let index = this.messages.length - 1; index >= 0; index -= 1) {
526
+ const message = this.messages[index];
527
+ if (message.role !== role) {
528
+ continue;
529
+ }
530
+ const normalizedIncoming = content.trim().replace(/\s+/g, " ");
531
+ const normalizedExisting = message.content.replace(/\s+/g, " ");
532
+ return normalizedIncoming === normalizedExisting;
533
+ }
534
+ return false;
535
+ }
536
+ addUserMessage(content) {
537
+ this.addMessage("user", content);
538
+ }
539
+ addAssistantMessage(content) {
540
+ this.addMessage("assistant", content);
541
+ }
542
+ hasHistory() {
543
+ return this.messages.length > 0;
544
+ }
545
+ size() {
546
+ return this.messages.length;
547
+ }
548
+ clear() {
549
+ this.messages = [];
550
+ api.logger.debug("[ConversationHistory] History cleared");
551
+ }
552
+ getContextForNewSession(prefixMessage = "Continue from the prior session using the conversation below as context.") {
553
+ if (this.messages.length === 0) {
554
+ return "";
555
+ }
556
+ const formattedMessages = this.messages.map((message) => {
557
+ const role = message.role === "user" ? "User" : "Assistant";
558
+ const content = message.content.length > 2e3 ? `${message.content.slice(0, 2e3)}... [truncated]` : message.content;
559
+ return `${role}: ${content}`;
560
+ }).join("\n\n");
561
+ return [
562
+ "[PREVIOUS CONVERSATION CONTEXT]",
563
+ prefixMessage,
564
+ "",
565
+ formattedMessages,
566
+ "",
567
+ "[END OF PREVIOUS CONTEXT]",
568
+ ""
569
+ ].join("\n");
570
+ }
571
+ getSummary() {
572
+ const totalChars = this.messages.reduce((sum, message) => sum + message.content.length, 0);
573
+ const userCount = this.messages.filter((message) => message.role === "user").length;
574
+ const assistantCount = this.messages.filter((message) => message.role === "assistant").length;
575
+ return `${this.messages.length} messages (${userCount} user, ${assistantCount} assistant), ${totalChars} chars`;
576
+ }
577
+ addMessage(role, content) {
578
+ const trimmedContent = content.trim();
579
+ if (!trimmedContent) {
580
+ return;
581
+ }
582
+ if (this.isDuplicate(role, trimmedContent)) {
583
+ api.logger.debug(`[ConversationHistory] Skipping duplicate ${role} message (${trimmedContent.length} chars)`);
584
+ return;
585
+ }
586
+ this.messages.push({
587
+ role,
588
+ content: trimmedContent,
589
+ timestamp: Date.now()
590
+ });
591
+ this.trimHistory();
592
+ api.logger.debug(`[ConversationHistory] Added ${role} message (${trimmedContent.length} chars), total: ${this.messages.length}`);
593
+ }
594
+ trimHistory() {
595
+ while (this.messages.length > this.maxMessages) {
596
+ this.messages.shift();
597
+ }
598
+ let totalChars = this.messages.reduce((sum, message) => sum + message.content.length, 0);
599
+ while (totalChars > this.maxCharacters && this.messages.length > 1) {
600
+ const removed = this.messages.shift();
601
+ if (removed) {
602
+ totalChars -= removed.content.length;
603
+ }
604
+ }
605
+ }
606
+ };
607
+
608
+ const INTERACTION_SUPERSEDED_ERROR = "Interaction superseded by new user message";
609
+ const INTERACTION_TIMED_OUT_ERROR = "Interaction timed out waiting for user response";
610
+ const DEFAULT_INTERACTION_TIMEOUT_MS = 2 * 60 * 1e3;
611
+ function getPendingInteractionTimeoutMs() {
612
+ const raw = Number(process.env.HAPPY_INTERACTION_TIMEOUT_MS);
613
+ if (Number.isFinite(raw) && raw > 0) {
614
+ return raw;
615
+ }
616
+ return DEFAULT_INTERACTION_TIMEOUT_MS;
617
+ }
618
+ class BasePermissionHandler {
619
+ pendingRequests = /* @__PURE__ */ new Map();
620
+ session;
621
+ isResetting = false;
622
+ constructor(session) {
623
+ this.session = session;
624
+ this.setupRpcHandler();
625
+ }
626
+ /**
627
+ * Update the session reference (used after offline reconnection swaps sessions).
628
+ * This is critical for avoiding stale session references after onSessionSwap.
629
+ */
630
+ updateSession(newSession) {
631
+ api.logger.debug(`${this.getLogPrefix()} Session reference updated`);
632
+ this.session = newSession;
633
+ this.setupRpcHandler();
634
+ }
635
+ /**
636
+ * Setup RPC handler for permission responses.
637
+ */
638
+ setupRpcHandler() {
639
+ this.session.rpcHandlerManager.registerHandler(
640
+ "permission",
641
+ async (response) => {
642
+ const pending = this.pendingRequests.get(response.id);
643
+ if (!pending) {
644
+ api.logger.debug(`${this.getLogPrefix()} Permission request not found or already resolved`);
645
+ return;
646
+ }
647
+ this.pendingRequests.delete(response.id);
648
+ this.clearPendingRequestTimeout(pending);
649
+ const result = response.approved ? { decision: response.decision === "approved_for_session" ? "approved_for_session" : "approved" } : { decision: response.decision === "denied" ? "denied" : "abort" };
650
+ pending.resolve(result);
651
+ this.session.updateAgentState((currentState) => {
652
+ const request = currentState.requests?.[response.id];
653
+ if (!request) return currentState;
654
+ const { [response.id]: _, ...remainingRequests } = currentState.requests || {};
655
+ let res = {
656
+ ...currentState,
657
+ requests: remainingRequests,
658
+ completedRequests: {
659
+ ...currentState.completedRequests,
660
+ [response.id]: {
661
+ ...request,
662
+ completedAt: Date.now(),
663
+ status: response.approved ? "approved" : "denied",
664
+ decision: result.decision
665
+ }
666
+ }
667
+ };
668
+ return res;
669
+ });
670
+ api.logger.debug(`${this.getLogPrefix()} Permission ${response.approved ? "approved" : "denied"} for ${pending.toolName}`);
671
+ }
672
+ );
673
+ }
674
+ /**
675
+ * Add a pending request to the agent state.
676
+ */
677
+ addPendingRequestToState(toolCallId, toolName, input) {
678
+ this.session.updateAgentState((currentState) => ({
679
+ ...currentState,
680
+ requests: {
681
+ ...currentState.requests,
682
+ [toolCallId]: {
683
+ tool: toolName,
684
+ arguments: input,
685
+ createdAt: Date.now()
686
+ }
687
+ }
688
+ }));
689
+ }
690
+ registerPendingRequest(toolCallId, toolName, input, logSuffix = "") {
691
+ return new Promise((resolve, reject) => {
692
+ const pending = {
693
+ resolve,
694
+ reject,
695
+ toolName,
696
+ input
697
+ };
698
+ pending.timeoutHandle = setTimeout(() => {
699
+ this.handlePendingRequestTimeout(toolCallId, pending);
700
+ }, getPendingInteractionTimeoutMs());
701
+ this.pendingRequests.set(toolCallId, pending);
702
+ this.addPendingRequestToState(toolCallId, toolName, input);
703
+ api.logger.debug(`${this.getLogPrefix()} Permission request sent for tool: ${toolName} (${toolCallId})${logSuffix}`);
704
+ });
705
+ }
706
+ hasPendingRequests() {
707
+ return this.pendingRequests.size > 0;
708
+ }
709
+ supersedePendingRequests(reason = INTERACTION_SUPERSEDED_ERROR) {
710
+ const pendingSnapshot = Array.from(this.pendingRequests.entries());
711
+ if (pendingSnapshot.length === 0) {
712
+ return 0;
713
+ }
714
+ this.pendingRequests.clear();
715
+ const completedAt = Date.now();
716
+ for (const [, pending] of pendingSnapshot) {
717
+ this.clearPendingRequestTimeout(pending);
718
+ pending.resolve({ decision: "abort" });
719
+ }
720
+ this.session.updateAgentState((currentState) => {
721
+ const requests = { ...currentState.requests || {} };
722
+ const completedRequests = { ...currentState.completedRequests || {} };
723
+ for (const [id, request] of Object.entries(requests)) {
724
+ if (request.requestKind === "selection") {
725
+ continue;
726
+ }
727
+ completedRequests[id] = {
728
+ ...request,
729
+ completedAt,
730
+ status: "denied",
731
+ reason,
732
+ decision: "abort",
733
+ requestKind: request.requestKind || "permission"
734
+ };
735
+ delete requests[id];
736
+ }
737
+ return {
738
+ ...currentState,
739
+ requests,
740
+ completedRequests
741
+ };
742
+ });
743
+ api.logger.debug(`${this.getLogPrefix()} Superseded ${pendingSnapshot.length} pending permission request(s)`);
744
+ return pendingSnapshot.length;
745
+ }
746
+ /**
747
+ * Reset state for new sessions.
748
+ * This method is idempotent - safe to call multiple times.
749
+ */
750
+ reset() {
751
+ if (this.isResetting) {
752
+ api.logger.debug(`${this.getLogPrefix()} Reset already in progress, skipping`);
753
+ return;
754
+ }
755
+ this.isResetting = true;
756
+ try {
757
+ const pendingSnapshot = Array.from(this.pendingRequests.entries());
758
+ this.pendingRequests.clear();
759
+ for (const [id, pending] of pendingSnapshot) {
760
+ try {
761
+ this.clearPendingRequestTimeout(pending);
762
+ pending.reject(new Error("Session reset"));
763
+ } catch (err) {
764
+ api.logger.debug(`${this.getLogPrefix()} Error rejecting pending request ${id}:`, err);
765
+ }
766
+ }
767
+ this.session.updateAgentState((currentState) => {
768
+ const pendingRequests = currentState.requests || {};
769
+ const completedRequests = { ...currentState.completedRequests };
770
+ for (const [id, request] of Object.entries(pendingRequests)) {
771
+ completedRequests[id] = {
772
+ ...request,
773
+ completedAt: Date.now(),
774
+ status: "canceled",
775
+ reason: "Session reset"
776
+ };
777
+ }
778
+ return {
779
+ ...currentState,
780
+ requests: {},
781
+ completedRequests
782
+ };
783
+ });
784
+ api.logger.debug(`${this.getLogPrefix()} Permission handler reset`);
785
+ } finally {
786
+ this.isResetting = false;
787
+ }
788
+ }
789
+ clearPendingRequestTimeout(pending) {
790
+ if (pending?.timeoutHandle) {
791
+ clearTimeout(pending.timeoutHandle);
792
+ pending.timeoutHandle = void 0;
793
+ }
794
+ }
795
+ handlePendingRequestTimeout(toolCallId, pending) {
796
+ const active = this.pendingRequests.get(toolCallId);
797
+ if (!active || active !== pending) {
798
+ return;
799
+ }
800
+ this.pendingRequests.delete(toolCallId);
801
+ this.clearPendingRequestTimeout(active);
802
+ active.resolve({ decision: "abort" });
803
+ this.session.updateAgentState((currentState) => {
804
+ const request = currentState.requests?.[toolCallId] || {
805
+ tool: active.toolName,
806
+ arguments: active.input,
807
+ createdAt: Date.now(),
808
+ requestKind: "permission"
809
+ };
810
+ const { [toolCallId]: _, ...remainingRequests } = currentState.requests || {};
811
+ return {
812
+ ...currentState,
813
+ requests: remainingRequests,
814
+ completedRequests: {
815
+ ...currentState.completedRequests,
816
+ [toolCallId]: {
817
+ ...request,
818
+ completedAt: Date.now(),
819
+ status: "canceled",
820
+ reason: INTERACTION_TIMED_OUT_ERROR,
821
+ decision: "abort",
822
+ requestKind: request.requestKind || "permission"
823
+ }
824
+ }
825
+ };
826
+ });
827
+ this.session.sendSessionEvent({
828
+ type: "message",
829
+ message: "Pending interaction timed out waiting for a response. Send a new message to continue."
830
+ });
831
+ api.logger.debug(`${this.getLogPrefix()} Permission request timed out for ${active.toolName} (${toolCallId})`);
832
+ }
833
+ }
834
+
299
835
  class MessageQueue2 {
300
836
  queue = [];
301
837
  // Made public for testing
@@ -642,12 +1178,21 @@ function registerKillSessionHandler(rpcHandlerManager, killThisHappy) {
642
1178
  });
643
1179
  }
644
1180
 
1181
+ exports.BasePermissionHandler = BasePermissionHandler;
1182
+ exports.ConversationHistory = ConversationHistory$1;
1183
+ exports.INTERACTION_SUPERSEDED_ERROR = INTERACTION_SUPERSEDED_ERROR;
1184
+ exports.INTERACTION_TIMED_OUT_ERROR = INTERACTION_TIMED_OUT_ERROR;
645
1185
  exports.MessageBuffer = MessageBuffer;
646
1186
  exports.MessageQueue2 = MessageQueue2;
647
1187
  exports.MissingMachineIdError = MissingMachineIdError;
648
1188
  exports.closeProviderSession = closeProviderSession;
649
1189
  exports.createSessionMetadata = createSessionMetadata;
650
1190
  exports.ensureManagedProviderMachine = ensureManagedProviderMachine;
1191
+ exports.forwardAgentMessageToProviderSession = forwardAgentMessageToProviderSession;
1192
+ exports.getPendingInteractionTimeoutMs = getPendingInteractionTimeoutMs;
651
1193
  exports.hashObject = hashObject;
1194
+ exports.inferToolResultError = inferToolResultError;
1195
+ exports.launchRuntimeHandleWithFactoryResult = launchRuntimeHandleWithFactoryResult;
652
1196
  exports.registerKillSessionHandler = registerKillSessionHandler;
653
1197
  exports.syncControlledByUserState = syncControlledByUserState;
1198
+ exports.waitForResponseCompleteWithAbort = waitForResponseCompleteWithAbort;