@code-yeongyu/senpi 2026.8.30-3 → 2026.8.31

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 (188) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +3 -0
  3. package/dist/core/agent-session.d.ts +26 -0
  4. package/dist/core/agent-session.d.ts.map +1 -1
  5. package/dist/core/agent-session.js +67 -0
  6. package/dist/core/agent-session.js.map +1 -1
  7. package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry.d.ts +9 -1
  8. package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry.d.ts.map +1 -1
  9. package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry.js +10 -3
  10. package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry.js.map +1 -1
  11. package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts +1 -1
  12. package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts.map +1 -1
  13. package/dist/core/extensions/builtin/compaction/deterministic-fallback.js +4 -1
  14. package/dist/core/extensions/builtin/compaction/deterministic-fallback.js.map +1 -1
  15. package/dist/core/extensions/builtin/compaction/speculative-summary.d.ts +1 -0
  16. package/dist/core/extensions/builtin/compaction/speculative-summary.d.ts.map +1 -1
  17. package/dist/core/extensions/builtin/compaction/speculative-summary.js +1 -0
  18. package/dist/core/extensions/builtin/compaction/speculative-summary.js.map +1 -1
  19. package/dist/core/extensions/builtin/compaction/speculative.d.ts.map +1 -1
  20. package/dist/core/extensions/builtin/compaction/speculative.js +14 -1
  21. package/dist/core/extensions/builtin/compaction/speculative.js.map +1 -1
  22. package/dist/core/extensions/builtin/hooks/trust-state-json.d.ts +5 -0
  23. package/dist/core/extensions/builtin/hooks/trust-state-json.d.ts.map +1 -0
  24. package/dist/core/extensions/builtin/hooks/trust-state-json.js +76 -0
  25. package/dist/core/extensions/builtin/hooks/trust-state-json.js.map +1 -0
  26. package/dist/core/extensions/builtin/hooks/trust-storage.d.ts +7 -1
  27. package/dist/core/extensions/builtin/hooks/trust-storage.d.ts.map +1 -1
  28. package/dist/core/extensions/builtin/hooks/trust-storage.js +60 -8
  29. package/dist/core/extensions/builtin/hooks/trust-storage.js.map +1 -1
  30. package/dist/core/extensions/builtin/hooks/trust.d.ts +1 -2
  31. package/dist/core/extensions/builtin/hooks/trust.d.ts.map +1 -1
  32. package/dist/core/extensions/builtin/hooks/trust.js +1 -72
  33. package/dist/core/extensions/builtin/hooks/trust.js.map +1 -1
  34. package/dist/core/extensions/builtin/ttsr/index.d.ts.map +1 -1
  35. package/dist/core/extensions/builtin/ttsr/index.js +4 -0
  36. package/dist/core/extensions/builtin/ttsr/index.js.map +1 -1
  37. package/dist/core/extensions/builtin/ttsr/manager.d.ts +2 -0
  38. package/dist/core/extensions/builtin/ttsr/manager.d.ts.map +1 -1
  39. package/dist/core/extensions/builtin/ttsr/manager.js +28 -1
  40. package/dist/core/extensions/builtin/ttsr/manager.js.map +1 -1
  41. package/dist/core/extensions/runner.d.ts +5 -0
  42. package/dist/core/extensions/runner.d.ts.map +1 -1
  43. package/dist/core/extensions/runner.js +7 -0
  44. package/dist/core/extensions/runner.js.map +1 -1
  45. package/dist/core/retry-fallback/controller.d.ts +14 -0
  46. package/dist/core/retry-fallback/controller.d.ts.map +1 -1
  47. package/dist/core/retry-fallback/controller.js +33 -3
  48. package/dist/core/retry-fallback/controller.js.map +1 -1
  49. package/dist/core/retry-fallback/log.js +1 -1
  50. package/dist/core/retry-fallback/log.js.map +1 -1
  51. package/dist/core/session-activity.d.ts +47 -0
  52. package/dist/core/session-activity.d.ts.map +1 -0
  53. package/dist/core/session-activity.js +58 -0
  54. package/dist/core/session-activity.js.map +1 -0
  55. package/dist/core/session-manager.d.ts +8 -12
  56. package/dist/core/session-manager.d.ts.map +1 -1
  57. package/dist/core/session-manager.js +118 -7
  58. package/dist/core/session-manager.js.map +1 -1
  59. package/dist/core/session-resident-store.d.ts +8 -1
  60. package/dist/core/session-resident-store.d.ts.map +1 -1
  61. package/dist/core/session-resident-store.js +12 -5
  62. package/dist/core/session-resident-store.js.map +1 -1
  63. package/dist/modes/app-server/daemon.js +3 -3
  64. package/dist/modes/app-server/daemon.js.map +1 -1
  65. package/dist/modes/interactive/interactive-host-runtime.d.ts +3 -1
  66. package/dist/modes/interactive/interactive-host-runtime.d.ts.map +1 -1
  67. package/dist/modes/interactive/interactive-host-runtime.js +26 -4
  68. package/dist/modes/interactive/interactive-host-runtime.js.map +1 -1
  69. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  70. package/dist/modes/interactive/interactive-mode.js +24 -0
  71. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  72. package/dist/modes/rpc/connection-handler.d.ts +12 -5
  73. package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
  74. package/dist/modes/rpc/connection-handler.js +149 -12
  75. package/dist/modes/rpc/connection-handler.js.map +1 -1
  76. package/dist/modes/rpc/custom-capability.d.ts +1 -0
  77. package/dist/modes/rpc/custom-capability.d.ts.map +1 -1
  78. package/dist/modes/rpc/custom-capability.js +1 -0
  79. package/dist/modes/rpc/custom-capability.js.map +1 -1
  80. package/dist/modes/rpc/host-ensure.d.ts.map +1 -1
  81. package/dist/modes/rpc/host-ensure.js +3 -3
  82. package/dist/modes/rpc/host-ensure.js.map +1 -1
  83. package/dist/modes/rpc/host-lifecycle.d.ts +10 -0
  84. package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
  85. package/dist/modes/rpc/host-lifecycle.js +15 -2
  86. package/dist/modes/rpc/host-lifecycle.js.map +1 -1
  87. package/dist/modes/rpc/multi-session-host.d.ts +38 -0
  88. package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
  89. package/dist/modes/rpc/multi-session-host.js +55 -5
  90. package/dist/modes/rpc/multi-session-host.js.map +1 -1
  91. package/dist/modes/rpc/ownership-safe-lock.d.ts +14 -0
  92. package/dist/modes/rpc/ownership-safe-lock.d.ts.map +1 -0
  93. package/dist/modes/rpc/ownership-safe-lock.js +87 -0
  94. package/dist/modes/rpc/ownership-safe-lock.js.map +1 -0
  95. package/dist/modes/rpc/rpc-client.d.ts +1 -0
  96. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  97. package/dist/modes/rpc/rpc-client.js +3 -0
  98. package/dist/modes/rpc/rpc-client.js.map +1 -1
  99. package/dist/modes/rpc/rpc-types.d.ts +12 -1
  100. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  101. package/dist/modes/rpc/rpc-types.js +1 -0
  102. package/dist/modes/rpc/rpc-types.js.map +1 -1
  103. package/dist/modes/rpc/session-binding.d.ts +2 -1
  104. package/dist/modes/rpc/session-binding.d.ts.map +1 -1
  105. package/dist/modes/rpc/session-binding.js +1 -0
  106. package/dist/modes/rpc/session-binding.js.map +1 -1
  107. package/dist/modes/rpc/session-command-router.d.ts +54 -1
  108. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  109. package/dist/modes/rpc/session-command-router.js +174 -2
  110. package/dist/modes/rpc/session-command-router.js.map +1 -1
  111. package/dist/modes/rpc/session-event-writer.d.ts +18 -0
  112. package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
  113. package/dist/modes/rpc/session-event-writer.js +88 -8
  114. package/dist/modes/rpc/session-event-writer.js.map +1 -1
  115. package/dist/modes/rpc/session-registry.d.ts +11 -1
  116. package/dist/modes/rpc/session-registry.d.ts.map +1 -1
  117. package/dist/modes/rpc/session-registry.js +25 -0
  118. package/dist/modes/rpc/session-registry.js.map +1 -1
  119. package/dist/modes/rpc/widget-line-renderer.d.ts +17 -0
  120. package/dist/modes/rpc/widget-line-renderer.d.ts.map +1 -0
  121. package/dist/modes/rpc/widget-line-renderer.js +73 -0
  122. package/dist/modes/rpc/widget-line-renderer.js.map +1 -0
  123. package/dist/utils/fs-watch.d.ts.map +1 -1
  124. package/dist/utils/fs-watch.js +11 -2
  125. package/dist/utils/fs-watch.js.map +1 -1
  126. package/docs/app-server.md +2 -2
  127. package/docs/containerization.md +2 -2
  128. package/docs/development.md +7 -7
  129. package/docs/extensions.md +4 -4
  130. package/docs/grok-neo.md +1 -1
  131. package/docs/index.md +1 -1
  132. package/docs/packages.md +2 -2
  133. package/docs/quickstart.md +4 -4
  134. package/docs/release-guide.md +21 -21
  135. package/docs/rpc.md +59 -4
  136. package/docs/sdk.md +1 -1
  137. package/docs/skills.md +2 -2
  138. package/docs/terminal-tools.md +1 -1
  139. package/docs/termux.md +1 -1
  140. package/docs/tui.md +1 -1
  141. package/examples/AGENTS.md +1 -1
  142. package/examples/sdk/README.md +1 -1
  143. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +16 -0
  144. package/node_modules/@code-yeongyu/senpi-codemode/README.md +2 -2
  145. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  146. package/node_modules/@code-yeongyu/senpi-codemode/src/extension/skill-contribution.ts +71 -0
  147. package/node_modules/@code-yeongyu/senpi-codemode/src/index.ts +3 -1
  148. package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/SKILL.md +44 -0
  149. package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/breaking-changes.md +75 -0
  150. package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/build.md +114 -0
  151. package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/dev-tooling.md +34 -0
  152. package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/http-networking.md +113 -0
  153. package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/install.md +93 -0
  154. package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/node-compat-platforms.md +36 -0
  155. package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/performance.md +33 -0
  156. package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/runtime-apis.md +156 -0
  157. package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/security.md +52 -0
  158. package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/test.md +103 -0
  159. package/node_modules/@earendil-works/pi-agent-core/README.md +3 -0
  160. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  161. package/node_modules/@earendil-works/pi-ai/README.md +6 -3
  162. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.d.ts.map +1 -1
  163. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +15 -0
  164. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js.map +1 -1
  165. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts +7 -0
  166. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts.map +1 -1
  167. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js +316 -2
  168. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js.map +1 -1
  169. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-conversation-rotation.d.ts +4 -0
  170. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-conversation-rotation.d.ts.map +1 -1
  171. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-conversation-rotation.js +23 -0
  172. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-conversation-rotation.js.map +1 -1
  173. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts +24 -0
  174. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts.map +1 -1
  175. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +20 -2
  176. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js.map +1 -1
  177. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  178. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  179. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  180. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  181. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  182. package/node_modules/@earendil-works/pi-telemetry/README.md +6 -3
  183. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  184. package/node_modules/@earendil-works/pi-tui/README.md +5 -4
  185. package/node_modules/@earendil-works/pi-tui/native/darwin/README.md +2 -2
  186. package/node_modules/@earendil-works/pi-tui/native/win32/README.md +2 -2
  187. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  188. package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"file":"speculative.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/speculative.ts"],"names":[],"mappings":"AACA,OAAO,EAEN,oBAAoB,EACpB,iBAAiB,EACjB,yBAAyB,EACzB,uBAAuB,EAGvB,kBAAkB,GAElB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAGN,2BAA2B,EAC3B,qBAAqB,EACrB,iBAAiB,GACjB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,yBAAyB,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAC3G,OAAO,EACN,wBAAwB,EACxB,wBAAwB,GAExB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAIpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EACN,kBAAkB,EAClB,uBAAuB,EACvB,gCAAgC,EAChC,mCAAmC,EACnC,wCAAwC,GACxC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,gCAAgC,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAC1F,OAAO,EAAE,WAAW,EAAsC,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAEtG,OAAO,EAAE,uBAAuB,EAAE,kCAAkC,EAAE,MAAM,0BAA0B,CAAC;AAEvG,OAAO,EAAE,iBAAiB,EAAE,0BAA0B,EAAE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AU,EAAE;QAChD,MAAM,EAAE,WAAW;QACnB,GAAG,CAAC,iBAAiB,IAAI,CAAC,UAAU;YACnC,CAAC,CAAC,EAAE,gBAAgB,EAAE,QAAQ,CAAC,gBAAgB,EAAE;YACjD,CAAC,CAAC,EAAE,kBAAkB,EAAE,UAAU,EAAE,CAAC;QACtC,MAAM;KACN,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC/C,OAAqC,EACrC,QAAmD,EACnD,oBAAkC,EAClC,QAAqD;IAErD,IAAI,CAAC,QAAQ;QAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC;IAEhE,MAAM,UAAU,GAAG,MAAM,QAAQ,EAAE,CAAC;IACpC,OAAO,MAAM,wBAAwB,CAAC,OAAO,EAAE,QAAQ,EAAE,oBAAoB,EAAE,UAAU,CAAC,CAAC;AAC5F,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype AssistantMessage,\n\thasCredentialHeaders,\n\tisContextOverflow,\n\tisRetryableAssistantError,\n\tisRetryableErrorMessage,\n\ttype Message,\n\ttype Model,\n\tretryTransientCall,\n\ttype Tool,\n} from \"@earendil-works/pi-ai\";\nimport {\n\ttype CompactionPreparation,\n\ttype CompactionResult,\n\tDEFAULT_COMPACTION_SETTINGS,\n\testimateContextTokens,\n\tprepareCompaction,\n} from \"../../../compaction/index.ts\";\nimport { StreamDurationBudgetError, StreamIdleTimeoutError } from \"../../../compaction/stream-watchdog.ts\";\nimport {\n\tcreateWarmAnchorSnapshot,\n\tisWarmSummaryAnchorValid,\n\ttype WarmAnchorSnapshot,\n} from \"../../../compaction/warm-anchor.ts\";\nimport { convertToLlm } from \"../../../messages.ts\";\nimport type { ModelRegistry } from \"../../../model-registry.ts\";\nimport type { ReadonlySessionManager } from \"../../../session-manager.ts\";\nimport type { ApplyCompactionResult, ContextUsage, ProviderRequestPreparation } from \"../../types.ts\";\nimport { pruneToolResults } from \"./emergency-prune.ts\";\nimport {\n\tallowOverflowRetry,\n\tboundSummarizationInput,\n\tSUMMARIZATION_INPUT_BUDGET_RATIO,\n\tSummarizationOverflowExhaustedError,\n\tshrinkSummarizationInputForOverflowRetry,\n} from \"./overflow-retry.ts\";\nimport { computeEffectiveKeepRecentTokens, computeEffectiveThreshold } from \"./policy.ts\";\nimport { buildPrompt, type MergedCompactionPromptVariant } from \"./prompts.ts\";\nimport { generateSummaryMessage, getSummaryText, isAssistantMessage } from \"./speculative-summary.ts\";\n\nimport { allowSummarizationRetry, DEFAULT_SUMMARIZATION_RETRY_POLICY } from \"./summarization-retry.ts\";\n\nimport { extractTaskIntent, resolveInheritedTaskIntent } from \"./task-intent.ts\";\n\nexport {\n\tcreateEmergencyPruneLatch,\n\ttype EmergencyPruneLatch,\n\thardLimitEmergencyPrune,\n\ttruncateContextMessages,\n} from \"./emergency-prune.ts\";\n\nimport { computeStructuralYield } from \"./yield.ts\";\n\nconst DEFAULT_CONTEXT_WINDOW = 200_000;\n// Hysteresis: the emergency prune engages at EMERGENCY_CONTEXT_TARGET_RATIO but only\n// releases once the context falls below this lower ratio. A single threshold makes a\n// session parked near the limit alternate between the pruned and un-pruned history on\n// consecutive requests; because pruning rewrites old tool results, every alternation\n// invalidates the provider prompt-cache prefix and re-bills the whole conversation.\nconst SUMMARY_SCHEMA = \"senpi.compaction.summary.v1\";\ntype CompactionProgressCallback = (delta: string) => void;\n\nexport interface SpeculativeCompactionContext {\n\tmodel: Model<any> | undefined;\n\tsessionManager: ReadonlySessionManager;\n\tmodelRegistry?: ModelRegistry;\n\tgetContextUsage(): ContextUsage | undefined;\n\tgetCompactionSettings?(): CompactionPreparation[\"settings\"];\n\tgetMessageRevision(): number;\n\tgetSystemPrompt?(): string;\n\tprepareProviderRequest?(messages: AgentMessage[]): Promise<ProviderRequestPreparation>;\n\tisIdle?(): boolean;\n\tapplyCompaction(\n\t\tprecomputed: CompactionResult,\n\t\toptions: {\n\t\t\treason: \"extension\";\n\t\t\texpectedRevision?: number;\n\t\t\texpectedWarmAnchor?: WarmAnchorSnapshot;\n\t\t\tsignal?: AbortSignal;\n\t\t},\n\t): Promise<ApplyCompactionResult>;\n}\n\nexport interface SpeculativeCompactionSnapshot {\n\tgeneration: number;\n\texpectedRevision: number;\n\tmodel: Model<any>;\n\tcontextWindow: number;\n\tpreparation: CompactionPreparation;\n\tbranchEntries?: ReturnType<ReadonlySessionManager[\"getBranch\"]>;\n\tpromptVariant: MergedCompactionPromptVariant;\n\torigin?: \"speculative\" | \"blocking\" | \"core-route\";\n\tcustomInstructions?: string;\n\t/** Agent system prompt; used to make the summarization request look like normal agent traffic. */\n\tsystemPrompt?: string;\n\t/** Agent tool definitions; forwarded so the request shape matches normal agent traffic. */\n\ttools?: Tool[];\n}\n\nexport type SpeculativeCompactionResult = ApplyCompactionResult | { applied: false; reason: \"unavailable\" | \"failed\" };\n\nfunction approxTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\n/**\n * Summary-generation failure with a user-facing diagnosis. Distinct from a\n * user abort (which resolves `undefined`): callers surface `message` on the\n * manual route and degrade to \"unavailable\" on automatic routes.\n */\n/**\n * Provider `error` stop during summarization, carrying the metadata-aware\n * transient classification from the full assistant message. A refusal whose\n * text happens to look retryable must still surface loudly; the message\n * string alone cannot encode that.\n */\nexport type SummaryRequestFailureKind = \"upstream-stream-truncated\";\n\nexport class SummaryRequestError extends Error {\n\treadonly transient: boolean;\n\treadonly failureKind?: SummaryRequestFailureKind;\n\n\tconstructor(message: string, transient: boolean, failureKind?: SummaryRequestFailureKind) {\n\t\tsuper(message);\n\t\tthis.name = \"SummaryRequestError\";\n\t\tthis.transient = transient;\n\t\tthis.failureKind = failureKind;\n\t}\n}\n\nconst UPSTREAM_STREAM_TRUNCATED_PATTERN = /(?:^|[^A-Za-z0-9_])upstream_stream_truncated(?:[^A-Za-z0-9_]|$)/;\n\n/**\n * Only failures with no cheaper recovery earn another billed request.\n *\n * Every class that `classifyRequiredCompactionFallbackFailure` recognizes\n * (watchdog timeouts, `upstream-stream-truncated`, overflow exhaustion) already\n * has a deterministic zero-LLM recovery, and context overflow is answered by\n * shrinking the input in the surrounding loop - replaying those would pay for a\n * summarization the fallback can rebuild for free. The classes checked here are\n * mirrored from that classifier rather than imported, because\n * `deterministic-fallback.ts` imports this module.\n */\nfunction isRetryableSummaryAttempt(error: unknown): boolean {\n\tif (error instanceof StreamDurationBudgetError || error instanceof StreamIdleTimeoutError) return false;\n\tif (error instanceof SummarizationOverflowExhaustedError) return false;\n\tif (error instanceof SummaryGenerationError) return false;\n\tif (error instanceof SummaryRequestError) return error.failureKind === undefined && error.transient;\n\tif (error instanceof Error) return isRetryableErrorMessage(error.message);\n\treturn false;\n}\n\nfunction summaryRequestFailureKind(response: AssistantMessage): SummaryRequestFailureKind | undefined {\n\tif (response.stopDetails?.type === \"refusal\" || response.stopDetails?.type === \"sensitive\") return undefined;\n\treturn UPSTREAM_STREAM_TRUNCATED_PATTERN.test(response.errorMessage ?? \"\") ? \"upstream-stream-truncated\" : undefined;\n}\n\nexport class SummaryGenerationError extends Error {\n\treadonly kind: \"auth\" | \"empty-summary\";\n\n\tconstructor(kind: \"auth\" | \"empty-summary\", message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"SummaryGenerationError\";\n\t\tthis.kind = kind;\n\t}\n}\n\n/**\n * Output budget for one summarization request. Adaptive-thinking models emit\n * reasoning tokens before the summary text, so the legacy flat 8192 cap could\n * be consumed entirely by thinking, ending the stream with zero text blocks.\n * Grant generous headroom, clamped to what the model can actually emit and to\n * half the context window: providers that enforce input + output <= window\n * would otherwise reject the request for models advertising contextWindow ==\n * maxTokens (every summarization request also carries conversation input).\n */\n\nexport function getPromptVariant(options: {\n\treason: string;\n\tpreparation: { previousSummary?: string; isSplitTurn: boolean };\n}): MergedCompactionPromptVariant {\n\tif (options.reason === \"branch\") return \"branch\";\n\tif (options.preparation.previousSummary) return \"update\";\n\tif (options.preparation.isSplitTurn) return \"turn_prefix\";\n\treturn \"default\";\n}\n\nexport function createSpeculativeCompactionSnapshot(\n\tcontext: SpeculativeCompactionContext,\n\toptions: {\n\t\tcustomInstructions?: string;\n\t\tgeneration: number;\n\t\torigin?: \"speculative\" | \"blocking\" | \"core-route\";\n\t\ttools?: Tool[];\n\t},\n): SpeculativeCompactionSnapshot | undefined {\n\tconst model = context.model;\n\tif (!model) return undefined;\n\n\tconst expectedRevision = context.getMessageRevision();\n\tconst branchEntries = context.sessionManager.getBranch();\n\tconst contextWindow = context.getContextUsage()?.contextWindow ?? model.contextWindow ?? DEFAULT_CONTEXT_WINDOW;\n\tconst settings = context.getCompactionSettings?.() ?? DEFAULT_COMPACTION_SETTINGS;\n\tconst thresholdRatio = computeEffectiveThreshold(contextWindow);\n\tconst preparation = prepareCompaction(branchEntries, {\n\t\t...settings,\n\t\tkeepRecentTokens: computeEffectiveKeepRecentTokens(settings.keepRecentTokens, contextWindow, thresholdRatio),\n\t});\n\tif (!preparation) return undefined;\n\n\treturn {\n\t\t...options,\n\t\texpectedRevision,\n\t\tmodel,\n\t\tcontextWindow,\n\t\tpreparation,\n\t\tbranchEntries,\n\t\tpromptVariant: getPromptVariant({ reason: \"extension\", preparation }),\n\t\tsystemPrompt: context.getSystemPrompt?.(),\n\t};\n}\n\n/**\n * Generate a compaction summary for the snapshot. Resolves `undefined` only\n * when the request was aborted (caller signal or an aborted stream); every\n * other failure throws — {@link SummaryGenerationError} for diagnosable\n * generation failures, the raw provider error otherwise. Abort is checked\n * before and after credential resolution so a cancelled request never\n * misreports as an auth failure.\n */\nexport async function runExtensionCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot,\n\tsignal?: AbortSignal,\n\tonProgress?: CompactionProgressCallback,\n): Promise<CompactionResult | undefined> {\n\tif (signal?.aborted) return undefined;\n\tconst auth = await context.modelRegistry?.getApiKeyAndHeaders(snapshot.model);\n\tif (signal?.aborted) return undefined;\n\t// A provider is authenticated for summarization by either a resolved key or a\n\t// credential request header: `headers`-authenticated providers (models.json and\n\t// extension providers alike) never resolve an apiKey, yet their normal agent\n\t// turns are fully authenticated.\n\tif (!auth?.ok || !(auth.apiKey || hasCredentialHeaders(auth.headers))) {\n\t\tconst detail =\n\t\t\tauth && !auth.ok ? auth.error : `no credentials resolved for provider \"${snapshot.model.provider}\"`;\n\t\tthrow new SummaryGenerationError(\"auth\", `summarization credentials unavailable: ${detail}`);\n\t}\n\tconst requestSnapshot = auth.baseUrl\n\t\t? { ...snapshot, model: { ...snapshot.model, baseUrl: auth.baseUrl } }\n\t\t: snapshot;\n\n\tconst prompt = buildPrompt({\n\t\tvariant: requestSnapshot.promptVariant,\n\t\tpreviousSummary: requestSnapshot.preparation.previousSummary,\n\t\ttaskIntent: resolveInheritedTaskIntent(requestSnapshot.branchEntries ?? []),\n\t\tcustomInstructions: requestSnapshot.customInstructions,\n\t});\n\tconst promptTokens = approxTokens(prompt.user);\n\tlet messages = boundSummarizationInput(\n\t\tpruneToolResults(\n\t\t\t[...requestSnapshot.preparation.messagesToSummarize, ...requestSnapshot.preparation.turnPrefixMessages],\n\t\t\trequestSnapshot.contextWindow,\n\t\t\tSUMMARIZATION_INPUT_BUDGET_RATIO,\n\t\t),\n\t\trequestSnapshot.contextWindow,\n\t\tpromptTokens,\n\t);\n\tconst overflowRetryStartMs = Date.now();\n\tlet overflowAttempts = 0;\n\n\twhile (true) {\n\t\tif (signal?.aborted) return undefined;\n\t\tlet response: Message | undefined;\n\t\tconst currentMessages = messages;\n\t\tconst retryStartedMs = Date.now();\n\t\t// Only the routes that block the user's turn retry here. The speculative\n\t\t// warm-up owns its own bounded retry (`idle-retry.ts`) with idle/breaker\n\t\t// guards re-evaluated between attempts, and a failed warm job must stay\n\t\t// inheritable so the next blocking route degrades on it instead of paying\n\t\t// for a second request.\n\t\tconst retryEligible = snapshot.origin === \"core-route\" || snapshot.origin === \"blocking\";\n\t\ttry {\n\t\t\t// The provider `error` stop is raised INSIDE the retried producer so a\n\t\t\t// transient summarization failure spends the shared retry budget. The\n\t\t\t// surrounding loop keeps overflow shrinking and abort handling, which\n\t\t\t// must never be answered by replaying the same request.\n\t\t\tresponse = await retryTransientCall(\n\t\t\t\tasync () => {\n\t\t\t\t\tconst attempt = await generateSummaryMessage({\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\tmessages: currentMessages,\n\t\t\t\t\t\tonProgress,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tsnapshot: requestSnapshot,\n\t\t\t\t\t\tauth: {\n\t\t\t\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\t\t\t\theaders: auth.headers,\n\t\t\t\t\t\t\textraBody: auth.extraBody,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tif (\n\t\t\t\t\t\tattempt &&\n\t\t\t\t\t\tisAssistantMessage(attempt) &&\n\t\t\t\t\t\tattempt.stopReason === \"error\" &&\n\t\t\t\t\t\t!isContextOverflow(attempt, snapshot.contextWindow)\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst failureKind = summaryRequestFailureKind(attempt);\n\t\t\t\t\t\tthrow new SummaryRequestError(\n\t\t\t\t\t\t\tattempt.errorMessage || \"Compaction summary request failed\",\n\t\t\t\t\t\t\tfailureKind !== undefined || isRetryableAssistantError(attempt),\n\t\t\t\t\t\t\tfailureKind,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn attempt;\n\t\t\t\t},\n\t\t\t\t(error) =>\n\t\t\t\t\tretryEligible &&\n\t\t\t\t\tallowSummarizationRetry(Date.now() - retryStartedMs) &&\n\t\t\t\t\tisRetryableSummaryAttempt(error),\n\t\t\t\tDEFAULT_SUMMARIZATION_RETRY_POLICY,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) return undefined;\n\t\t\tthrow error;\n\t\t}\n\t\tif (!response) return undefined;\n\n\t\tif (isAssistantMessage(response) && isContextOverflow(response, snapshot.contextWindow)) {\n\t\t\toverflowAttempts++;\n\t\t\tconst elapsedMs = Date.now() - overflowRetryStartMs;\n\t\t\tconst retryMessages = allowOverflowRetry(overflowAttempts, elapsedMs)\n\t\t\t\t? shrinkSummarizationInputForOverflowRetry(messages, snapshot.contextWindow, promptTokens)\n\t\t\t\t: undefined;\n\t\t\tif (!retryMessages) {\n\t\t\t\tthrow new SummarizationOverflowExhaustedError(overflowAttempts, elapsedMs);\n\t\t\t}\n\t\t\tmessages = retryMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (isAssistantMessage(response) && response.stopReason === \"aborted\") {\n\t\t\t// A partial summary from an aborted stream must never be applied.\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (isAssistantMessage(response) && response.stopReason === \"error\") {\n\t\t\t// Surface the real provider failure instead of silently degrading\n\t\t\t// into a generic \"Compaction cancelled\". Preserve the structured\n\t\t\t// truncation class here so downstream recovery never trusts arbitrary\n\t\t\t// thrown error text as authorization for destructive context reduction.\n\t\t\tconst failureKind = summaryRequestFailureKind(response);\n\t\t\tthrow new SummaryRequestError(\n\t\t\t\tresponse.errorMessage || \"Compaction summary request failed\",\n\t\t\t\tfailureKind !== undefined || isRetryableAssistantError(response),\n\t\t\t\tfailureKind,\n\t\t\t);\n\t\t}\n\n\t\tconst summary = getSummaryText(response);\n\t\tif (!summary) {\n\t\t\tconst stopReason = isAssistantMessage(response) ? response.stopReason : \"unknown\";\n\t\t\tthrow new SummaryGenerationError(\n\t\t\t\t\"empty-summary\",\n\t\t\t\t`summarization response contained no text (stopReason: ${stopReason})`,\n\t\t\t);\n\t\t}\n\n\t\t// Informational only: the core rejects an applied compaction that would\n\t\t// still overflow (_wouldCompactionOverflow). Rejecting here based on the\n\t\t// size of the *discarded* input made large sessions uncompactable.\n\t\tconst tokenEstimate = estimateContextTokens(convertToLlm(messages)).tokens + approxTokens(summary);\n\t\tconst parsedSummary = extractTaskIntent(summary);\n\t\tconst taskIntent = parsedSummary.taskIntent ?? resolveInheritedTaskIntent(snapshot.branchEntries ?? []);\n\n\t\treturn {\n\t\t\tsummary: parsedSummary.summaryText,\n\t\t\tfirstKeptEntryId: snapshot.preparation.firstKeptEntryId,\n\t\t\ttokensBefore: snapshot.preparation.tokensBefore,\n\t\t\tdetails: {\n\t\t\t\tschema: SUMMARY_SCHEMA,\n\t\t\t\tpromptVariant: snapshot.promptVariant,\n\t\t\t\ttokenEstimate,\n\t\t\t\tstructuralYield: computeStructuralYield({\n\t\t\t\t\tpreviousSummary: snapshot.preparation.previousSummary ?? \"\",\n\t\t\t\t\tmessagesToSummarize: snapshot.preparation.messagesToSummarize,\n\t\t\t\t\tturnPrefixMessages: snapshot.preparation.turnPrefixMessages,\n\t\t\t\t\tsummary: parsedSummary.summaryText,\n\t\t\t\t\ttokensBefore: snapshot.preparation.tokensBefore,\n\t\t\t\t}),\n\t\t\t\t...(snapshot.origin ? { origin: snapshot.origin } : {}),\n\t\t\t\t...(taskIntent ? { taskIntent } : {}),\n\t\t\t},\n\t\t};\n\t}\n}\n\nexport async function applyGeneratedCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot | undefined,\n\tgetCurrentGeneration: () => number,\n\tcompaction: CompactionResult | undefined,\n\tsignal?: AbortSignal,\n): Promise<SpeculativeCompactionResult> {\n\tconst provider = context.model?.provider;\n\tif ((provider === \"cursor\" || provider === \"cursor-cli-oauth\") && context.isIdle && !context.isIdle()) {\n\t\treturn { applied: false, reason: \"rejected\" };\n\t}\n\tif (!snapshot || !compaction) return { applied: false, reason: \"unavailable\" };\n\n\tif (snapshot.generation !== getCurrentGeneration()) {\n\t\treturn { applied: false, reason: \"stale\" };\n\t}\n\n\tconst revisionUnchanged = snapshot.expectedRevision === context.getMessageRevision();\n\tconst warmAnchor = createWarmAnchorSnapshot(snapshot.preparation.firstKeptEntryId, snapshot.branchEntries ?? []);\n\tif (\n\t\t!revisionUnchanged &&\n\t\t(!warmAnchor || !isWarmSummaryAnchorValid(warmAnchor, context.sessionManager.getBranch()))\n\t) {\n\t\treturn { applied: false, reason: \"stale\" };\n\t}\n\n\treturn await context.applyCompaction(compaction, {\n\t\treason: \"extension\",\n\t\t...(revisionUnchanged || !warmAnchor\n\t\t\t? { expectedRevision: snapshot.expectedRevision }\n\t\t\t: { expectedWarmAnchor: warmAnchor }),\n\t\tsignal,\n\t});\n}\n\nexport async function applySpeculativeCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot | undefined,\n\tgetCurrentGeneration: () => number,\n\tgenerate: () => Promise<CompactionResult | undefined>,\n): Promise<SpeculativeCompactionResult> {\n\tif (!snapshot) return { applied: false, reason: \"unavailable\" };\n\n\tconst compaction = await generate();\n\treturn await applyGeneratedCompaction(context, snapshot, getCurrentGeneration, compaction);\n}\n"]}
