@code-yeongyu/senpi 2026.8.23 → 2026.8.24

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 (165) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/core/agent-abort-provenance.d.ts +5 -5
  3. package/dist/core/agent-abort-provenance.d.ts.map +1 -1
  4. package/dist/core/agent-abort-provenance.js +3 -0
  5. package/dist/core/agent-abort-provenance.js.map +1 -1
  6. package/dist/core/agent-session.d.ts +3 -0
  7. package/dist/core/agent-session.d.ts.map +1 -1
  8. package/dist/core/agent-session.js +4 -0
  9. package/dist/core/agent-session.js.map +1 -1
  10. package/dist/core/extensions/builtin/goal/agent-end-continuation.d.ts.map +1 -1
  11. package/dist/core/extensions/builtin/goal/agent-end-continuation.js +10 -0
  12. package/dist/core/extensions/builtin/goal/agent-end-continuation.js.map +1 -1
  13. package/dist/core/extensions/builtin/goal/continuation.d.ts +1 -1
  14. package/dist/core/extensions/builtin/goal/continuation.d.ts.map +1 -1
  15. package/dist/core/extensions/builtin/goal/continuation.js +1 -1
  16. package/dist/core/extensions/builtin/goal/continuation.js.map +1 -1
  17. package/dist/core/extensions/builtin/goal/index.d.ts.map +1 -1
  18. package/dist/core/extensions/builtin/goal/index.js +0 -8
  19. package/dist/core/extensions/builtin/goal/index.js.map +1 -1
  20. package/dist/core/extensions/builtin/goal/monitor-continuation-types.d.ts +1 -0
  21. package/dist/core/extensions/builtin/goal/monitor-continuation-types.d.ts.map +1 -1
  22. package/dist/core/extensions/builtin/goal/monitor-continuation-types.js.map +1 -1
  23. package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts +2 -1
  24. package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts.map +1 -1
  25. package/dist/core/extensions/builtin/goal/monitor-continuation.js +31 -3
  26. package/dist/core/extensions/builtin/goal/monitor-continuation.js.map +1 -1
  27. package/dist/core/extensions/builtin/goal/wait-ticker.d.ts.map +1 -1
  28. package/dist/core/extensions/builtin/goal/wait-ticker.js +14 -9
  29. package/dist/core/extensions/builtin/goal/wait-ticker.js.map +1 -1
  30. package/dist/core/extensions/builtin/webfetch/webfetch/fetcher.d.ts.map +1 -1
  31. package/dist/core/extensions/builtin/webfetch/webfetch/fetcher.js +5 -23
  32. package/dist/core/extensions/builtin/webfetch/webfetch/fetcher.js.map +1 -1
  33. package/dist/core/extensions/builtin/webfetch/webfetch/response-body.d.ts +11 -0
  34. package/dist/core/extensions/builtin/webfetch/webfetch/response-body.d.ts.map +1 -0
  35. package/dist/core/extensions/builtin/webfetch/webfetch/response-body.js +54 -0
  36. package/dist/core/extensions/builtin/webfetch/webfetch/response-body.js.map +1 -0
  37. package/dist/core/tools/read.d.ts.map +1 -1
  38. package/dist/core/tools/read.js +5 -0
  39. package/dist/core/tools/read.js.map +1 -1
  40. package/dist/modes/interactive/aborted-error-label.d.ts +2 -1
  41. package/dist/modes/interactive/aborted-error-label.d.ts.map +1 -1
  42. package/dist/modes/interactive/aborted-error-label.js +20 -5
  43. package/dist/modes/interactive/aborted-error-label.js.map +1 -1
  44. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  45. package/dist/modes/interactive/interactive-mode.js +11 -3
  46. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  47. package/dist/modes/interactive/streaming-reveal.d.ts +8 -0
  48. package/dist/modes/interactive/streaming-reveal.d.ts.map +1 -1
  49. package/dist/modes/interactive/streaming-reveal.js +12 -0
  50. package/dist/modes/interactive/streaming-reveal.js.map +1 -1
  51. package/docs/AGENTS.md +3 -1
  52. package/examples/AGENTS.md +21 -6
  53. package/examples/extensions/AGENTS.md +50 -0
  54. package/node_modules/@anthropic-ai/claude-agent-sdk/bridge.mjs +90 -88
  55. package/node_modules/@anthropic-ai/claude-agent-sdk/browser-sdk.js +40 -40
  56. package/node_modules/@anthropic-ai/claude-agent-sdk/manifest.json +20 -21
  57. package/node_modules/@anthropic-ai/claude-agent-sdk/manifest.zst.json +24 -25
  58. package/node_modules/@anthropic-ai/claude-agent-sdk/package.json +2 -2
  59. package/node_modules/@anthropic-ai/claude-agent-sdk/sdk-tools.d.ts +102 -5
  60. package/node_modules/@anthropic-ai/claude-agent-sdk/sdk.d.ts +31 -15
  61. package/node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs +80 -78
  62. package/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/index.js +1 -1
  63. package/node_modules/@aws-sdk/client-bedrock-runtime/package.json +13 -13
  64. package/node_modules/@aws-sdk/core/package.json +5 -5
  65. package/node_modules/@aws-sdk/credential-provider-env/package.json +5 -5
  66. package/node_modules/@aws-sdk/credential-provider-http/package.json +7 -7
  67. package/node_modules/@aws-sdk/credential-provider-ini/package.json +12 -12
  68. package/node_modules/@aws-sdk/credential-provider-login/package.json +6 -6
  69. package/node_modules/@aws-sdk/credential-provider-node/package.json +10 -10
  70. package/node_modules/@aws-sdk/credential-provider-process/package.json +5 -5
  71. package/node_modules/@aws-sdk/credential-provider-sso/package.json +7 -7
  72. package/node_modules/@aws-sdk/credential-provider-web-identity/package.json +6 -6
  73. package/node_modules/@aws-sdk/eventstream-handler-node/package.json +4 -4
  74. package/node_modules/@aws-sdk/middleware-eventstream/package.json +4 -4
  75. package/node_modules/@aws-sdk/middleware-websocket/package.json +6 -6
  76. package/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/cognito-identity/index.js +1 -1
  77. package/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js +1 -1
  78. package/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/index.js +1 -1
  79. package/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js +1 -1
  80. package/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/index.js +1 -1
  81. package/node_modules/@aws-sdk/nested-clients/package.json +8 -8
  82. package/node_modules/@aws-sdk/signature-v4-multi-region/package.json +3 -3
  83. package/node_modules/@aws-sdk/token-providers/package.json +6 -6
  84. package/node_modules/@aws-sdk/types/package.json +2 -2
  85. package/node_modules/@aws-sdk/xml-builder/package.json +2 -2
  86. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +14 -0
  87. package/node_modules/@code-yeongyu/senpi-codemode/package.json +5 -5
  88. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/AGENTS.md +40 -0
  89. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/AGENTS.md +40 -0
  90. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-manager.ts +1 -1
  91. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-notification.ts +3 -8
  92. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-notification-queue.ts +2 -6
  93. package/node_modules/@earendil-works/pi-agent-core/package.json +4 -4
  94. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  95. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  96. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
  97. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  98. package/node_modules/@earendil-works/pi-ai/package.json +4 -4
  99. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  100. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  101. package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts.map +1 -1
  102. package/node_modules/@earendil-works/pi-tui/dist/terminal.js +7 -4
  103. package/node_modules/@earendil-works/pi-tui/dist/terminal.js.map +1 -1
  104. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  105. package/node_modules/@smithy/signature-v4/dist-cjs/index.js +19 -7
  106. package/node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js +4 -1
  107. package/node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js +4 -1
  108. package/node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js +4 -1
  109. package/node_modules/@smithy/signature-v4/dist-es/headerUtil.js +10 -3
  110. package/node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js +4 -1
  111. package/node_modules/@smithy/signature-v4/dist-es/prepareRequest.js +4 -1
  112. package/node_modules/@smithy/signature-v4/package.json +2 -2
  113. package/node_modules/typebox/build/format/email.mjs +1 -1
  114. package/node_modules/typebox/build/format/idna/idn-hostname.mjs +19 -1
  115. package/node_modules/typebox/build/format/json_pointer.d.mts +2 -2
  116. package/node_modules/typebox/build/format/json_pointer.mjs +2 -2
  117. package/node_modules/typebox/build/format/json_pointer_uri_fragment.d.mts +2 -2
  118. package/node_modules/typebox/build/format/json_pointer_uri_fragment.mjs +2 -2
  119. package/node_modules/typebox/build/format/relative_json_pointer.d.mts +2 -2
  120. package/node_modules/typebox/build/format/relative_json_pointer.mjs +2 -2
  121. package/node_modules/typebox/build/system/memory/assign.mjs +2 -1
  122. package/node_modules/typebox/build/system/memory/create.mjs +3 -4
  123. package/node_modules/typebox/build/system/memory/discard.mjs +2 -2
  124. package/node_modules/typebox/build/system/memory/freeze.d.mts +4 -0
  125. package/node_modules/typebox/build/system/memory/freeze.mjs +6 -0
  126. package/node_modules/typebox/build/system/memory/update.mjs +3 -2
  127. package/node_modules/typebox/package.json +1 -1
  128. package/package.json +36 -36
  129. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/LICENSE +0 -201
  130. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/README.md +0 -62
  131. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-cjs/index.js +0 -154
  132. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-es/constants.js +0 -2
  133. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-es/fromEnvSigningName.js +0 -16
  134. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-es/fromSso.js +0 -80
  135. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-es/fromStatic.js +0 -8
  136. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-es/getNewSsoOidcToken.js +0 -11
  137. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-es/getSsoOidcClient.js +0 -10
  138. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-es/index.js +0 -4
  139. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-es/nodeProvider.js +0 -5
  140. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-es/validateTokenExpiry.js +0 -7
  141. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-es/validateTokenKey.js +0 -7
  142. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-es/writeSSOTokenToFile.js +0 -8
  143. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/constants.d.ts +0 -8
  144. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/fromEnvSigningName.d.ts +0 -18
  145. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/fromSso.d.ts +0 -12
  146. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/fromStatic.d.ts +0 -9
  147. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/getNewSsoOidcToken.d.ts +0 -8
  148. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/getSsoOidcClient.d.ts +0 -7
  149. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/index.d.ts +0 -7
  150. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/nodeProvider.d.ts +0 -18
  151. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/ts3.4/constants.d.ts +0 -3
  152. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/ts3.4/fromEnvSigningName.d.ts +0 -8
  153. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/ts3.4/fromSso.d.ts +0 -10
  154. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/ts3.4/fromStatic.d.ts +0 -5
  155. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/ts3.4/getNewSsoOidcToken.d.ts +0 -9
  156. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/ts3.4/getSsoOidcClient.d.ts +0 -7
  157. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/ts3.4/index.d.ts +0 -7
  158. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/ts3.4/nodeProvider.d.ts +0 -3
  159. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/ts3.4/validateTokenExpiry.d.ts +0 -2
  160. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/ts3.4/validateTokenKey.d.ts +0 -1
  161. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/ts3.4/writeSSOTokenToFile.d.ts +0 -2
  162. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/validateTokenExpiry.d.ts +0 -5
  163. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/validateTokenKey.d.ts +0 -4
  164. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-types/writeSSOTokenToFile.d.ts +0 -5
  165. package/node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/package.json +0 -69
