@0xmaxma/claude-gateway 2.1.15 → 2.1.16

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 (41) hide show
  1. package/dist/agent/runner.js +1 -1
  2. package/dist/agent/runner.js.map +1 -1
  3. package/dist/build-provenance.json +4 -4
  4. package/dist/history/types.d.ts +1 -1
  5. package/dist/history/types.js +1 -1
  6. package/dist/orchestration/agent-cli-session.d.ts +58 -6
  7. package/dist/orchestration/agent-cli-session.d.ts.map +1 -1
  8. package/dist/orchestration/agent-cli-session.js +207 -27
  9. package/dist/orchestration/agent-cli-session.js.map +1 -1
  10. package/dist/orchestration/context-delivery.d.ts +2 -0
  11. package/dist/orchestration/context-delivery.d.ts.map +1 -1
  12. package/dist/orchestration/context-delivery.js +8 -0
  13. package/dist/orchestration/context-delivery.js.map +1 -1
  14. package/dist/orchestration/gateway-tasks/computer.d.ts +2 -0
  15. package/dist/orchestration/gateway-tasks/computer.d.ts.map +1 -1
  16. package/dist/orchestration/gateway-tasks/computer.js +4 -2
  17. package/dist/orchestration/gateway-tasks/computer.js.map +1 -1
  18. package/dist/orchestration/input-images.d.ts +4 -0
  19. package/dist/orchestration/input-images.d.ts.map +1 -1
  20. package/dist/orchestration/input-images.js +28 -0
  21. package/dist/orchestration/input-images.js.map +1 -1
  22. package/dist/orchestration/runtime.d.ts +3 -0
  23. package/dist/orchestration/runtime.d.ts.map +1 -1
  24. package/dist/orchestration/runtime.js +103 -44
  25. package/dist/orchestration/runtime.js.map +1 -1
  26. package/dist/orchestration/session-compaction.d.ts.map +1 -1
  27. package/dist/orchestration/session-compaction.js +16 -6
  28. package/dist/orchestration/session-compaction.js.map +1 -1
  29. package/dist/orchestration/tasks/driver.d.ts.map +1 -1
  30. package/dist/orchestration/tasks/driver.js +8 -1
  31. package/dist/orchestration/tasks/driver.js.map +1 -1
  32. package/dist/orchestration/tasks/pool.d.ts +3 -2
  33. package/dist/orchestration/tasks/pool.d.ts.map +1 -1
  34. package/dist/orchestration/tasks/pool.js +4 -3
  35. package/dist/orchestration/tasks/pool.js.map +1 -1
  36. package/dist/ui/memory-activity.js +1 -1
  37. package/package.json +1 -1
  38. package/dist/session/compactor.d.ts +0 -53
  39. package/dist/session/compactor.d.ts.map +0 -1
  40. package/dist/session/compactor.js +0 -274
  41. package/dist/session/compactor.js.map +0 -1
@@ -111,6 +111,8 @@ const worker_shares_1 = require("./worker-shares");
111
111
  const provider_admission_1 = require("./provider-admission");
112
112
  const provider_scope_1 = require("./provider-scope");
113
113
  const model_registry_1 = require("../agent/model-registry");
114
+ /** Computer tasks whose screenshot one decision turn may attach to its prompt. */
115
+ const COMPUTER_PROMPT_SCREENSHOTS = 2;
114
116
  /** Estimated tokens per attached image (a ~1.15-megapixel image is about 1,600). */
115
117
  const IMAGE_TOKEN_ESTIMATE = 1600;
116
118
  /** How long a failed voice note can be retried from its kept recording. */
@@ -666,6 +668,7 @@ class AgentOrchestrationRuntime {
666
668
  const responseId = this.decisions.notice(conversationId, text, deliver);
667
669
  await this.history.write(`response:${responseId}`);
668
670
  this.publishText(sessionId, responseId, text, true);
671
+ return responseId;
669
672
  }