1
+ {"version":3,"file":"speculative.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/compaction/speculative.ts"],"names":[],"mappings":"AACA,OAAO,EAEN,oBAAoB,EACpB,iBAAiB,EACjB,yBAAyB,EACzB,uBAAuB,EAGvB,kBAAkB,GAElB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAGN,2BAA2B,EAC3B,qBAAqB,EACrB,iBAAiB,GACjB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,yBAAyB,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAC3G,OAAO,EACN,wBAAwB,EACxB,wBAAwB,GAExB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAIpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EACN,kBAAkB,EAClB,uBAAuB,EACvB,gCAAgC,EAChC,mCAAmC,EACnC,wCAAwC,GACxC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,gCAAgC,EAAE,yBAAyB,EAA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ent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype AssistantMessage,\n\thasCredentialHeaders,\n\tisContextOverflow,\n\tisRetryableAssistantError,\n\tisRetryableErrorMessage,\n\ttype Message,\n\ttype Model,\n\tretryTransientCall,\n\ttype Tool,\n} from \"@earendil-works/pi-ai\";\nimport {\n\ttype CompactionPreparation,\n\ttype CompactionResult,\n\tDEFAULT_COMPACTION_SETTINGS,\n\testimateContextTokens,\n\tprepareCompaction,\n} from \"../../../compaction/index.ts\";\nimport { StreamDurationBudgetError, StreamIdleTimeoutError } from \"../../../compaction/stream-watchdog.ts\";\nimport {\n\tcreateWarmAnchorSnapshot,\n\tisWarmSummaryAnchorValid,\n\ttype WarmAnchorSnapshot,\n} from \"../../../compaction/warm-anchor.ts\";\nimport { convertToLlm } from \"../../../messages.ts\";\nimport type { ModelRegistry } from \"../../../model-registry.ts\";\nimport type { ReadonlySessionManager } from \"../../../session-manager.ts\";\nimport type { ApplyCompactionResult, ContextUsage, ProviderRequestPreparation } from \"../../types.ts\";\nimport { pruneToolResults } from \"./emergency-prune.ts\";\nimport {\n\tallowOverflowRetry,\n\tboundSummarizationInput,\n\tSUMMARIZATION_INPUT_BUDGET_RATIO,\n\tSummarizationOverflowExhaustedError,\n\tshrinkSummarizationInputForOverflowRetry,\n} from \"./overflow-retry.ts\";\nimport { computeEffectiveKeepRecentTokens, computeEffectiveThreshold } from \"./policy.ts\";\nimport { buildPrompt, type MergedCompactionPromptVariant } from \"./prompts.ts\";\nimport { generateSummaryMessage, getSummaryText, isAssistantMessage } from \"./speculative-summary.ts\";\n\nimport { allowSummarizationRetry, DEFAULT_SUMMARIZATION_RETRY_POLICY } from \"./summarization-retry.ts\";\n\nimport { extractTaskIntent, resolveInheritedTaskIntent } from \"./task-intent.ts\";\n\nexport {\n\tcreateEmergencyPruneLatch,\n\ttype EmergencyPruneLatch,\n\thardLimitEmergencyPrune,\n\ttruncateContextMessages,\n} from \"./emergency-prune.ts\";\n\nimport { computeStructuralYield } from \"./yield.ts\";\n\nconst DEFAULT_CONTEXT_WINDOW = 200_000;\n// Hysteresis: the emergency prune engages at EMERGENCY_CONTEXT_TARGET_RATIO but only\n// releases once the context falls below this lower ratio. A single threshold makes a\n// session parked near the limit alternate between the pruned and un-pruned history on\n// consecutive requests; because pruning rewrites old tool results, every alternation\n// invalidates the provider prompt-cache prefix and re-bills the whole conversation.\nconst SUMMARY_SCHEMA = \"senpi.compaction.summary.v1\";\ntype CompactionProgressCallback = (delta: string) => void;\n\nexport interface SpeculativeCompactionContext {\n\tmodel: Model<any> | undefined;\n\tsessionManager: ReadonlySessionManager;\n\tmodelRegistry?: ModelRegistry;\n\tgetContextUsage(): ContextUsage | undefined;\n\tgetCompactionSettings?(): CompactionPreparation[\"settings\"];\n\tgetMessageRevision(): number;\n\tgetSystemPrompt?(): string;\n\tprepareProviderRequest?(messages: AgentMessage[]): Promise<ProviderRequestPreparation>;\n\tisIdle?(): boolean;\n\tapplyCompaction(\n\t\tprecomputed: CompactionResult,\n\t\toptions: {\n\t\t\treason: \"extension\";\n\t\t\texpectedRevision?: number;\n\t\t\texpectedWarmAnchor?: WarmAnchorSnapshot;\n\t\t\tsignal?: AbortSignal;\n\t\t},\n\t): Promise<ApplyCompactionResult>;\n}\n\nexport interface SpeculativeCompactionSnapshot {\n\tgeneration: number;\n\texpectedRevision: number;\n\tmodel: Model<any>;\n\tcontextWindow: number;\n\tpreparation: CompactionPreparation;\n\tbranchEntries?: ReturnType<ReadonlySessionManager[\"getBranch\"]>;\n\tpromptVariant: MergedCompactionPromptVariant;\n\torigin?: \"speculative\" | \"blocking\" | \"core-route\";\n\tcustomInstructions?: string;\n\t/** Agent system prompt; used to make the summarization request look like normal agent traffic. */\n\tsystemPrompt?: string;\n\t/** Agent tool definitions; forwarded so the request shape matches normal agent traffic. */\n\ttools?: Tool[];\n}\n\nexport type SpeculativeCompactionResult = ApplyCompactionResult | { applied: false; reason: \"unavailable\" | \"failed\" };\n\nfunction approxTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\n/**\n * Summary-generation failure with a user-facing diagnosis. Distinct from a\n * user abort (which resolves `undefined`): callers surface `message` on the\n * manual route and degrade to \"unavailable\" on automatic routes.\n */\n/**\n * Provider `error` stop during summarization, carrying the metadata-aware\n * transient classification from the full assistant message. A refusal whose\n * text happens to look retryable must still surface loudly; the message\n * string alone cannot encode that.\n */\nexport type SummaryRequestFailureKind = \"upstream-stream-truncated\";\n\nexport class SummaryRequestError extends Error {\n\treadonly transient: boolean;\n\treadonly failureKind?: SummaryRequestFailureKind;\n\n\tconstructor(message: string, transient: boolean, failureKind?: SummaryRequestFailureKind) {\n\t\tsuper(message);\n\t\tthis.name = \"SummaryRequestError\";\n\t\tthis.transient = transient;\n\t\tthis.failureKind = failureKind;\n\t}\n}\n\nconst UPSTREAM_STREAM_TRUNCATED_PATTERN = /(?:^|[^A-Za-z0-9_])upstream_stream_truncated(?:[^A-Za-z0-9_]|$)/;\n\n/**\n * Only failures with no cheaper recovery earn another billed request.\n *\n * Every class that `classifyRequiredCompactionFallbackFailure` recognizes\n * (watchdog timeouts, `upstream-stream-truncated`, overflow exhaustion,\n * empty-summary generation failures) already\n * has a deterministic zero-LLM recovery, and context overflow is answered by\n * shrinking the input in the surrounding loop - replaying those would pay for a\n * summarization the fallback can rebuild for free. The classes checked here are\n * mirrored from that classifier rather than imported, because\n * `deterministic-fallback.ts` imports this module.\n */\nfunction isRetryableSummaryAttempt(error: unknown): boolean {\n\tif (error instanceof StreamDurationBudgetError || error instanceof StreamIdleTimeoutError) return false;\n\tif (error instanceof SummarizationOverflowExhaustedError) return false;\n\tif (error instanceof SummaryGenerationError) return false;\n\tif (error instanceof SummaryRequestError) return error.failureKind === undefined && error.transient;\n\tif (error instanceof Error) return isRetryableErrorMessage(error.message);\n\treturn false;\n}\n\nfunction summaryRequestFailureKind(response: AssistantMessage): SummaryRequestFailureKind | undefined {\n\tif (response.stopDetails?.type === \"refusal\" || response.stopDetails?.type === \"sensitive\") return undefined;\n\treturn UPSTREAM_STREAM_TRUNCATED_PATTERN.test(response.errorMessage ?? \"\") ? \"upstream-stream-truncated\" : undefined;\n}\n\nexport class SummaryGenerationError extends Error {\n\treadonly kind: \"auth\" | \"empty-summary\";\n\n\tconstructor(kind: \"auth\" | \"empty-summary\", message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"SummaryGenerationError\";\n\t\tthis.kind = kind;\n\t}\n}\n\n/**\n * Output budget for one summarization request. Adaptive-thinking models emit\n * reasoning tokens before the summary text, so the legacy flat 8192 cap could\n * be consumed entirely by thinking, ending the stream with zero text blocks.\n * Grant generous headroom, clamped to what the model can actually emit and to\n * half the context window: providers that enforce input + output <= window\n * would otherwise reject the request for models advertising contextWindow ==\n * maxTokens (every summarization request also carries conversation input).\n */\n\nexport function getPromptVariant(options: {\n\treason: string;\n\tpreparation: { previousSummary?: string; isSplitTurn: boolean };\n}): MergedCompactionPromptVariant {\n\tif (options.reason === \"branch\") return \"branch\";\n\tif (options.preparation.previousSummary) return \"update\";\n\tif (options.preparation.isSplitTurn) return \"turn_prefix\";\n\treturn \"default\";\n}\n\nexport function createSpeculativeCompactionSnapshot(\n\tcontext: SpeculativeCompactionContext,\n\toptions: {\n\t\tcustomInstructions?: string;\n\t\tgeneration: number;\n\t\torigin?: \"speculative\" | \"blocking\" | \"core-route\";\n\t\ttools?: Tool[];\n\t},\n): SpeculativeCompactionSnapshot | undefined {\n\tconst model = context.model;\n\tif (!model) return undefined;\n\n\tconst expectedRevision = context.getMessageRevision();\n\tconst branchEntries = context.sessionManager.getBranch();\n\tconst contextWindow = context.getContextUsage()?.contextWindow ?? model.contextWindow ?? DEFAULT_CONTEXT_WINDOW;\n\tconst settings = context.getCompactionSettings?.() ?? DEFAULT_COMPACTION_SETTINGS;\n\tconst thresholdRatio = computeEffectiveThreshold(contextWindow);\n\tconst preparation = prepareCompaction(branchEntries, {\n\t\t...settings,\n\t\tkeepRecentTokens: computeEffectiveKeepRecentTokens(settings.keepRecentTokens, contextWindow, thresholdRatio),\n\t});\n\tif (!preparation) return undefined;\n\n\treturn {\n\t\t...options,\n\t\texpectedRevision,\n\t\tmodel,\n\t\tcontextWindow,\n\t\tpreparation,\n\t\tbranchEntries,\n\t\tpromptVariant: getPromptVariant({ reason: \"extension\", preparation }),\n\t\tsystemPrompt: context.getSystemPrompt?.(),\n\t};\n}\n\n/**\n * Generate a compaction summary for the snapshot. Resolves `undefined` only\n * when the request was aborted (caller signal or an aborted stream); every\n * other failure throws — {@link SummaryGenerationError} for diagnosable\n * generation failures, the raw provider error otherwise. Abort is checked\n * before and after credential resolution so a cancelled request never\n * misreports as an auth failure.\n */\nexport async function runExtensionCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot,\n\tsignal?: AbortSignal,\n\tonProgress?: CompactionProgressCallback,\n): Promise<CompactionResult | undefined> {\n\tif (signal?.aborted) return undefined;\n\tconst auth = await context.modelRegistry?.getApiKeyAndHeaders(snapshot.model);\n\tif (signal?.aborted) return undefined;\n\t// A provider is authenticated for summarization by either a resolved key or a\n\t// credential request header: `headers`-authenticated providers (models.json and\n\t// extension providers alike) never resolve an apiKey, yet their normal agent\n\t// turns are fully authenticated.\n\tif (!auth?.ok || !(auth.apiKey || hasCredentialHeaders(auth.headers))) {\n\t\tconst detail =\n\t\t\tauth && !auth.ok ? auth.error : `no credentials resolved for provider \"${snapshot.model.provider}\"`;\n\t\tthrow new SummaryGenerationError(\"auth\", `summarization credentials unavailable: ${detail}`);\n\t}\n\tconst requestSnapshot = auth.baseUrl\n\t\t? { ...snapshot, model: { ...snapshot.model, baseUrl: auth.baseUrl } }\n\t\t: snapshot;\n\n\tconst prompt = buildPrompt({\n\t\tvariant: requestSnapshot.promptVariant,\n\t\tpreviousSummary: requestSnapshot.preparation.previousSummary,\n\t\ttaskIntent: resolveInheritedTaskIntent(requestSnapshot.branchEntries ?? []),\n\t\tcustomInstructions: requestSnapshot.customInstructions,\n\t});\n\tconst promptTokens = approxTokens(prompt.user);\n\tlet messages = boundSummarizationInput(\n\t\tpruneToolResults(\n\t\t\t[...requestSnapshot.preparation.messagesToSummarize, ...requestSnapshot.preparation.turnPrefixMessages],\n\t\t\trequestSnapshot.contextWindow,\n\t\t\tSUMMARIZATION_INPUT_BUDGET_RATIO,\n\t\t),\n\t\trequestSnapshot.contextWindow,\n\t\tpromptTokens,\n\t);\n\tconst overflowRetryStartMs = Date.now();\n\tlet overflowAttempts = 0;\n\tconst summarizationToolsOffered = (requestSnapshot.tools?.length ?? 0) > 0;\n\tlet toolUseRetrySpent = false;\n\n\twhile (true) {\n\t\tif (signal?.aborted) return undefined;\n\t\tlet response: Message | undefined;\n\t\tconst currentMessages = messages;\n\t\tconst retryStartedMs = Date.now();\n\t\t// Only the routes that block the user's turn retry here. The speculative\n\t\t// warm-up owns its own bounded retry (`idle-retry.ts`) with idle/breaker\n\t\t// guards re-evaluated between attempts, and a failed warm job must stay\n\t\t// inheritable so the next blocking route degrades on it instead of paying\n\t\t// for a second request.\n\t\tconst retryEligible = snapshot.origin === \"core-route\" || snapshot.origin === \"blocking\";\n\t\ttry {\n\t\t\t// The provider `error` stop is raised INSIDE the retried producer so a\n\t\t\t// transient summarization failure spends the shared retry budget. The\n\t\t\t// surrounding loop keeps overflow shrinking and abort handling, which\n\t\t\t// must never be answered by replaying the same request.\n\t\t\tresponse = await retryTransientCall(\n\t\t\t\tasync () => {\n\t\t\t\t\tconst attempt = await generateSummaryMessage({\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\tforbidToolCalls: toolUseRetrySpent,\n\t\t\t\t\t\tmessages: currentMessages,\n\t\t\t\t\t\tonProgress,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tsnapshot: requestSnapshot,\n\t\t\t\t\t\tauth: {\n\t\t\t\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\t\t\t\theaders: auth.headers,\n\t\t\t\t\t\t\textraBody: auth.extraBody,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tif (\n\t\t\t\t\t\tattempt &&\n\t\t\t\t\t\tisAssistantMessage(attempt) &&\n\t\t\t\t\t\tattempt.stopReason === \"error\" &&\n\t\t\t\t\t\t!isContextOverflow(attempt, snapshot.contextWindow)\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst failureKind = summaryRequestFailureKind(attempt);\n\t\t\t\t\t\tthrow new SummaryRequestError(\n\t\t\t\t\t\t\tattempt.errorMessage || \"Compaction summary request failed\",\n\t\t\t\t\t\t\tfailureKind !== undefined || isRetryableAssistantError(attempt),\n\t\t\t\t\t\t\tfailureKind,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn attempt;\n\t\t\t\t},\n\t\t\t\t(error) =>\n\t\t\t\t\tretryEligible &&\n\t\t\t\t\tallowSummarizationRetry(Date.now() - retryStartedMs) &&\n\t\t\t\t\tisRetryableSummaryAttempt(error),\n\t\t\t\tDEFAULT_SUMMARIZATION_RETRY_POLICY,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) return undefined;\n\t\t\tthrow error;\n\t\t}\n\t\tif (!response) return undefined;\n\n\t\tif (isAssistantMessage(response) && isContextOverflow(response, snapshot.contextWindow)) {\n\t\t\toverflowAttempts++;\n\t\t\tconst elapsedMs = Date.now() - overflowRetryStartMs;\n\t\t\tconst retryMessages = allowOverflowRetry(overflowAttempts, elapsedMs)\n\t\t\t\t? shrinkSummarizationInputForOverflowRetry(messages, snapshot.contextWindow, promptTokens)\n\t\t\t\t: undefined;\n\t\t\tif (!retryMessages) {\n\t\t\t\tthrow new SummarizationOverflowExhaustedError(overflowAttempts, elapsedMs);\n\t\t\t}\n\t\t\tmessages = retryMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (isAssistantMessage(response) && response.stopReason === \"aborted\") {\n\t\t\t// A partial summary from an aborted stream must never be applied.\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (isAssistantMessage(response) && response.stopReason === \"error\") {\n\t\t\t// Surface the real provider failure instead of silently degrading\n\t\t\t// into a generic \"Compaction cancelled\". Preserve the structured\n\t\t\t// truncation class here so downstream recovery never trusts arbitrary\n\t\t\t// thrown error text as authorization for destructive context reduction.\n\t\t\tconst failureKind = summaryRequestFailureKind(response);\n\t\t\tthrow new SummaryRequestError(\n\t\t\t\tresponse.errorMessage || \"Compaction summary request failed\",\n\t\t\t\tfailureKind !== undefined || isRetryableAssistantError(response),\n\t\t\t\tfailureKind,\n\t\t\t);\n\t\t}\n\n\t\tconst summary = getSummaryText(response);\n\t\tif (!summary) {\n\t\t\tconst stopReason = isAssistantMessage(response) ? response.stopReason : \"unknown\";\n\t\t\t// A summarizer can hijack the forwarded agent tools and answer with a\n\t\t\t// bare tool call (observed on openai-codex gpt-5.6-sol, 2026-08-31),\n\t\t\t// which used to surface as a terminal empty-summary failure. Spend one\n\t\t\t// retry with tool calling forbidden; the tools stay in the request\n\t\t\t// because Anthropic rejects tool_use history without the tools param.\n\t\t\tif (stopReason === \"toolUse\" && summarizationToolsOffered && !toolUseRetrySpent) {\n\t\t\t\ttoolUseRetrySpent = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new SummaryGenerationError(\n\t\t\t\t\"empty-summary\",\n\t\t\t\t`summarization response contained no text (stopReason: ${stopReason})`,\n\t\t\t);\n\t\t}\n\n\t\t// Informational only: the core rejects an applied compaction that would\n\t\t// still overflow (_wouldCompactionOverflow). Rejecting here based on the\n\t\t// size of the *discarded* input made large sessions uncompactable.\n\t\tconst tokenEstimate = estimateContextTokens(convertToLlm(messages)).tokens + approxTokens(summary);\n\t\tconst parsedSummary = extractTaskIntent(summary);\n\t\tconst taskIntent = parsedSummary.taskIntent ?? resolveInheritedTaskIntent(snapshot.branchEntries ?? []);\n\n\t\treturn {\n\t\t\tsummary: parsedSummary.summaryText,\n\t\t\tfirstKeptEntryId: snapshot.preparation.firstKeptEntryId,\n\t\t\ttokensBefore: snapshot.preparation.tokensBefore,\n\t\t\tdetails: {\n\t\t\t\tschema: SUMMARY_SCHEMA,\n\t\t\t\tpromptVariant: snapshot.promptVariant,\n\t\t\t\ttokenEstimate,\n\t\t\t\tstructuralYield: computeStructuralYield({\n\t\t\t\t\tpreviousSummary: snapshot.preparation.previousSummary ?? \"\",\n\t\t\t\t\tmessagesToSummarize: snapshot.preparation.messagesToSummarize,\n\t\t\t\t\tturnPrefixMessages: snapshot.preparation.turnPrefixMessages,\n\t\t\t\t\tsummary: parsedSummary.summaryText,\n\t\t\t\t\ttokensBefore: snapshot.preparation.tokensBefore,\n\t\t\t\t}),\n\t\t\t\t...(snapshot.origin ? { origin: snapshot.origin } : {}),\n\t\t\t\t...(taskIntent ? { taskIntent } : {}),\n\t\t\t},\n\t\t};\n\t}\n}\n\nexport async function applyGeneratedCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot | undefined,\n\tgetCurrentGeneration: () => number,\n\tcompaction: CompactionResult | undefined,\n\tsignal?: AbortSignal,\n): Promise<SpeculativeCompactionResult> {\n\tconst provider = context.model?.provider;\n\tif ((provider === \"cursor\" || provider === \"cursor-cli-oauth\") && context.isIdle && !context.isIdle()) {\n\t\treturn { applied: false, reason: \"rejected\" };\n\t}\n\tif (!snapshot || !compaction) return { applied: false, reason: \"unavailable\" };\n\n\tif (snapshot.generation !== getCurrentGeneration()) {\n\t\treturn { applied: false, reason: \"stale\" };\n\t}\n\n\tconst revisionUnchanged = snapshot.expectedRevision === context.getMessageRevision();\n\tconst warmAnchor = createWarmAnchorSnapshot(snapshot.preparation.firstKeptEntryId, snapshot.branchEntries ?? []);\n\tif (\n\t\t!revisionUnchanged &&\n\t\t(!warmAnchor || !isWarmSummaryAnchorValid(warmAnchor, context.sessionManager.getBranch()))\n\t) {\n\t\treturn { applied: false, reason: \"stale\" };\n\t}\n\n\treturn await context.applyCompaction(compaction, {\n\t\treason: \"extension\",\n\t\t...(revisionUnchanged || !warmAnchor\n\t\t\t? { expectedRevision: snapshot.expectedRevision }\n\t\t\t: { expectedWarmAnchor: warmAnchor }),\n\t\tsignal,\n\t});\n}\n\nexport async function applySpeculativeCompaction(\n\tcontext: SpeculativeCompactionContext,\n\tsnapshot: SpeculativeCompactionSnapshot | undefined,\n\tgetCurrentGeneration: () => number,\n\tgenerate: () => Promise<CompactionResult | undefined>,\n): Promise<SpeculativeCompactionResult> {\n\tif (!snapshot) return { applied: false, reason: \"unavailable\" };\n\n\tconst compaction = await generate();\n\treturn await applyGeneratedCompaction(context, snapshot, getCurrentGeneration, compaction);\n}\n"]}
@@ -0,0 +1,5 @@
1
+ import type { HookTrustState } from "./types.ts";
2
+ export declare function emptyHookTrustState(): HookTrustState;
3
+ export declare function parseHookTrustStateJson(input: string | undefined): HookTrustState | undefined;
4
+ export declare function readHookTrustStateJson(input: string | undefined): HookTrustState;
5
+ //# sourceMappingURL=trust-state-json.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trust-state-json.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/trust-state-json.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAmC,cAAc,EAAE,MAAM,YAAY,CAAC;AAIlF,wBAAgB,mBAAmB,IAAI,cAAc,CAEpD;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,cAAc,GAAG,SAAS,CAY7F;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,cAAc,CAEhF"}
@@ -0,0 +1,76 @@
1
+ const HOOK_STATE_VERSION = 1;
2
+ export function emptyHookTrustState() {
3
+ return { version: HOOK_STATE_VERSION, hooks: {} };
4
+ }
5
+ export function parseHookTrustStateJson(input) {
6
+ if (input === undefined || input.trim() === "") {
7
+ return undefined;
8
+ }
9
+ try {
10
+ return parseHookTrustState(JSON.parse(input));
11
+ }
12
+ catch (error) {
13
+ if (error instanceof SyntaxError) {
14
+ return undefined;
15
+ }
16
+ throw error;
17
+ }
18
+ }
19
+ export function readHookTrustStateJson(input) {
20
+ return parseHookTrustStateJson(input) ?? emptyHookTrustState();
21
+ }
22
+ function parseHookTrustState(input) {
23
+ if (!isRecord(input) || input.version !== HOOK_STATE_VERSION || !isRecord(input.hooks)) {
24
+ return undefined;
25
+ }
26
+ const hooks = {};
27
+ for (const [id, entry] of Object.entries(input.hooks)) {
28
+ const parsed = parseHookTrustEntry(entry);
29
+ if (parsed !== undefined) {
30
+ hooks[id] = parsed;
31
+ }
32
+ }
33
+ return { version: HOOK_STATE_VERSION, hooks };
34
+ }
35
+ function parseHookTrustEntry(input) {
36
+ if (!isRecord(input)) {
37
+ return undefined;
38
+ }
39
+ const enabled = input.enabled;
40
+ const trustedHash = input.trustedHash;
41
+ const scope = input.scope;
42
+ const sourcePath = input.sourcePath;
43
+ const matcher = input.matcher;
44
+ const commandPreview = input.commandPreview;
45
+ const updatedAt = input.updatedAt;
46
+ if (typeof enabled !== "boolean" ||
47
+ (trustedHash !== undefined && typeof trustedHash !== "string") ||
48
+ !isHookSourceScope(scope) ||
49
+ typeof sourcePath !== "string" ||
50
+ (matcher !== undefined && typeof matcher !== "string") ||
51
+ typeof commandPreview !== "string" ||
52
+ typeof updatedAt !== "string") {
53
+ return undefined;
54
+ }
55
+ return {
56
+ enabled,
57
+ ...(trustedHash === undefined ? {} : { trustedHash }),
58
+ scope,
59
+ sourcePath,
60
+ ...(matcher === undefined ? {} : { matcher }),
61
+ commandPreview,
62
+ updatedAt,
63
+ };
64
+ }
65
+ function isRecord(value) {
66
+ return typeof value === "object" && value !== null && !Array.isArray(value);
67
+ }
68
+ function isHookSourceScope(value) {
69
+ return (value === "global" ||
70
+ value === "project" ||
71
+ value === "plugin" ||
72
+ value === "runtime" ||
73
+ value === "cli" ||
74
+ value === "managed");
75
+ }
76
+ //# sourceMappingURL=trust-state-json.js.map
@@ -0,0 +1 @@
1
+ {"version":3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AS;KACT,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc;IACxC,OAAO,CACN,KAAK,KAAK,QAAQ;QAClB,KAAK,KAAK,SAAS;QACnB,KAAK,KAAK,QAAQ;QAClB,KAAK,KAAK,SAAS;QACnB,KAAK,KAAK,KAAK;QACf,KAAK,KAAK,SAAS,CACnB,CAAC;AACH,CAAC","sourcesContent":["import type { HookSourceScope, HookTrustEntry, HookTrustState } from \"./types.ts\";\n\nconst HOOK_STATE_VERSION = 1;\n\nexport function emptyHookTrustState(): HookTrustState {\n\treturn { version: HOOK_STATE_VERSION, hooks: {} };\n}\n\nexport function parseHookTrustStateJson(input: string | undefined): HookTrustState | undefined {\n\tif (input === undefined || input.trim() === \"\") {\n\t\treturn undefined;\n\t}\n\ttry {\n\t\treturn parseHookTrustState(JSON.parse(input));\n\t} catch (error) {\n\t\tif (error instanceof SyntaxError) {\n\t\t\treturn undefined;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nexport function readHookTrustStateJson(input: string | undefined): HookTrustState {\n\treturn parseHookTrustStateJson(input) ?? emptyHookTrustState();\n}\n\nfunction parseHookTrustState(input: unknown): HookTrustState | undefined {\n\tif (!isRecord(input) || input.version !== HOOK_STATE_VERSION || !isRecord(input.hooks)) {\n\t\treturn undefined;\n\t}\n\n\tconst hooks: Record<string, HookTrustEntry> = {};\n\tfor (const [id, entry] of Object.entries(input.hooks)) {\n\t\tconst parsed = parseHookTrustEntry(entry);\n\t\tif (parsed !== undefined) {\n\t\t\thooks[id] = parsed;\n\t\t}\n\t}\n\treturn { version: HOOK_STATE_VERSION, hooks };\n}\n\nfunction parseHookTrustEntry(input: unknown): HookTrustEntry | undefined {\n\tif (!isRecord(input)) {\n\t\treturn undefined;\n\t}\n\tconst enabled = input.enabled;\n\tconst trustedHash = input.trustedHash;\n\tconst scope = input.scope;\n\tconst sourcePath = input.sourcePath;\n\tconst matcher = input.matcher;\n\tconst commandPreview = input.commandPreview;\n\tconst updatedAt = input.updatedAt;\n\tif (\n\t\ttypeof enabled !== \"boolean\" ||\n\t\t(trustedHash !== undefined && typeof trustedHash !== \"string\") ||\n\t\t!isHookSourceScope(scope) ||\n\t\ttypeof sourcePath !== \"string\" ||\n\t\t(matcher !== undefined && typeof matcher !== \"string\") ||\n\t\ttypeof commandPreview !== \"string\" ||\n\t\ttypeof updatedAt !== \"string\"\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tenabled,\n\t\t...(trustedHash === undefined ? {} : { trustedHash }),\n\t\tscope,\n\t\tsourcePath,\n\t\t...(matcher === undefined ? {} : { matcher }),\n\t\tcommandPreview,\n\t\tupdatedAt,\n\t};\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isHookSourceScope(value: unknown): value is HookSourceScope {\n\treturn (\n\t\tvalue === \"global\" ||\n\t\tvalue === \"project\" ||\n\t\tvalue === \"plugin\" ||\n\t\tvalue === \"runtime\" ||\n\t\tvalue === \"cli\" ||\n\t\tvalue === \"managed\"\n\t);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { type HookTrustStorageScope } from "./trust.ts";
1
+ import type { HookTrustStorageScope } from "./trust.ts";
2
2
  import type { HookTrustState } from "./types.ts";
3
3
  export interface HookStateStorage {
4
4
  read(scope: HookTrustStorageScope): HookTrustState;
@@ -8,6 +8,12 @@ export type FileHookStateStorageOptions = {
8
8
  readonly agentDir?: string;
9
9
  readonly cwd: string;
10
10
  };
11
+ /**
12
+ * Internal same-account application state at `<agentDir>/hooks-state.json` and
13
+ * `<cwd>/.senpi/hooks-state.json`. POSIX files retain their numeric mode and new
14
+ * files use 0600; reassigned ownership, named ACLs, and custom DACLs are outside
15
+ * this storage contract.
16
+ */
11
17
  export declare class FileHookStateStorage implements HookStateStorage {
12
18
  private readonly globalStatePath;
13
19
  private readonly projectStatePath;
@@ -1 +1 @@
1
- {"version":3,"file":"trust-storage.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/trust-storage.ts"],"names":[],"mappings":"AAIA,OAAO,EAAuB,KAAK,qBAAqB,EAA0B,MAAM,YAAY,CAAC;AACrG,OAAO,KAAK,EAAkB,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjE,MAAM,WAAW,gBAAgB;IAChC,IAAI,CAAC,KAAK,EAAE,qBAAqB,GAAG,cAAc,CAAC;IACnD,MAAM,CAAC,KAAK,EAAE,qBAAqB,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,cAAc,GAAG,cAAc,CAAC;CAC3G;AAED,MAAM,MAAM,2BAA2B,GAAG;IACzC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,qBAAa,oBAAqB,YAAW,gBAAgB;IAC5D,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IACzC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAS;gBAE9B,OAAO,EAAE,2BAA2B;IAMhD,IAAI,CAAC,KAAK,EAAE,qBAAqB,GAAG,cAAc;IAMlD,MAAM,CAAC,KAAK,EAAE,qBAAqB,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,cAAc,GAAG,cAAc;CAQ1G;AAED,qBAAa,wBAAyB,YAAW,gBAAgB;IAChE,OAAO,CAAC,WAAW,CAAyC;IAC5D,OAAO,CAAC,YAAY,CAAyC;IAE7D,IAAI,CAAC,KAAK,EAAE,qBAAqB,GAAG,cAAc;IAIlD,MAAM,CAAC,KAAK,EAAE,qBAAqB,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,cAAc,GAAG,cAAc;CAS1G"}
1
+ {"version":3,"file":"trust-storage.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/trust-storage.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAExD,OAAO,KAAK,EAAkB,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjE,MAAM,WAAW,gBAAgB;IAChC,IAAI,CAAC,KAAK,EAAE,qBAAqB,GAAG,cAAc,CAAC;IACnD,MAAM,CAAC,KAAK,EAAE,qBAAqB,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,cAAc,GAAG,cAAc,CAAC;CAC3G;AAED,MAAM,MAAM,2BAA2B,GAAG;IACzC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;;;;GAKG;AACH,qBAAa,oBAAqB,YAAW,gBAAgB;IAC5D,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IACzC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAS;gBAE9B,OAAO,EAAE,2BAA2B;IAMhD,IAAI,CAAC,KAAK,EAAE,qBAAqB,GAAG,cAAc;IAqBlD,MAAM,CAAC,KAAK,EAAE,qBAAqB,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,cAAc,GAAG,cAAc;CAyB1G;AAED,qBAAa,wBAAyB,YAAW,gBAAgB;IAChE,OAAO,CAAC,WAAW,CAAyC;IAC5D,OAAO,CAAC,YAAY,CAAyC;IAE7D,IAAI,CAAC,KAAK,EAAE,qBAAqB,GAAG,cAAc;IAIlD,MAAM,CAAC,KAAK,EAAE,qBAAqB,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,cAAc,GAAG,cAAc;CAS1G"}
@@ -1,8 +1,15 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { randomUUID } from "node:crypto";
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
3
  import { dirname, join } from "node:path";
3
4
  import lockfile from "proper-lockfile";
4
5
  import { CONFIG_DIR_NAME, getAgentDir } from "../../../../config.js";
5
- import { emptyHookTrustState, readHookTrustStateJson } from "./trust.js";
6
+ import { emptyHookTrustState, parseHookTrustStateJson, readHookTrustStateJson } from "./trust-state-json.js";
7
+ /**
8
+ * Internal same-account application state at `<agentDir>/hooks-state.json` and
9
+ * `<cwd>/.senpi/hooks-state.json`. POSIX files retain their numeric mode and new
10
+ * files use 0600; reassigned ownership, named ACLs, and custom DACLs are outside
11
+ * this storage contract.
12
+ */
6
13
  export class FileHookStateStorage {
7
14
  constructor(options) {
8
15
  const agentDir = options.agentDir ?? getAgentDir();
@@ -10,13 +17,44 @@ export class FileHookStateStorage {
10
17
  this.projectStatePath = join(options.cwd, CONFIG_DIR_NAME, "hooks-state.json");
11
18
  }
12
19
  read(scope) {
13
- return withHookStateFileLock(statePathForScope(scope, this.globalStatePath, this.projectStatePath), (path) => readHookTrustStateJson(existsSync(path) ? readFileSync(path, "utf-8") : undefined));
20
+ const path = statePathForScope(scope, this.globalStatePath, this.projectStatePath);
21
+ const snapshot = parseHookTrustStateJson(existsSync(path) ? readFileSync(path, "utf-8") : undefined);
22
+ if (snapshot !== undefined) {
23
+ return snapshot;
24
+ }
25
+ let release;
26
+ try {
27
+ release = acquireHookStateLockSync(path);
28
+ }
29
+ catch (error) {
30
+ if (errorCode(error) === "ELOCKED") {
31
+ return emptyHookTrustState();
32
+ }
33
+ throw error;
34
+ }
35
+ return runWithHookStateLockRelease(release, () => readHookTrustStateJson(existsSync(path) ? readFileSync(path, "utf-8") : undefined));
14
36
  }
15
37
  update(scope, updater) {
16
38
  return withHookStateFileLock(statePathForScope(scope, this.globalStatePath, this.projectStatePath), (path) => {
17
- const current = readHookTrustStateJson(existsSync(path) ? readFileSync(path, "utf-8") : undefined);
39
+ const stateExists = existsSync(path);
40
+ const current = readHookTrustStateJson(stateExists ? readFileSync(path, "utf-8") : undefined);
41
+ const mode = stateExists ? statSync(path).mode & 0o777 : 0o600;
18
42
  const next = updater(current);
19
- writeFileSync(path, serializeHookTrustState(next), "utf-8");
43
+ const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
44
+ try {
45
+ writeFileSync(tempPath, serializeHookTrustState(next), { encoding: "utf-8", mode });
46
+ chmodSync(tempPath, mode);
47
+ renameSync(tempPath, path);
48
+ }
49
+ catch (publicationError) {
50
+ try {
51
+ rmSync(tempPath, { force: true });
52
+ }
53
+ catch (cleanupError) {
54
+ throw new AggregateError([publicationError, cleanupError], "Failed to publish and clean up hook trust state snapshot");
55
+ }
56
+ throw publicationError;
57
+ }
20
58
  return next;
21
59
  });
22
60
  }
@@ -92,11 +130,25 @@ function isRecord(value) {
92
130
  }
93
131
  function withHookStateFileLock(path, fn) {
94
132
  const release = acquireHookStateLockSync(path);
133
+ return runWithHookStateLockRelease(release, () => fn(path));
134
+ }
135
+ function runWithHookStateLockRelease(release, operation) {
136
+ let result;
95
137
  try {
96
- return fn(path);
138
+ result = operation();
97
139
  }
98
- finally {
99
- release();
140
+ catch (operationError) {
141
+ try {
142
+ release();
143
+ }
144
+ catch (releaseError) {
145
+ throw new AggregateError(operationError instanceof AggregateError
146
+ ? [...operationError.errors, releaseError]
147
+ : [operationError, releaseError], "Hook state operation and lock release both failed");
148
+ }
149
+ throw operationError;
100
150
  }
151
+ release();
152
+ return result;
101
153
  }
102
154
  //# sourceMappingURL=trust-storage.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"trust-storage.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/trust-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,I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AAc;IAChC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACtB,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IACxB,OAAO,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AACpD,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,qBAAqB,CAAI,IAAY,EAAE,EAAuB;IACtE,MAAM,OAAO,GAAG,wBAAwB,CAAC,IAAI,CAAC,CAAC;IAC/C,IAAI,CAAC;QACJ,OAAO,EAAE,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;YAAS,CAAC;QACV,OAAO,EAAE,CAAC;IACX,CAAC;AACF,CAAC","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../../../../config.ts\";\nimport { emptyHookTrustState, type HookTrustStorageScope, readHookTrustStateJson } from \"./trust.ts\";\nimport type { HookTrustEntry, HookTrustState } from \"./types.ts\";\n\nexport interface HookStateStorage {\n\tread(scope: HookTrustStorageScope): HookTrustState;\n\tupdate(scope: HookTrustStorageScope, updater: (current: HookTrustState) => HookTrustState): HookTrustState;\n}\n\nexport type FileHookStateStorageOptions = {\n\treadonly agentDir?: string;\n\treadonly cwd: string;\n};\n\nexport class FileHookStateStorage implements HookStateStorage {\n\tprivate readonly globalStatePath: string;\n\tprivate readonly projectStatePath: string;\n\n\tconstructor(options: FileHookStateStorageOptions) {\n\t\tconst agentDir = options.agentDir ?? getAgentDir();\n\t\tthis.globalStatePath = join(agentDir, \"hooks-state.json\");\n\t\tthis.projectStatePath = join(options.cwd, CONFIG_DIR_NAME, \"hooks-state.json\");\n\t}\n\n\tread(scope: HookTrustStorageScope): HookTrustState {\n\t\treturn withHookStateFileLock(statePathForScope(scope, this.globalStatePath, this.projectStatePath), (path) =>\n\t\t\treadHookTrustStateJson(existsSync(path) ? readFileSync(path, \"utf-8\") : undefined),\n\t\t);\n\t}\n\n\tupdate(scope: HookTrustStorageScope, updater: (current: HookTrustState) => HookTrustState): HookTrustState {\n\t\treturn withHookStateFileLock(statePathForScope(scope, this.globalStatePath, this.projectStatePath), (path) => {\n\t\t\tconst current = readHookTrustStateJson(existsSync(path) ? readFileSync(path, \"utf-8\") : undefined);\n\t\t\tconst next = updater(current);\n\t\t\twriteFileSync(path, serializeHookTrustState(next), \"utf-8\");\n\t\t\treturn next;\n\t\t});\n\t}\n}\n\nexport class InMemoryHookStateStorage implements HookStateStorage {\n\tprivate globalState: HookTrustState = emptyHookTrustState();\n\tprivate projectState: HookTrustState = emptyHookTrustState();\n\n\tread(scope: HookTrustStorageScope): HookTrustState {\n\t\treturn scope === \"global\" ? this.globalState : this.projectState;\n\t}\n\n\tupdate(scope: HookTrustStorageScope, updater: (current: HookTrustState) => HookTrustState): HookTrustState {\n\t\tconst next = updater(this.read(scope));\n\t\tif (scope === \"global\") {\n\t\t\tthis.globalState = next;\n\t\t} else {\n\t\t\tthis.projectState = next;\n\t\t}\n\t\treturn next;\n\t}\n}\n\nfunction statePathForScope(scope: HookTrustStorageScope, globalStatePath: string, projectStatePath: string): string {\n\treturn scope === \"global\" ? globalStatePath : projectStatePath;\n}\n\nfunction serializeHookTrustState(state: HookTrustState): string {\n\tconst sortedHooks: Record<string, HookTrustEntry> = {};\n\tfor (const key of Object.keys(state.hooks).sort()) {\n\t\tconst entry = state.hooks[key];\n\t\tif (entry !== undefined) {\n\t\t\tsortedHooks[key] = entry;\n\t\t}\n\t}\n\treturn `${JSON.stringify({ version: 1, hooks: sortedHooks }, null, 2)}\\n`;\n}\n\nfunction acquireHookStateLockSync(path: string): () => void {\n\tconst stateDir = dirname(path);\n\tmkdirSync(stateDir, { recursive: true });\n\tconst maxAttempts = 10;\n\tconst delayMs = 20;\n\tlet lastError: unknown;\n\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\ttry {\n\t\t\treturn lockfile.lockSync(stateDir, { realpath: false, lockfilePath: `${path}.lock` });\n\t\t} catch (error) {\n\t\t\tconst code = errorCode(error);\n\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tlastError = error;\n\t\t\tconst start = Date.now();\n\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\tDate.now();\n\t\t\t}\n\t\t}\n\t}\n\n\tif (lastError instanceof Error) {\n\t\tthrow lastError;\n\t}\n\tthrow new Error(\"Failed to acquire hook state lock\");\n}\n\nfunction errorCode(error: unknown): string | undefined {\n\tif (!isRecord(error)) {\n\t\treturn undefined;\n\t}\n\tconst code = error.code;\n\treturn typeof code === \"string\" ? code : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction withHookStateFileLock<T>(path: string, fn: (path: string) => T): T {\n\tconst release = acquireHookStateLockSync(path);\n\ttry {\n\t\treturn fn(path);\n\t} finally {\n\t\trelease();\n\t}\n}\n"]}
1
+ {"version":3,"file":"trust-storage.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/trust-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACtH,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,QA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odSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../../../../config.ts\";\nimport type { HookTrustStorageScope } from \"./trust.ts\";\nimport { emptyHookTrustState, parseHookTrustStateJson, readHookTrustStateJson } from \"./trust-state-json.ts\";\nimport type { HookTrustEntry, HookTrustState } from \"./types.ts\";\n\nexport interface HookStateStorage {\n\tread(scope: HookTrustStorageScope): HookTrustState;\n\tupdate(scope: HookTrustStorageScope, updater: (current: HookTrustState) => HookTrustState): HookTrustState;\n}\n\nexport type FileHookStateStorageOptions = {\n\treadonly agentDir?: string;\n\treadonly cwd: string;\n};\n\n/**\n * Internal same-account application state at `<agentDir>/hooks-state.json` and\n * `<cwd>/.senpi/hooks-state.json`. POSIX files retain their numeric mode and new\n * files use 0600; reassigned ownership, named ACLs, and custom DACLs are outside\n * this storage contract.\n */\nexport class FileHookStateStorage implements HookStateStorage {\n\tprivate readonly globalStatePath: string;\n\tprivate readonly projectStatePath: string;\n\n\tconstructor(options: FileHookStateStorageOptions) {\n\t\tconst agentDir = options.agentDir ?? getAgentDir();\n\t\tthis.globalStatePath = join(agentDir, \"hooks-state.json\");\n\t\tthis.projectStatePath = join(options.cwd, CONFIG_DIR_NAME, \"hooks-state.json\");\n\t}\n\n\tread(scope: HookTrustStorageScope): HookTrustState {\n\t\tconst path = statePathForScope(scope, this.globalStatePath, this.projectStatePath);\n\t\tconst snapshot = parseHookTrustStateJson(existsSync(path) ? readFileSync(path, \"utf-8\") : undefined);\n\t\tif (snapshot !== undefined) {\n\t\t\treturn snapshot;\n\t\t}\n\n\t\tlet release: () => void;\n\t\ttry {\n\t\t\trelease = acquireHookStateLockSync(path);\n\t\t} catch (error) {\n\t\t\tif (errorCode(error) === \"ELOCKED\") {\n\t\t\t\treturn emptyHookTrustState();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\treturn runWithHookStateLockRelease(release, () =>\n\t\t\treadHookTrustStateJson(existsSync(path) ? readFileSync(path, \"utf-8\") : undefined),\n\t\t);\n\t}\n\n\tupdate(scope: HookTrustStorageScope, updater: (current: HookTrustState) => HookTrustState): HookTrustState {\n\t\treturn withHookStateFileLock(statePathForScope(scope, this.globalStatePath, this.projectStatePath), (path) => {\n\t\t\tconst stateExists = existsSync(path);\n\t\t\tconst current = readHookTrustStateJson(stateExists ? readFileSync(path, \"utf-8\") : undefined);\n\t\t\tconst mode = stateExists ? statSync(path).mode & 0o777 : 0o600;\n\t\t\tconst next = updater(current);\n\t\t\tconst tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;\n\t\t\ttry {\n\t\t\t\twriteFileSync(tempPath, serializeHookTrustState(next), { encoding: \"utf-8\", mode });\n\t\t\t\tchmodSync(tempPath, mode);\n\t\t\t\trenameSync(tempPath, path);\n\t\t\t} catch (publicationError) {\n\t\t\t\ttry {\n\t\t\t\t\trmSync(tempPath, { force: true });\n\t\t\t\t} catch (cleanupError) {\n\t\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t\t[publicationError, cleanupError],\n\t\t\t\t\t\t\"Failed to publish and clean up hook trust state snapshot\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow publicationError;\n\t\t\t}\n\t\t\treturn next;\n\t\t});\n\t}\n}\n\nexport class InMemoryHookStateStorage implements HookStateStorage {\n\tprivate globalState: HookTrustState = emptyHookTrustState();\n\tprivate projectState: HookTrustState = emptyHookTrustState();\n\n\tread(scope: HookTrustStorageScope): HookTrustState {\n\t\treturn scope === \"global\" ? this.globalState : this.projectState;\n\t}\n\n\tupdate(scope: HookTrustStorageScope, updater: (current: HookTrustState) => HookTrustState): HookTrustState {\n\t\tconst next = updater(this.read(scope));\n\t\tif (scope === \"global\") {\n\t\t\tthis.globalState = next;\n\t\t} else {\n\t\t\tthis.projectState = next;\n\t\t}\n\t\treturn next;\n\t}\n}\n\nfunction statePathForScope(scope: HookTrustStorageScope, globalStatePath: string, projectStatePath: string): string {\n\treturn scope === \"global\" ? globalStatePath : projectStatePath;\n}\n\nfunction serializeHookTrustState(state: HookTrustState): string {\n\tconst sortedHooks: Record<string, HookTrustEntry> = {};\n\tfor (const key of Object.keys(state.hooks).sort()) {\n\t\tconst entry = state.hooks[key];\n\t\tif (entry !== undefined) {\n\t\t\tsortedHooks[key] = entry;\n\t\t}\n\t}\n\treturn `${JSON.stringify({ version: 1, hooks: sortedHooks }, null, 2)}\\n`;\n}\n\nfunction acquireHookStateLockSync(path: string): () => void {\n\tconst stateDir = dirname(path);\n\tmkdirSync(stateDir, { recursive: true });\n\tconst maxAttempts = 10;\n\tconst delayMs = 20;\n\tlet lastError: unknown;\n\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\ttry {\n\t\t\treturn lockfile.lockSync(stateDir, { realpath: false, lockfilePath: `${path}.lock` });\n\t\t} catch (error) {\n\t\t\tconst code = errorCode(error);\n\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tlastError = error;\n\t\t\tconst start = Date.now();\n\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\tDate.now();\n\t\t\t}\n\t\t}\n\t}\n\n\tif (lastError instanceof Error) {\n\t\tthrow lastError;\n\t}\n\tthrow new Error(\"Failed to acquire hook state lock\");\n}\n\nfunction errorCode(error: unknown): string | undefined {\n\tif (!isRecord(error)) {\n\t\treturn undefined;\n\t}\n\tconst code = error.code;\n\treturn typeof code === \"string\" ? code : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction withHookStateFileLock<T>(path: string, fn: (path: string) => T): T {\n\tconst release = acquireHookStateLockSync(path);\n\treturn runWithHookStateLockRelease(release, () => fn(path));\n}\n\nfunction runWithHookStateLockRelease<T>(release: () => void, operation: () => T): T {\n\tlet result: T;\n\ttry {\n\t\tresult = operation();\n\t} catch (operationError) {\n\t\ttry {\n\t\t\trelease();\n\t\t} catch (releaseError) {\n\t\t\tthrow new AggregateError(\n\t\t\t\toperationError instanceof AggregateError\n\t\t\t\t\t? [...operationError.errors, releaseError]\n\t\t\t\t\t: [operationError, releaseError],\n\t\t\t\t\"Hook state operation and lock release both failed\",\n\t\t\t);\n\t\t}\n\t\tthrow operationError;\n\t}\n\trelease();\n\treturn result;\n}\n"]}
@@ -19,7 +19,7 @@ export type HookTrustRecord = {
19
19
  readonly commandPreview: string;
20
20
  readonly entry?: HookTrustEntry;
21
21
  };
22
- export declare function emptyHookTrustState(): HookTrustState;
22
+ export { emptyHookTrustState, readHookTrustStateJson } from "./trust-state-json.ts";
23
23
  export declare function hookTrustId(handler: ExecutableHookHandler): string;
24
24
  export declare function buildHookTrustRecord(handler: ExecutableHookHandler, options?: HookTrustOptions): HookTrustRecord;
25
25
  export declare function createHookTrustEntry(handler: ExecutableHookHandler, options?: HookTrustOptions & {
@@ -29,6 +29,5 @@ export declare function hashCommandHook(handler: ExecutableHookHandler, options?
29
29
  export declare function isCommandHookTrusted(handler: ExecutableHookHandler, state: HookTrustState, options?: HookTrustOptions): boolean;
30
30
  export declare function listHookTrustRecords(handlers: readonly ExecutableHookHandler[], state: HookTrustState, options?: HookTrustOptions): readonly HookTrustRecord[];
31
31
  export declare function filterExecutableTrustedHooks(handlers: readonly ExecutableHookHandler[], state: HookTrustState, options?: HookTrustOptions): readonly ExecutableHookHandler[];
32
- export declare function readHookTrustStateJson(input: string | undefined): HookTrustState;
33
32
  export declare function hookTrustStorageScope(handler: ExecutableHookHandler, options: HookTrustStorageOptions): HookTrustStorageScope | undefined;
34
33
  //# sourceMappingURL=trust.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"trust.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/trust.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACX,qBAAqB,EAErB,eAAe,EAC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Ac,EACrB,OAAO,GAAE,gBAAqB,GAC5B,SAAS,qBAAqB,EAAE,CAElC;AAED,wBAAgB,qBAAqB,CACpC,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE,uBAAuB,GAC9B,qBAAqB,GAAG,SAAS,CAKnC"}
@@ -1,9 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { DEFAULT_HOOK_TIMEOUT_SECONDS, isValidHookTimeoutSeconds } from "./safety.js";
3
- const HOOK_STATE_VERSION = 1;
4
- export function emptyHookTrustState() {
5
- return { version: HOOK_STATE_VERSION, hooks: {} };
6
- }
3
+ export { emptyHookTrustState, readHookTrustStateJson } from "./trust-state-json.js";
7
4
  export function hookTrustId(handler) {
8
5
  return `hk_${sourceKeyHash(handler.source)}_${handler.event}_${handler.groupIndex}_${handler.handlerIndex}`;
9
6
  }
@@ -64,20 +61,6 @@ export function listHookTrustRecords(handlers, state, options = {}) {
64
61
  export function filterExecutableTrustedHooks(handlers, state, options = {}) {
65
62
  return handlers.filter((handler) => buildStatefulHookTrustRecord(handler, state, options).executable);
66
63
  }
67
- export function readHookTrustStateJson(input) {
68
- if (input === undefined || input.trim() === "") {
69
- return emptyHookTrustState();
70
- }
71
- try {
72
- return parseHookTrustState(JSON.parse(input));
73
- }
74
- catch (error) {
75
- if (error instanceof Error) {
76
- return emptyHookTrustState();
77
- }
78
- return emptyHookTrustState();
79
- }
80
- }
81
64
  export function hookTrustStorageScope(handler, options) {
82
65
  if (handler.source.scope === "project") {
83
66
  return options.projectTrusted ? "project" : undefined;
@@ -97,49 +80,6 @@ function buildStatefulHookTrustRecord(handler, state, options) {
97
80
  ...(entry === undefined ? {} : { entry }),
98
81
  };
99
82
  }
100
- function parseHookTrustState(input) {
101
- if (!isRecord(input) || input.version !== HOOK_STATE_VERSION || !isRecord(input.hooks)) {
102
- return emptyHookTrustState();
103
- }
104
- const hooks = {};
105
- for (const [id, entry] of Object.entries(input.hooks)) {
106
- const parsed = parseHookTrustEntry(entry);
107
- if (parsed !== undefined) {
108
- hooks[id] = parsed;
109
- }
110
- }
111
- return { version: HOOK_STATE_VERSION, hooks };
112
- }
113
- function parseHookTrustEntry(input) {
114
- if (!isRecord(input)) {
115
- return undefined;
116
- }
117
- const enabled = input.enabled;
118
- const trustedHash = input.trustedHash;
119
- const scope = input.scope;
120
- const sourcePath = input.sourcePath;
121
- const matcher = input.matcher;
122
- const commandPreview = input.commandPreview;
123
- const updatedAt = input.updatedAt;
124
- if (typeof enabled !== "boolean" ||
125
- (trustedHash !== undefined && typeof trustedHash !== "string") ||
126
- !isHookSourceScope(scope) ||
127
- typeof sourcePath !== "string" ||
128
- (matcher !== undefined && typeof matcher !== "string") ||
129
- typeof commandPreview !== "string" ||
130
- typeof updatedAt !== "string") {
131
- return undefined;
132
- }
133
- return {
134
- enabled,
135
- ...(trustedHash === undefined ? {} : { trustedHash }),
136
- scope,
137
- sourcePath,
138
- ...(matcher === undefined ? {} : { matcher }),
139
- commandPreview,
140
- updatedAt,
141
- };
142
- }
143
83
  function selectedCommand(handler, platform) {
144
84
  if (platform === "win32" && handler.config.commandWindows !== undefined) {
145
85
  return handler.config.commandWindows;
@@ -177,18 +117,7 @@ function canonicalJson(value) {
177
117
  }
178
118
  return result;
179
119
  }
180
- function isRecord(value) {
181
- return typeof value === "object" && value !== null && !Array.isArray(value);
182
- }
183
120
  function isJsonRecord(value) {
184
121
  return typeof value === "object" && value !== null && !Array.isArray(value);
185
122
  }
186
- function isHookSourceScope(value) {
187
- return (value === "global" ||
188
- value === "project" ||
189
- value === "plugin" ||
190
- value === "runtime" ||
191
- value === "cli" ||
192
- value === "managed");
193
- }
194
123
  //# sourceMappingURL=trust.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"trust.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/trust.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,4BAA4B,EAAE,yBAAyB,E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GAAG,CAAC,CAAC;QACzB,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACzB,MAAM,CAAC,GAAG,CAAC,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;QACpC,CAAC;IACF,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,YAAY,CAAC,KAAgB;IACrC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc;IACxC,OAAO,CACN,KAAK,KAAK,QAAQ;QAClB,KAAK,KAAK,SAAS;QACnB,KAAK,KAAK,QAAQ;QAClB,KAAK,KAAK,SAAS;QACnB,KAAK,KAAK,KAAK;QACf,KAAK,KAAK,SAAS,CACnB,CAAC;AACH,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { DEFAULT_HOOK_TIMEOUT_SECONDS, isValidHookTimeoutSeconds } from \"./safety.ts\";\nimport type {\n\tExecutableHookHandler,\n\tHookSourceMetadata,\n\tHookSourceScope,\n\tHookTrustEntry,\n\tHookTrustState,\n} from \"./types.ts\";\n\nexport type HookTrustPlatform = NodeJS.Platform;\nexport type HookTrustStorageScope = \"global\" | \"project\";\n\nexport type HookTrustOptions = {\n\treadonly platform?: HookTrustPlatform;\n};\n\nexport type HookTrustStorageOptions = {\n\treadonly projectTrusted: boolean;\n};\n\nexport type HookTrustRecord = {\n\treadonly id: string;\n\treadonly currentHash: string;\n\treadonly enabled: boolean;\n\treadonly trusted: boolean;\n\treadonly executable: boolean;\n\treadonly scope: HookSourceScope;\n\treadonly sourcePath: string;\n\treadonly matcher?: string;\n\treadonly commandPreview: string;\n\treadonly entry?: HookTrustEntry;\n};\n\ntype JsonValue =\n\t| null\n\t| boolean\n\t| number\n\t| string\n\t| readonly JsonValue[]\n\t| { readonly [key: string]: JsonValue | undefined };\n\nconst HOOK_STATE_VERSION = 1;\n\nexport function emptyHookTrustState(): HookTrustState {\n\treturn { version: HOOK_STATE_VERSION, hooks: {} };\n}\n\nexport function hookTrustId(handler: ExecutableHookHandler): string {\n\treturn `hk_${sourceKeyHash(handler.source)}_${handler.event}_${handler.groupIndex}_${handler.handlerIndex}`;\n}\n\nexport function buildHookTrustRecord(handler: ExecutableHookHandler, options: HookTrustOptions = {}): HookTrustRecord {\n\tconst id = hookTrustId(handler);\n\tconst currentHash = hashCommandHook(handler, options);\n\tconst commandPreview = selectedCommand(handler, options.platform ?? process.platform);\n\treturn {\n\t\tid,\n\t\tcurrentHash,\n\t\tenabled: true,\n\t\ttrusted: false,\n\t\texecutable: false,\n\t\tscope: handler.source.scope,\n\t\tsourcePath: handler.source.sourcePath,\n\t\t...(handler.matcher === undefined ? {} : { matcher: handler.matcher }),\n\t\tcommandPreview,\n\t};\n}\n\nexport function createHookTrustEntry(\n\thandler: ExecutableHookHandler,\n\toptions: HookTrustOptions & { readonly updatedAt?: string } = {},\n): HookTrustEntry {\n\tconst commandPreview = selectedCommand(handler, options.platform ?? process.platform);\n\treturn {\n\t\tenabled: true,\n\t\ttrustedHash: hashCommandHook(handler, options),\n\t\tscope: handler.source.scope,\n\t\tsourcePath: handler.source.sourcePath,\n\t\t...(handler.matcher === undefined ? {} : { matcher: handler.matcher }),\n\t\tcommandPreview,\n\t\tupdatedAt: options.updatedAt ?? new Date().toISOString(),\n\t};\n}\n\nexport function hashCommandHook(handler: ExecutableHookHandler, options: HookTrustOptions = {}): string {\n\tconst platform = options.platform ?? process.platform;\n\tconst hook: { [key: string]: JsonValue | undefined } = {\n\t\tasync: false,\n\t\tcommand: handler.config.command,\n\t\tcommandWindows: handler.config.commandWindows,\n\t\tplatformCommand: selectedCommand(handler, platform),\n\t\tstatusMessage: handler.config.statusMessage,\n\t\ttimeout: normalizedTimeout(handler.config.timeout),\n\t\ttype: \"command\",\n\t};\n\tconst identity: { [key: string]: JsonValue | undefined } = {\n\t\tevent: handler.event,\n\t\thook,\n\t\tmatcher: handler.matcher,\n\t\tsourceKeyHash: sourceKeyHash(handler.source),\n\t};\n\treturn `sha256:${sha256Hex(JSON.stringify(canonicalJson(identity)))}`;\n}\n\nexport function isCommandHookTrusted(\n\thandler: ExecutableHookHandler,\n\tstate: HookTrustState,\n\toptions: HookTrustOptions = {},\n): boolean {\n\tconst record = buildStatefulHookTrustRecord(handler, state, options);\n\treturn record.executable;\n}\n\nexport function listHookTrustRecords(\n\thandlers: readonly ExecutableHookHandler[],\n\tstate: HookTrustState,\n\toptions: HookTrustOptions = {},\n): readonly HookTrustRecord[] {\n\treturn handlers.map((handler) => buildStatefulHookTrustRecord(handler, state, options));\n}\n\nexport function filterExecutableTrustedHooks(\n\thandlers: readonly ExecutableHookHandler[],\n\tstate: HookTrustState,\n\toptions: HookTrustOptions = {},\n): readonly ExecutableHookHandler[] {\n\treturn handlers.filter((handler) => buildStatefulHookTrustRecord(handler, state, options).executable);\n}\n\nexport function readHookTrustStateJson(input: string | undefined): HookTrustState {\n\tif (input === undefined || input.trim() === \"\") {\n\t\treturn emptyHookTrustState();\n\t}\n\ttry {\n\t\treturn parseHookTrustState(JSON.parse(input));\n\t} catch (error) {\n\t\tif (error instanceof Error) {\n\t\t\treturn emptyHookTrustState();\n\t\t}\n\t\treturn emptyHookTrustState();\n\t}\n}\n\nexport function hookTrustStorageScope(\n\thandler: ExecutableHookHandler,\n\toptions: HookTrustStorageOptions,\n): HookTrustStorageScope | undefined {\n\tif (handler.source.scope === \"project\") {\n\t\treturn options.projectTrusted ? \"project\" : undefined;\n\t}\n\treturn \"global\";\n}\n\nfunction buildStatefulHookTrustRecord(\n\thandler: ExecutableHookHandler,\n\tstate: HookTrustState,\n\toptions: HookTrustOptions,\n): HookTrustRecord {\n\tconst base = buildHookTrustRecord(handler, options);\n\tconst entry = state.hooks[base.id];\n\tconst enabled = entry?.enabled ?? true;\n\tconst trusted = entry?.trustedHash === base.currentHash;\n\treturn {\n\t\t...base,\n\t\tenabled,\n\t\ttrusted,\n\t\texecutable: enabled && trusted,\n\t\t...(entry === undefined ? {} : { entry }),\n\t};\n}\n\nfunction parseHookTrustState(input: unknown): HookTrustState {\n\tif (!isRecord(input) || input.version !== HOOK_STATE_VERSION || !isRecord(input.hooks)) {\n\t\treturn emptyHookTrustState();\n\t}\n\n\tconst hooks: Record<string, HookTrustEntry> = {};\n\tfor (const [id, entry] of Object.entries(input.hooks)) {\n\t\tconst parsed = parseHookTrustEntry(entry);\n\t\tif (parsed !== undefined) {\n\t\t\thooks[id] = parsed;\n\t\t}\n\t}\n\treturn { version: HOOK_STATE_VERSION, hooks };\n}\n\nfunction parseHookTrustEntry(input: unknown): HookTrustEntry | undefined {\n\tif (!isRecord(input)) {\n\t\treturn undefined;\n\t}\n\tconst enabled = input.enabled;\n\tconst trustedHash = input.trustedHash;\n\tconst scope = input.scope;\n\tconst sourcePath = input.sourcePath;\n\tconst matcher = input.matcher;\n\tconst commandPreview = input.commandPreview;\n\tconst updatedAt = input.updatedAt;\n\tif (\n\t\ttypeof enabled !== \"boolean\" ||\n\t\t(trustedHash !== undefined && typeof trustedHash !== \"string\") ||\n\t\t!isHookSourceScope(scope) ||\n\t\ttypeof sourcePath !== \"string\" ||\n\t\t(matcher !== undefined && typeof matcher !== \"string\") ||\n\t\ttypeof commandPreview !== \"string\" ||\n\t\ttypeof updatedAt !== \"string\"\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tenabled,\n\t\t...(trustedHash === undefined ? {} : { trustedHash }),\n\t\tscope,\n\t\tsourcePath,\n\t\t...(matcher === undefined ? {} : { matcher }),\n\t\tcommandPreview,\n\t\tupdatedAt,\n\t};\n}\n\nfunction selectedCommand(handler: ExecutableHookHandler, platform: HookTrustPlatform): string {\n\tif (platform === \"win32\" && handler.config.commandWindows !== undefined) {\n\t\treturn handler.config.commandWindows;\n\t}\n\treturn handler.config.command;\n}\n\nfunction normalizedTimeout(timeout: number | undefined): number {\n\tif (timeout === undefined) {\n\t\treturn DEFAULT_HOOK_TIMEOUT_SECONDS;\n\t}\n\tif (!isValidHookTimeoutSeconds(timeout)) {\n\t\tthrow new Error(\"Invalid command hook timeout reached trust hashing.\");\n\t}\n\treturn timeout;\n}\n\nfunction sourceKeyHash(source: HookSourceMetadata): string {\n\treturn sha256Hex(\n\t\t[source.scope, source.sourcePath, source.pluginRoot ?? \"\", source.manifestPath ?? \"\"].join(\"\\0\"),\n\t).slice(0, 12);\n}\n\nfunction sha256Hex(value: string): string {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction canonicalJson(value: JsonValue): JsonValue {\n\tif (Array.isArray(value)) {\n\t\treturn value.map(canonicalJson);\n\t}\n\tif (!isJsonRecord(value)) {\n\t\treturn value;\n\t}\n\tconst result: { [key: string]: JsonValue } = {};\n\tfor (const key of Object.keys(value).sort()) {\n\t\tconst child = value[key];\n\t\tif (child !== undefined) {\n\t\t\tresult[key] = canonicalJson(child);\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isJsonRecord(value: JsonValue): value is { readonly [key: string]: JsonValue | undefined } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isHookSourceScope(value: unknown): value is HookSourceScope {\n\treturn (\n\t\tvalue === \"global\" ||\n\t\tvalue === \"project\" ||\n\t\tvalue === \"plugin\" ||\n\t\tvalue === \"runtime\" ||\n\t\tvalue === \"cli\" ||\n\t\tvalue === \"managed\"\n\t);\n}\n"]}
1
+ {"version":3,"file":"trust.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/trust.ts"],"names":[],"mappings":"AAAA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aAAa,CAAC,CAAC;IACjC,CAAC;IACD,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,KAAK,CAAC;IACd,CAAC;IACD,MAAM,MAAM,GAAiC,EAAE,CAAC;IAChD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QAC7C,MAAM,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;QACzB,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACzB,MAAM,CAAC,GAAG,CAAC,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;QACpC,CAAC;IACF,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC;AAED,SAAS,YAAY,CAAC,KAAgB;IACrC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { DEFAULT_HOOK_TIMEOUT_SECONDS, isValidHookTimeoutSeconds } from \"./safety.ts\";\nimport type {\n\tExecutableHookHandler,\n\tHookSourceMetadata,\n\tHookSourceScope,\n\tHookTrustEntry,\n\tHookTrustState,\n} from \"./types.ts\";\n\nexport type HookTrustPlatform = NodeJS.Platform;\nexport type HookTrustStorageScope = \"global\" | \"project\";\n\nexport type HookTrustOptions = {\n\treadonly platform?: HookTrustPlatform;\n};\n\nexport type HookTrustStorageOptions = {\n\treadonly projectTrusted: boolean;\n};\n\nexport type HookTrustRecord = {\n\treadonly id: string;\n\treadonly currentHash: string;\n\treadonly enabled: boolean;\n\treadonly trusted: boolean;\n\treadonly executable: boolean;\n\treadonly scope: HookSourceScope;\n\treadonly sourcePath: string;\n\treadonly matcher?: string;\n\treadonly commandPreview: string;\n\treadonly entry?: HookTrustEntry;\n};\n\ntype JsonValue =\n\t| null\n\t| boolean\n\t| number\n\t| string\n\t| readonly JsonValue[]\n\t| { readonly [key: string]: JsonValue | undefined };\n\nexport { emptyHookTrustState, readHookTrustStateJson } from \"./trust-state-json.ts\";\n\nexport function hookTrustId(handler: ExecutableHookHandler): string {\n\treturn `hk_${sourceKeyHash(handler.source)}_${handler.event}_${handler.groupIndex}_${handler.handlerIndex}`;\n}\n\nexport function buildHookTrustRecord(handler: ExecutableHookHandler, options: HookTrustOptions = {}): HookTrustRecord {\n\tconst id = hookTrustId(handler);\n\tconst currentHash = hashCommandHook(handler, options);\n\tconst commandPreview = selectedCommand(handler, options.platform ?? process.platform);\n\treturn {\n\t\tid,\n\t\tcurrentHash,\n\t\tenabled: true,\n\t\ttrusted: false,\n\t\texecutable: false,\n\t\tscope: handler.source.scope,\n\t\tsourcePath: handler.source.sourcePath,\n\t\t...(handler.matcher === undefined ? {} : { matcher: handler.matcher }),\n\t\tcommandPreview,\n\t};\n}\n\nexport function createHookTrustEntry(\n\thandler: ExecutableHookHandler,\n\toptions: HookTrustOptions & { readonly updatedAt?: string } = {},\n): HookTrustEntry {\n\tconst commandPreview = selectedCommand(handler, options.platform ?? process.platform);\n\treturn {\n\t\tenabled: true,\n\t\ttrustedHash: hashCommandHook(handler, options),\n\t\tscope: handler.source.scope,\n\t\tsourcePath: handler.source.sourcePath,\n\t\t...(handler.matcher === undefined ? {} : { matcher: handler.matcher }),\n\t\tcommandPreview,\n\t\tupdatedAt: options.updatedAt ?? new Date().toISOString(),\n\t};\n}\n\nexport function hashCommandHook(handler: ExecutableHookHandler, options: HookTrustOptions = {}): string {\n\tconst platform = options.platform ?? process.platform;\n\tconst hook: { [key: string]: JsonValue | undefined } = {\n\t\tasync: false,\n\t\tcommand: handler.config.command,\n\t\tcommandWindows: handler.config.commandWindows,\n\t\tplatformCommand: selectedCommand(handler, platform),\n\t\tstatusMessage: handler.config.statusMessage,\n\t\ttimeout: normalizedTimeout(handler.config.timeout),\n\t\ttype: \"command\",\n\t};\n\tconst identity: { [key: string]: JsonValue | undefined } = {\n\t\tevent: handler.event,\n\t\thook,\n\t\tmatcher: handler.matcher,\n\t\tsourceKeyHash: sourceKeyHash(handler.source),\n\t};\n\treturn `sha256:${sha256Hex(JSON.stringify(canonicalJson(identity)))}`;\n}\n\nexport function isCommandHookTrusted(\n\thandler: ExecutableHookHandler,\n\tstate: HookTrustState,\n\toptions: HookTrustOptions = {},\n): boolean {\n\tconst record = buildStatefulHookTrustRecord(handler, state, options);\n\treturn record.executable;\n}\n\nexport function listHookTrustRecords(\n\thandlers: readonly ExecutableHookHandler[],\n\tstate: HookTrustState,\n\toptions: HookTrustOptions = {},\n): readonly HookTrustRecord[] {\n\treturn handlers.map((handler) => buildStatefulHookTrustRecord(handler, state, options));\n}\n\nexport function filterExecutableTrustedHooks(\n\thandlers: readonly ExecutableHookHandler[],\n\tstate: HookTrustState,\n\toptions: HookTrustOptions = {},\n): readonly ExecutableHookHandler[] {\n\treturn handlers.filter((handler) => buildStatefulHookTrustRecord(handler, state, options).executable);\n}\n\nexport function hookTrustStorageScope(\n\thandler: ExecutableHookHandler,\n\toptions: HookTrustStorageOptions,\n): HookTrustStorageScope | undefined {\n\tif (handler.source.scope === \"project\") {\n\t\treturn options.projectTrusted ? \"project\" : undefined;\n\t}\n\treturn \"global\";\n}\n\nfunction buildStatefulHookTrustRecord(\n\thandler: ExecutableHookHandler,\n\tstate: HookTrustState,\n\toptions: HookTrustOptions,\n): HookTrustRecord {\n\tconst base = buildHookTrustRecord(handler, options);\n\tconst entry = state.hooks[base.id];\n\tconst enabled = entry?.enabled ?? true;\n\tconst trusted = entry?.trustedHash === base.currentHash;\n\treturn {\n\t\t...base,\n\t\tenabled,\n\t\ttrusted,\n\t\texecutable: enabled && trusted,\n\t\t...(entry === undefined ? {} : { entry }),\n\t};\n}\n\nfunction selectedCommand(handler: ExecutableHookHandler, platform: HookTrustPlatform): string {\n\tif (platform === \"win32\" && handler.config.commandWindows !== undefined) {\n\t\treturn handler.config.commandWindows;\n\t}\n\treturn handler.config.command;\n}\n\nfunction normalizedTimeout(timeout: number | undefined): number {\n\tif (timeout === undefined) {\n\t\treturn DEFAULT_HOOK_TIMEOUT_SECONDS;\n\t}\n\tif (!isValidHookTimeoutSeconds(timeout)) {\n\t\tthrow new Error(\"Invalid command hook timeout reached trust hashing.\");\n\t}\n\treturn timeout;\n}\n\nfunction sourceKeyHash(source: HookSourceMetadata): string {\n\treturn sha256Hex(\n\t\t[source.scope, source.sourcePath, source.pluginRoot ?? \"\", source.manifestPath ?? \"\"].join(\"\\0\"),\n\t).slice(0, 12);\n}\n\nfunction sha256Hex(value: string): string {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction canonicalJson(value: JsonValue): JsonValue {\n\tif (Array.isArray(value)) {\n\t\treturn value.map(canonicalJson);\n\t}\n\tif (!isJsonRecord(value)) {\n\t\treturn value;\n\t}\n\tconst result: { [key: string]: JsonValue } = {};\n\tfor (const key of Object.keys(value).sort()) {\n\t\tconst child = value[key];\n\t\tif (child !== undefined) {\n\t\t\tresult[key] = canonicalJson(child);\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction isJsonRecord(value: JsonValue): value is { readonly [key: string]: JsonValue | undefined } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/ttsr/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAiB,YAAY,EAAwC,MAAM,gBAAgB,CAAC;AAoDxG,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CA0N5D"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/ttsr/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAiB,YAAY,EAAwC,MAAM,gBAAgB,CAAC;AAoDxG,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CA8N5D"}