@@ -1 +1 @@
1
- {"version":3,"file":"monitor-continuation.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/monitor-continuation.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,+BAA+B,EAC/B,wBAAwB,EACxB,4BAA4B,EAC5B,2CAA2C,EAI3C,qCAAqC,GACrC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAE7E,OAAO,EAAE,2CAA2C,EAAE,MAAM,iBAAiB,CAAC;AAE9E,OAAO,EACN,yBAAyB,EACzB,wBAAwB,EACxB,wBAAwB,EAGxB,2BAA2B,EAC3B,iBAAiB,EACjB,sBAAsB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EACN,6BAA6B,EAC7B,qCAAqC,EACrC,iBAAiB,GACjB,MAAM,wBAAwB,CAAC;AAShC,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,6BAA6B,EAAE,MAAM,aAAa,CAAC;AAC3G,OAAO,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAIxD,MAAM,CAAC,MAAM,iCAAiC,GAAG,6BAA6B,CAAC;AAC/E,MAAM,CAAC,MAAM,+BAA+B,GAAG,2BAA2B,CAAC;AAC3E,MAAM,CAAC,MAAM,mCAAmC,GAAG,+BAA+B,CAAC;AACnF,MAAM,CAAC,MAAM,wBAAwB,GAAG,iCAAiC,CAAC;AAE1E,MAAM,OAAO,4BAA4B;IAC/B,GAAG,CAAe;IAClB,sBAAsB,CAAgB;IACtC,wBAAwB,CAAa;IACrC,WAAW,CAA6B;IACjD,Y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,wBAAwB;QACvB,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;QAC7B,IAAI,CAAC,4BAA4B,GAAG,SAAS,CAAC;IAC/C,CAAC;IAED,gCAAgC;QAC/B,IAAI,CAAC,2BAA2B,GAAG,CAAC,CAAC;QACrC,IAAI,CAAC,qBAAqB,GAAG,IAAI,CAAC;IACnC,CAAC;IAED,YAAY;QACX,MAAM,IAAI,GAAG,IAAI,CAAC,0BAA0B,CAAC;QAC7C,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QACnC,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QACnC,IAAI,CAAC,4BAA4B,GAAG,SAAS,CAAC;QAC9C,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YAAE,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,IAAI,CAAC,0BAA0B,GAAG,SAAS,CAAC;QAC5C,IAAI,IAAI,KAAK,SAAS;YAAE,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,mCAAmC,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3G,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC;IAC1B,CAAC;CACD","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ExtensionAPI, ExtensionContext } from \"../../types.ts\";\nimport {\n\tcreateGoalCacheWarmScheduleData,\n\testimateCacheWarmMetrics,\n\tGOAL_CACHE_WARMUP_ENTRY_TYPE,\n\tGOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS,\n\ttype GoalCacheWarmMetrics,\n\ttype GoalCacheWarmupEntryData,\n\ttype LiveGoalCacheWarmupEntryData,\n\tresolveGoalMonitorContinuationDelayMs,\n} from \"./cache-warm.ts\";\nimport { subscribeGoalChannelState } from \"./channel-state-subscriptions.ts\";\n\nexport { GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS } from \"./cache-warm.ts\";\n\nimport {\n\tcontinuationTurnUsedTools,\n\tevaluateGoalContinuation,\n\tGOAL_USER_GRACE_DELAY_MS,\n\ttype GoalContinuationInput,\n\ttype GoalContinuationPath,\n\thasGoalContinuationProgress,\n\thashAssistantText,\n\tnormalizeAssistantText,\n} from \"./continuation.ts\";\nimport { lastAssistantMessage } from \"./last-assistant-message.ts\";\nimport {\n\tadmitAndQueueGoalContinuation,\n\tbuildCurrentGoalContinuationSignature,\n\tlastAssistantText,\n} from \"./lifecycle-helpers.ts\";\nimport type {\n\tAgentEndOptions,\n\tContinuingGoalContinuationVerdict,\n\tDelayedContinuationKind,\n\tGoalContinuationAdmission,\n\tResumptionChannelCounts,\n\tSystemAbortOptions,\n} from \"./monitor-continuation-types.ts\";\nimport { buildContinuationPrompt, buildGoalStallNotice, buildTruncationRecoveryPrompt } from \"./prompt.ts\";\nimport { resetContinuationStreak } from \"./store.ts\";\nimport { goalStoreRef } from \"./store-ref.ts\";\nimport { collectAssistantUsage } from \"./turn-usage.ts\";\nimport type { Goal, TokenUsageSnapshot } from \"./types.ts\";\nimport type { GoalWaitTicker } from \"./wait-ticker.ts\";\n\nexport const GOAL_CONTINUATION_SCHEDULED_EVENT = \"goal_continuation_scheduled\";\nexport const GOAL_CONTINUATION_RESUMED_EVENT = \"goal_continuation_resumed\";\nexport const GOAL_CONTINUATION_TIMER_STATE_EVENT = \"goal_continuation_timer_state\";\nexport const GOAL_MONITOR_STALL_EVENT = \"goal_monitor_continuation_stall\";\n\nexport class MonitorAwareGoalContinuation {\n\treadonly #pi: ExtensionAPI;\n\treadonly #isContinuationPending: () => boolean;\n\treadonly #markContinuationPending: () => void;\n\treadonly #waitTicker: GoalWaitTicker | undefined;\n\t#wakeSources = new Map<string, number>();\n\t#hasStarted = false;\n\t#ctx: ExtensionContext | undefined;\n\t#goal: Goal | null = null;\n\t#timer: ReturnType<typeof setTimeout> | undefined;\n\t#scheduledContinuationKind: DelayedContinuationKind | undefined;\n\t#channelStateUnsubscribers: Array<() => void> = [];\n\t#lastAgentEndMessages: readonly AgentMessage[] = [];\n\t#consecutiveLengthRecoveries = new Map<string, number>();\n\t#recentNormalizedOutputHashes: string[] = [];\n\t#toollessContinuationStreak = 0;\n\t#toollessStreakGoalId: string | null = null;\n\t#endedTurnWasUserInitiated = false;\n\t#lastTurnUsage: TokenUsageSnapshot | undefined;\n\t#scheduledAtMs: number | undefined;\n\t#scheduledDueAtMs: number | undefined;\n\t#scheduledCache: GoalCacheWarmMetrics | undefined;\n\t#scheduledDelayMs: number | undefined;\n\t#cacheWarmIteration = 0;\n\t#scheduledCacheWarmIteration: number | undefined;\n\t#heldTimer:\n\t\t| { kind: DelayedContinuationKind; remainingMs: number; heldAtMs: number; totalMs: number; drainFire: boolean }\n\t\t| undefined;\n\t#directInputHolds = new Set<string>();\n\t#pendingSystemRecovery: SystemAbortOptions | undefined;\n\n\tconstructor(\n\t\tpi: ExtensionAPI,\n\t\tisContinuationPending: () => boolean = () => false,\n\t\tmarkContinuationPending: () => void = () => {},\n\t\twaitTicker?: GoalWaitTicker,\n\t) {\n\t\tthis.#pi = pi;\n\t\tthis.#isContinuationPending = isContinuationPending;\n\t\tthis.#markContinuationPending = markContinuationPending;\n\t\tthis.#waitTicker = waitTicker;\n\t\tthis.#subscribeToChannelState();\n\t}\n\n\tstart(ctx: ExtensionContext): void {\n\t\tthis.#cancelTimer();\n\t\tthis.#ctx = ctx;\n\t\tif (this.#hasStarted) this.#wakeSources.clear();\n\t\telse this.#hasStarted = true;\n\t\tthis.#goal = null;\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\tasync afterAgentEnd(options: AgentEndOptions): Promise<Goal | null> {\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tthis.#resetLengthRecoveryAfterCleanStop(options.goal, options.messages);\n\t\tconst turnUsedTools = continuationTurnUsedTools(options.messages);\n\t\tthis.#recordAssistantOutput(options.messages, turnUsedTools);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tthis.#recordToollessContinuationTurn(options.goal, turnUsedTools);\n\t\tconst immediateInput = this.#buildVerdictInput(options.ctx, options.goal, \"immediate\", options.messages);\n\t\tconst goal =\n\t\t\t!this.#endedTurnWasUserInitiated && (turnUsedTools || hasGoalContinuationProgress(immediateInput))\n\t\t\t\t? ((await resetContinuationStreak(goalStoreRef(options.ctx.sessionManager, options.ctx.cwd))) ??\n\t\t\t\t\toptions.goal)\n\t\t\t\t: options.goal;\n\t\tthis.#goal = goal;\n\t\tconst immediateVerdict = evaluateGoalContinuation({\n\t\t\tgoal,\n\t\t\t...this.#buildVerdictInput(options.ctx, goal, \"immediate\", options.messages),\n\t\t});\n\t\tif (this.#endedTurnWasUserInitiated) {\n\t\t\tthis.#endedTurnWasUserInitiated = false;\n\t\t\tthis.#cancelTimer();\n\t\t\tif (immediateVerdict.kind === \"continue\") {\n\t\t\t\tthis.#schedule(goal, \"userGrace\");\n\t\t\t\treturn goal;\n\t\t\t}\n\t\t\tswitch (immediateVerdict.reason) {\n\t\t\t\tcase \"not-eligible\":\n\t\t\t\tcase \"single-flight\":\n\t\t\t\tcase \"stale\":\n\t\t\t\t\treturn goal;\n\t\t\t\tcase \"cap\":\n\t\t\t\tcase \"repetition\":\n\t\t\t\tcase \"length-exhausted\": {\n\t\t\t\t\tconst admission = await this.#admitAndQueue(options.ctx, goal, \"immediate\", options.messages);\n\t\t\t\t\treturn admission.goal;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (immediateVerdict.kind === \"deny\" && immediateVerdict.reason === \"not-eligible\") return goal;\n\n\t\tif (this.#activeWakeSourceCount() === 0) {\n\t\t\tthis.#cancelTimer();\n\t\t\tconst admission = await this.#admitAndQueue(options.ctx, goal, \"immediate\", options.messages);\n\t\t\treturn admission.goal;\n\t\t}\n\t\tthis.#schedule(goal, \"monitor\");\n\t\treturn goal;\n\t}\n\n\tasync afterSystemAbort(options: SystemAbortOptions): Promise<Goal | null> {\n\t\tthis.noteContinuationStarted();\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tif (options.willRetry) return options.goal;\n\t\tif (this.#activeWakeSourceCount() > 0) this.#schedule(options.goal, \"monitor\");\n\t\telse if (lastAssistantMessage(options.messages)?.stopReason === \"error\") {\n\t\t\tthis.#pendingSystemRecovery = options;\n\t\t}\n\t\treturn options.goal;\n\t}\n\n\tasync afterAgentSettled(): Promise<Goal | null | undefined> {\n\t\tconst pending = this.#pendingSystemRecovery;\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tif (pending === undefined || pending.goal === null || pending.event.abortSource === \"user\") return undefined;\n\t\treturn (await this.#admitAndQueue(pending.ctx, pending.goal, \"systemRecovery\", pending.messages)).goal;\n\t}\n\n\tsyncGoal(goal: Goal | null): void {\n\t\tif (goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#goal = goal;\n\t\tif (goal?.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetContinuationState();\n\t\t}\n\t}\n\n\t/** Live resumption channels known to this generation (e.g. terminal snapshots replayed on reload). */\n\thasActiveWakeSources(): boolean {\n\t\treturn this.#activeWakeSourceCount() > 0;\n\t}\n\n\t/**\n\t * Re-arms the monitor-delayed backstop a reload tore down with the retired\n\t * generation, so a later wake-source drain can still deliver the goal\n\t * continuation. No-op unless the goal is active, a wake source is live, and\n\t * no continuation is already scheduled.\n\t */\n\trearmMonitorBackstop(goal: Goal): void {\n\t\tif (goal.status !== \"active\" || this.#activeWakeSourceCount() === 0) return;\n\t\tthis.#goal = goal;\n\t\tthis.#schedule(goal, \"monitor\");\n\t}\n\n\t/** Temporarily prevents a scheduled continuation from racing unresolved direct-input admission. */\n\tholdDirectInput(inputId: string): void {\n\t\tif (this.#directInputHolds.has(inputId)) return;\n\t\tthis.#directInputHolds.add(inputId);\n\t\tif (\n\t\t\tthis.#directInputHolds.size !== 1 ||\n\t\t\tthis.#timer === undefined ||\n\t\t\tthis.#scheduledContinuationKind === undefined\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst heldAtMs = Date.now();\n\t\tthis.#heldTimer = {\n\t\t\tkind: this.#scheduledContinuationKind,\n\t\t\tremainingMs: Math.max(0, (this.#scheduledDueAtMs ?? heldAtMs) - heldAtMs),\n\t\t\theldAtMs,\n\t\t\ttotalMs: this.#scheduledDelayMs ?? GOAL_USER_GRACE_DELAY_MS,\n\t\t\tdrainFire: false,\n\t\t};\n\t\tclearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#waitTicker?.stop();\n\t}\n\n\t/** Resolves one admission hold without allowing overlapping inputs to consume each other. */\n\tresolveDirectInput(inputId: string, accepted: boolean): void {\n\t\tif (!this.#directInputHolds.delete(inputId)) return;\n\t\tif (accepted) {\n\t\t\tthis.#heldTimer = undefined;\n\t\t\tthis.noteUserPrompt();\n\t\t\treturn;\n\t\t}\n\t\tif (this.#directInputHolds.size > 0 || this.#heldTimer === undefined) return;\n\t\tconst held = this.#heldTimer;\n\t\tthis.#heldTimer = undefined;\n\t\tconst elapsedWhileHeldMs = Math.max(0, Date.now() - held.heldAtMs);\n\t\tthis.#armTimer(held.kind, Math.max(0, held.remainingMs - elapsedWhileHeldMs), held.totalMs, held.drainFire);\n\t}\n\n\t/** An accepted real user prompt starts a grace-governed user turn. */\n\tnoteUserPrompt(): void {\n\t\tthis.#cancelTimer();\n\t\tthis.#endedTurnWasUserInitiated = true;\n\t\tthis.#resetContinuationState();\n\t}\n\n\t/** A hidden continuation or system recovery has started, so the next end is not user-initiated. */\n\tnoteContinuationStarted(): void {\n\t\tthis.#endedTurnWasUserInitiated = false;\n\t}\n\n\tdispose(): void {\n\t\tthis.#cancelTimer();\n\t\tfor (const unsubscribe of this.#channelStateUnsubscribers) unsubscribe();\n\t\tthis.#channelStateUnsubscribers = [];\n\t\tthis.#ctx = undefined;\n\t\tthis.#goal = null;\n\t\tthis.#wakeSources.clear();\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\t#schedule(goal: Goal, kind: DelayedContinuationKind): void {\n\t\tif (this.#scheduledContinuationKind !== undefined) return;\n\t\tconst delayMs =\n\t\t\tkind === \"monitor\"\n\t\t\t\t? resolveGoalMonitorContinuationDelayMs(\n\t\t\t\t\t\tthis.#ctx?.getPromptCacheSafeWaitSeconds?.(),\n\t\t\t\t\t\tthis.#ctx?.getPromptCacheGoalBackstopMaxSeconds?.(),\n\t\t\t\t\t)\n\t\t\t\t: GOAL_USER_GRACE_DELAY_MS;\n\t\tthis.#scheduledDelayMs = delayMs;\n\t\tif (kind === \"monitor\") {\n\t\t\tthis.#cacheWarmIteration += 1;\n\t\t\tthis.#scheduledCacheWarmIteration = this.#cacheWarmIteration;\n\t\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\t\tconst cache = estimateCacheWarmMetrics(this.#ctx?.model, process.env, this.#lastTurnUsage);\n\t\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\t\tthis.#scheduledCache = cache;\n\t\t\tthis.#scheduledAtMs = Date.now();\n\t\t\tconst scheduleData = createGoalCacheWarmScheduleData({\n\t\t\t\tgoalId: goal.id,\n\t\t\t\tdelayMs,\n\t\t\t\tscheduledAtMs: this.#scheduledAtMs,\n\t\t\t\titeration,\n\t\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\t\twakeSources,\n\t\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t\t});\n\t\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_SCHEDULED_EVENT, scheduleData);\n\t\t\tthis.#appendWarmupEntry({\n\t\t\t\tphase: \"scheduled\",\n\t\t\t\t...scheduleData,\n\t\t\t});\n\t\t} else {\n\t\t\tthis.#scheduledAtMs = undefined;\n\t\t\tthis.#scheduledCache = undefined;\n\t\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\t}\n\t\tthis.#scheduledContinuationKind = kind;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: true, kind });\n\t\tif (this.#directInputHolds.size > 0) {\n\t\t\tthis.#heldTimer = { kind, remainingMs: delayMs, heldAtMs: Date.now(), totalMs: delayMs, drainFire: false };\n\t\t\treturn;\n\t\t}\n\t\tthis.#armTimer(kind, delayMs, delayMs);\n\t}\n\n\t#armTimer(kind: DelayedContinuationKind, delayMs: number, totalMs: number, drainFire = false): void {\n\t\tthis.#scheduledDueAtMs = Date.now() + delayMs;\n\t\tconst ctx = this.#ctx;\n\t\tif (ctx?.hasUI) {\n\t\t\tthis.#waitTicker?.sync(ctx, {\n\t\t\t\tkind,\n\t\t\t\tremainingMs: delayMs,\n\t\t\t\ttotalMs,\n\t\t\t\tchannelCounts: this.#wakeSourceSnapshot(),\n\t\t\t});\n\t\t}\n\t\tthis.#timer = setTimeout(() => {\n\t\t\tvoid this.#continueIfEligible(kind, drainFire).catch((error: unknown) => {\n\t\t\t\tif (this.#ctx?.hasUI) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tthis.#ctx.ui.notify(`Goal continuation delivery failed: ${message}`, \"error\");\n\t\t\t\t}\n\t\t\t});\n\t\t}, delayMs);\n\t}\n\n\tasync #continueIfEligible(kind: DelayedContinuationKind, drainFire = false): Promise<void> {\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#scheduledContinuationKind = undefined;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind });\n\t\tthis.#waitTicker?.stop();\n\t\tconst delayMs =\n\t\t\tthis.#scheduledDelayMs ??\n\t\t\t(kind === \"monitor\" ? GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS : GOAL_USER_GRACE_DELAY_MS);\n\t\tconst waitedMs = this.#scheduledAtMs === undefined ? delayMs : Math.max(0, Date.now() - this.#scheduledAtMs);\n\t\tconst cache = this.#scheduledCache;\n\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\tthis.#scheduledAtMs = undefined;\n\t\tthis.#scheduledCache = undefined;\n\t\tthis.#scheduledDelayMs = undefined;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\tconst ctx = this.#ctx;\n\t\tconst goal = this.#goal;\n\t\tif (ctx === undefined || goal?.status !== \"active\" || !ctx.isIdle() || ctx.hasPendingMessages()) return;\n\t\tif (kind === \"monitor\" && this.#activeWakeSourceCount() === 0 && !drainFire) return;\n\t\tconst admission = await this.#admitAndQueue(\n\t\t\tctx,\n\t\t\tgoal,\n\t\t\tkind === \"monitor\" ? \"monitorDelayed\" : \"userGrace\",\n\t\t\tthis.#lastAgentEndMessages,\n\t\t);\n\t\tif (kind !== \"monitor\" || !admission.admitted || iteration === undefined) return;\n\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_RESUMED_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\tcache,\n\t\t});\n\t\tthis.#appendWarmupEntry({\n\t\t\tphase: \"resumed\",\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t});\n\t\tif (drainFire || admission.goal.status !== \"active\") this.#resetCacheWarmIteration();\n\t}\n\n\tasync #admitAndQueue(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Promise<GoalContinuationAdmission> {\n\t\tconst input = this.#buildVerdictInput(ctx, goal, path, messages);\n\t\tconst verdict = evaluateGoalContinuation({ goal, ...input });\n\t\tconst admittedGoal = await admitAndQueueGoalContinuation(this.#pi, ctx, goal, {\n\t\t\tinput,\n\t\t\tcontent: (continuationVerdict) => this.#buildContinuationContent(ctx, goal, continuationVerdict),\n\t\t\tmarkContinuationPending: this.#markContinuationPending,\n\t\t});\n\t\tif (admittedGoal === null) {\n\t\t\tthis.#goal = null;\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t\treturn { goal, admitted: false };\n\t\t}\n\t\tif (verdict.kind === \"continue\" && input.lastStopReason === \"length\") {\n\t\t\tthis.#consecutiveLengthRecoveries.set(goal.id, input.consecutiveLengthRecoveries + 1);\n\t\t}\n\t\tthis.#goal = admittedGoal;\n\t\tif (admittedGoal.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t}\n\t\treturn { goal: admittedGoal, admitted: verdict.kind === \"continue\" };\n\t}\n\n\t#appendWarmupEntry(data: LiveGoalCacheWarmupEntryData): void {\n\t\tthis.#pi.appendEntry?.<GoalCacheWarmupEntryData>(GOAL_CACHE_WARMUP_ENTRY_TYPE, data);\n\t}\n\n\t#buildVerdictInput(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Omit<GoalContinuationInput, \"goal\"> {\n\t\tconst lastAssistant = lastAssistantMessage(messages);\n\t\treturn {\n\t\t\tisIdle: ctx.isIdle(),\n\t\t\thasPendingMessages: ctx.hasPendingMessages(),\n\t\t\tpath,\n\t\t\tlastStopReason: lastAssistant?.stopReason,\n\t\t\tconsecutiveContinuations: goal.consecutiveContinuations ?? 0,\n\t\t\tlastContinuationSignature: goal.lastContinuationSignature,\n\t\t\tcurrentSignature: buildCurrentGoalContinuationSignature(ctx, goal, lastAssistantText(messages)),\n\t\t\tconsecutiveLengthRecoveries: this.#consecutiveLengthRecoveries.get(goal.id) ?? 0,\n\t\t\trecentNormalizedOutputHashes: this.#recentNormalizedOutputHashes,\n\t\t\ttoollessContinuationStreak: this.#toollessContinuationStreak,\n\t\t\tcontinuationPending: this.#isContinuationPending(),\n\t\t};\n\t}\n\n\t#buildContinuationContent(ctx: ExtensionContext, goal: Goal, verdict: ContinuingGoalContinuationVerdict): string {\n\t\tlet content = verdict.prompt === \"minimal\" ? buildTruncationRecoveryPrompt() : buildContinuationPrompt(goal);\n\t\tif (!verdict.stallNotice) return content;\n\n\t\tconst liveSources = this.#liveWakeSources();\n\t\tthis.#pi.events?.emit(GOAL_MONITOR_STALL_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tconsecutiveContinuations: this.#toollessContinuationStreak,\n\t\t\ttoolless: true,\n\t\t});\n\t\tif (ctx.hasUI) {\n\t\t\tconst context =\n\t\t\t\tliveSources.length > 0 ? `while ${liveSources.join(\", \")} channels stayed active` : \"without tool use\";\n\t\t\tctx.ui.notify(\n\t\t\t\t`Goal continuation repeated ${this.#toollessContinuationStreak} toolless turns ${context} - injected a stall check.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t}\n\t\tcontent = `${buildGoalStallNotice(this.#toollessContinuationStreak, { liveSources })}\\n\\n${content}`;\n\t\treturn content;\n\t}\n\n\t/** A tool-using turn is forward progress, so it clears the repetition window instead of extending it. */\n\t#recordAssistantOutput(messages: readonly AgentMessage[], turnUsedTools: boolean): void {\n\t\tif (turnUsedTools) {\n\t\t\tthis.#recentNormalizedOutputHashes = [];\n\t\t\treturn;\n\t\t}\n\t\tconst text = lastAssistantText(messages);\n\t\tif (normalizeAssistantText(text).length === 0) return;\n\t\tthis.#recentNormalizedOutputHashes = [...this.#recentNormalizedOutputHashes, hashAssistantText(text)].slice(-3);\n\t}\n\n\t#recordToollessContinuationTurn(goal: Goal, turnUsedTools: boolean): void {\n\t\tif (goal.id !== this.#toollessStreakGoalId) {\n\t\t\tthis.#toollessStreakGoalId = goal.id;\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t}\n\t\tif (this.#endedTurnWasUserInitiated) return;\n\t\tif (turnUsedTools) {\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.#toollessContinuationStreak += 1;\n\t}\n\n\t#resetLengthRecoveryAfterCleanStop(goal: Goal | null, messages: readonly AgentMessage[]): void {\n\t\tif (goal === null || lastAssistantMessage(messages)?.stopReason !== \"stop\") return;\n\t\tthis.#consecutiveLengthRecoveries.delete(goal.id);\n\t}\n\n\t#subscribeToChannelState(): void {\n\t\tconst events = this.#pi.events;\n\t\tif (events === undefined) return;\n\t\tthis.#channelStateUnsubscribers.push(\n\t\t\t...subscribeGoalChannelState(events, {\n\t\t\t\tonWakeSource: (source, activeCount) => this.#setWakeSourceCount(source, activeCount),\n\t\t\t\tonContinuationHold: (source, active) => {\n\t\t\t\t\tconst inputId = `external:${source}`;\n\t\t\t\t\tif (active) this.holdDirectInput(inputId);\n\t\t\t\t\telse this.resolveDirectInput(inputId, false);\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t}\n\n\t#setWakeSourceCount(source: string, activeCount: number): void {\n\t\tconst previousTotal = this.#activeWakeSourceCount();\n\t\tthis.#wakeSources.set(source, activeCount);\n\t\tconst nextTotal = this.#activeWakeSourceCount();\n\t\tif (previousTotal > 0 && nextTotal === 0) {\n\t\t\tif (this.#scheduledContinuationKind === \"monitor\") this.#armDrainFire();\n\t\t\telse this.#resetCacheWarmIteration();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t\treturn;\n\t\t}\n\t\tif (this.#scheduledContinuationKind === \"monitor\") {\n\t\t\tthis.#waitTicker?.setChannelCounts(this.#wakeSourceSnapshot());\n\t\t}\n\t}\n\n\t#armDrainFire(): void {\n\t\tif (this.#directInputHolds.size > 0) {\n\t\t\tthis.#heldTimer = {\n\t\t\t\tkind: \"monitor\",\n\t\t\t\tremainingMs: 1_000,\n\t\t\t\theldAtMs: Date.now(),\n\t\t\t\ttotalMs: 1_000,\n\t\t\t\tdrainFire: true,\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\t\tif (this.#timer !== undefined) clearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#waitTicker?.stop();\n\t\tthis.#armTimer(\"monitor\", 1_000, 1_000, true);\n\t}\n\n\t#activeWakeSourceCount(): number {\n\t\tlet total = 0;\n\t\tfor (const count of this.#wakeSources.values()) total += count;\n\t\treturn total;\n\t}\n\n\t#wakeSourceSnapshot(): ResumptionChannelCounts {\n\t\treturn Object.fromEntries([...this.#wakeSources.entries()].sort(([left], [right]) => left.localeCompare(right)));\n\t}\n\n\t#liveWakeSources(): string[] {\n\t\treturn [...this.#wakeSources.entries()]\n\t\t\t.filter(([, count]) => count > 0)\n\t\t\t.map(([source]) => source)\n\t\t\t.sort();\n\t}\n\n\t#resetContinuationState(): void {\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#consecutiveLengthRecoveries.clear();\n\t\tthis.#recentNormalizedOutputHashes = [];\n\t\tthis.#resetToollessContinuationStreak();\n\t\tthis.#resetCacheWarmIteration();\n\t}\n\n\t#resetCacheWarmIteration(): void {\n\t\tthis.#cacheWarmIteration = 0;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t}\n\n\t#resetToollessContinuationStreak(): void {\n\t\tthis.#toollessContinuationStreak = 0;\n\t\tthis.#toollessStreakGoalId = null;\n\t}\n\n\t#cancelTimer(): void {\n\t\tconst kind = this.#scheduledContinuationKind;\n\t\tthis.#scheduledAtMs = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#scheduledCache = undefined;\n\t\tthis.#scheduledDelayMs = undefined;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\tthis.#heldTimer = undefined;\n\t\tif (this.#timer !== undefined) clearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledContinuationKind = undefined;\n\t\tif (kind !== undefined) this.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind });\n\t\tthis.#waitTicker?.stop();\n\t}\n}\n"]}
1
+ {"version":3,"file":"monitor-continuation.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/monitor-continuation.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,+BAA+B,EAC/B,wBAAwB,EACxB,4BAA4B,EAC5B,2CAA2C,EAI3C,qCAAqC,GACrC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAE7E,OAAO,EAAE,2CAA2C,EAAE,MAAM,iBAAiB,CAAC;AAE9E,OAAO,EACN,yBAAyB,EACzB,wBAAwB,EACxB,wBAAwB,EAGxB,2BAA2B,EAC3B,iBAAiB,EACjB,sBAAsB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EACN,6BAA6B,EAC7B,qC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,SAAS,CAAC;QAC5B,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YAAE,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,IAAI,CAAC,0BAA0B,GAAG,SAAS,CAAC;QAC5C,IAAI,IAAI,KAAK,SAAS;YAAE,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,mCAAmC,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3G,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC;IAC1B,CAAC;CACD","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ExtensionAPI, ExtensionContext } from \"../../types.ts\";\nimport {\n\tcreateGoalCacheWarmScheduleData,\n\testimateCacheWarmMetrics,\n\tGOAL_CACHE_WARMUP_ENTRY_TYPE,\n\tGOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS,\n\ttype GoalCacheWarmMetrics,\n\ttype GoalCacheWarmupEntryData,\n\ttype LiveGoalCacheWarmupEntryData,\n\tresolveGoalMonitorContinuationDelayMs,\n} from \"./cache-warm.ts\";\nimport { subscribeGoalChannelState } from \"./channel-state-subscriptions.ts\";\n\nexport { GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS } from \"./cache-warm.ts\";\n\nimport {\n\tcontinuationTurnUsedTools,\n\tevaluateGoalContinuation,\n\tGOAL_USER_GRACE_DELAY_MS,\n\ttype GoalContinuationInput,\n\ttype GoalContinuationPath,\n\thasGoalContinuationProgress,\n\thashAssistantText,\n\tnormalizeAssistantText,\n} from \"./continuation.ts\";\nimport { lastAssistantMessage } from \"./last-assistant-message.ts\";\nimport {\n\tadmitAndQueueGoalContinuation,\n\tbuildCurrentGoalContinuationSignature,\n\tlastAssistantText,\n} from \"./lifecycle-helpers.ts\";\nimport type {\n\tAgentEndOptions,\n\tContinuingGoalContinuationVerdict,\n\tDelayedContinuationKind,\n\tGoalContinuationAdmission,\n\tProviderRecoveryOptions,\n\tResumptionChannelCounts,\n\tSystemAbortOptions,\n} from \"./monitor-continuation-types.ts\";\nimport { buildContinuationPrompt, buildGoalStallNotice, buildTruncationRecoveryPrompt } from \"./prompt.ts\";\nimport { resetContinuationStreak } from \"./store.ts\";\nimport { goalStoreRef } from \"./store-ref.ts\";\nimport { collectAssistantUsage } from \"./turn-usage.ts\";\nimport type { Goal, TokenUsageSnapshot } from \"./types.ts\";\nimport type { GoalWaitTicker } from \"./wait-ticker.ts\";\n\nexport const GOAL_CONTINUATION_SCHEDULED_EVENT = \"goal_continuation_scheduled\";\nexport const GOAL_CONTINUATION_RESUMED_EVENT = \"goal_continuation_resumed\";\nexport const GOAL_CONTINUATION_TIMER_STATE_EVENT = \"goal_continuation_timer_state\";\nexport const GOAL_MONITOR_STALL_EVENT = \"goal_monitor_continuation_stall\";\n\nexport class MonitorAwareGoalContinuation {\n\treadonly #pi: ExtensionAPI;\n\treadonly #isContinuationPending: () => boolean;\n\treadonly #markContinuationPending: () => void;\n\treadonly #waitTicker: GoalWaitTicker | undefined;\n\t#wakeSources = new Map<string, number>();\n\t#hasStarted = false;\n\t#ctx: ExtensionContext | undefined;\n\t#goal: Goal | null = null;\n\t#timer: ReturnType<typeof setTimeout> | undefined;\n\t#scheduledContinuationKind: DelayedContinuationKind | undefined;\n\t#channelStateUnsubscribers: Array<() => void> = [];\n\t#lastAgentEndMessages: readonly AgentMessage[] = [];\n\t#consecutiveLengthRecoveries = new Map<string, number>();\n\t#recentNormalizedOutputHashes: string[] = [];\n\t#toollessContinuationStreak = 0;\n\t#toollessStreakGoalId: string | null = null;\n\t#endedTurnWasUserInitiated = false;\n\t#lastTurnUsage: TokenUsageSnapshot | undefined;\n\t#scheduledAtMs: number | undefined;\n\t#scheduledDueAtMs: number | undefined;\n\t#scheduledCache: GoalCacheWarmMetrics | undefined;\n\t#scheduledDelayMs: number | undefined;\n\t#cacheWarmIteration = 0;\n\t#scheduledCacheWarmIteration: number | undefined;\n\t#heldTimer:\n\t\t| { kind: DelayedContinuationKind; remainingMs: number; heldAtMs: number; totalMs: number; drainFire: boolean }\n\t\t| undefined;\n\t#directInputHolds = new Set<string>();\n\t#pendingSystemRecovery: SystemAbortOptions | undefined;\n\t#pendingProviderRecovery: ProviderRecoveryOptions | undefined;\n\n\tconstructor(\n\t\tpi: ExtensionAPI,\n\t\tisContinuationPending: () => boolean = () => false,\n\t\tmarkContinuationPending: () => void = () => {},\n\t\twaitTicker?: GoalWaitTicker,\n\t) {\n\t\tthis.#pi = pi;\n\t\tthis.#isContinuationPending = isContinuationPending;\n\t\tthis.#markContinuationPending = markContinuationPending;\n\t\tthis.#waitTicker = waitTicker;\n\t\tthis.#subscribeToChannelState();\n\t}\n\n\tstart(ctx: ExtensionContext): void {\n\t\tthis.#cancelTimer();\n\t\tthis.#ctx = ctx;\n\t\tif (this.#hasStarted) this.#wakeSources.clear();\n\t\telse this.#hasStarted = true;\n\t\tthis.#goal = null;\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\tasync afterAgentEnd(options: AgentEndOptions): Promise<Goal | null> {\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tthis.#resetLengthRecoveryAfterCleanStop(options.goal, options.messages);\n\t\tconst turnUsedTools = continuationTurnUsedTools(options.messages);\n\t\tthis.#recordAssistantOutput(options.messages, turnUsedTools);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tthis.#recordToollessContinuationTurn(options.goal, turnUsedTools);\n\t\tconst immediateInput = this.#buildVerdictInput(options.ctx, options.goal, \"immediate\", options.messages);\n\t\tconst goal =\n\t\t\t!this.#endedTurnWasUserInitiated && (turnUsedTools || hasGoalContinuationProgress(immediateInput))\n\t\t\t\t? ((await resetContinuationStreak(goalStoreRef(options.ctx.sessionManager, options.ctx.cwd))) ??\n\t\t\t\t\toptions.goal)\n\t\t\t\t: options.goal;\n\t\tthis.#goal = goal;\n\t\tconst immediateVerdict = evaluateGoalContinuation({\n\t\t\tgoal,\n\t\t\t...this.#buildVerdictInput(options.ctx, goal, \"immediate\", options.messages),\n\t\t});\n\t\tif (this.#endedTurnWasUserInitiated) {\n\t\t\tthis.#endedTurnWasUserInitiated = false;\n\t\t\tthis.#cancelTimer();\n\t\t\tif (immediateVerdict.kind === \"continue\") {\n\t\t\t\tthis.#schedule(goal, \"userGrace\");\n\t\t\t\treturn goal;\n\t\t\t}\n\t\t\tswitch (immediateVerdict.reason) {\n\t\t\t\tcase \"not-eligible\":\n\t\t\t\tcase \"single-flight\":\n\t\t\t\tcase \"stale\":\n\t\t\t\t\treturn goal;\n\t\t\t\tcase \"cap\":\n\t\t\t\tcase \"repetition\":\n\t\t\t\tcase \"length-exhausted\": {\n\t\t\t\t\tconst admission = await this.#admitAndQueue(options.ctx, goal, \"immediate\", options.messages);\n\t\t\t\t\treturn admission.goal;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (immediateVerdict.kind === \"deny\" && immediateVerdict.reason === \"not-eligible\") return goal;\n\n\t\tif (this.#activeWakeSourceCount() === 0) {\n\t\t\tthis.#cancelTimer();\n\t\t\tconst admission = await this.#admitAndQueue(options.ctx, goal, \"immediate\", options.messages);\n\t\t\treturn admission.goal;\n\t\t}\n\t\tthis.#schedule(goal, \"monitor\");\n\t\treturn goal;\n\t}\n\n\tasync afterSystemAbort(options: SystemAbortOptions): Promise<Goal | null> {\n\t\tthis.noteContinuationStarted();\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tif (options.willRetry) return options.goal;\n\t\tif (this.#activeWakeSourceCount() > 0) this.#schedule(options.goal, \"monitor\");\n\t\telse if (lastAssistantMessage(options.messages)?.stopReason === \"error\") {\n\t\t\tthis.#pendingSystemRecovery = options;\n\t\t}\n\t\treturn options.goal;\n\t}\n\n\tasync afterProviderFailure(options: ProviderRecoveryOptions): Promise<Goal | null> {\n\t\tthis.noteContinuationStarted();\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tif (!options.willRetry) this.#pendingProviderRecovery = options;\n\t\treturn options.goal;\n\t}\n\n\tasync afterAgentSettled(): Promise<Goal | null | undefined> {\n\t\tconst pendingSystem = this.#pendingSystemRecovery;\n\t\tconst pendingProvider = this.#pendingProviderRecovery;\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tif (pendingSystem !== undefined && pendingSystem.goal !== null && pendingSystem.event.abortSource !== \"user\") {\n\t\t\treturn (\n\t\t\t\tawait this.#admitAndQueue(pendingSystem.ctx, pendingSystem.goal, \"systemRecovery\", pendingSystem.messages)\n\t\t\t).goal;\n\t\t}\n\t\tif (\n\t\t\tpendingProvider === undefined ||\n\t\t\tpendingProvider.goal === null ||\n\t\t\tpendingProvider.event.abortSource === \"user\"\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn (\n\t\t\tawait this.#admitAndQueue(\n\t\t\t\tpendingProvider.ctx,\n\t\t\t\tpendingProvider.goal,\n\t\t\t\t\"providerRecovery\",\n\t\t\t\tpendingProvider.messages,\n\t\t\t)\n\t\t).goal;\n\t}\n\n\tsyncGoal(goal: Goal | null): void {\n\t\tif (goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#goal = goal;\n\t\tif (goal?.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetContinuationState();\n\t\t}\n\t}\n\n\t/** Live resumption channels known to this generation (e.g. terminal snapshots replayed on reload). */\n\thasActiveWakeSources(): boolean {\n\t\treturn this.#activeWakeSourceCount() > 0;\n\t}\n\n\t/**\n\t * Re-arms the monitor-delayed backstop a reload tore down with the retired\n\t * generation, so a later wake-source drain can still deliver the goal\n\t * continuation. No-op unless the goal is active, a wake source is live, and\n\t * no continuation is already scheduled.\n\t */\n\trearmMonitorBackstop(goal: Goal): void {\n\t\tif (goal.status !== \"active\" || this.#activeWakeSourceCount() === 0) return;\n\t\tthis.#goal = goal;\n\t\tthis.#schedule(goal, \"monitor\");\n\t}\n\n\t/** Temporarily prevents a scheduled continuation from racing unresolved direct-input admission. */\n\tholdDirectInput(inputId: string): void {\n\t\tif (this.#directInputHolds.has(inputId)) return;\n\t\tthis.#directInputHolds.add(inputId);\n\t\tif (\n\t\t\tthis.#directInputHolds.size !== 1 ||\n\t\t\tthis.#timer === undefined ||\n\t\t\tthis.#scheduledContinuationKind === undefined\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst heldAtMs = Date.now();\n\t\tthis.#heldTimer = {\n\t\t\tkind: this.#scheduledContinuationKind,\n\t\t\tremainingMs: Math.max(0, (this.#scheduledDueAtMs ?? heldAtMs) - heldAtMs),\n\t\t\theldAtMs,\n\t\t\ttotalMs: this.#scheduledDelayMs ?? GOAL_USER_GRACE_DELAY_MS,\n\t\t\tdrainFire: false,\n\t\t};\n\t\tclearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#waitTicker?.stop();\n\t}\n\n\t/** Resolves one admission hold without allowing overlapping inputs to consume each other. */\n\tresolveDirectInput(inputId: string, accepted: boolean): void {\n\t\tif (!this.#directInputHolds.delete(inputId)) return;\n\t\tif (accepted) {\n\t\t\tthis.#heldTimer = undefined;\n\t\t\tthis.noteUserPrompt();\n\t\t\treturn;\n\t\t}\n\t\tif (this.#directInputHolds.size > 0 || this.#heldTimer === undefined) return;\n\t\tconst held = this.#heldTimer;\n\t\tthis.#heldTimer = undefined;\n\t\tconst elapsedWhileHeldMs = Math.max(0, Date.now() - held.heldAtMs);\n\t\tthis.#armTimer(held.kind, Math.max(0, held.remainingMs - elapsedWhileHeldMs), held.totalMs, held.drainFire);\n\t}\n\n\t/** An accepted real user prompt starts a grace-governed user turn. */\n\tnoteUserPrompt(): void {\n\t\tthis.#cancelTimer();\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#endedTurnWasUserInitiated = true;\n\t\tthis.#resetContinuationState();\n\t}\n\n\t/** A hidden continuation or system recovery has started, so the next end is not user-initiated. */\n\tnoteContinuationStarted(): void {\n\t\tthis.#endedTurnWasUserInitiated = false;\n\t}\n\n\tdispose(): void {\n\t\tthis.#cancelTimer();\n\t\tfor (const unsubscribe of this.#channelStateUnsubscribers) unsubscribe();\n\t\tthis.#channelStateUnsubscribers = [];\n\t\tthis.#ctx = undefined;\n\t\tthis.#goal = null;\n\t\tthis.#wakeSources.clear();\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\t#schedule(goal: Goal, kind: DelayedContinuationKind): void {\n\t\tif (this.#scheduledContinuationKind !== undefined) return;\n\t\tconst delayMs =\n\t\t\tkind === \"monitor\"\n\t\t\t\t? resolveGoalMonitorContinuationDelayMs(\n\t\t\t\t\t\tthis.#ctx?.getPromptCacheSafeWaitSeconds?.(),\n\t\t\t\t\t\tthis.#ctx?.getPromptCacheGoalBackstopMaxSeconds?.(),\n\t\t\t\t\t)\n\t\t\t\t: GOAL_USER_GRACE_DELAY_MS;\n\t\tthis.#scheduledDelayMs = delayMs;\n\t\tif (kind === \"monitor\") {\n\t\t\tthis.#cacheWarmIteration += 1;\n\t\t\tthis.#scheduledCacheWarmIteration = this.#cacheWarmIteration;\n\t\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\t\tconst cache = estimateCacheWarmMetrics(this.#ctx?.model, process.env, this.#lastTurnUsage);\n\t\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\t\tthis.#scheduledCache = cache;\n\t\t\tthis.#scheduledAtMs = Date.now();\n\t\t\tconst scheduleData = createGoalCacheWarmScheduleData({\n\t\t\t\tgoalId: goal.id,\n\t\t\t\tdelayMs,\n\t\t\t\tscheduledAtMs: this.#scheduledAtMs,\n\t\t\t\titeration,\n\t\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\t\twakeSources,\n\t\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t\t});\n\t\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_SCHEDULED_EVENT, scheduleData);\n\t\t\tthis.#appendWarmupEntry({\n\t\t\t\tphase: \"scheduled\",\n\t\t\t\t...scheduleData,\n\t\t\t});\n\t\t} else {\n\t\t\tthis.#scheduledAtMs = undefined;\n\t\t\tthis.#scheduledCache = undefined;\n\t\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\t}\n\t\tthis.#scheduledContinuationKind = kind;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: true, kind });\n\t\tif (this.#directInputHolds.size > 0) {\n\t\t\tthis.#heldTimer = { kind, remainingMs: delayMs, heldAtMs: Date.now(), totalMs: delayMs, drainFire: false };\n\t\t\treturn;\n\t\t}\n\t\tthis.#armTimer(kind, delayMs, delayMs);\n\t}\n\n\t#armTimer(kind: DelayedContinuationKind, delayMs: number, totalMs: number, drainFire = false): void {\n\t\tthis.#scheduledDueAtMs = Date.now() + delayMs;\n\t\tconst ctx = this.#ctx;\n\t\tif (ctx?.hasUI) {\n\t\t\tthis.#waitTicker?.sync(ctx, {\n\t\t\t\tkind,\n\t\t\t\tremainingMs: delayMs,\n\t\t\t\ttotalMs,\n\t\t\t\tchannelCounts: this.#wakeSourceSnapshot(),\n\t\t\t});\n\t\t}\n\t\tthis.#timer = setTimeout(() => {\n\t\t\tvoid this.#continueIfEligible(kind, drainFire).catch((error: unknown) => {\n\t\t\t\tif (this.#ctx?.hasUI) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tthis.#ctx.ui.notify(`Goal continuation delivery failed: ${message}`, \"error\");\n\t\t\t\t}\n\t\t\t});\n\t\t}, delayMs);\n\t}\n\n\tasync #continueIfEligible(kind: DelayedContinuationKind, drainFire = false): Promise<void> {\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#scheduledContinuationKind = undefined;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind });\n\t\tthis.#waitTicker?.stop();\n\t\tconst delayMs =\n\t\t\tthis.#scheduledDelayMs ??\n\t\t\t(kind === \"monitor\" ? GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS : GOAL_USER_GRACE_DELAY_MS);\n\t\tconst waitedMs = this.#scheduledAtMs === undefined ? delayMs : Math.max(0, Date.now() - this.#scheduledAtMs);\n\t\tconst cache = this.#scheduledCache;\n\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\tthis.#scheduledAtMs = undefined;\n\t\tthis.#scheduledCache = undefined;\n\t\tthis.#scheduledDelayMs = undefined;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\tconst ctx = this.#ctx;\n\t\tconst goal = this.#goal;\n\t\tif (ctx === undefined || goal?.status !== \"active\" || !ctx.isIdle() || ctx.hasPendingMessages()) return;\n\t\tif (kind === \"monitor\" && this.#activeWakeSourceCount() === 0 && !drainFire) return;\n\t\tconst admission = await this.#admitAndQueue(\n\t\t\tctx,\n\t\t\tgoal,\n\t\t\tkind === \"monitor\" ? \"monitorDelayed\" : \"userGrace\",\n\t\t\tthis.#lastAgentEndMessages,\n\t\t);\n\t\tif (kind !== \"monitor\" || !admission.admitted || iteration === undefined) return;\n\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_RESUMED_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\tcache,\n\t\t});\n\t\tthis.#appendWarmupEntry({\n\t\t\tphase: \"resumed\",\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t});\n\t\tif (drainFire || admission.goal.status !== \"active\") this.#resetCacheWarmIteration();\n\t}\n\n\tasync #admitAndQueue(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Promise<GoalContinuationAdmission> {\n\t\tconst input = this.#buildVerdictInput(ctx, goal, path, messages);\n\t\tconst verdict = evaluateGoalContinuation({ goal, ...input });\n\t\tconst admittedGoal = await admitAndQueueGoalContinuation(this.#pi, ctx, goal, {\n\t\t\tinput,\n\t\t\tcontent: (continuationVerdict) => this.#buildContinuationContent(ctx, goal, continuationVerdict),\n\t\t\tmarkContinuationPending: this.#markContinuationPending,\n\t\t});\n\t\tif (admittedGoal === null) {\n\t\t\tthis.#goal = null;\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t\treturn { goal, admitted: false };\n\t\t}\n\t\tif (verdict.kind === \"continue\" && input.lastStopReason === \"length\") {\n\t\t\tthis.#consecutiveLengthRecoveries.set(goal.id, input.consecutiveLengthRecoveries + 1);\n\t\t}\n\t\tthis.#goal = admittedGoal;\n\t\tif (admittedGoal.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t}\n\t\treturn { goal: admittedGoal, admitted: verdict.kind === \"continue\" };\n\t}\n\n\t#appendWarmupEntry(data: LiveGoalCacheWarmupEntryData): void {\n\t\tthis.#pi.appendEntry?.<GoalCacheWarmupEntryData>(GOAL_CACHE_WARMUP_ENTRY_TYPE, data);\n\t}\n\n\t#buildVerdictInput(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Omit<GoalContinuationInput, \"goal\"> {\n\t\tconst lastAssistant = lastAssistantMessage(messages);\n\t\treturn {\n\t\t\tisIdle: ctx.isIdle(),\n\t\t\thasPendingMessages: ctx.hasPendingMessages(),\n\t\t\tpath,\n\t\t\tlastStopReason: lastAssistant?.stopReason,\n\t\t\tconsecutiveContinuations: goal.consecutiveContinuations ?? 0,\n\t\t\tlastContinuationSignature: goal.lastContinuationSignature,\n\t\t\tcurrentSignature: buildCurrentGoalContinuationSignature(ctx, goal, lastAssistantText(messages)),\n\t\t\tconsecutiveLengthRecoveries: this.#consecutiveLengthRecoveries.get(goal.id) ?? 0,\n\t\t\trecentNormalizedOutputHashes: this.#recentNormalizedOutputHashes,\n\t\t\ttoollessContinuationStreak: this.#toollessContinuationStreak,\n\t\t\tcontinuationPending: this.#isContinuationPending(),\n\t\t};\n\t}\n\n\t#buildContinuationContent(ctx: ExtensionContext, goal: Goal, verdict: ContinuingGoalContinuationVerdict): string {\n\t\tlet content = verdict.prompt === \"minimal\" ? buildTruncationRecoveryPrompt() : buildContinuationPrompt(goal);\n\t\tif (!verdict.stallNotice) return content;\n\n\t\tconst liveSources = this.#liveWakeSources();\n\t\tthis.#pi.events?.emit(GOAL_MONITOR_STALL_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tconsecutiveContinuations: this.#toollessContinuationStreak,\n\t\t\ttoolless: true,\n\t\t});\n\t\tif (ctx.hasUI) {\n\t\t\tconst context =\n\t\t\t\tliveSources.length > 0 ? `while ${liveSources.join(\", \")} channels stayed active` : \"without tool use\";\n\t\t\tctx.ui.notify(\n\t\t\t\t`Goal continuation repeated ${this.#toollessContinuationStreak} toolless turns ${context} - injected a stall check.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t}\n\t\tcontent = `${buildGoalStallNotice(this.#toollessContinuationStreak, { liveSources })}\\n\\n${content}`;\n\t\treturn content;\n\t}\n\n\t/** A tool-using turn is forward progress, so it clears the repetition window instead of extending it. */\n\t#recordAssistantOutput(messages: readonly AgentMessage[], turnUsedTools: boolean): void {\n\t\tif (turnUsedTools) {\n\t\t\tthis.#recentNormalizedOutputHashes = [];\n\t\t\treturn;\n\t\t}\n\t\tconst text = lastAssistantText(messages);\n\t\tif (normalizeAssistantText(text).length === 0) return;\n\t\tthis.#recentNormalizedOutputHashes = [...this.#recentNormalizedOutputHashes, hashAssistantText(text)].slice(-3);\n\t}\n\n\t#recordToollessContinuationTurn(goal: Goal, turnUsedTools: boolean): void {\n\t\tif (goal.id !== this.#toollessStreakGoalId) {\n\t\t\tthis.#toollessStreakGoalId = goal.id;\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t}\n\t\tif (this.#endedTurnWasUserInitiated) return;\n\t\tif (turnUsedTools) {\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.#toollessContinuationStreak += 1;\n\t}\n\n\t#resetLengthRecoveryAfterCleanStop(goal: Goal | null, messages: readonly AgentMessage[]): void {\n\t\tif (goal === null || lastAssistantMessage(messages)?.stopReason !== \"stop\") return;\n\t\tthis.#consecutiveLengthRecoveries.delete(goal.id);\n\t}\n\n\t#subscribeToChannelState(): void {\n\t\tconst events = this.#pi.events;\n\t\tif (events === undefined) return;\n\t\tthis.#channelStateUnsubscribers.push(\n\t\t\t...subscribeGoalChannelState(events, {\n\t\t\t\tonWakeSource: (source, activeCount) => this.#setWakeSourceCount(source, activeCount),\n\t\t\t\tonContinuationHold: (source, active) => {\n\t\t\t\t\tconst inputId = `external:${source}`;\n\t\t\t\t\tif (active) this.holdDirectInput(inputId);\n\t\t\t\t\telse this.resolveDirectInput(inputId, false);\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t}\n\n\t#setWakeSourceCount(source: string, activeCount: number): void {\n\t\tconst previousTotal = this.#activeWakeSourceCount();\n\t\tthis.#wakeSources.set(source, activeCount);\n\t\tconst nextTotal = this.#activeWakeSourceCount();\n\t\tif (previousTotal > 0 && nextTotal === 0) {\n\t\t\tif (this.#scheduledContinuationKind === \"monitor\") this.#armDrainFire();\n\t\t\telse this.#resetCacheWarmIteration();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t\treturn;\n\t\t}\n\t\tif (this.#scheduledContinuationKind === \"monitor\") {\n\t\t\tthis.#waitTicker?.setChannelCounts(this.#wakeSourceSnapshot());\n\t\t}\n\t}\n\n\t#armDrainFire(): void {\n\t\tif (this.#directInputHolds.size > 0) {\n\t\t\tthis.#heldTimer = {\n\t\t\t\tkind: \"monitor\",\n\t\t\t\tremainingMs: 1_000,\n\t\t\t\theldAtMs: Date.now(),\n\t\t\t\ttotalMs: 1_000,\n\t\t\t\tdrainFire: true,\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\t\tif (this.#timer !== undefined) clearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#waitTicker?.stop();\n\t\tthis.#armTimer(\"monitor\", 1_000, 1_000, true);\n\t}\n\n\t#activeWakeSourceCount(): number {\n\t\tlet total = 0;\n\t\tfor (const count of this.#wakeSources.values()) total += count;\n\t\treturn total;\n\t}\n\n\t#wakeSourceSnapshot(): ResumptionChannelCounts {\n\t\treturn Object.fromEntries([...this.#wakeSources.entries()].sort(([left], [right]) => left.localeCompare(right)));\n\t}\n\n\t#liveWakeSources(): string[] {\n\t\treturn [...this.#wakeSources.entries()]\n\t\t\t.filter(([, count]) => count > 0)\n\t\t\t.map(([source]) => source)\n\t\t\t.sort();\n\t}\n\n\t#resetContinuationState(): void {\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#consecutiveLengthRecoveries.clear();\n\t\tthis.#recentNormalizedOutputHashes = [];\n\t\tthis.#resetToollessContinuationStreak();\n\t\tthis.#resetCacheWarmIteration();\n\t}\n\n\t#resetCacheWarmIteration(): void {\n\t\tthis.#cacheWarmIteration = 0;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t}\n\n\t#resetToollessContinuationStreak(): void {\n\t\tthis.#toollessContinuationStreak = 0;\n\t\tthis.#toollessStreakGoalId = null;\n\t}\n\n\t#cancelTimer(): void {\n\t\tconst kind = this.#scheduledContinuationKind;\n\t\tthis.#scheduledAtMs = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#scheduledCache = undefined;\n\t\tthis.#scheduledDelayMs = undefined;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\tthis.#heldTimer = undefined;\n\t\tif (this.#timer !== undefined) clearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledContinuationKind = undefined;\n\t\tif (kind !== undefined) this.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind });\n\t\tthis.#waitTicker?.stop();\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"wait-ticker.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/wait-ticker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,E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,IAAI;IAmBZ;;;;;;OAMG;IACH,OAAO,CAAC,MAAM;IAUd,OAAO,CAAC,IAAI;CAyBZ"}
@@ -81,16 +81,21 @@ export class GoalWaitTicker {
81
81
  tick() {
82
82
  if (this.ctx === undefined || this.kind === undefined)
83
83
  return;
84
- const status = formatGoalWaitLabel({
85
- kind: this.kind,
86
- remainingMs: Math.max(0, this.dueAtMs - this.now()),
87
- totalMs: this.totalMs,
88
- channelCounts: this.channelCounts,
89
- });
90
- if (status === this.lastRenderedStatus)
91
- return;
92
- this.lastRenderedStatus = status;
93
84
  try {
85
+ // The countdown is a parked-state display: while a turn runs the goal is
86
+ // pursued, not waited on, so the segment clears. The armed timer (and its
87
+ // cache-TTL deadline) is untouched, so the next idle tick re-renders it.
88
+ const status = this.ctx.isIdle()
89
+ ? formatGoalWaitLabel({
90
+ kind: this.kind,
91
+ remainingMs: Math.max(0, this.dueAtMs - this.now()),
92
+ totalMs: this.totalMs,
93
+ channelCounts: this.channelCounts,
94
+ })
95
+ : undefined;
96
+ if (status === this.lastRenderedStatus)
97
+ return;
98
+ this.lastRenderedStatus = status;
94
99
  this.render(this.ctx, status);
95
100
  }
96
101
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"wait-ticker.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/wait-ticker.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAA8C,MAAM,oBAAoB,CAAC;AAErG,6EAA6E;AAC7E,MAAM,CAAC,MAAM,0BAA0B,GAAG,IAAI,CAAC;AAC/C,MAAM,CAAC,MAAM,oBAAoB,GAAG,WAAW,CAAC;AAWhD;;;;GAIG;AACH,MAAM,OAAO,cAAc;IAW1B,YAAY,OAA8B;QALlC,YAAO,GAAG,CAAC,CAAC;QACZ,YAAO,GAAG,CAAC,CAAC;QACZ,kBAAa,GAA4B,EAAE,CAAC;QAInD,IAAI,CA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C,OAAO;YACrB,aAAa,EAAE,IAAI,CAAC,aAAa;SACjC,CAAC,CAAC;QACH,IAAI,MAAM,KAAK,IAAI,CAAC,kBAAkB;YAAE,OAAO;QAC/C,IAAI,CAAC,kBAAkB,GAAG,MAAM,CAAC;QACjC,IAAI,CAAC;YACJ,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC/B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,IAAI,4BAA4B,CAAC,KAAK,CAAC,EAAE,CAAC;gBACzC,IAAI,CAAC,MAAM,EAAE,CAAC;gBACd,OAAO;YACR,CAAC;YACD,MAAM,KAAK,CAAC;QACb,CAAC;IACF,CAAC;CACD","sourcesContent":["import type { ExtensionContext } from \"../../types.ts\";\nimport type { ResumptionChannelCounts } from \"./monitor-continuation-types.ts\";\nimport { isStaleExtensionContextError } from \"./stale-context.ts\";\nimport { formatGoalWaitLabel, type GoalWaitKind, type GoalWaitLabelInput } from \"./wait-progress.ts\";\n\n/** Footer countdown refresh cadence while a Goal continuation is delayed. */\nexport const GOAL_WAIT_TICK_INTERVAL_MS = 1000;\nexport const GOAL_WAIT_STATUS_KEY = \"goal-wait\";\n\n/** Receives the freshly formatted footer status text (undefined clears the status). */\nexport type GoalWaitRender = (ctx: ExtensionContext, status: string | undefined) => void;\n\nexport interface GoalWaitTickerOptions {\n\treadonly render: GoalWaitRender;\n\t/** Injectable clock for tests; defaults to Date.now. */\n\treadonly now?: () => number;\n}\n\n/**\n * Drives a once-per-second footer countdown while a Goal continuation timer is\n * armed. Mirrors the existing GoalElapsedTicker and MonitorStatusTicker: the\n * interval is unref'd and unchanged visible labels are not rendered again.\n */\nexport class GoalWaitTicker {\n\tprivate readonly render: GoalWaitRender;\n\tprivate readonly now: () => number;\n\tprivate intervalId: NodeJS.Timeout | undefined;\n\tprivate ctx: ExtensionContext | undefined;\n\tprivate kind: GoalWaitKind | undefined;\n\tprivate dueAtMs = 0;\n\tprivate totalMs = 0;\n\tprivate channelCounts: ResumptionChannelCounts = {};\n\tprivate lastRenderedStatus: string | undefined;\n\n\tconstructor(options: GoalWaitTickerOptions) {\n\t\tthis.render = options.render;\n\t\tthis.now = options.now ?? Date.now;\n\t}\n\n\tget running(): boolean {\n\t\treturn this.intervalId !== undefined;\n\t}\n\n\t/** Render the current wait immediately and keep it live until stopped. */\n\tsync(ctx: ExtensionContext, input: GoalWaitLabelInput): void {\n\t\tthis.ctx = ctx;\n\t\tthis.kind = input.kind;\n\t\tthis.dueAtMs = this.now() + Math.max(0, input.remainingMs);\n\t\tthis.totalMs = input.totalMs;\n\t\tthis.channelCounts = { ...input.channelCounts };\n\t\tthis.lastRenderedStatus = undefined;\n\t\tthis.tick();\n\t\tif (this.intervalId !== undefined) return;\n\t\tconst handle = setInterval(() => this.tick(), GOAL_WAIT_TICK_INTERVAL_MS);\n\t\thandle.unref();\n\t\tthis.intervalId = handle;\n\t}\n\n\t/** Refresh channel wording without changing the countdown deadline. */\n\tsetChannelCounts(channelCounts: ResumptionChannelCounts): void {\n\t\tif (this.ctx === undefined || this.kind !== \"monitor\") return;\n\t\tthis.channelCounts = { ...channelCounts };\n\t\tthis.tick();\n\t}\n\n\t/** Stop ticking, clear the footer segment, and drop the retained context. */\n\tstop(): void {\n\t\tif (this.intervalId !== undefined) {\n\t\t\tclearInterval(this.intervalId);\n\t\t\tthis.intervalId = undefined;\n\t\t}\n\t\tconst ctx = this.ctx;\n\t\tthis.ctx = undefined;\n\t\tthis.kind = undefined;\n\t\tthis.lastRenderedStatus = undefined;\n\t\tif (ctx !== undefined) {\n\t\t\ttry {\n\t\t\t\tthis.render(ctx, undefined);\n\t\t\t} catch (error) {\n\t\t\t\t// A stale ctx cannot clear its own footer status; dropping it is enough.\n\t\t\t\tif (!isStaleExtensionContextError(error)) throw error;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Drop the interval and retained ctx without a final render. Used when a tick\n\t * discovers the ctx was retired by a session replacement or reload: every\n\t * render against it throws from now on, and a ticker that keeps ticking dead\n\t * renders freezes the footer forever without crashing. The next sync() with a\n\t * live ctx re-arms everything.\n\t */\n\tprivate retire(): void {\n\t\tif (this.intervalId !== undefined) {\n\t\t\tclearInterval(this.intervalId);\n\t\t\tthis.intervalId = undefined;\n\t\t}\n\t\tthis.ctx = undefined;\n\t\tthis.kind = undefined;\n\t\tthis.lastRenderedStatus = undefined;\n\t}\n\n\tprivate tick(): void {\n\t\tif (this.ctx === undefined || this.kind === undefined) return;\n\t\tconst status = formatGoalWaitLabel({\n\t\t\tkind: this.kind,\n\t\t\tremainingMs: Math.max(0, this.dueAtMs - this.now()),\n\t\t\ttotalMs: this.totalMs,\n\t\t\tchannelCounts: this.channelCounts,\n\t\t});\n\t\tif (status === this.lastRenderedStatus) return;\n\t\tthis.lastRenderedStatus = status;\n\t\ttry {\n\t\t\tthis.render(this.ctx, status);\n\t\t} catch (error) {\n\t\t\tif (isStaleExtensionContextError(error)) {\n\t\t\t\tthis.retire();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"wait-ticker.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/wait-ticker.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAA8C,MAAM,oBAAoB,CAAC;AAErG,6EAA6E;AAC7E,MAAM,CAAC,MAAM,0BAA0B,GAAG,IAAI,CAAC;AAC/C,MAAM,CAAC,MAAM,oBAAoB,GAAG,WAAW,CAAC;AAWhD;;;;GAIG;AACH,MAAM,OAAO,cAAc;IAW1B,YAAY,OAA8B;QALlC,YAAO,GAAG,CAAC,CAAC;QACZ,YAAO,GAAG,CAAC,CAAC;QACZ,kBAAa,GAA4B,EAAE,CAAC;QAInD,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,C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AO,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;oBACnD,OAAO,EAAE,IAAI,CAAC,OAAO;oBACrB,aAAa,EAAE,IAAI,CAAC,aAAa;iBACjC,CAAC;gBACH,CAAC,CAAC,SAAS,CAAC;YACb,IAAI,MAAM,KAAK,IAAI,CAAC,kBAAkB;gBAAE,OAAO;YAC/C,IAAI,CAAC,kBAAkB,GAAG,MAAM,CAAC;YACjC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC/B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,IAAI,4BAA4B,CAAC,KAAK,CAAC,EAAE,CAAC;gBACzC,IAAI,CAAC,MAAM,EAAE,CAAC;gBACd,OAAO;YACR,CAAC;YACD,MAAM,KAAK,CAAC;QACb,CAAC;IACF,CAAC;CACD","sourcesContent":["import type { ExtensionContext } from \"../../types.ts\";\nimport type { ResumptionChannelCounts } from \"./monitor-continuation-types.ts\";\nimport { isStaleExtensionContextError } from \"./stale-context.ts\";\nimport { formatGoalWaitLabel, type GoalWaitKind, type GoalWaitLabelInput } from \"./wait-progress.ts\";\n\n/** Footer countdown refresh cadence while a Goal continuation is delayed. */\nexport const GOAL_WAIT_TICK_INTERVAL_MS = 1000;\nexport const GOAL_WAIT_STATUS_KEY = \"goal-wait\";\n\n/** Receives the freshly formatted footer status text (undefined clears the status). */\nexport type GoalWaitRender = (ctx: ExtensionContext, status: string | undefined) => void;\n\nexport interface GoalWaitTickerOptions {\n\treadonly render: GoalWaitRender;\n\t/** Injectable clock for tests; defaults to Date.now. */\n\treadonly now?: () => number;\n}\n\n/**\n * Drives a once-per-second footer countdown while a Goal continuation timer is\n * armed. Mirrors the existing GoalElapsedTicker and MonitorStatusTicker: the\n * interval is unref'd and unchanged visible labels are not rendered again.\n */\nexport class GoalWaitTicker {\n\tprivate readonly render: GoalWaitRender;\n\tprivate readonly now: () => number;\n\tprivate intervalId: NodeJS.Timeout | undefined;\n\tprivate ctx: ExtensionContext | undefined;\n\tprivate kind: GoalWaitKind | undefined;\n\tprivate dueAtMs = 0;\n\tprivate totalMs = 0;\n\tprivate channelCounts: ResumptionChannelCounts = {};\n\tprivate lastRenderedStatus: string | undefined;\n\n\tconstructor(options: GoalWaitTickerOptions) {\n\t\tthis.render = options.render;\n\t\tthis.now = options.now ?? Date.now;\n\t}\n\n\tget running(): boolean {\n\t\treturn this.intervalId !== undefined;\n\t}\n\n\t/** Render the current wait immediately and keep it live until stopped. */\n\tsync(ctx: ExtensionContext, input: GoalWaitLabelInput): void {\n\t\tthis.ctx = ctx;\n\t\tthis.kind = input.kind;\n\t\tthis.dueAtMs = this.now() + Math.max(0, input.remainingMs);\n\t\tthis.totalMs = input.totalMs;\n\t\tthis.channelCounts = { ...input.channelCounts };\n\t\tthis.lastRenderedStatus = undefined;\n\t\tthis.tick();\n\t\tif (this.intervalId !== undefined) return;\n\t\tconst handle = setInterval(() => this.tick(), GOAL_WAIT_TICK_INTERVAL_MS);\n\t\thandle.unref();\n\t\tthis.intervalId = handle;\n\t}\n\n\t/** Refresh channel wording without changing the countdown deadline. */\n\tsetChannelCounts(channelCounts: ResumptionChannelCounts): void {\n\t\tif (this.ctx === undefined || this.kind !== \"monitor\") return;\n\t\tthis.channelCounts = { ...channelCounts };\n\t\tthis.tick();\n\t}\n\n\t/** Stop ticking, clear the footer segment, and drop the retained context. */\n\tstop(): void {\n\t\tif (this.intervalId !== undefined) {\n\t\t\tclearInterval(this.intervalId);\n\t\t\tthis.intervalId = undefined;\n\t\t}\n\t\tconst ctx = this.ctx;\n\t\tthis.ctx = undefined;\n\t\tthis.kind = undefined;\n\t\tthis.lastRenderedStatus = undefined;\n\t\tif (ctx !== undefined) {\n\t\t\ttry {\n\t\t\t\tthis.render(ctx, undefined);\n\t\t\t} catch (error) {\n\t\t\t\t// A stale ctx cannot clear its own footer status; dropping it is enough.\n\t\t\t\tif (!isStaleExtensionContextError(error)) throw error;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Drop the interval and retained ctx without a final render. Used when a tick\n\t * discovers the ctx was retired by a session replacement or reload: every\n\t * render against it throws from now on, and a ticker that keeps ticking dead\n\t * renders freezes the footer forever without crashing. The next sync() with a\n\t * live ctx re-arms everything.\n\t */\n\tprivate retire(): void {\n\t\tif (this.intervalId !== undefined) {\n\t\t\tclearInterval(this.intervalId);\n\t\t\tthis.intervalId = undefined;\n\t\t}\n\t\tthis.ctx = undefined;\n\t\tthis.kind = undefined;\n\t\tthis.lastRenderedStatus = undefined;\n\t}\n\n\tprivate tick(): void {\n\t\tif (this.ctx === undefined || this.kind === undefined) return;\n\t\ttry {\n\t\t\t// The countdown is a parked-state display: while a turn runs the goal is\n\t\t\t// pursued, not waited on, so the segment clears. The armed timer (and its\n\t\t\t// cache-TTL deadline) is untouched, so the next idle tick re-renders it.\n\t\t\tconst status = this.ctx.isIdle()\n\t\t\t\t? formatGoalWaitLabel({\n\t\t\t\t\t\tkind: this.kind,\n\t\t\t\t\t\tremainingMs: Math.max(0, this.dueAtMs - this.now()),\n\t\t\t\t\t\ttotalMs: this.totalMs,\n\t\t\t\t\t\tchannelCounts: this.channelCounts,\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\t\t\tif (status === this.lastRenderedStatus) return;\n\t\t\tthis.lastRenderedStatus = status;\n\t\t\tthis.render(this.ctx, status);\n\t\t} catch (error) {\n\t\t\tif (isStaleExtensionContextError(error)) {\n\t\t\t\tthis.retire();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"fetcher.d.ts","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/webfetch/webfetch/fetcher.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,uBAAuB,QAAkB,CAAC;AACvD,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAC1C,eAAO,MAAM,mBAAmB,MAAM,CAAC;AAQvC,MAAM,MAAM,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E,MAAM,CAAC;IACxB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,UAAU,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;CAC9D;AAED,MAAM,WAAW,WAAW;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,UAAU,CAAC;IACjB,SAAS,EAAE,OAAO,CAAC;CACnB;AAUD,wBAAsB,QAAQ,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,WAAW,CAAC,CAyB1E;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAU7C;AAED,wBAAgB,YAAY,CAAC,cAAc,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAIvE;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,CAShE"}
@@ -1,5 +1,6 @@
1
1
  import { request } from "undici";
2
2
  import { InvalidWebfetchUrlError, WebfetchAbortError, WebfetchResponseTooLargeError, WebfetchTimeoutError, } from "./errors.js";
3
+ import { discardBody, toUint8Array } from "./response-body.js";
3
4
  export const MAX_RESPONSE_SIZE_BYTES = 5 * 1024 * 1024;
4
5
  export const DEFAULT_TIMEOUT_SECONDS = 30;
5
6
  export const MAX_TIMEOUT_SECONDS = 120;
@@ -110,13 +111,13 @@ async function requestUrl(options) {
110
111
  body: response.body,
111
112
  };
112
113
  }
113
- await discardBody(response.body);
114
+ await discardBody(response.body, MAX_RESPONSE_SIZE_BYTES, options.signal);
114
115
  currentUrl = new URL(location, currentUrl).toString();
115
116
  }
116
117
  throw new WebfetchAbortError("Redirect resolution aborted");
117
118
  }
118
119
  async function readHttpResponse(response, signal, onProgress) {
119
- await rejectOversizedContentLength(response);
120
+ await rejectOversizedContentLength(response, signal);
120
121
  const body = await readResponseBody(response, signal, onProgress);
121
122
  return {
122
123
  url: response.url,
@@ -128,10 +129,10 @@ async function readHttpResponse(response, signal, onProgress) {
128
129
  truncated: body.length === MAX_RESPONSE_SIZE_BYTES,
129
130
  };
130
131
  }
131
- async function rejectOversizedContentLength(response) {
132
+ async function rejectOversizedContentLength(response, signal) {
132
133
  const contentLength = getHeader(response.headers, "content-length");
133
134
  if (contentLength && Number.parseInt(contentLength, 10) > MAX_RESPONSE_SIZE_BYTES) {
134
- await discardBody(response.body);
135
+ await discardBody(response.body, MAX_RESPONSE_SIZE_BYTES, signal);
135
136
  throw new WebfetchResponseTooLargeError("Response too large (exceeds 5MB limit)");
136
137
  }
137
138
  }
@@ -141,18 +142,6 @@ function getHeader(headers, name) {
141
142
  return value.join(", ");
142
143
  return value ?? "";
143
144
  }
144
- async function discardBody(body) {
145
- try {
146
- await body.dump({ limit: 1024 });
147
- }
148
- catch (error) {
149
- if (error instanceof Error) {
150
- body.destroy(error);
151
- return;
152
- }
153
- throw error;
154
- }
155
- }
156
145
  async function readResponseBody(response, signal, onProgress) {
157
146
  const chunks = [];
158
147
  const totalBytes = parseContentLength(response);
@@ -194,13 +183,6 @@ function parseContentLength(response) {
194
183
  const parsed = Number.parseInt(contentLength, 10);
195
184
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
196
185
  }
197
- function toUint8Array(chunk) {
198
- if (chunk instanceof Uint8Array)
199
- return chunk;
200
- if (typeof chunk === "string")
201
- return new TextEncoder().encode(chunk);
202
- throw new Error("Unexpected response body chunk");
203
- }
204
186
  function forwardAbort(signal, controller) {
205
187
  if (!signal)
206
188
  return () => { };
@@ -1 +1 @@
1
- {"version":3,"file":"fetcher.js","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/webfetch/webfetch/fetcher.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC,OAAO,EACN,uBA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AAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;AACpE,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IACnC,IAAI,KAAK,YAAY,UAAU;QAAE,OAAO,KAAK,CAAC;IAC9C,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACtE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;AACnD,CAAC;AAED,SAAS,YAAY,CAAC,MAA+B,EAAE,UAA2B;IACjF,IAAI,CAAC,MAAM;QAAE,OAAO,GAAG,EAAE,GAAE,CAAC,CAAC;IAC7B,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAChC,OAAO,GAAG,EAAE,GAAE,CAAC,CAAC;IACjB,CAAC;IAED,MAAM,QAAQ,GAAG,GAAS,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC7D,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IAC3D,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["import type { IncomingHttpHeaders } from \"node:http\";\nimport { request } from \"undici\";\n\nimport {\n\tInvalidWebfetchUrlError,\n\tWebfetchAbortError,\n\tWebfetchResponseTooLargeError,\n\tWebfetchTimeoutError,\n} from \"./errors.ts\";\n\nexport const MAX_RESPONSE_SIZE_BYTES = 5 * 1024 * 1024;\nexport const DEFAULT_TIMEOUT_SECONDS = 30;\nexport const MAX_TIMEOUT_SECONDS = 120;\nconst MAX_REDIRECTS = 20;\n\nconst BROWSER_USER_AGENT =\n\t\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36\";\nconst CHROME_MAJOR_VERSION = \"143\";\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\nexport type WebfetchFormat = \"markdown\" | \"text\" | \"html\";\n\nexport interface FetchOptions {\n\turl: string;\n\tformat: WebfetchFormat;\n\ttimeoutSeconds?: number;\n\tsignal?: AbortSignal;\n\tonProgress?: (bytesRead: number, totalBytes?: number) => void;\n}\n\nexport interface FetchResult {\n\turl: string;\n\tstatus: number;\n\tstatusText: string;\n\tcontentType: string;\n\tbytes: number;\n\tbody: Uint8Array;\n\ttruncated: boolean;\n}\n\ninterface HttpResponse {\n\treadonly url: string;\n\treadonly status: number;\n\treadonly statusText: string;\n\treadonly headers: IncomingHttpHeaders;\n\treadonly body: ResponseBodyStream;\n}\n\ninterface ResponseBodyStream extends AsyncIterable<unknown> {\n\tdestroy(error?: Error): void;\n\tdump(options?: { limit: number; signal?: AbortSignal }): Promise<void>;\n}\n\nexport async function fetchUrl(options: FetchOptions): Promise<FetchResult> {\n\tvalidateUrl(options.url);\n\n\tconst timeoutSeconds = clampTimeout(options.timeoutSeconds);\n\tconst timeoutMs = timeoutSeconds * 1000;\n\tconst controller = new AbortController();\n\tconst timeout = setTimeout(\n\t\t() => controller.abort(new WebfetchTimeoutError(`Request timed out after ${timeoutSeconds}s`)),\n\t\ttimeoutMs,\n\t);\n\tconst removeAbortForwarder = forwardAbort(options.signal, controller);\n\n\ttry {\n\t\tconst response = await requestUrl({\n\t\t\turl: options.url,\n\t\t\tformat: options.format,\n\t\t\tsignal: controller.signal,\n\t\t\ttimeoutMs,\n\t\t});\n\n\t\treturn await readHttpResponse(response, controller.signal, options.onProgress);\n\t} finally {\n\t\tclearTimeout(timeout);\n\t\tremoveAbortForwarder();\n\t}\n}\n\nexport function validateUrl(url: string): void {\n\tif (!url.startsWith(\"http://\") && !url.startsWith(\"https://\")) {\n\t\tthrow new InvalidWebfetchUrlError(\"URL must start with http:// or https://\");\n\t}\n\n\ttry {\n\t\tnew URL(url);\n\t} catch {\n\t\tthrow new InvalidWebfetchUrlError(`Invalid URL: ${url}`);\n\t}\n}\n\nexport function clampTimeout(timeoutSeconds: number | undefined): number {\n\tif (timeoutSeconds === undefined) return DEFAULT_TIMEOUT_SECONDS;\n\tif (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) return DEFAULT_TIMEOUT_SECONDS;\n\treturn Math.min(Math.ceil(timeoutSeconds), MAX_TIMEOUT_SECONDS);\n}\n\nexport function buildAcceptHeader(format: WebfetchFormat): string {\n\tswitch (format) {\n\t\tcase \"markdown\":\n\t\t\treturn \"text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1\";\n\t\tcase \"text\":\n\t\t\treturn \"text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1\";\n\t\tcase \"html\":\n\t\t\treturn \"text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1\";\n\t}\n}\n\nfunction buildHeaders(format: WebfetchFormat): Record<string, string> {\n\treturn {\n\t\tAccept: buildAcceptHeader(format),\n\t\t\"Accept-Language\": \"en-US,en;q=0.9\",\n\t\t\"Sec-CH-UA\": `\"Google Chrome\";v=\"${CHROME_MAJOR_VERSION}\", \"Chromium\";v=\"${CHROME_MAJOR_VERSION}\", \"Not A(Brand\";v=\"24\"`,\n\t\t\"Sec-CH-UA-Mobile\": \"?0\",\n\t\t\"Sec-CH-UA-Platform\": '\"Windows\"',\n\t\t\"Sec-Fetch-Dest\": \"document\",\n\t\t\"Sec-Fetch-Mode\": \"navigate\",\n\t\t\"Sec-Fetch-Site\": \"none\",\n\t\t\"Sec-Fetch-User\": \"?1\",\n\t\t\"Upgrade-Insecure-Requests\": \"1\",\n\t\t\"User-Agent\": BROWSER_USER_AGENT,\n\t};\n}\n\ninterface RequestUrlOptions {\n\treadonly url: string;\n\treadonly format: WebfetchFormat;\n\treadonly signal: AbortSignal;\n\treadonly timeoutMs: number;\n}\n\nasync function requestUrl(options: RequestUrlOptions): Promise<HttpResponse> {\n\tconst headers = buildHeaders(options.format);\n\tlet currentUrl = options.url;\n\n\tfor (let redirectCount = 0; redirectCount <= MAX_REDIRECTS; redirectCount += 1) {\n\t\tconst response = await request(currentUrl, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders,\n\t\t\tsignal: options.signal,\n\t\t\theadersTimeout: options.timeoutMs,\n\t\t\tbodyTimeout: options.timeoutMs,\n\t\t});\n\n\t\tif (!REDIRECT_STATUSES.has(response.statusCode)) {\n\t\t\treturn {\n\t\t\t\turl: currentUrl,\n\t\t\t\tstatus: response.statusCode,\n\t\t\t\tstatusText: response.statusText,\n\t\t\t\theaders: response.headers,\n\t\t\t\tbody: response.body,\n\t\t\t};\n\t\t}\n\n\t\tconst location = getHeader(response.headers, \"location\");\n\t\tif (!location) {\n\t\t\treturn {\n\t\t\t\turl: currentUrl,\n\t\t\t\tstatus: response.statusCode,\n\t\t\t\tstatusText: response.statusText,\n\t\t\t\theaders: response.headers,\n\t\t\t\tbody: response.body,\n\t\t\t};\n\t\t}\n\n\t\tif (redirectCount === MAX_REDIRECTS) {\n\t\t\treturn {\n\t\t\t\turl: currentUrl,\n\t\t\t\tstatus: response.statusCode,\n\t\t\t\tstatusText: response.statusText,\n\t\t\t\theaders: response.headers,\n\t\t\t\tbody: response.body,\n\t\t\t};\n\t\t}\n\n\t\tawait discardBody(response.body);\n\t\tcurrentUrl = new URL(location, currentUrl).toString();\n\t}\n\n\tthrow new WebfetchAbortError(\"Redirect resolution aborted\");\n}\n\nasync function readHttpResponse(\n\tresponse: HttpResponse,\n\tsignal: AbortSignal,\n\tonProgress: FetchOptions[\"onProgress\"],\n): Promise<FetchResult> {\n\tawait rejectOversizedContentLength(response);\n\tconst body = await readResponseBody(response, signal, onProgress);\n\treturn {\n\t\turl: response.url,\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\tcontentType: getHeader(response.headers, \"content-type\"),\n\t\tbytes: body.length,\n\t\tbody,\n\t\ttruncated: body.length === MAX_RESPONSE_SIZE_BYTES,\n\t};\n}\n\nasync function rejectOversizedContentLength(response: HttpResponse): Promise<void> {\n\tconst contentLength = getHeader(response.headers, \"content-length\");\n\tif (contentLength && Number.parseInt(contentLength, 10) > MAX_RESPONSE_SIZE_BYTES) {\n\t\tawait discardBody(response.body);\n\t\tthrow new WebfetchResponseTooLargeError(\"Response too large (exceeds 5MB limit)\");\n\t}\n}\n\nfunction getHeader(headers: IncomingHttpHeaders, name: string): string {\n\tconst value = headers[name.toLowerCase()];\n\tif (Array.isArray(value)) return value.join(\", \");\n\treturn value ?? \"\";\n}\n\nasync function discardBody(body: ResponseBodyStream): Promise<void> {\n\ttry {\n\t\tawait body.dump({ limit: 1024 });\n\t} catch (error) {\n\t\tif (error instanceof Error) {\n\t\t\tbody.destroy(error);\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nasync function readResponseBody(\n\tresponse: HttpResponse,\n\tsignal: AbortSignal,\n\tonProgress: FetchOptions[\"onProgress\"],\n): Promise<Uint8Array> {\n\tconst chunks: Uint8Array[] = [];\n\tconst totalBytes = parseContentLength(response);\n\tlet total = 0;\n\n\ttry {\n\t\tfor await (const chunk of response.body) {\n\t\t\tif (signal.aborted) {\n\t\t\t\tresponse.body.destroy();\n\t\t\t\tthrow new WebfetchAbortError(\"Request aborted\");\n\t\t\t}\n\t\t\tconst bytes = toUint8Array(chunk);\n\t\t\tchunks.push(bytes);\n\t\t\ttotal += bytes.length;\n\t\t\tif (total > MAX_RESPONSE_SIZE_BYTES) {\n\t\t\t\tresponse.body.destroy();\n\t\t\t\tthrow new WebfetchResponseTooLargeError(\"Response too large (exceeds 5MB limit)\");\n\t\t\t}\n\t\t\tonProgress?.(total, totalBytes);\n\t\t}\n\t} catch (error) {\n\t\tif (signal.aborted) {\n\t\t\tthrow new WebfetchAbortError(\"Request aborted\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tconst body = new Uint8Array(total);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tbody.set(chunk, offset);\n\t\toffset += chunk.length;\n\t}\n\treturn body;\n}\n\nfunction parseContentLength(response: HttpResponse): number | undefined {\n\tconst contentLength = getHeader(response.headers, \"content-length\");\n\tif (contentLength === \"\") return undefined;\n\tconst parsed = Number.parseInt(contentLength, 10);\n\treturn Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\nfunction toUint8Array(chunk: unknown): Uint8Array {\n\tif (chunk instanceof Uint8Array) return chunk;\n\tif (typeof chunk === \"string\") return new TextEncoder().encode(chunk);\n\tthrow new Error(\"Unexpected response body chunk\");\n}\n\nfunction forwardAbort(signal: AbortSignal | undefined, controller: AbortController): () => void {\n\tif (!signal) return () => {};\n\tif (signal.aborted) {\n\t\tcontroller.abort(signal.reason);\n\t\treturn () => {};\n\t}\n\n\tconst listener = (): void => controller.abort(signal.reason);\n\tsignal.addEventListener(\"abort\", listener, { once: true });\n\treturn () => signal.removeEventListener(\"abort\", listener);\n}\n"]}
1
+ {"version":3,"file":"fetcher.js","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/webfetch/webfetch/fetcher.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC,OAAO,EACN,uBAAuB,EACvB,kBAAkB,EAClB,6BAA6B,EAC7B,oBAAoB,GACpB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,WAAW,EAA2B,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAExF,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AACvD,MAAM,CAAC,MAAM,uBAAuB,GAAG,EAAE,CAAC;AAC1C,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AACvC,MAAM,aAAa,GAAG,EAAE,CAAC;A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OAAO,GAAG,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["import type { IncomingHttpHeaders } from \"node:http\";\nimport { request } from \"undici\";\n\nimport {\n\tInvalidWebfetchUrlError,\n\tWebfetchAbortError,\n\tWebfetchResponseTooLargeError,\n\tWebfetchTimeoutError,\n} from \"./errors.ts\";\nimport { discardBody, type ResponseBodyStream, toUint8Array } from \"./response-body.ts\";\n\nexport const MAX_RESPONSE_SIZE_BYTES = 5 * 1024 * 1024;\nexport const DEFAULT_TIMEOUT_SECONDS = 30;\nexport const MAX_TIMEOUT_SECONDS = 120;\nconst MAX_REDIRECTS = 20;\n\nconst BROWSER_USER_AGENT =\n\t\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36\";\nconst CHROME_MAJOR_VERSION = \"143\";\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\nexport type WebfetchFormat = \"markdown\" | \"text\" | \"html\";\n\nexport interface FetchOptions {\n\turl: string;\n\tformat: WebfetchFormat;\n\ttimeoutSeconds?: number;\n\tsignal?: AbortSignal;\n\tonProgress?: (bytesRead: number, totalBytes?: number) => void;\n}\n\nexport interface FetchResult {\n\turl: string;\n\tstatus: number;\n\tstatusText: string;\n\tcontentType: string;\n\tbytes: number;\n\tbody: Uint8Array;\n\ttruncated: boolean;\n}\n\ninterface HttpResponse {\n\treadonly url: string;\n\treadonly status: number;\n\treadonly statusText: string;\n\treadonly headers: IncomingHttpHeaders;\n\treadonly body: ResponseBodyStream;\n}\n\nexport async function fetchUrl(options: FetchOptions): Promise<FetchResult> {\n\tvalidateUrl(options.url);\n\n\tconst timeoutSeconds = clampTimeout(options.timeoutSeconds);\n\tconst timeoutMs = timeoutSeconds * 1000;\n\tconst controller = new AbortController();\n\tconst timeout = setTimeout(\n\t\t() => controller.abort(new WebfetchTimeoutError(`Request timed out after ${timeoutSeconds}s`)),\n\t\ttimeoutMs,\n\t);\n\tconst removeAbortForwarder = forwardAbort(options.signal, controller);\n\n\ttry {\n\t\tconst response = await requestUrl({\n\t\t\turl: options.url,\n\t\t\tformat: options.format,\n\t\t\tsignal: controller.signal,\n\t\t\ttimeoutMs,\n\t\t});\n\n\t\treturn await readHttpResponse(response, controller.signal, options.onProgress);\n\t} finally {\n\t\tclearTimeout(timeout);\n\t\tremoveAbortForwarder();\n\t}\n}\n\nexport function validateUrl(url: string): void {\n\tif (!url.startsWith(\"http://\") && !url.startsWith(\"https://\")) {\n\t\tthrow new InvalidWebfetchUrlError(\"URL must start with http:// or https://\");\n\t}\n\n\ttry {\n\t\tnew URL(url);\n\t} catch {\n\t\tthrow new InvalidWebfetchUrlError(`Invalid URL: ${url}`);\n\t}\n}\n\nexport function clampTimeout(timeoutSeconds: number | undefined): number {\n\tif (timeoutSeconds === undefined) return DEFAULT_TIMEOUT_SECONDS;\n\tif (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) return DEFAULT_TIMEOUT_SECONDS;\n\treturn Math.min(Math.ceil(timeoutSeconds), MAX_TIMEOUT_SECONDS);\n}\n\nexport function buildAcceptHeader(format: WebfetchFormat): string {\n\tswitch (format) {\n\t\tcase \"markdown\":\n\t\t\treturn \"text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1\";\n\t\tcase \"text\":\n\t\t\treturn \"text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1\";\n\t\tcase \"html\":\n\t\t\treturn \"text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1\";\n\t}\n}\n\nfunction buildHeaders(format: WebfetchFormat): Record<string, string> {\n\treturn {\n\t\tAccept: buildAcceptHeader(format),\n\t\t\"Accept-Language\": \"en-US,en;q=0.9\",\n\t\t\"Sec-CH-UA\": `\"Google Chrome\";v=\"${CHROME_MAJOR_VERSION}\", \"Chromium\";v=\"${CHROME_MAJOR_VERSION}\", \"Not A(Brand\";v=\"24\"`,\n\t\t\"Sec-CH-UA-Mobile\": \"?0\",\n\t\t\"Sec-CH-UA-Platform\": '\"Windows\"',\n\t\t\"Sec-Fetch-Dest\": \"document\",\n\t\t\"Sec-Fetch-Mode\": \"navigate\",\n\t\t\"Sec-Fetch-Site\": \"none\",\n\t\t\"Sec-Fetch-User\": \"?1\",\n\t\t\"Upgrade-Insecure-Requests\": \"1\",\n\t\t\"User-Agent\": BROWSER_USER_AGENT,\n\t};\n}\n\ninterface RequestUrlOptions {\n\treadonly url: string;\n\treadonly format: WebfetchFormat;\n\treadonly signal: AbortSignal;\n\treadonly timeoutMs: number;\n}\n\nasync function requestUrl(options: RequestUrlOptions): Promise<HttpResponse> {\n\tconst headers = buildHeaders(options.format);\n\tlet currentUrl = options.url;\n\n\tfor (let redirectCount = 0; redirectCount <= MAX_REDIRECTS; redirectCount += 1) {\n\t\tconst response = await request(currentUrl, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders,\n\t\t\tsignal: options.signal,\n\t\t\theadersTimeout: options.timeoutMs,\n\t\t\tbodyTimeout: options.timeoutMs,\n\t\t});\n\n\t\tif (!REDIRECT_STATUSES.has(response.statusCode)) {\n\t\t\treturn {\n\t\t\t\turl: currentUrl,\n\t\t\t\tstatus: response.statusCode,\n\t\t\t\tstatusText: response.statusText,\n\t\t\t\theaders: response.headers,\n\t\t\t\tbody: response.body,\n\t\t\t};\n\t\t}\n\n\t\tconst location = getHeader(response.headers, \"location\");\n\t\tif (!location) {\n\t\t\treturn {\n\t\t\t\turl: currentUrl,\n\t\t\t\tstatus: response.statusCode,\n\t\t\t\tstatusText: response.statusText,\n\t\t\t\theaders: response.headers,\n\t\t\t\tbody: response.body,\n\t\t\t};\n\t\t}\n\n\t\tif (redirectCount === MAX_REDIRECTS) {\n\t\t\treturn {\n\t\t\t\turl: currentUrl,\n\t\t\t\tstatus: response.statusCode,\n\t\t\t\tstatusText: response.statusText,\n\t\t\t\theaders: response.headers,\n\t\t\t\tbody: response.body,\n\t\t\t};\n\t\t}\n\n\t\tawait discardBody(response.body, MAX_RESPONSE_SIZE_BYTES, options.signal);\n\t\tcurrentUrl = new URL(location, currentUrl).toString();\n\t}\n\n\tthrow new WebfetchAbortError(\"Redirect resolution aborted\");\n}\n\nasync function readHttpResponse(\n\tresponse: HttpResponse,\n\tsignal: AbortSignal,\n\tonProgress: FetchOptions[\"onProgress\"],\n): Promise<FetchResult> {\n\tawait rejectOversizedContentLength(response, signal);\n\tconst body = await readResponseBody(response, signal, onProgress);\n\treturn {\n\t\turl: response.url,\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\tcontentType: getHeader(response.headers, \"content-type\"),\n\t\tbytes: body.length,\n\t\tbody,\n\t\ttruncated: body.length === MAX_RESPONSE_SIZE_BYTES,\n\t};\n}\n\nasync function rejectOversizedContentLength(response: HttpResponse, signal: AbortSignal): Promise<void> {\n\tconst contentLength = getHeader(response.headers, \"content-length\");\n\tif (contentLength && Number.parseInt(contentLength, 10) > MAX_RESPONSE_SIZE_BYTES) {\n\t\tawait discardBody(response.body, MAX_RESPONSE_SIZE_BYTES, signal);\n\t\tthrow new WebfetchResponseTooLargeError(\"Response too large (exceeds 5MB limit)\");\n\t}\n}\n\nfunction getHeader(headers: IncomingHttpHeaders, name: string): string {\n\tconst value = headers[name.toLowerCase()];\n\tif (Array.isArray(value)) return value.join(\", \");\n\treturn value ?? \"\";\n}\n\nasync function readResponseBody(\n\tresponse: HttpResponse,\n\tsignal: AbortSignal,\n\tonProgress: FetchOptions[\"onProgress\"],\n): Promise<Uint8Array> {\n\tconst chunks: Uint8Array[] = [];\n\tconst totalBytes = parseContentLength(response);\n\tlet total = 0;\n\n\ttry {\n\t\tfor await (const chunk of response.body) {\n\t\t\tif (signal.aborted) {\n\t\t\t\tresponse.body.destroy();\n\t\t\t\tthrow new WebfetchAbortError(\"Request aborted\");\n\t\t\t}\n\t\t\tconst bytes = toUint8Array(chunk);\n\t\t\tchunks.push(bytes);\n\t\t\ttotal += bytes.length;\n\t\t\tif (total > MAX_RESPONSE_SIZE_BYTES) {\n\t\t\t\tresponse.body.destroy();\n\t\t\t\tthrow new WebfetchResponseTooLargeError(\"Response too large (exceeds 5MB limit)\");\n\t\t\t}\n\t\t\tonProgress?.(total, totalBytes);\n\t\t}\n\t} catch (error) {\n\t\tif (signal.aborted) {\n\t\t\tthrow new WebfetchAbortError(\"Request aborted\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tconst body = new Uint8Array(total);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tbody.set(chunk, offset);\n\t\toffset += chunk.length;\n\t}\n\treturn body;\n}\n\nfunction parseContentLength(response: HttpResponse): number | undefined {\n\tconst contentLength = getHeader(response.headers, \"content-length\");\n\tif (contentLength === \"\") return undefined;\n\tconst parsed = Number.parseInt(contentLength, 10);\n\treturn Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\nfunction forwardAbort(signal: AbortSignal | undefined, controller: AbortController): () => void {\n\tif (!signal) return () => {};\n\tif (signal.aborted) {\n\t\tcontroller.abort(signal.reason);\n\t\treturn () => {};\n\t}\n\n\tconst listener = (): void => controller.abort(signal.reason);\n\tsignal.addEventListener(\"abort\", listener, { once: true });\n\treturn () => signal.removeEventListener(\"abort\", listener);\n}\n"]}
@@ -0,0 +1,11 @@
1
+ export interface ResponseBodyStream extends AsyncIterable<unknown> {
2
+ on?(event: "error", listener: (error: Error) => void): unknown;
3
+ destroy(error?: Error): void;
4
+ dump?(options?: {
5
+ limit: number;
6
+ signal?: AbortSignal;
7
+ }): Promise<void>;
8
+ }
9
+ export declare function discardBody(body: ResponseBodyStream, maxBytes: number, signal?: AbortSignal): Promise<void>;
10
+ export declare function toUint8Array(chunk: unknown): Uint8Array;
11
+ //# sourceMappingURL=response-body.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response-body.d.ts","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/webfetch/webfetch/response-body.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,kBAAmB,SAAQ,aAAa,CAAC,OAAO,CAAC;IACjE,EAAE,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,GAAG,OAAO,CAAC;IAC/D,OAAO,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC;IAC7B,IAAI,CAAC,CAAC,OAAO,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACxE;AAED,wBAAsB,WAAW,CAAC,IAAI,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAajH;AAiCD,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,UAAU,CAIvD"}
@@ -0,0 +1,54 @@
1
+ export async function discardBody(body, maxBytes, signal) {
2
+ body.on?.("error", () => { });
3
+ try {
4
+ if (typeof body.dump === "function") {
5
+ await body.dump(signal ? { limit: 1024, signal } : { limit: 1024 });
6
+ return;
7
+ }
8
+ await drainBody(body, maxBytes, signal);
9
+ }
10
+ catch {
11
+ // no-excuse-ok: catch - discard failures are not actionable for the caller.
12
+ }
13
+ finally {
14
+ body.destroy();
15
+ }
16
+ }
17
+ async function drainBody(body, maxBytes, signal) {
18
+ let drained = 0;
19
+ const iterator = body[Symbol.asyncIterator]();
20
+ while (true) {
21
+ const result = await nextChunk(iterator, signal);
22
+ if (!result || result.done)
23
+ return;
24
+ drained += toUint8Array(result.value).length;
25
+ if (drained > maxBytes)
26
+ return;
27
+ }
28
+ }
29
+ async function nextChunk(iterator, signal) {
30
+ if (!signal)
31
+ return iterator.next();
32
+ if (signal.aborted)
33
+ return undefined;
34
+ let resolveAbort = () => { };
35
+ const aborted = new Promise((resolve) => {
36
+ resolveAbort = () => resolve(undefined);
37
+ });
38
+ const onAbort = () => resolveAbort();
39
+ signal.addEventListener("abort", onAbort, { once: true });
40
+ try {
41
+ return await Promise.race([iterator.next(), aborted]);
42
+ }
43
+ finally {
44
+ signal.removeEventListener("abort", onAbort);
45
+ }
46
+ }
47
+ export function toUint8Array(chunk) {
48
+ if (chunk instanceof Uint8Array)
49
+ return chunk;
50
+ if (typeof chunk === "string")
51
+ return new TextEncoder().encode(chunk);
52
+ throw new Error("Unexpected response body chunk");
53
+ }
54
+ //# sourceMappingURL=response-body.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response-body.js","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/webfetch/webfetch/response-body.ts"],"names":[],"mappings":"AAMA,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,IAAwB,EAAE,QAAgB,EAAE,MAAoB;IACjG,IAAI,CAAC,EAAE,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IAC7B,IAAI,CAAC;QACJ,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;YACrC,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YACpE,OAAO;QACR,CAAC;QACD,MAAM,SAAS,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;IACzC,CAAC;IAAC,MAAM,CAAC;QACR,4EAA4E;IAC7E,CAAC;YAAS,CAAC;QACV,IAAI,CAAC,OAAO,EAAE,CAAC;IAChB,CAAC;AACF,CAAC;AAED,KAAK,UAAU,SAAS,CAAC,IAAwB,EAAE,QAAgB,EAAE,MAAoB;IACxF,IAAI,OAAO,GAAG,CAA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AAO,KAAK,CAAC;IAC9C,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACtE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;AACnD,CAAC","sourcesContent":["export interface ResponseBodyStream extends AsyncIterable<unknown> {\n\ton?(event: \"error\", listener: (error: Error) => void): unknown;\n\tdestroy(error?: Error): void;\n\tdump?(options?: { limit: number; signal?: AbortSignal }): Promise<void>;\n}\n\nexport async function discardBody(body: ResponseBodyStream, maxBytes: number, signal?: AbortSignal): Promise<void> {\n\tbody.on?.(\"error\", () => {});\n\ttry {\n\t\tif (typeof body.dump === \"function\") {\n\t\t\tawait body.dump(signal ? { limit: 1024, signal } : { limit: 1024 });\n\t\t\treturn;\n\t\t}\n\t\tawait drainBody(body, maxBytes, signal);\n\t} catch {\n\t\t// no-excuse-ok: catch - discard failures are not actionable for the caller.\n\t} finally {\n\t\tbody.destroy();\n\t}\n}\n\nasync function drainBody(body: ResponseBodyStream, maxBytes: number, signal?: AbortSignal): Promise<void> {\n\tlet drained = 0;\n\tconst iterator = body[Symbol.asyncIterator]();\n\twhile (true) {\n\t\tconst result = await nextChunk(iterator, signal);\n\t\tif (!result || result.done) return;\n\t\tdrained += toUint8Array(result.value).length;\n\t\tif (drained > maxBytes) return;\n\t}\n}\n\nasync function nextChunk(\n\titerator: AsyncIterator<unknown>,\n\tsignal?: AbortSignal,\n): Promise<IteratorResult<unknown> | undefined> {\n\tif (!signal) return iterator.next();\n\tif (signal.aborted) return undefined;\n\n\tlet resolveAbort: () => void = () => {};\n\tconst aborted = new Promise<undefined>((resolve) => {\n\t\tresolveAbort = () => resolve(undefined);\n\t});\n\tconst onAbort = (): void => resolveAbort();\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\ttry {\n\t\treturn await Promise.race([iterator.next(), aborted]);\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n}\n\nexport function toUint8Array(chunk: unknown): Uint8Array {\n\tif (chunk instanceof Uint8Array) return chunk;\n\tif (typeof chunk === \"string\") return new TextEncoder().encode(chunk);\n\tthrow new Error(\"Unexpected response body chunk\");\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAK/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAQ5C,OAAO,KAAK,EAAE,uBAAuB,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAK/G,OAAO,EAAoD,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAEtH,QAAA,MAAM,UAAU;;;;EAId,CAAC;AAEH,eAAO,MAAM,gCAAgC;;;CAGnC,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC9B;AASD;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B,qCAAqC;IACrC,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACpD,+CAA+C;IAC/C,MAAM,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,sEAAsE;IACtE,mBAAmB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;CACnF;AAQD,MAAM,WAAW,eAAe;IAC/B,oEAAoE;IACpE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,oEAAoE;IACpE,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,sDAAsD;IACtD,gBAAgB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IAC/B,oEAAoE;IACpE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,oEAAoE;IACpE,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,sDAAsD;IACtD,gBAAgB,CAAC,EAAE,uBAAuB,CAAC;CAC3C;AA4ID,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CA2JhE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG"}
@@ -25,6 +25,8 @@ export const readToolSystemPromptContribution = {
25
25
  guidelines: ["Use read to examine files instead of cat or sed."],
26
26
  };
27
27
  const COMPACT_RESOURCE_FILE_NAMES = new Set(["AGENTS.override.md", "AGENTS.md", "AGENTS.MD", "CLAUDE.md", "CLAUDE.MD"]);
28
+ const LOCAL_URI_SCHEME = /^local:\/\//i;
29
+ const LOCAL_URI_GUIDANCE = "local:// URIs resolve only inside eval cells via the kernel read()/write() helpers; the read tool takes filesystem paths. Re-read this with the eval read() helper, or retry with the plain absolute file path.";
28
30
  const defaultReadOperations = {
29
31
  readFile: (path) => fsReadFile(path),
30
32
  access: (path) => fsAccess(path, constants.R_OK),
@@ -146,6 +148,9 @@ export function createReadToolDefinition(cwd, options) {
146
148
  parameters: readSchema,
147
149
  constrainedSampling: getExperimentalToolSampling(),
148
150
  async execute(_toolCallId, { path, offset, limit }, signal, _onUpdate, ctx) {
151
+ if (LOCAL_URI_SCHEME.test(path)) {
152
+ throw new Error(LOCAL_URI_GUIDANCE);
153
+ }
149
154
  return new Promise((resolve, reject) => {
150
155
  if (signal?.aborted) {
151
156
  reject(new Error("Operation aborted"));