670
673
  ownsSession(sessionId) { return Boolean(this.store.get('SELECT id FROM conversations WHERE agent_session_id=?', sessionId)); }
671
674
  ownsChannelIngress(source) {
@@ -747,52 +750,61 @@ class AgentOrchestrationRuntime {
747
750
  const active = { stopping: false, maintenance: 'compact' };
748
751
  this.active.set(sessionId, active);
749
752
  const operation = (async () => {
750
- let process;
751
- let revoke;
752
753
  try {
753
754
  const cli = this.agent.type === 'app-agent'
754
755
  ? await this.cliSessions.resolveContainer(sessionId, await this.executionAgent(String(conversation.source), String(conversation.chat_id), sessionId), true)
755
756
  : this.cliSessions.resolve(sessionId, this.agent.workspace, true);
756
757
  if (!cli.resume || cli.id !== stored.cli_session_id)
757
758
  throw new types_2.OrchestrationError('NO_CLI_SESSION', 'The previous Claude Code transcript is unavailable. Chat history was not changed.');
758
- if (active.stopping || this.closing)
759
- throw new types_2.OrchestrationError('INTERRUPTED');
760
- const ticket = this.bridge.issue({ role: 'agent', compactOnly: true, context: { conversationId: String(conversation.id), principalId: String(conversation.owner_principal_id), inputId: (0, crypto_2.randomUUID)(), decisionId: (0, crypto_2.randomUUID)(), epoch: Number(conversation.epoch), execute: false, writeMemory: false } }, (0, path_1.join)(this.root, 'compactions', (0, crypto_2.randomUUID)()), this.agent.workspace, '');
761
- revoke = ticket.revoke;
762
- ticket.profile.cliSession = { id: cli.id, resume: true };
763
- ticket.profile.connectorsAllowed = false;
764
- ticket.profile.overlay = 'Perform only the requested native context compaction. Do not execute tasks or tools.';
765
- process = await this.host.createAgentSession(sessionId, ticket.profile, model, { agentId: this.agent.id, agentSessionId: sessionId, source: conversation.source, accountId: String(conversation.account_id), chatId: String(conversation.chat_id), threadKey: String(conversation.thread_key), principalId: String(conversation.owner_principal_id) });
766
- if (active.stopping || this.closing)
767
- throw new types_2.OrchestrationError('INTERRUPTED');
768
- this.contextDelivery.invalidateConversation(String(conversation.id));
769
- const startedAt = Date.now(), compact = (0, native_compact_1.startNativeCompact)(process);
770
- active.turn = compact;
771
- await compact.result;
772
- let measured = compact.measurements();
773
- if (this.agent.type !== 'app-agent' && measured?.afterTokens == null) {
774
- const storedMetrics = await (0, compact_measurements_1.readCompactMeasurements)((0, claude_settings_1.transcriptPath)(this.agent.workspace, cli.id), startedAt, Date.now());
775
- if (storedMetrics)
776
- measured = storedMetrics;
777
- }
778
- this.store.transaction(() => this.store.appendEvent(String(conversation.id), 'session.context_compacted', { sessionId, cliSessionId: cli.id }));
779
- return measured;
759
+ return await this.nativeCompact(sessionId, conversation, cli.id, model, active);
780
760
  }
781
761
  finally {
782
- revoke?.();
783
- try {
784
- if (process)
785
- await this.host.releaseAgentSession(sessionId, process);
786
- }
787
- finally {
788
- this.active.delete(sessionId);
789
- }
762
+ this.active.delete(sessionId);
790
763
  }
791
764
  })();
792
765
  this.pending.add(operation);
793
766
  void operation.finally(() => this.pending.delete(operation)).catch(() => { });
794
767
  return operation;
795
768
  }
769
+ /** Run Claude Code's native /compact on `cliId`. Shared by /compact, nightly compaction and
770
+ * the byte trigger of a decision turn, which runs it under the turn's own `active` entry. */
771
+ async nativeCompact(sessionId, conversation, cliId, model, active) {
772
+ let process;
773
+ let revoke;
774
+ const previous = active.maintenance;
775
+ active.maintenance = 'compact';
776
+ try {
777
+ if (active.stopping || this.closing)
778
+ throw new types_2.OrchestrationError('INTERRUPTED');
779
+ const ticket = this.bridge.issue({ role: 'agent', compactOnly: true, context: { conversationId: String(conversation.id), principalId: String(conversation.owner_principal_id), inputId: (0, crypto_2.randomUUID)(), decisionId: (0, crypto_2.randomUUID)(), epoch: Number(conversation.epoch), execute: false, writeMemory: false } }, (0, path_1.join)(this.root, 'compactions', (0, crypto_2.randomUUID)()), this.agent.workspace, '');
780
+ revoke = ticket.revoke;
781
+ ticket.profile.cliSession = { id: cliId, resume: true };
782
+ ticket.profile.connectorsAllowed = false;
783
+ ticket.profile.overlay = 'Perform only the requested native context compaction. Do not execute tasks or tools.';
784
+ process = await this.host.createAgentSession(sessionId, ticket.profile, model, { agentId: this.agent.id, agentSessionId: sessionId, source: conversation.source, accountId: String(conversation.account_id), chatId: String(conversation.chat_id), threadKey: String(conversation.thread_key), principalId: String(conversation.owner_principal_id) });
785
+ if (active.stopping || this.closing)
786
+ throw new types_2.OrchestrationError('INTERRUPTED');
787
+ this.contextDelivery.invalidateConversation(String(conversation.id));
788
+ const startedAt = Date.now(), compact = (0, native_compact_1.startNativeCompact)(process);
789
+ active.turn = compact;
790
+ await compact.result;
791
+ let measured = compact.measurements();
792
+ if (this.agent.type !== 'app-agent' && measured?.afterTokens == null) {
793
+ const storedMetrics = await (0, compact_measurements_1.readCompactMeasurements)((0, claude_settings_1.transcriptPath)(this.agent.workspace, cliId), startedAt, Date.now());
794
+ if (storedMetrics)
795
+ measured = storedMetrics;
796
+ }
797
+ this.store.transaction(() => this.store.appendEvent(String(conversation.id), 'session.context_compacted', { sessionId, cliSessionId: cliId }));
798
+ return measured;
799
+ }
800
+ finally {
801
+ active.turn = undefined;
802
+ active.maintenance = previous;
803
+ revoke?.();
804
+ if (process)
805
+ await this.host.releaseAgentSession(sessionId, process);
806
+ }
807
+ }
796
808
  compactionMaintenance(window) {
797
809
  return this.sessionCompaction ?? (this.sessionCompaction = new session_compaction_1.SessionCompaction(this.store, this.agent.id, {
798
810
  busy: id => this.active.has(id), stopping: () => this.closing || this.draining,
@@ -1535,9 +1547,62 @@ class AgentOrchestrationRuntime {
1535
1547
  const preparedRefs = preparedInputs.flatMap(row => JSON.parse(String(row.attachment_refs_json)));
1536
1548
  if (preparedRefs.length)
1537
1549
  input = { ...input, attachmentIds: [...new Set([...(input.attachmentIds ?? []), ...preparedRefs])] };
1538
- const cliSession = this.agent.type === 'app-agent'
1539
- ? await this.cliSessions.resolveContainer(sessionId, await this.executionAgent(input.scope.source, input.scope.chatId, sessionId))
1540
- : this.cliSessions.resolve(sessionId, this.agent.workspace);
1550
+ // This turn's new images ride on top of the resumed transcript in the same request;
1551
+ // images that context already holds are not re-sent (compaction forgets them all).
1552
+ // Computer screenshots are attached only after the session is chosen (see the
1553
+ // COMPUTER_PROMPT_SCREENSHOTS loop), so reserve every candidate at its size cap.
1554
+ const screenshotReserve = computer_1.MAX_SCREENSHOT_BASE64 * this.tasks.context(receipt.conversationId, input.scope.principalId, decision.decisionId)
1555
+ .filter(task => task.gatewayTarget?.adapter === 'computer' && (task.pendingQuestion || this.store.get("SELECT 1 FROM notifications WHERE task_id=? AND decision_id=? AND status='assigned' LIMIT 1", task.taskId, decision.decisionId)))
1556
+ .slice(0, COMPUTER_PROMPT_SCREENSHOTS).length;
1557
+ const resolveCli = async (compacted) => {
1558
+ const storedCli = this.store.get('SELECT cli_session_id FROM agent_cli_sessions WHERE session_id=?', sessionId);
1559
+ const delivered = storedCli ? this.contextDelivery.deliveredImageRefs(receipt.conversationId, input.scope.principalId, String(admitted.binding_id), String(storedCli.cli_session_id)) : new Set();
1560
+ const reserveBytes = screenshotReserve + await (0, input_images_1.inputImageBytes)((0, path_1.join)(this.agent.workspace, '../..'), this.agent.id, input.attachmentIds?.filter(ref => !delivered.has(ref)));
1561
+ return this.agent.type === 'app-agent'
1562
+ ? this.cliSessions.resolveContainer(sessionId, await this.executionAgent(input.scope.source, input.scope.chatId, sessionId), false, reserveBytes, compacted)
1563
+ : this.cliSessions.resolve(sessionId, this.agent.workspace, false, reserveBytes, compacted);
1564
+ };
1565
+ let resetNoticeOperation;
1566
+ let cliSession = await resolveCli(false);
1567
+ if (cliSession.compact) {
1568
+ // The ladder's byte trigger (see MAX_RESUMABLE_TRANSCRIPT_BYTES): compact natively now,
1569
+ // while the compact request still fits, then re-check. A failed compaction is not this
1570
+ // turn's failure; the re-check resumes if the turn still fits and resets only if not.
1571
+ const conversation = this.store.get('SELECT * FROM conversations WHERE id=?', receipt.conversationId);
1572
+ try {
1573
+ await this.nativeCompact(sessionId, conversation, cliSession.id, options.model, active);
1574
+ }
1575
+ catch (error) {
1576
+ if (active.stopping || this.closing)
1577
+ throw error;
1578
+ this.cliSessions.compactionFailed(cliSession.id);
1579
+ const code = error?.code;
1580
+ console.warn(JSON.stringify({ ts: new Date().toISOString(), level: 'warn', event: 'Byte-triggered context compaction failed', agentId: this.agent.id,
1581
+ sessionId, cliSessionId: cliSession.id, code: typeof code === 'string' && /^[A-Za-z0-9_]{1,80}$/.test(code) ? code : 'ERROR' }));
1582
+ }
1583
+ cliSession = await resolveCli(true);
1584
+ }
1585
+ // Recorded right away: resolve() has already moved the mapping to the new id, so an
1586
+ // interruption before the spawn must not lose the reason or the user's notice.
1587
+ if (cliSession.fallback) {
1588
+ // No silent failure: a session we had already started could not be continued, so this
1589
+ // turn re-seeds history and pays a cache write. Record why before it happens.
1590
+ this.store.transaction(() => this.store.appendEvent(receipt.conversationId, 'session.transcript_unavailable', { sessionId, cliSessionId: cliSession.id, reason: cliSession.fallback }));
1591
+ console.warn(JSON.stringify({ ts: new Date().toISOString(), level: 'warn',
1592
+ event: 'Agent CLI session could not be resumed; reseeding history', agentId: this.agent.id,
1593
+ sessionId, cliSessionId: cliSession.id, reason: cliSession.fallback }));
1594
+ // Unlike the other fallbacks this one drops context the user can see (images, tool
1595
+ // output), so tell them rather than letting the agent appear to forget.
1596
+ if (cliSession.fallback === 'TRANSCRIPT_TOO_LARGE') {
1597
+ try {
1598
+ resetNoticeOperation = `response:${await this.publishNotice(sessionId, receipt.conversationId, agent_cli_session_1.TRANSCRIPT_TOO_LARGE_NOTICE, true)}`;
1599
+ }
1600
+ catch (error) {
1601
+ const code = error?.code;
1602
+ console.warn('[orchestration] transcript reset notice not delivered', { sessionId, code: typeof code === 'string' && /^[A-Za-z0-9_]{1,80}$/.test(code) ? code : 'ERROR' });
1603
+ }
1604
+ }
1605
+ }
1541
1606
  const contextPlan = this.contextDelivery.begin({ conversationId: receipt.conversationId,
1542
1607
  principalId: input.scope.principalId, bindingId: String(admitted.binding_id),
1543
1608
  cliSessionId: cliSession.id, resume: cliSession.resume });
@@ -1853,18 +1918,12 @@ class AgentOrchestrationRuntime {
1853
1918
  transcriptCheckpoint = await (0, transcript_checkpoint_1.checkpointTranscript)((0, claude_settings_1.transcriptPath)(this.agent.workspace, cliSession.id));
1854
1919
  if (cliSession.resume && this.agent.type === 'app-agent')
1855
1920
  restoreContainerTranscript = await (0, agent_cli_session_1.containerTranscriptCheckpoint)((await this.executionAgent(input.scope.source, input.scope.chatId, sessionId)).container, cliSession.id);
1856
- if (cliSession.fallback) {
1857
- // No silent failure: a session we had already started could not be continued, so this
1858
- // turn re-seeds history and pays a cache write. Record why before it happens.
1859
- this.store.transaction(() => this.store.appendEvent(receipt.conversationId, 'session.transcript_unavailable', { sessionId, cliSessionId: cliSession.id, reason: cliSession.fallback }));
1860
- console.warn(JSON.stringify({ ts: new Date().toISOString(), level: 'warn',
1861
- event: 'Agent CLI session could not be resumed; reseeding history', agentId: this.agent.id,
1862
- sessionId, cliSessionId: cliSession.id, reason: cliSession.fallback }));
1863
- }
1864
1921
  }
1865
1922
  ticket.profile.excludedHistoryOperationIds = this.store.all(`SELECT r.id FROM assistant_responses r
1866
1923
  JOIN conversation_decisions d ON d.id=r.decision_id WHERE d.session_id=? AND r.state='failed'`, sessionId)
1867
1924
  .map(row => `response:${row.id}`)
1925
+ // The reset notice is for the user; seeded into the fresh context it reads as the agent's own reply.
1926
+ .concat(resetNoticeOperation ? [resetNoticeOperation] : [])
1868
1927
  // This turn's own inputs are already persisted, and the prompt delivers them as the current
1869
1928
  // message; seeding them too would end the history on an unanswered user turn.
1870
1929
  .concat(decision.inputIds.map(id => `input:${id}`));
@@ -1879,7 +1938,7 @@ class AgentOrchestrationRuntime {
1879
1938
  const endScreenshots = [];
1880
1939
  const controlEvidence = [];
1881
1940
  const computerImageContext = [];
1882
- for (const row of taskCandidates.filter(t => t.gatewayTarget?.adapter === 'computer' && (reportingTasks.has(t.taskId) || t.pendingQuestion)).slice(0, 2)) {
1941
+ for (const row of taskCandidates.filter(t => t.gatewayTarget?.adapter === 'computer' && (reportingTasks.has(t.taskId) || t.pendingQuestion)).slice(0, COMPUTER_PROMPT_SCREENSHOTS)) {
1883
1942
  const task = this.store.task(row.taskId);
1884
1943
  if (!task || task.ownerPrincipalId !== input.scope.principalId || task.conversationId !== receipt.conversationId)
1885
1944
  continue;