dal-code 1.0.37 → 1.0.39

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 (111) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dal-docs/settings.md +1 -1
  3. package/dist/core/agent-session.js +4 -4
  4. package/dist/core/auth-storage.js +1 -1
  5. package/dist/core/compaction/compaction.js +31 -13
  6. package/dist/core/package-manager.d.ts +4 -0
  7. package/dist/core/package-manager.js +2 -2
  8. package/dist/core/permissions/tool-policy.js +1 -1
  9. package/dist/core/project-facts.d.ts +16 -0
  10. package/dist/core/project-facts.js +2 -0
  11. package/dist/core/sandbox/policy.js +1 -1
  12. package/dist/core/sandbox/windows.js +1 -1
  13. package/dist/core/session-manager.d.ts +3 -0
  14. package/dist/core/session-manager.js +12 -12
  15. package/dist/core/settings-diagnostics.js +1 -1
  16. package/dist/core/settings-manager.d.ts +3 -0
  17. package/dist/core/settings-manager.js +1 -1
  18. package/dist/core/shared-data.js +1 -0
  19. package/dist/core/system-prompt.d.ts +1 -0
  20. package/dist/core/system-prompt.js +13 -13
  21. package/dist/core/trust-manager.js +2 -2
  22. package/dist/core/workspace-lock.d.ts +29 -0
  23. package/dist/core/workspace-lock.js +3 -0
  24. package/dist/dal/reviewed/endorsed-cli.js +1 -0
  25. package/dist/dal/reviewed/endorsed-plan.js +1 -0
  26. package/dist/dal/reviewed/endorsed.js +1 -0
  27. package/dist/dal/reviewed/version.js +1 -0
  28. package/dist/extensions/mcp/config.js +2 -2
  29. package/dist/index.d.ts +2 -0
  30. package/dist/index.js +1 -1
  31. package/dist/main.js +3 -3
  32. package/dist/modes/print-mode.js +5 -5
  33. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  34. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  35. package/dist/node_modules/@dalcode/dal-goal/package.json +2 -2
  36. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  37. package/dist/node_modules/@dalcode/dal-guard/src/attribution.js +1 -0
  38. package/dist/node_modules/@dalcode/dal-guard/src/credentials.js +1 -1
  39. package/dist/node_modules/@dalcode/dal-guard/src/index.js +1 -1
  40. package/dist/node_modules/@dalcode/dal-guard/src/mode.js +2 -2
  41. package/dist/node_modules/@dalcode/dal-guard/src/package-manager.js +1 -0
  42. package/dist/node_modules/@dalcode/dal-guard/src/workspace.js +2 -0
  43. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  44. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  45. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  46. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  47. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  48. package/dist/node_modules/@dalcode/dal-mcp/src/config-edit.js +2 -2
  49. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  50. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +4 -2
  51. package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
  52. package/dist/node_modules/@dalcode/dal-pi-kit/dist/shared-data.js +1 -0
  53. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  54. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +4 -2
  55. package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
  56. package/dist/node_modules/@dalcode/dal-pi-kit/src/shared-data.js +1 -0
  57. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  58. package/dist/node_modules/@dalcode/dal-plugins/src/state.js +2 -2
  59. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  60. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  61. package/dist/node_modules/@dalcode/dal-router/package.json +5 -4
  62. package/dist/node_modules/@dalcode/dal-router/src/commands.js +7 -7
  63. package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +3 -1
  64. package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
  65. package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
  66. package/dist/node_modules/@dalcode/dal-router/src/runtime.js +1 -1
  67. package/dist/node_modules/@dalcode/dal-router/src/subagent.js +1 -1
  68. package/dist/node_modules/@dalcode/dal-router/src/suggest.js +2 -0
  69. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  70. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  71. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +12 -12
  72. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  73. package/dist/node_modules/@dalcode/dal-telemetry/src/config.js +2 -2
  74. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  75. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  76. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  77. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  78. package/dist/node_modules/@dalcode/dal-workflow/src/completion-check.js +4 -0
  79. package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
  80. package/dist/node_modules/@dalcode/dal-workflow/src/ledger.js +3 -0
  81. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  82. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  83. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  84. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  85. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  86. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  87. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  88. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  89. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts +1 -1
  90. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +1 -1
  91. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  92. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  93. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  94. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  95. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  96. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  97. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  98. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  99. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  100. package/dist/package-manager-cli.js +72 -72
  101. package/dist/utils/version-check.d.ts +1 -0
  102. package/dist/utils/version-check.js +2 -2
  103. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  104. package/examples/extensions/gondolin/package-lock.json +2 -2
  105. package/examples/extensions/gondolin/package.json +1 -1
  106. package/examples/extensions/sandbox/package-lock.json +2 -2
  107. package/examples/extensions/sandbox/package.json +1 -1
  108. package/examples/extensions/with-deps/package-lock.json +2 -2
  109. package/examples/extensions/with-deps/package.json +1 -1
  110. package/npm-shrinkwrap.json +2 -2
  111. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- var q=Object.defineProperty;var f=(e,t)=>q(e,"name",{value:t,configurable:!0});import{contentText as b,getCurrentSystemMessage as G,normalizeContext as Y,retryAssistantCall as H,uuidv7 as J}from"@earendil-works/pi-ai";import{completeSimple as Q}from"@earendil-works/pi-ai/compat";import{convertToLlm as N}from"../messages.js";import{buildSessionProjection as ee,sessionEntryToContextMessages as C}from"../session-manager.js";import{DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS as te}from"../settings-manager.js";import{combineUsage as ne}from"../usage-totals.js";import{shrinkToolResultsForSummary as se}from"./tool-output-pruning.js";import{computeFileLists as oe,createFileOps as re,estimateTokens as P,extractFileOpsFromMessage as _,formatFileOperations as ie,SUMMARIZATION_SYSTEM_PROMPT as ae,serializeConversation as D}from"./utils.js";function ce(e,t,o){const n=re();if(o>=0){const s=t[o];if(!s.fromHook&&s.details){const i=s.details;if(Array.isArray(i.readFiles))for(const a of i.readFiles)n.read.add(a);if(Array.isArray(i.modifiedFiles))for(const a of i.modifiedFiles)n.edited.add(a)}}for(const s of e)_(s,n);return n}f(ce,"extractFileOperations");function F(e){return e.sourceEntry.type==="compaction"?[]:e.messages.filter(t=>t.role!=="system")}f(F,"getMessagesFromProjectedEntryForCompaction");const Ue={enabled:!0,reserveTokens:16384,keepRecentTokens:2e4};function z(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}f(z,"calculateContextTokens");function K(e){if(e.role==="assistant"&&"usage"in e){const t=e;if(t.stopReason!=="aborted"&&t.stopReason!=="error"&&t.usage&&z(t.usage)>0)return t.usage}}f(K,"getAssistantUsage");function be(e){for(let t=e.length-1;t>=0;t--){const o=e[t];if(o.type==="message"){const n=K(o.message);if(n)return n}}}f(be,"getLastAssistantUsage");function ue(e){for(let t=e.length-1;t>=0;t--){const o=K(e[t]);if(o)return{usage:o,index:t}}}f(ue,"getLastAssistantUsageInfo");function fe(e){const t=ue(e);if(!t){let s=0;for(const i of e)s+=P(i);return{tokens:s,usageTokens:0,trailingTokens:s,lastUsageIndex:null}}const o=z(t.usage);let n=0;for(let s=t.index+1;s<e.length;s++)n+=P(e[s]);return{tokens:o+n,usageTokens:o,trailingTokens:n,lastUsageIndex:t.index}}f(fe,"estimateContextTokens");function me(e,t){const o=fe(e.messages);if(o.lastUsageIndex!==null){let i=0,a;for(const m of e.entries){const c=i+m.messages.length;if(o.lastUsageIndex<c){a=m.sourceEntry.id;break}i=c}const u=a?t.findIndex(m=>m.id===a):-1;let l=-1;for(let m=t.length-1;m>=0;m--){const c=t[m];if(c.type==="context_edit"||c.type==="compaction"){l=m;break}}if(u>l)return o}const n=G(e.messages);let s=n?P(n):0;for(const i of e.messages)i.role!=="system"&&(s+=P(i));return{tokens:s,usageTokens:0,trailingTokens:s,lastUsageIndex:null}}f(me,"estimateProjectedContextTokens");const le=32e3;function pe(e,t,o=0){const n=e-t.reserveTokens;if(!t.maxContextTokens)return n;if(t.maxContextTokens!==te)return Math.min(n,t.maxContextTokens);const s=o+t.keepRecentTokens+le;return Math.min(n,Math.max(t.maxContextTokens,s))}f(pe,"compactionThreshold");function Ne(e,t,o,n=0){return o.enabled?e>pe(t,o,n):!1}f(Ne,"shouldCompact");function $(e){switch(e.role){case"user":case"assistant":case"bashExecution":case"custom":case"branchSummary":case"compactionSummary":return!0;case"toolResult":return!1}return!1}f($,"isCutPointMessage");function B(e){switch(e.role){case"user":case"bashExecution":case"custom":case"branchSummary":case"compactionSummary":return!0;case"assistant":case"toolResult":return!1}return!1}f(B,"isTurnStartMessage");function L(e){return e.type==="compaction"?!1:C(e).some(B)}f(L,"isTurnStartEntry");function de(e,t,o){const n=[];for(let s=t;s<o;s++){const i=e[s];i.type!=="compaction"&&C(i).some($)&&n.push(s)}return n}f(de,"findValidCutPoints");function ge(e,t,o){for(let n=t;n>=o;n--)if(L(e[n]))return n;return-1}f(ge,"findTurnStartIndex");function _e(e,t,o,n){const s=de(e,t,o);if(s.length===0)return{firstKeptEntryIndex:t,turnStartIndex:-1,isSplitTurn:!1};let i=0,a=s[0];for(let c=o-1;c>=t;c--){const d=e[c],x=C(d).reduce((y,T)=>y+P(T),0);if(x!==0&&(i+=x,i>=n)){a=s.find(y=>y>=c)??s[s.length-1];break}}for(;a>t;){const c=e[a-1];if(c.type==="compaction"||C(c).length>0)break;a--}const u=e[a],l=L(u),m=l?-1:ge(e,a,t);return{firstKeptEntryIndex:a,turnStartIndex:m,isSplitTurn:!l&&m!==-1}}f(_e,"findCutPoint");const xe=`The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
1
+ var q=Object.defineProperty;var m=(e,t)=>q(e,"name",{value:t,configurable:!0});import{contentText as U,getCurrentSystemMessage as G,normalizeContext as Y,retryAssistantCall as H,uuidv7 as J}from"@earendil-works/pi-ai";import{completeSimple as Q}from"@earendil-works/pi-ai/compat";import{convertToLlm as N}from"../messages.js";import{buildSessionProjection as ee,sessionEntryToContextMessages as P}from"../session-manager.js";import{DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS as te}from"../settings-manager.js";import{combineUsage as ne}from"../usage-totals.js";import{shrinkToolResultsForSummary as se}from"./tool-output-pruning.js";import{computeFileLists as oe,createFileOps as re,estimateTokens as I,extractFileOpsFromMessage as _,formatFileOperations as ae,SUMMARIZATION_SYSTEM_PROMPT as ie,serializeConversation as D}from"./utils.js";function ce(e,t,o){const n=re();if(o>=0){const s=t[o];if(!s.fromHook&&s.details){const a=s.details;if(Array.isArray(a.readFiles))for(const i of a.readFiles)n.read.add(i);if(Array.isArray(a.modifiedFiles))for(const i of a.modifiedFiles)n.edited.add(i)}}for(const s of e)_(s,n);return n}m(ce,"extractFileOperations");function F(e){return e.sourceEntry.type==="compaction"?[]:e.messages.filter(t=>t.role!=="system")}m(F,"getMessagesFromProjectedEntryForCompaction");const Ae={enabled:!0,reserveTokens:16384,keepRecentTokens:2e4};function z(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}m(z,"calculateContextTokens");function K(e){if(e.role==="assistant"&&"usage"in e){const t=e;if(t.stopReason!=="aborted"&&t.stopReason!=="error"&&t.usage&&z(t.usage)>0)return t.usage}}m(K,"getAssistantUsage");function Ue(e){for(let t=e.length-1;t>=0;t--){const o=e[t];if(o.type==="message"){const n=K(o.message);if(n)return n}}}m(Ue,"getLastAssistantUsage");function ue(e){for(let t=e.length-1;t>=0;t--){const o=K(e[t]);if(o)return{usage:o,index:t}}}m(ue,"getLastAssistantUsageInfo");function me(e){const t=ue(e);if(!t){let s=0;for(const a of e)s+=I(a);return{tokens:s,usageTokens:0,trailingTokens:s,lastUsageIndex:null}}const o=z(t.usage);let n=0;for(let s=t.index+1;s<e.length;s++)n+=I(e[s]);return{tokens:o+n,usageTokens:o,trailingTokens:n,lastUsageIndex:t.index}}m(me,"estimateContextTokens");function le(e,t){const o=me(e.messages);if(o.lastUsageIndex!==null){let a=0,i;for(const l of e.entries){const c=a+l.messages.length;if(o.lastUsageIndex<c){i=l.sourceEntry.id;break}a=c}const u=i?t.findIndex(l=>l.id===i):-1;let f=-1;for(let l=t.length-1;l>=0;l--){const c=t[l];if(c.type==="context_edit"||c.type==="compaction"){f=l;break}}if(u>f)return o}const n=G(e.messages);let s=n?I(n):0;for(const a of e.messages)a.role!=="system"&&(s+=I(a));return{tokens:s,usageTokens:0,trailingTokens:s,lastUsageIndex:null}}m(le,"estimateProjectedContextTokens");const fe=32e3;function de(e,t,o=0){const n=e-t.reserveTokens;if(!t.maxContextTokens)return n;if(t.maxContextTokens!==te)return Math.min(n,t.maxContextTokens);const s=o+t.keepRecentTokens+fe;return Math.min(n,Math.max(t.maxContextTokens,s))}m(de,"compactionThreshold");function Ne(e,t,o,n=0){return o.enabled?e>de(t,o,n):!1}m(Ne,"shouldCompact");function $(e){switch(e.role){case"user":case"assistant":case"bashExecution":case"custom":case"branchSummary":case"compactionSummary":return!0;case"toolResult":return!1}return!1}m($,"isCutPointMessage");function W(e){switch(e.role){case"user":case"bashExecution":case"custom":case"branchSummary":case"compactionSummary":return!0;case"assistant":case"toolResult":return!1}return!1}m(W,"isTurnStartMessage");function L(e){return e.type==="compaction"?!1:P(e).some(W)}m(L,"isTurnStartEntry");function pe(e,t,o){const n=[];for(let s=t;s<o;s++){const a=e[s];a.type!=="compaction"&&P(a).some($)&&n.push(s)}return n}m(pe,"findValidCutPoints");function he(e,t,o){for(let n=t;n>=o;n--)if(L(e[n]))return n;return-1}m(he,"findTurnStartIndex");function _e(e,t,o,n){const s=pe(e,t,o);if(s.length===0)return{firstKeptEntryIndex:t,turnStartIndex:-1,isSplitTurn:!1};let a=0,i=s[0];for(let c=o-1;c>=t;c--){const p=e[c],g=P(p).reduce((x,y)=>x+I(y),0);if(g!==0&&(a+=g,a>=n)){i=s.find(x=>x>=c)??s[s.length-1];break}}for(;i>t;){const c=e[i-1];if(c.type==="compaction"||P(c).length>0)break;i--}const u=e[i],f=L(u),l=f?-1:he(e,i,t);return{firstKeptEntryIndex:i,turnStartIndex:l,isSplitTurn:!f&&l!==-1}}m(_e,"findCutPoint");const ge=`The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
2
2
 
3
3
  Use this EXACT format:
4
4
 
@@ -19,6 +19,14 @@ Use this EXACT format:
19
19
  ### Blocked
20
20
  - [Issues preventing progress, if any]
21
21
 
22
+ ## Tracks
23
+ - **[Track name]**: [where it stands, in one line] \u2014 workspace: [directory or worktree], branch [name], last commit [short hash and subject], uncommitted: [yes/no, which files]; next: [the next step]
24
+ - [One line per separate line of work; "(single track)" when there is only one]
25
+
26
+ ## Workspace State
27
+ - [Every repository, worktree or directory the work happened in, with the branch, last commit and whether changes are uncommitted, as last seen in the conversation; who else is working there, if known]
28
+ - [Or "(none)"]
29
+
22
30
  ## Key Decisions
23
31
  - **[Decision]**: [Brief rationale]
24
32
 
@@ -26,15 +34,16 @@ Use this EXACT format:
26
34
  1. [Ordered list of what should happen next]
27
35
 
28
36
  ## Critical Context
29
- - [Any data, examples, or references needed to continue]
37
+ - [Any data, examples, or references needed to continue: commands that work in this environment (package manager, how tests are run), ids, URLs, exact error messages]
30
38
  - [Or "(none)" if not applicable]
31
39
 
32
- Keep each section concise. Preserve exact file paths, function names, and error messages.`,ye=`Update the existing structured summary with new information. RULES:
40
+ Keep each section concise. Preserve exact file paths, function names, and error messages. Record facts that would otherwise have to be looked up again (git state, which commands work), so the work can continue without re-checking them.`,xe=`Update the existing structured summary with new information. RULES:
33
41
  - PRESERVE all existing information from the previous summary
34
42
  - ADD new progress, decisions, and context from the new messages
35
43
  - UPDATE the Progress section: move items from "In Progress" to "Done" when completed
36
44
  - UPDATE "Next Steps" based on what was accomplished
37
45
  - PRESERVE exact file paths, function names, and error messages
46
+ - UPDATE "Tracks" and "Workspace State" so they describe the state at the end of the new messages
38
47
  - If something is no longer relevant, you may remove it
39
48
 
40
49
  Use this EXACT format:
@@ -55,6 +64,12 @@ Use this EXACT format:
55
64
  ### Blocked
56
65
  - [Current blockers - remove if resolved]
57
66
 
67
+ ## Tracks
68
+ - **[Track name]**: [where it stands] \u2014 workspace, branch, last commit, uncommitted changes; next step (update each track, keep finished ones as one "done" line)
69
+
70
+ ## Workspace State
71
+ - [Update the branch, last commit and uncommitted state of every repository or worktree in use, as last seen]
72
+
58
73
  ## Key Decisions
59
74
  - **[Decision]**: [Brief rationale] (preserve all previous, add new)
60
75
 
@@ -64,19 +79,19 @@ Use this EXACT format:
64
79
  ## Critical Context
65
80
  - [Preserve important context, add new if needed]
66
81
 
67
- Keep each section concise. Preserve exact file paths, function names, and error messages.`,Te=`The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
82
+ Keep each section concise. Preserve exact file paths, function names, and error messages.`,ye=`The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
68
83
 
69
- ${ye}`;function j(e,t){if(e.stopReason==="error")return`${t} failed: ${e.errorMessage||"Unknown error"}`;if(e.stopReason==="length")return`${t} failed: generation hit the token cap and the summary is incomplete`}f(j,"getSummarizationFailure");function V(e,t,o,n,s,i,a,u){const l={maxTokens:t,signal:i,apiKey:o,headers:n,env:s,sessionId:u};return e.reasoning&&a&&a!=="off"&&(l.reasoning=a),l}f(V,"createSummarizationOptions");async function W(e,t,o,n,s,i){const a={...o,cacheRetention:"none",sessionId:o.sessionId??J()};return H(f(async()=>n?(await n(e,t,a)).result():Q(e,t,a),"produce"),s,a.signal,i)}f(W,"completeSummarization");async function De(e,t,o,n,s,i,a,u,l,m,c,d,x,y){return(await A(e,t,o,n,s,i,a,u,l,m,c,d,x,y)).text}f(De,"generateSummary");function X(e){return Y({systemPrompt:ae,messages:[{role:"user",content:[{type:"text",text:e}],timestamp:Date.now()}]})}f(X,"buildSummarizationContext");async function A(e,t,o,n,s,i,a,u,l,m,c,d,x,y){const T=Math.min(Math.floor(.8*o),t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY);let g=u?Te:xe;a&&(g=`${g}
84
+ ${xe}`;function j(e,t){if(e.stopReason==="error")return`${t} failed: ${e.errorMessage||"Unknown error"}`;if(e.stopReason==="length")return`${t} failed: generation hit the token cap and the summary is incomplete`}m(j,"getSummarizationFailure");function B(e,t,o,n,s,a,i,u){const f={maxTokens:t,signal:a,apiKey:o,headers:n,env:s,sessionId:u};return e.reasoning&&i&&i!=="off"&&(f.reasoning=i),f}m(B,"createSummarizationOptions");async function V(e,t,o,n,s,a){const i={...o,cacheRetention:"none",sessionId:o.sessionId??J()};return H(m(async()=>n?(await n(e,t,i)).result():Q(e,t,i),"produce"),s,i.signal,a)}m(V,"completeSummarization");async function De(e,t,o,n,s,a,i,u,f,l,c,p,g,x){return(await b(e,t,o,n,s,a,i,u,f,l,c,p,g,x)).text}m(De,"generateSummary");function X(e){return Y({systemPrompt:ie,messages:[{role:"user",content:[{type:"text",text:e}],timestamp:Date.now()}]})}m(X,"buildSummarizationContext");async function b(e,t,o,n,s,a,i,u,f,l,c,p,g,x){const y=Math.min(Math.floor(.8*o),t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY);let h=u?ye:ge;i&&(h=`${h}
70
85
 
71
- Additional focus: ${a}`);const r=N(e);let h=`<conversation>
86
+ Additional focus: ${i}`);const r=N(e);let T=`<conversation>
72
87
  ${D(r)}
73
88
  </conversation>
74
89
 
75
- `;u&&(h+=`<previous-summary>
90
+ `;u&&(T+=`<previous-summary>
76
91
  ${u}
77
92
  </previous-summary>
78
93
 
79
- `),h+=g;const S=V(t,T,n,s,c,i,l,y),E=await W(t,X(h),S,m,d,x),k=j(E,"Summarization");if(k)throw new Error(k);if(E.content.some(v=>v.type==="toolCall"))throw new Error("Summarization attempted to call a tool");return{text:b(E.content),usage:E.usage}}f(A,"generateSummaryWithUsage");function Z(e){return e.sourceEntry.type==="compaction"?!1:e.messages.some(B)}f(Z,"isProjectedTurnStart");function he(e,t,o){for(let n=t;n>=o;n--)if(Z(e[n]))return n;return-1}f(he,"findProjectedTurnStartIndex");function Se(e,t,o,n){const s=[];for(let r=t;r<o;r++){const p=e[r];p.sourceEntry.type!=="compaction"&&p.messages.some($)&&s.push(r)}if(s.length===0)return{firstKeptEntryIndex:t,turnStartIndex:-1,isSplitTurn:!1};let i=0,a=!1,u=s[0];for(let r=o-1;r>=t;r--){const p=e[r].messages.reduce((h,S)=>h+P(S),0);if(p!==0&&(i+=p,i>=n)){a=!0,u=s.find(h=>h>=r)??s[s.length-1];break}}const l=e.slice(u+1,o),m=f(r=>r.sourceEntry.type!=="context_edit"&&C(r.sourceEntry).length>0,"isIntrinsicallyVisible"),c=f(r=>m(r)&&r.messages.length===0,"isOmitted"),d=new Set(l.filter(c).map(r=>r.sourceEntry.id)),x=l.some(r=>r.sourceEntry.type==="context_edit"&&r.sourceEntry.replacement!==null&&!d.has(r.sourceEntry.targetId));for(a&&!x&&l.some(r=>r.sourceEntry.type==="message"&&r.sourceEntry.message.role==="assistant"&&c(r))&&l.every(r=>r.sourceEntry.type!=="compaction"&&(!m(r)||c(r)))&&u++;u>t;){const r=e[u-1];if(r.sourceEntry.type==="compaction"||r.messages.length>0)break;u--}const T=Z(e[u]),g=T?-1:he(e,u,t);return{firstKeptEntryIndex:u,turnStartIndex:g,isSplitTurn:!T&&g!==-1}}f(Se,"findProjectedCutPoint");function Fe(e,t){if(e.length>0&&e[e.length-1].type==="compaction")return;const o=ee(e),n=o.entries,s=n.map(p=>p.sourceEntry),i=n.findIndex(p=>p.sourceEntry.type==="compaction"&&p.messages.length>0);let a,u=0;i>=0&&(a=n[i].sourceEntry.summary,u=i+1);const l=n.length,m=me(o,e).tokens,c=Se(n,u,l,t.keepRecentTokens),d=n[c.firstKeptEntryIndex]?.sourceEntry;if(!d?.id)return;const x=d.id,y=c.isSplitTurn?c.turnStartIndex:c.firstKeptEntryIndex,T=n.slice(u,y).flatMap(F),g=c.isSplitTurn?n.slice(c.turnStartIndex,c.firstKeptEntryIndex).flatMap(F):[];if(T.length===0&&g.length===0)return;const r=ce(T,s,i);if(c.isSplitTurn)for(const p of g)_(p,r);return{firstKeptEntryId:x,messagesToSummarize:T,turnPrefixMessages:g,isSplitTurn:c.isSplitTurn,tokensBefore:m,previousSummary:a,fileOps:r,settings:t}}f(Fe,"prepareCompaction");const Ee=`The messages above are earlier context from an ongoing conversation. Later messages are stored separately and do not need to be reconstructed.
94
+ `),T+=h;const k=B(t,y,n,s,c,a,f,x),w=await V(t,X(T),k,l,p,g),S=j(w,"Summarization");if(S)throw new Error(S);if(w.content.some(v=>v.type==="toolCall"))throw new Error("Summarization attempted to call a tool");return{text:U(w.content),usage:w.usage}}m(b,"generateSummaryWithUsage");function Z(e){return e.sourceEntry.type==="compaction"?!1:e.messages.some(W)}m(Z,"isProjectedTurnStart");function Te(e,t,o){for(let n=t;n>=o;n--)if(Z(e[n]))return n;return-1}m(Te,"findProjectedTurnStartIndex");function ke(e,t,o,n){const s=[];for(let r=t;r<o;r++){const d=e[r];d.sourceEntry.type!=="compaction"&&d.messages.some($)&&s.push(r)}if(s.length===0)return{firstKeptEntryIndex:t,turnStartIndex:-1,isSplitTurn:!1};let a=0,i=!1,u=s[0];for(let r=o-1;r>=t;r--){const d=e[r].messages.reduce((T,k)=>T+I(k),0);if(d!==0&&(a+=d,a>=n)){i=!0,u=s.find(T=>T>=r)??s[s.length-1];break}}const f=e.slice(u+1,o),l=m(r=>r.sourceEntry.type!=="context_edit"&&P(r.sourceEntry).length>0,"isIntrinsicallyVisible"),c=m(r=>l(r)&&r.messages.length===0,"isOmitted"),p=new Set(f.filter(c).map(r=>r.sourceEntry.id)),g=f.some(r=>r.sourceEntry.type==="context_edit"&&r.sourceEntry.replacement!==null&&!p.has(r.sourceEntry.targetId));for(i&&!g&&f.some(r=>r.sourceEntry.type==="message"&&r.sourceEntry.message.role==="assistant"&&c(r))&&f.every(r=>r.sourceEntry.type!=="compaction"&&(!l(r)||c(r)))&&u++;u>t;){const r=e[u-1];if(r.sourceEntry.type==="compaction"||r.messages.length>0)break;u--}const y=Z(e[u]),h=y?-1:Te(e,u,t);return{firstKeptEntryIndex:u,turnStartIndex:h,isSplitTurn:!y&&h!==-1}}m(ke,"findProjectedCutPoint");function Fe(e,t){if(e.length>0&&e[e.length-1].type==="compaction")return;const o=ee(e),n=o.entries,s=n.map(d=>d.sourceEntry),a=n.findIndex(d=>d.sourceEntry.type==="compaction"&&d.messages.length>0);let i,u=0;a>=0&&(i=n[a].sourceEntry.summary,u=a+1);const f=n.length,l=le(o,e).tokens,c=ke(n,u,f,t.keepRecentTokens),p=n[c.firstKeptEntryIndex]?.sourceEntry;if(!p?.id)return;const g=p.id,x=c.isSplitTurn?c.turnStartIndex:c.firstKeptEntryIndex,y=n.slice(u,x).flatMap(F),h=c.isSplitTurn?n.slice(c.turnStartIndex,c.firstKeptEntryIndex).flatMap(F):[];if(y.length===0&&h.length===0)return;const r=ce(y,s,a);if(c.isSplitTurn)for(const d of h)_(d,r);return{firstKeptEntryId:g,messagesToSummarize:y,turnPrefixMessages:h,isSplitTurn:c.isSplitTurn,tokensBefore:l,previousSummary:i,fileOps:r,settings:t}}m(Fe,"prepareCompaction");const we=`The messages above are earlier context from an ongoing conversation. Later messages are stored separately and do not need to be reconstructed.
80
95
 
81
96
  Create a concise checkpoint of the user's request and the progress shown above. This checkpoint will be placed before the later messages so the conversation can continue with the necessary context.
82
97
 
@@ -86,17 +101,20 @@ Create a concise checkpoint of the user's request and the progress shown above.
86
101
  ## Progress So Far
87
102
  - [Key decisions and work completed in these messages]
88
103
 
104
+ ## Tracks & Workspace State
105
+ - [Each separate line of work: where it stands, the directory or worktree it happens in, branch, last commit, uncommitted changes, next step; or "(single track)"]
106
+
89
107
  ## Context Needed to Continue
90
- - [Information from these messages needed to understand the later work]
108
+ - [Information from these messages needed to understand the later work: commands that work here (package manager, how tests run), ids, exact error messages]
91
109
 
92
- Only summarize information explicitly present above. Do not infer or recreate later messages.`;async function ze(e,t,o,n,s,i,a,u,l,m,c,d){const{firstKeptEntryId:x,isSplitTurn:y,tokensBefore:T,previousSummary:g,fileOps:r,settings:p}=e,h=p.pruneToolOutputs===!1?I=>I:se,S=h(e.messagesToSummarize),E=h(e.turnPrefixMessages);let k,w;if(y&&E.length>0){let I=g??"No prior history.",M;if(S.length>0){const U=await A(S,t,p.reserveTokens,o,n,i,s,g,a,u,l,m,c,d);I=U.text,M=U.usage}const O=await ke(E,t,p.reserveTokens,o,n,l,i,a,u,m,c,d);k=`${I}
110
+ Only summarize information explicitly present above. Do not infer or recreate later messages.`;async function ze(e,t,o,n,s,a,i,u,f,l,c,p){const{firstKeptEntryId:g,isSplitTurn:x,tokensBefore:y,previousSummary:h,fileOps:r,settings:d}=e,T=d.pruneToolOutputs===!1?E=>E:se,k=T(e.messagesToSummarize),w=T(e.turnPrefixMessages);let S,C;if(x&&w.length>0){let E=h??"No prior history.",M;if(k.length>0){const A=await b(k,t,d.reserveTokens,o,n,a,s,h,i,u,f,l,c,p);E=A.text,M=A.usage}const O=await Se(w,t,d.reserveTokens,o,n,f,a,i,u,l,c,p);S=`${E}
93
111
 
94
112
  ---
95
113
 
96
114
  **Turn Context (split turn):**
97
115
 
98
- ${O.text}`,w=M?ne(M,O.usage):O.usage}else{const I=await A(S,t,p.reserveTokens,o,n,i,s,g,a,u,l,m,c,d);k=I.text,w=I.usage}const{readFiles:v,modifiedFiles:R}=oe(r);if(k+=ie(v,R),!x)throw new Error("First kept entry has no UUID - session may need migration");return{summary:k,firstKeptEntryId:x,tokensBefore:T,usage:w,details:{readFiles:v,modifiedFiles:R}}}f(ze,"compact");async function ke(e,t,o,n,s,i,a,u,l,m,c,d){const x=Math.min(Math.floor(.5*o),t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY),y=N(e),g=`# Conversation
99
- ${D(y)}
116
+ ${O.text}`,C=M?ne(M,O.usage):O.usage}else{const E=await b(k,t,d.reserveTokens,o,n,a,s,h,i,u,f,l,c,p);S=E.text,C=E.usage}const{readFiles:v,modifiedFiles:R}=oe(r);if(S+=ae(v,R),!g)throw new Error("First kept entry has no UUID - session may need migration");return{summary:S,firstKeptEntryId:g,tokensBefore:y,usage:C,details:{readFiles:v,modifiedFiles:R}}}m(ze,"compact");async function Se(e,t,o,n,s,a,i,u,f,l,c,p){const g=Math.min(Math.floor(.5*o),t.maxTokens>0?t.maxTokens:Number.POSITIVE_INFINITY),x=N(e),h=`# Conversation
117
+ ${D(x)}
100
118
 
101
119
  # Instructions
102
- ${Ee}`,r=await W(t,X(g),V(t,x,n,s,i,a,u,d),l,m,c),p=j(r,"Turn prefix summarization");if(p)throw new Error(p);if(r.content.some(h=>h.type==="toolCall"))throw new Error("Turn prefix summarization attempted to call a tool");return{text:b(r.content),usage:r.usage}}f(ke,"generateTurnPrefixSummary");export{Ue as DEFAULT_COMPACTION_SETTINGS,le as MIN_COMPACTION_HEADROOM_TOKENS,z as calculateContextTokens,ze as compact,pe as compactionThreshold,W as completeSummarization,fe as estimateContextTokens,me as estimateProjectedContextTokens,_e as findCutPoint,ge as findTurnStartIndex,De as generateSummary,A as generateSummaryWithUsage,be as getLastAssistantUsage,j as getSummarizationFailure,Fe as prepareCompaction,Ne as shouldCompact};
120
+ ${we}`,r=await V(t,X(h),B(t,g,n,s,a,i,u,p),f,l,c),d=j(r,"Turn prefix summarization");if(d)throw new Error(d);if(r.content.some(T=>T.type==="toolCall"))throw new Error("Turn prefix summarization attempted to call a tool");return{text:U(r.content),usage:r.usage}}m(Se,"generateTurnPrefixSummary");export{Ae as DEFAULT_COMPACTION_SETTINGS,fe as MIN_COMPACTION_HEADROOM_TOKENS,z as calculateContextTokens,ze as compact,de as compactionThreshold,V as completeSummarization,me as estimateContextTokens,le as estimateProjectedContextTokens,_e as findCutPoint,he as findTurnStartIndex,De as generateSummary,b as generateSummaryWithUsage,Ue as getLastAssistantUsage,j as getSummarizationFailure,Fe as prepareCompaction,Ne as shouldCompact};
@@ -75,6 +75,8 @@ export interface PackageManager {
75
75
  }): boolean;
76
76
  setProgressCallback(callback: ProgressCallback | undefined): void;
77
77
  getInstalledPath(source: string, scope: "user" | "project"): string | undefined;
78
+ getRegistryIntegrity(source: string): Promise<string | undefined>;
79
+ getRecordedIntegrity(name: string, scope: "user" | "project"): string | null | undefined;
78
80
  }
79
81
  interface PackageManagerOptions {
80
82
  cwd: string;
@@ -102,6 +104,8 @@ export declare class DefaultPackageManager implements PackageManager {
102
104
  local?: boolean;
103
105
  }): boolean;
104
106
  getInstalledPath(source: string, scope: "user" | "project"): string | undefined;
107
+ getRegistryIntegrity(source: string): Promise<string | undefined>;
108
+ getRecordedIntegrity(name: string, scope: "user" | "project"): string | null | undefined;
105
109
  readDeclaredPermissions(installedPath: string | undefined): string[] | undefined;
106
110
  readGitHead(installedPath: string | undefined): Promise<string | undefined>;
107
111
  private getStoredResolvedCommit;
@@ -1,3 +1,3 @@
1
- var wt=Object.defineProperty;var m=(c,t)=>wt(c,"name",{value:t,configurable:!0});import{createHash as kt}from"node:crypto";import{chmodSync as St,existsSync as f,globSync as vt,mkdirSync as W,readdirSync as x,readFileSync as H,rmSync as I,statSync as N,writeFileSync as z}from"node:fs";import{homedir as Mt}from"node:os";function Y(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{const c=H("/proc/self/environ","utf-8"),t={};for(const e of c.split("\0")){const s=e.indexOf("=");s>0&&(t[e.slice(0,s)]=e.slice(s+1))}return t}catch{return process.env}}m(Y,"getEnv");import{basename as $,dirname as w,join as h,relative as k,resolve as S,sep as U}from"node:path";import G from"ignore";import{minimatch as j}from"minimatch";import{gt as st,maxSatisfying as Ct,rcompare as Nt,satisfies as Et,valid as bt,validRange as Ft}from"semver";import{CONFIG_DIR_NAME as A,isOfficialExtensionsPackage as xt,SHARED_SKILL_CONFIG_DIRS as nt}from"../config.js";import{spawnProcess as rt,spawnProcessSync as It}from"../utils/child-process.js";import{parseGitUrl as jt}from"../utils/git.js";import{isOfflineModeEnabled as b}from"../utils/offline.js";import{canonicalizePath as Rt,isLocalPath as $t,markPathIgnoredByCloudSync as Gt,resolvePath as L}from"../utils/paths.js";import{stripBom as it}from"../utils/text.js";import{isStdoutTakenOver as At}from"./output-guard.js";import{findNearestPiManifest as Dt,readPiManifest as _}from"./pi-manifest.js";import{BUILTIN_PATH_PREFIX as X}from"./source-info.js";const C=1e4,ot=4,Tt=4,Wt=Symbol.for("dalcode.packageManager.npmArgsHook");function Ht(c){return bt(c??"")!==null}m(Ht,"isExactNpmVersion");function Ut(c){return c?Ft(c)??void 0:void 0}m(Ut,"getNpmVersionRange");function at(c){return c.source==="builtin"?5:c.origin==="package"?4:(c.scope==="project"?0:2)+(c.source==="local"?0:1)}m(at,"resourcePrecedenceRank");const O=["extensions","skills","prompts","themes"],Lt={extensions:/\.(ts|js)$/,skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/},_t=[".gitignore",".ignore",".fdignore"];function y(c){return c.split(U).join("/")}m(y,"toPosixPath");function q(){return process.env.HOME||Mt()}m(q,"getHomeDir");function Ot(c){const t=h(c,"tmp","extensions");return W(t,{recursive:!0,mode:448}),St(t,448),t}m(Ot,"getExtensionTempFolder");function Bt(c,t){const e=c.trim();if(!e||e.startsWith("#")&&!e.startsWith("\\#"))return null;let s=c,n=!1;s.startsWith("!")?(n=!0,s=s.slice(1)):s.startsWith("\\!")&&(s=s.slice(1)),s.startsWith("/")&&(s=s.slice(1));const r=t?`${t}${s}`:s;return n?`!${r}`:r}m(Bt,"prefixIgnorePattern");function D(c,t,e){const s=k(e,t),n=s?`${y(s)}/`:"";for(const r of _t){const i=h(t,r);if(f(i))try{const a=H(i,"utf-8").split(/\r?\n/).map(l=>Bt(l,n)).filter(l=>!!l);a.length>0&&c.add(a)}catch{}}}m(D,"addIgnoreRules");function Vt(c){return c.startsWith("!")||c.startsWith("+")||c.startsWith("-")||c.includes("*")||c.includes("?")}m(Vt,"isPattern");function Q(c){return c.startsWith("!")||c.startsWith("+")||c.startsWith("-")}m(Q,"isOverridePattern");function Kt(c){return c.includes("*")||c.includes("?")}m(Kt,"hasGlobPattern");function Jt(c,t){return vt(c,{cwd:t}).map(e=>S(t,e)).filter(e=>k(t,e).split(U).every(s=>s===".."||!s.startsWith("."))).sort((e,s)=>e<s?-1:e>s?1:0)}m(Jt,"expandPackageGlob");function zt(c){const t=[],e=[];for(const s of c)Vt(s)?e.push(s):t.push(s);return{plain:t,patterns:e}}m(zt,"splitPatterns");function ct(c,t,e=!0,s,n){const r=[];if(!f(c))return r;const i=n??c,o=s??G();D(o,c,i);try{const a=x(c,{withFileTypes:!0});for(const l of a){if(l.name.startsWith(".")||e&&l.name==="node_modules")continue;const p=h(c,l.name);let u=l.isDirectory(),g=l.isFile();if(l.isSymbolicLink())try{const F=N(p);u=F.isDirectory(),g=F.isFile()}catch{continue}const P=y(k(i,p)),d=u?`${P}/`:P;o.ignores(d)||(u?r.push(...ct(p,t,e,o,i)):g&&t.test(l.name)&&r.push(p))}}catch{}return r}m(ct,"collectFiles");function Z(c,t,e,s){const n=[];if(!f(c))return n;const r=s??c,i=e??G();D(i,c,r);try{const o=x(c,{withFileTypes:!0});for(const a of o){if(a.name!=="SKILL.md")continue;const l=h(c,a.name);let p=a.isFile();if(a.isSymbolicLink())try{p=N(l).isFile()}catch{continue}const u=y(k(r,l));if(p&&!i.ignores(u))return n.push(l),n}for(const a of o){if(a.name.startsWith(".")||a.name==="node_modules")continue;const l=h(c,a.name);let p=a.isDirectory(),u=a.isFile();if(a.isSymbolicLink())try{const d=N(l);p=d.isDirectory(),u=d.isFile()}catch{continue}const g=y(k(r,l));if(u&&a.name.endsWith(".md")&&!i.ignores(g)&&(t==="pi"&&c===r||t==="agents"&&c!==r)){n.push(l);continue}p&&(i.ignores(`${g}/`)||n.push(...Z(l,t,i,r)))}}catch{}return n}m(Z,"collectSkillEntries");function B(c,t){return Z(c,t)}m(B,"collectAutoSkillEntries");function Yt(c){let t=S(c);for(;;){if(f(h(t,".git")))return t;const e=w(t);if(e===t)return null;t=e}}m(Yt,"findGitRepoRoot");function Xt(c=q()){return nt.map(t=>h(c,t,"skills"))}m(Xt,"userSharedSkillDirs");function qt(c){const t=[],e=S(c),s=Yt(e);let n=e;for(;;){for(const i of nt)t.push(h(n,i,"skills"));if(s&&n===s)break;const r=w(n);if(r===n)break;n=r}return t}m(qt,"collectAncestorAgentsSkillDirs");function lt(c){const t=[];if(!f(c))return t;const e=G();D(e,c,c);try{const s=x(c,{withFileTypes:!0});for(const n of s){if(n.name.startsWith(".")||n.name==="node_modules")continue;const r=h(c,n.name);let i=n.isFile();if(n.isSymbolicLink())try{i=N(r).isFile()}catch{continue}const o=y(k(c,r));e.ignores(o)||i&&n.name.endsWith(".md")&&t.push(r)}}catch{}return t}m(lt,"collectAutoPromptEntries");function ut(c){const t=[];if(!f(c))return t;const e=G();D(e,c,c);try{const s=x(c,{withFileTypes:!0});for(const n of s){if(n.name.startsWith(".")||n.name==="node_modules")continue;const r=h(c,n.name);let i=n.isFile();if(n.isSymbolicLink())try{i=N(r).isFile()}catch{continue}const o=y(k(c,r));e.ignores(o)||i&&n.name.endsWith(".json")&&t.push(r)}}catch{}return t}m(ut,"collectAutoThemeEntries");function pt(c){const t=h(c,"package.json");if(f(t)){const n=_(t);if(n?.extensions?.length){const r=[];for(const i of n.extensions){const o=S(c,i);f(o)&&r.push(o)}if(r.length>0)return r}}const e=h(c,"index.ts"),s=h(c,"index.js");return f(e)?[e]:f(s)?[s]:null}m(pt,"resolveExtensionEntries");function tt(c){const t=[];if(!f(c))return t;const e=pt(c);if(e)return e;const s=G();D(s,c,c);try{const n=x(c,{withFileTypes:!0});for(const r of n){if(r.name.startsWith(".")||r.name==="node_modules")continue;const i=h(c,r.name);let o=r.isDirectory(),a=r.isFile();if(r.isSymbolicLink())try{const u=N(i);o=u.isDirectory(),a=u.isFile()}catch{continue}const l=y(k(c,i)),p=o?`${l}/`:l;if(!s.ignores(p)){if(a&&(r.name.endsWith(".ts")||r.name.endsWith(".js")))t.push(i);else if(o){const u=pt(i);u&&t.push(...u)}}}}catch{}return t}m(tt,"collectAutoExtensionEntries");function V(c,t){return t==="skills"?Z(c,"pi"):t==="extensions"?tt(c):ct(c,Lt[t])}m(V,"collectResourceFiles");function K(c,t,e){const s=y(k(e,c)),n=$(c),r=y(c),i=n==="SKILL.md",o=i?w(c):void 0,a=i?y(k(e,o)):void 0,l=i?$(o):void 0,p=i?y(o):void 0;return t.some(u=>{const g=y(u);return j(s,g)||j(n,g)||j(r,g)?!0:i?j(a,g)||j(l,g)||j(p,g):!1})}m(K,"matchesAnyPattern");function Qt(c){const t=c.startsWith("./")||c.startsWith(".\\")?c.slice(2):c;return y(t)}m(Qt,"normalizeExactPattern");function T(c,t,e){if(t.length===0)return!1;const s=y(k(e,c)),n=$(c),r=y(c),i=n==="SKILL.md",o=i?w(c):void 0,a=i?y(k(e,o)):void 0,l=i?y(o):void 0;return t.some(p=>{const u=Qt(p);return u===s||u===r?!0:i?u===a||u===l:!1})}m(T,"matchesAnyExactPattern");function ht(c){return c.filter(t=>t.startsWith("!")||t.startsWith("+")||t.startsWith("-"))}m(ht,"getOverridePatterns");function ft(c,t,e){const s=ht(t),n=s.filter(a=>a.startsWith("!")).map(a=>a.slice(1)),r=s.filter(a=>a.startsWith("+")).map(a=>a.slice(1)),i=s.filter(a=>a.startsWith("-")).map(a=>a.slice(1));let o=!0;return n.length>0&&K(c,n,e)&&(o=!1),r.length>0&&T(c,r,e)&&(o=!0),i.length>0&&T(c,i,e)&&(o=!1),o}m(ft,"isEnabledByOverrides");function J(c,t,e){const s=[],n=[],r=[],i=[];for(const a of t)a.startsWith("+")?r.push(a.slice(1)):a.startsWith("-")?i.push(a.slice(1)):a.startsWith("!")?n.push(a.slice(1)):s.push(a);let o;if(s.length===0?o=[...c]:o=c.filter(a=>K(a,s,e)),n.length>0&&(o=o.filter(a=>!K(a,n,e))),r.length>0)for(const a of c)!o.includes(a)&&T(a,r,e)&&o.push(a);return i.length>0&&(o=o.filter(a=>!T(a,i,e))),new Set(o)}m(J,"applyPatterns");function mt(c,t,e){const s=new Map;for(const n of t){const r=n.slice(n.startsWith("+")||n.startsWith("-")||n.startsWith("!")?1:0),i=!n.startsWith("-")&&!n.startsWith("!"),o=n.startsWith("+")||n.startsWith("-");for(const a of c)(o?T(a,[r],e):K(a,[r],e))&&s.set(a,i)}return s}m(mt,"applyAutoloadDisabledPatterns");class de{static{m(this,"DefaultPackageManager")}cwd;agentDir;settingsManager;builtinExtensions;globalNpmRoot;globalNpmRootCommandKey;progressCallback;constructor(t){this.cwd=L(t.cwd),this.agentDir=L(t.agentDir),this.settingsManager=t.settingsManager,this.builtinExtensions=t.builtinExtensions??[]}setProgressCallback(t){this.progressCallback=t}addSourceToSettings(t,e){const s=e?.local?"project":"user",r=(s==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],i=this.normalizePackageSourceForSettings(t,s),o=m(p=>{const u=e?.resolvedCommit;return!u&&!p?i:typeof p=="string"||p===void 0?u?{source:i,resolvedCommit:u}:i:u?{...p,source:i,resolvedCommit:u}:{...p,source:i}},"toEntry"),a=r.findIndex(p=>this.packageSourcesMatch(p,t,s));if(a!==-1){const p=r[a];if(this.getPackageSourceString(p)===i&&!e?.resolvedCommit)return!1;const u=[...r];return u[a]=o(p),s==="project"?this.settingsManager.setProjectPackages(u):this.settingsManager.setPackages(u),!0}const l=[...r,o()];return s==="project"?this.settingsManager.setProjectPackages(l):this.settingsManager.setPackages(l),!0}removeSourceFromSettings(t,e){const s=e?.local?"project":"user",r=(s==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],i=r.filter(a=>!this.packageSourcesMatch(a,t,s));return i.length!==r.length?(s==="project"?this.settingsManager.setProjectPackages(i):this.settingsManager.setPackages(i),!0):!1}getInstalledPath(t,e){const s=this.parseSource(t);if(s.type==="npm"){const n=this.getNpmInstallPath(s,e);return f(n)?n:void 0}if(s.type==="git"){const n=this.getGitInstallPath(s,e);return f(n)?n:void 0}if(s.type==="local"){const n=this.getBaseDirForScope(e),r=this.resolvePathFromBase(s.path,n);return f(r)?r:void 0}}readDeclaredPermissions(t){if(!t)return;const s=Dt(t)?.manifest.permissions;return s&&s.length>0?[...s]:void 0}async readGitHead(t){if(t)try{const s=(await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:C})).trim();return/^[0-9a-f]{7,40}$/i.test(s)?s:void 0}catch{return}}getStoredResolvedCommit(t,e){const s=e==="project"?this.settingsManager.getProjectSettings().packages??[]:this.settingsManager.getGlobalSettings().packages??[];for(const n of s)if(typeof n!="string"&&this.packageSourcesMatch(n,t,e))return n.resolvedCommit}emitProgress(t){this.progressCallback?.(t)}async withProgress(t,e,s,n){this.emitProgress({type:"start",action:t,source:e,message:s});try{await n(),this.emitProgress({type:"complete",action:t,source:e})}catch(r){const i=r instanceof Error?r.message:String(r);throw this.emitProgress({type:"error",action:t,source:e,message:i}),r}}async resolve(t){const e=this.createAccumulator(),s=this.settingsManager.getGlobalSettings(),n=this.settingsManager.getProjectSettings(),r=[];for(const l of n.packages??[])r.push({pkg:l,scope:"project"});for(const l of s.packages??[])r.push({pkg:l,scope:"user"});const i=this.dedupePackages(r);await this.resolvePackageSources(i,e,t);const o=this.agentDir,a=h(this.cwd,A);for(const l of O){const p=this.getTargetMap(e,l),u=s[l]??[],g=n[l]??[];this.resolveLocalEntries(g,l,p,{source:"local",scope:"project",origin:"top-level"},a),this.resolveLocalEntries(u,l,p,{source:"local",scope:"user",origin:"top-level"},o)}this.addAutoDiscoveredResources(e,s,n,o,a);for(const l of this.builtinExtensions){const p=`${X}${l}`,u=mt([p],ht(n.extensions??[]),a).get(p);this.addResource(e.extensions,p,{source:"builtin",scope:u===void 0?"user":"project",origin:"top-level"},u??ft(p,s.extensions??[],o))}return this.toResolvedPaths(e)}async resolveExtensionSources(t,e){const s=this.createAccumulator(),n=e?.temporary?"temporary":e?.local?"project":"user";for(const i of t.filter(o=>o.startsWith(X)))this.addResource(s.extensions,i,{source:"builtin",scope:n,origin:"top-level"},!0);const r=t.filter(i=>!i.startsWith(X)).map(i=>({pkg:i,scope:n}));return await this.resolvePackageSources(r,s),this.toResolvedPaths(s)}listConfiguredPackages(){const t=this.settingsManager.getGlobalSettings(),e=this.settingsManager.getProjectSettings(),s=[];for(const n of t.packages??[]){const r=typeof n=="string"?n:n.source,i=this.getInstalledPath(r,"user");s.push({source:r,scope:"user",filtered:typeof n=="object",installedPath:i,resolvedCommit:typeof n=="object"?n.resolvedCommit:void 0,permissions:this.readDeclaredPermissions(i)})}for(const n of e.packages??[]){const r=typeof n=="string"?n:n.source,i=this.getInstalledPath(r,"project");s.push({source:r,scope:"project",filtered:typeof n=="object",installedPath:i,resolvedCommit:typeof n=="object"?n.resolvedCommit:void 0,permissions:this.readDeclaredPermissions(i)})}return s}async install(t,e){const s=this.parseSource(t),n=e?.local?"project":"user";this.assertProjectTrustedForScope(n),await this.withProgress("install",t,`Installing ${t}...`,async()=>{if(s.type==="npm"){await this.installNpm(s,n,!1);return}if(s.type==="git"){await this.installGit(s,n);return}if(s.type==="local"){const r=this.resolvePath(s.path);if(!f(r))throw new Error(`Path does not exist: ${r}`);return}throw new Error(`Unsupported install source: ${t}`)})}async installAndPersist(t,e){await this.install(t,e);const s=e?.local?"project":"user",n=this.getInstalledPath(t,s),r=await this.readGitHead(n);this.addSourceToSettings(t,{...e,resolvedCommit:r})}async remove(t,e){const s=this.parseSource(t),n=e?.local?"project":"user";this.assertProjectTrustedForScope(n),await this.withProgress("remove",t,`Removing ${t}...`,async()=>{if(s.type==="npm"){await this.uninstallNpm(s,n);return}if(s.type==="git"){await this.removeGit(s,n);return}if(s.type!=="local")throw new Error(`Unsupported remove source: ${t}`)})}async removeAndPersist(t,e){return await this.remove(t,e),this.removeSourceFromSettings(t,e)}async update(t,e){const s=e?.latest===!0,n=this.settingsManager.getGlobalSettings(),r=this.settingsManager.getProjectSettings(),i=t?this.getPackageIdentity(t):void 0;let o=!1;const a=[];for(const l of n.packages??[]){const p=typeof l=="string"?l:l.source;i&&this.getPackageIdentity(p,"user")!==i||(o=!0,a.push({source:p,scope:"user"}))}for(const l of r.packages??[]){const p=typeof l=="string"?l:l.source;i&&this.getPackageIdentity(p,"project")!==i||(o=!0,a.push({source:p,scope:"project"}))}if(t&&!o)throw new Error(this.buildNoMatchingPackageMessage(t,[...n.packages??[],...r.packages??[]]));await this.updateConfiguredSources(a,s)}async updateConfiguredSources(t,e=!1){if(b()||t.length===0)return;const s=[],n=[];for(const p of t){const u=this.parseSource(p.source);if(u.type==="npm")u.pinned||s.push({...p,parsed:u});else if(u.type==="git"){const g=this.getStoredResolvedCommit(p.source,p.scope);if(!u.ref&&g&&!e)continue;n.push({...p,parsed:u})}}const r=s.map(p=>async()=>({entry:p,shouldUpdate:await this.shouldUpdateNpmSource(p.parsed,p.scope)})),i=await this.runWithConcurrency(r,ot),o=[],a=[];for(const p of i)p.shouldUpdate&&(p.entry.scope==="user"?o.push(p.entry):a.push(p.entry));const l=[];if(o.length>0&&l.push(this.updateNpmBatch(o,"user")),a.length>0&&l.push(this.updateNpmBatch(a,"project")),n.length>0){const p=n.map(u=>async()=>this.withProgress("update",u.source,`Updating ${u.source}...`,async()=>{if(await this.updateGit(u.parsed,u.scope),!this.getStoredResolvedCommit(u.source,u.scope))return;const P=this.getInstalledPath(u.source,u.scope),d=await this.readGitHead(P);d&&this.addSourceToSettings(u.source,{local:u.scope==="project",resolvedCommit:d})}));l.push(this.runWithConcurrency(p,Tt).then(()=>{}))}await Promise.all(l)}async shouldUpdateNpmSource(t,e){const s=this.getManagedNpmInstallPath(t,e),n=f(s)?this.getInstalledNpmVersion(s):void 0;if(!n)return!0;try{const r=await this.getLatestNpmVersion(t.version?t.spec:t.name,t.range);return st(r,n)}catch{return!0}}async updateNpmBatch(t,e){if(t.length===0)return;const s=t.length===1?t[0].source:`${e} npm packages`,n=t.length===1?`Updating ${t[0].source}...`:`Updating ${e} npm packages...`,r=t.map(i=>i.parsed.version?i.parsed.spec:`${i.parsed.name}@latest`);await this.withProgress("update",s,n,async()=>{await this.installNpmBatch(r,e)})}async installNpmBatch(t,e){const s=this.getNpmInstallRoot(e,!1);this.ensureNpmProject(s),await this.runNpmCommand(this.getNpmInstallArgs(t,s))}async checkForAvailableUpdates(){if(b())return[];const t=this.settingsManager.getGlobalSettings(),e=this.settingsManager.getProjectSettings(),s=[];for(const o of e.packages??[])s.push({pkg:o,scope:"project"});for(const o of t.packages??[])s.push({pkg:o,scope:"user"});const r=this.dedupePackages(s).filter(o=>o.scope!=="temporary").map(o=>async()=>{const a=typeof o.pkg=="string"?o.pkg:o.pkg.source,l=this.parseSource(a);if(l.type==="local"||l.pinned)return;if(l.type==="npm"){const g=this.getNpmInstallPath(l,o.scope);return!f(g)||!await this.npmHasAvailableUpdate(l,g)?void 0:{source:a,displayName:l.name,type:"npm",scope:o.scope}}const p=this.getGitInstallPath(l,o.scope);if(!(!f(p)||!await this.gitHasAvailableUpdate(p)))return{source:a,displayName:`${l.host}/${l.path}`,type:"git",scope:o.scope}});return(await this.runWithConcurrency(r,ot)).filter(o=>o!==void 0)}async resolvePackageSources(t,e,s){for(const{pkg:n,scope:r}of t){const i=typeof n=="string"?n:n.source,o=typeof n=="object"?n:void 0,a=this.findAutoloadDeltaBase(n,r,t),l=a?.source??i,p=a?.scope??r,u=this.parseSource(l),g={source:i,scope:r,origin:"package"};if(u.type==="local"){const d=this.getBaseDirForScope(p);this.resolveLocalExtensionSource(u,e,o,g,d);continue}const P=m(async()=>{if(b())return!1;if(!s)return await this.installParsedSource(u,p),!0;const d=await s(l);if(d==="skip")return!1;if(d==="error")throw new Error(`Missing source: ${l}`);return await this.installParsedSource(u,p),!0},"installMissing");if(u.type==="npm"){let d=this.getNpmInstallPath(u,p);if(!f(d)||!await this.installedNpmMatchesConfiguredVersion(u,d)){if(!await P())continue;d=this.getNpmInstallPath(u,p)}g.baseDir=d,g.packageRoot=d,this.collectPackageResources(d,e,o,g);continue}if(u.type==="git"){const d=this.getGitInstallPath(u,p);if(f(d))p==="temporary"&&!u.pinned&&!b()&&await this.refreshTemporaryGitSource(u,l);else if(!await P())continue;g.baseDir=d,g.packageRoot=d,this.collectPackageResources(d,e,o,g)}}}findAutoloadDeltaBase(t,e,s){if(e!=="project"||typeof t!="object"||t.autoload!==!1)return;const n=this.getPackageIdentity(t.source,e),r=s.find(i=>i.scope==="user"&&this.getPackageIdentity(this.getPackageSourceString(i.pkg),"user")===n);return r?{source:this.getPackageSourceString(r.pkg),scope:"user"}:void 0}resolveLocalExtensionSource(t,e,s,n,r){const i=this.resolvePathFromBase(t.path,r);if(f(i))try{const o=N(i);if(o.isFile()){n.baseDir=w(i),this.addResource(e.extensions,i,n,!0);return}o.isDirectory()&&(n.baseDir=i,n.packageRoot=i,this.collectPackageResources(i,e,s,n)||this.addResource(e.extensions,i,n,!0))}catch{return}}async installParsedSource(t,e){if(t.type==="npm"){await this.installNpm(t,e,e==="temporary");return}if(t.type==="git"){await this.installGit(t,e);return}}getPackageSourceString(t){return typeof t=="string"?t:t.source}getSourceMatchKeyForInput(t){const e=this.parseSource(t);return e.type==="npm"?`npm:${e.name}`:e.type==="git"?`git:${e.host}/${e.path}`:`local:${this.resolvePath(e.path)}`}getSourceMatchKeyForSettings(t,e){const s=this.parseSource(t);if(s.type==="npm")return`npm:${s.name}`;if(s.type==="git")return`git:${s.host}/${s.path}`;const n=this.getBaseDirForScope(e);return`local:${this.resolvePathFromBase(s.path,n)}`}buildNoMatchingPackageMessage(t,e){const s=this.findSuggestedConfiguredSource(t,e);return s?`No matching package found for ${t}. Did you mean ${s}?`:`No matching package found for ${t}`}findSuggestedConfiguredSource(t,e){const s=t.trim(),n=new Set;for(const r of e){const i=this.getPackageSourceString(r),o=this.parseSource(i);if(o.type==="npm"){(s===o.name||s===o.spec)&&n.add(i);continue}if(o.type==="git"){const a=`${o.host}/${o.path}`,l=o.ref?`${a}@${o.ref}`:void 0;(s===a||l&&s===l)&&n.add(i)}}return n.values().next().value}packageSourcesMatch(t,e,s){const n=this.getSourceMatchKeyForSettings(this.getPackageSourceString(t),s),r=this.getSourceMatchKeyForInput(e);return n===r}normalizePackageSourceForSettings(t,e){const s=this.parseSource(t);if(s.type!=="local")return t;const n=this.getBaseDirForScope(e),r=this.resolvePath(s.path);return k(n,r)||"."}parseSource(t){if(t.startsWith("npm:")){const s=t.slice(4).trim(),{name:n,version:r}=this.parseNpmSpec(s);return{type:"npm",spec:s,name:n,version:r,range:Ut(r),pinned:Ht(r)}}if($t(t))return{type:"local",path:t};const e=jt(t);return e||{type:"local",path:t}}async installedNpmMatchesConfiguredVersion(t,e){const s=this.getInstalledNpmVersion(e);return s?t.range?Et(s,t.range):!0:!1}async npmHasAvailableUpdate(t,e){if(b())return!1;const s=this.getInstalledNpmVersion(e);if(!s)return!1;try{const n=await this.getLatestNpmVersion(t.version?t.spec:t.name,t.range);return st(n,s)}catch{return!1}}getInstalledNpmVersion(t){const e=h(t,"package.json");if(f(e))try{const s=H(e,"utf-8");return JSON.parse(it(s)).version}catch{return}}async getLatestNpmVersion(t,e){const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(["view",t,"version","--json"],this.cwd),i=(await this.runCommandCapture(s.command,[...s.args,...n],{cwd:this.cwd,timeoutMs:C})).trim();if(!i)throw new Error("Empty response from npm view");const o=JSON.parse(i);if(typeof o=="string")return o;if(Array.isArray(o)){const a=o.filter(p=>typeof p=="string"&&p.length>0),l=e?Ct(a,e):[...a].sort(Nt)[0];if(l)return l}throw new Error("Unexpected response from npm view")}async gitHasAvailableUpdate(t){if(b())return!1;try{const e=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:C}),s=await this.getRemoteGitHead(t);return e.trim()!==s.trim()}catch{return!1}}async getRemoteGitHead(t){const e=await this.getGitUpstreamRef(t);if(e){const i=(await this.runGitRemoteCommand(t,["ls-remote","origin",e])).match(/^([0-9a-f]{40})\s+/m);if(i?.[1])return i[1]}const n=(await this.runGitRemoteCommand(t,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!n?.[1])throw new Error("Failed to determine remote HEAD");return n[1]}async getLocalGitUpdateTarget(t){try{const s=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:t,timeoutMs:C})).trim();if(!s.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${s}`);const n=s.slice(7);if(!n)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:t,timeoutMs:C}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${n}:refs/remotes/origin/${n}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:t}).catch(()=>{});const e=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:t,timeoutMs:C}),n=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:t,timeoutMs:C}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return n?{ref:"origin/HEAD",head:e,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${n}:refs/remotes/origin/${n}`]}:{ref:"origin/HEAD",head:e,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(t){try{const s=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:t,timeoutMs:C})).trim();if(!s.startsWith("origin/"))return;const n=s.slice(7);return n?`refs/heads/${n}`:void 0}catch{return}}runGitRemoteCommand(t,e){return this.runCommandCapture("git",e,{cwd:t,timeoutMs:C,env:{GIT_TERMINAL_PROMPT:"0"}})}async runWithConcurrency(t,e){if(t.length===0)return[];const s=new Array(t.length);let n=0;const r=Math.max(1,Math.min(e,t.length)),i=m(async()=>{for(;;){const o=n;if(n+=1,o>=t.length)return;s[o]=await t[o]()}},"worker");return await Promise.all(Array.from({length:r},()=>i())),s}getPackageIdentity(t,e){const s=this.parseSource(t);if(s.type==="npm")return`npm:${s.name}`;if(s.type==="git")return`git:${s.host}/${s.path}`;if(e){const n=this.getBaseDirForScope(e);return`local:${this.resolvePathFromBase(s.path,n)}`}return`local:${this.resolvePath(s.path)}`}dedupePackages(t){const e=[],s=new Map;for(const n of t){const r=this.getPackageIdentity(this.getPackageSourceString(n.pkg),n.scope),i=s.get(r);if(i===void 0){s.set(r,e.length),e.push(n);continue}const o=e[i];o?.scope==="project"&&n.scope==="user"?typeof o.pkg=="object"&&o.pkg.autoload===!1&&e.push(n):n.scope==="project"&&(e[i]=n)}return e}parseNpmSpec(t){const e=t.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!e)return{name:t};const s=e[1]??t,n=e[2];return{name:s,version:n}}assertProjectTrustedForScope(t){if(t==="project"&&!this.settingsManager.isProjectTrusted())throw new Error("Project is not trusted; refusing to access project package storage")}getNpmCommand(){const t=this.settingsManager.getNpmCommand();if(!t||t.length===0)return{command:"npm",args:[]};const[e,...s]=t;if(!e)throw new Error("Invalid npmCommand: first array entry must be a non-empty command");return{command:e,args:s}}getPackageManagerName(){const t=this.getNpmCommand(),e=m(o=>$(o).replace(/\.(cmd|exe)$/i,""),"normalizeCommandName"),s=new Set(["npm","pnpm","bun"]),n=e(t.command),r=t.args.lastIndexOf("--");if(r>=0){const o=t.args[r+1];return o?e(o):n}if(s.has(n))return n;const i=[...new Set(t.args.map(e).filter(o=>s.has(o)))];if(i.length>1)throw new Error(`Ambiguous npmCommand package managers: ${i.join(", ")}`);return i[0]??n}async runNpmCommand(t,e){const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(t,e?.cwd);await this.runCommand(s.command,[...s.args,...n],e)}async applyNpmArgsHook(t,e){const s=globalThis[Wt];return typeof s!="function"?t:s(t,{cwd:e,packageManager:this.getPackageManagerName()})}getGitDependencyInstallArgs(){switch(this.getPackageManagerName()){case"bun":return["install","--omit=dev","--omit=peer"];case"pnpm":return["install","--prod","--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"];case"npm":return["install","--omit=dev","--legacy-peer-deps"];default:return["install"]}}runNpmCommandSync(t){const e=this.getNpmCommand();return this.runCommandSync(e.command,[...e.args,...t])}getNpmInstallArgs(t,e){const s=this.getPackageManagerName();return s==="bun"?["install",...t,"--cwd",e,"--omit=peer"]:s==="pnpm"?["install",...t,"--prefix",e,"--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"]:["install",...t,"--prefix",e,"--legacy-peer-deps"]}async installNpm(t,e,s){const n=this.getNpmInstallRoot(e,s);this.ensureNpmProject(n),await this.runNpmCommand(this.getNpmInstallArgs([t.spec],n))}async uninstallNpm(t,e){const s=this.getNpmInstallRoot(e,!1);if(!f(s))return;const n=this.getPackageManagerName();if(n==="bun"){await this.runNpmCommand(["uninstall",t.name,"--cwd",s]);return}const r=["uninstall",t.name,"--prefix",s];n!=="pnpm"&&r.push("--legacy-peer-deps"),await this.runNpmCommand(r)}async installGit(t,e){const s=this.getGitInstallPath(t,e);if(f(s)){if(t.ref){await this.ensureGitRef(s,["fetch","origin",t.ref],"FETCH_HEAD");return}const r=await this.getLocalGitUpdateTarget(s);await this.ensureGitRef(s,r.fetchArgs,r.ref);return}const n=this.getGitInstallRoot(e);n&&this.ensureGitIgnore(n),W(w(s),{recursive:!0}),I(this.getGitUpdateMarkerPath(s),{force:!0});try{await this.runCommand("git",["clone",t.repo,s]),t.ref&&await this.runCommand("git",["checkout",t.ref],{cwd:s});const r=h(s,"package.json");f(r)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:s})}catch(r){throw I(s,{recursive:!0,force:!0}),this.pruneEmptyGitParents(s,n),r}}async updateGit(t,e){const s=this.getGitInstallPath(t,e);if(!f(s)){await this.installGit(t,e);return}if(t.ref){await this.ensureGitRef(s,["fetch","origin",t.ref],"FETCH_HEAD");return}const n=await this.getLocalGitUpdateTarget(s);await this.ensureGitRef(s,n.fetchArgs,n.ref)}hasMissingGitDependencies(t){const e=h(t,"package.json");if(!f(e))return!1;try{const s=JSON.parse(it(H(e,"utf-8")));if(!s.dependencies||typeof s.dependencies!="object"||Array.isArray(s.dependencies))return!1;const n=S(t,"node_modules");return Object.keys(s.dependencies).some(r=>{const i=S(n,r);return i.startsWith(`${n}${U}`)?!f(i):!1})}catch{return!1}}async repairMissingGitDependencies(t){this.hasMissingGitDependencies(t)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:t})}getGitUpdateMarkerPath(t){return h(w(t),`.${$(t)}.pi-update-incomplete`)}async cleanAndInstallGitDependencies(t,e){try{await this.runCommand("git",["clean","-fdx"],{cwd:t})}catch(n){throw await this.repairMissingGitDependencies(t).catch(()=>{}),n}const s=h(t,"package.json");f(s)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:t}),I(e,{force:!0})}async ensureGitRef(t,e,s){await this.runCommand("git",e,{cwd:t});const n=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:C}),r=`${s}^{commit}`,i=await this.runCommandCapture("git",["rev-parse",r],{cwd:t,timeoutMs:C}),o=this.getGitUpdateMarkerPath(t);if(n.trim()===i.trim()){f(o)?await this.cleanAndInstallGitDependencies(t,o):await this.repairMissingGitDependencies(t);return}z(o,"","utf-8"),await this.runCommand("git",["reset","--hard",r],{cwd:t}),await this.cleanAndInstallGitDependencies(t,o)}async refreshTemporaryGitSource(t,e){if(!b())try{await this.withProgress("pull",e,`Refreshing ${e}...`,async()=>{await this.updateGit(t,"temporary")})}catch{}}async removeGit(t,e){const s=this.getGitInstallPath(t,e);I(s,{recursive:!0,force:!0}),I(this.getGitUpdateMarkerPath(s),{force:!0}),this.pruneEmptyGitParents(s,this.getGitInstallRoot(e))}pruneEmptyGitParents(t,e){if(!e)return;const s=S(e);let n=w(t);for(;n.startsWith(s)&&n!==s;){if(!f(n)){n=w(n);continue}if(x(n).length>0)break;try{I(n,{recursive:!0,force:!0})}catch{break}n=w(n)}}ensureNpmProject(t){f(t)||W(t,{recursive:!0}),Gt(t),this.ensureGitIgnore(t);const e=h(t,"package.json");f(e)||z(e,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(t){f(t)||W(t,{recursive:!0});const e=h(t,".gitignore");f(e)||z(e,`*
1
+ var wt=Object.defineProperty;var g=(c,t)=>wt(c,"name",{value:t,configurable:!0});import{createHash as kt}from"node:crypto";import{chmodSync as St,existsSync as f,globSync as vt,mkdirSync as H,readdirSync as x,readFileSync as $,rmSync as j,statSync as N,writeFileSync as z}from"node:fs";import{homedir as Mt}from"node:os";function Y(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{const c=$("/proc/self/environ","utf-8"),t={};for(const e of c.split("\0")){const s=e.indexOf("=");s>0&&(t[e.slice(0,s)]=e.slice(s+1))}return t}catch{return process.env}}g(Y,"getEnv");import{basename as A,dirname as w,join as h,relative as k,resolve as S,sep as U}from"node:path";import G from"ignore";import{minimatch as I}from"minimatch";import{gt as nt,maxSatisfying as Ct,rcompare as Nt,satisfies as Et,valid as bt,validRange as Ft}from"semver";import{CONFIG_DIR_NAME as D,isOfficialExtensionsPackage as xt,SHARED_SKILL_CONFIG_DIRS as rt}from"../config.js";import{spawnProcess as it,spawnProcessSync as jt}from"../utils/child-process.js";import{parseGitUrl as It}from"../utils/git.js";import{isOfflineModeEnabled as b}from"../utils/offline.js";import{canonicalizePath as Rt,isLocalPath as $t,markPathIgnoredByCloudSync as At,resolvePath as _}from"../utils/paths.js";import{stripBom as X}from"../utils/text.js";import{isStdoutTakenOver as Gt}from"./output-guard.js";import{findNearestPiManifest as Dt,readPiManifest as L}from"./pi-manifest.js";import{BUILTIN_PATH_PREFIX as q}from"./source-info.js";const v=1e4,ot=4,Tt=4,Wt=Symbol.for("dalcode.packageManager.npmArgsHook");function Ht(c){return bt(c??"")!==null}g(Ht,"isExactNpmVersion");function Ut(c){return c?Ft(c)??void 0:void 0}g(Ut,"getNpmVersionRange");function at(c){return c.source==="builtin"?5:c.origin==="package"?4:(c.scope==="project"?0:2)+(c.source==="local"?0:1)}g(at,"resourcePrecedenceRank");const O=["extensions","skills","prompts","themes"],_t={extensions:/\.(ts|js)$/,skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/},Lt=[".gitignore",".ignore",".fdignore"];function y(c){return c.split(U).join("/")}g(y,"toPosixPath");function Q(){return process.env.HOME||Mt()}g(Q,"getHomeDir");function Ot(c){const t=h(c,"tmp","extensions");return H(t,{recursive:!0,mode:448}),St(t,448),t}g(Ot,"getExtensionTempFolder");function Bt(c,t){const e=c.trim();if(!e||e.startsWith("#")&&!e.startsWith("\\#"))return null;let s=c,n=!1;s.startsWith("!")?(n=!0,s=s.slice(1)):s.startsWith("\\!")&&(s=s.slice(1)),s.startsWith("/")&&(s=s.slice(1));const r=t?`${t}${s}`:s;return n?`!${r}`:r}g(Bt,"prefixIgnorePattern");function T(c,t,e){const s=k(e,t),n=s?`${y(s)}/`:"";for(const r of Lt){const i=h(t,r);if(f(i))try{const a=$(i,"utf-8").split(/\r?\n/).map(l=>Bt(l,n)).filter(l=>!!l);a.length>0&&c.add(a)}catch{}}}g(T,"addIgnoreRules");function Jt(c){return c.startsWith("!")||c.startsWith("+")||c.startsWith("-")||c.includes("*")||c.includes("?")}g(Jt,"isPattern");function Z(c){return c.startsWith("!")||c.startsWith("+")||c.startsWith("-")}g(Z,"isOverridePattern");function Vt(c){return c.includes("*")||c.includes("?")}g(Vt,"hasGlobPattern");function Kt(c,t){return vt(c,{cwd:t}).map(e=>S(t,e)).filter(e=>k(t,e).split(U).every(s=>s===".."||!s.startsWith("."))).sort((e,s)=>e<s?-1:e>s?1:0)}g(Kt,"expandPackageGlob");function zt(c){const t=[],e=[];for(const s of c)Jt(s)?e.push(s):t.push(s);return{plain:t,patterns:e}}g(zt,"splitPatterns");function ct(c,t,e=!0,s,n){const r=[];if(!f(c))return r;const i=n??c,o=s??G();T(o,c,i);try{const a=x(c,{withFileTypes:!0});for(const l of a){if(l.name.startsWith(".")||e&&l.name==="node_modules")continue;const p=h(c,l.name);let u=l.isDirectory(),m=l.isFile();if(l.isSymbolicLink())try{const F=N(p);u=F.isDirectory(),m=F.isFile()}catch{continue}const P=y(k(i,p)),d=u?`${P}/`:P;o.ignores(d)||(u?r.push(...ct(p,t,e,o,i)):m&&t.test(l.name)&&r.push(p))}}catch{}return r}g(ct,"collectFiles");function tt(c,t,e,s){const n=[];if(!f(c))return n;const r=s??c,i=e??G();T(i,c,r);try{const o=x(c,{withFileTypes:!0});for(const a of o){if(a.name!=="SKILL.md")continue;const l=h(c,a.name);let p=a.isFile();if(a.isSymbolicLink())try{p=N(l).isFile()}catch{continue}const u=y(k(r,l));if(p&&!i.ignores(u))return n.push(l),n}for(const a of o){if(a.name.startsWith(".")||a.name==="node_modules")continue;const l=h(c,a.name);let p=a.isDirectory(),u=a.isFile();if(a.isSymbolicLink())try{const d=N(l);p=d.isDirectory(),u=d.isFile()}catch{continue}const m=y(k(r,l));if(u&&a.name.endsWith(".md")&&!i.ignores(m)&&(t==="pi"&&c===r||t==="agents"&&c!==r)){n.push(l);continue}p&&(i.ignores(`${m}/`)||n.push(...tt(l,t,i,r)))}}catch{}return n}g(tt,"collectSkillEntries");function B(c,t){return tt(c,t)}g(B,"collectAutoSkillEntries");function Yt(c){let t=S(c);for(;;){if(f(h(t,".git")))return t;const e=w(t);if(e===t)return null;t=e}}g(Yt,"findGitRepoRoot");function Xt(c=Q()){return rt.map(t=>h(c,t,"skills"))}g(Xt,"userSharedSkillDirs");function qt(c){const t=[],e=S(c),s=Yt(e);let n=e;for(;;){for(const i of rt)t.push(h(n,i,"skills"));if(s&&n===s)break;const r=w(n);if(r===n)break;n=r}return t}g(qt,"collectAncestorAgentsSkillDirs");function lt(c){const t=[];if(!f(c))return t;const e=G();T(e,c,c);try{const s=x(c,{withFileTypes:!0});for(const n of s){if(n.name.startsWith(".")||n.name==="node_modules")continue;const r=h(c,n.name);let i=n.isFile();if(n.isSymbolicLink())try{i=N(r).isFile()}catch{continue}const o=y(k(c,r));e.ignores(o)||i&&n.name.endsWith(".md")&&t.push(r)}}catch{}return t}g(lt,"collectAutoPromptEntries");function ut(c){const t=[];if(!f(c))return t;const e=G();T(e,c,c);try{const s=x(c,{withFileTypes:!0});for(const n of s){if(n.name.startsWith(".")||n.name==="node_modules")continue;const r=h(c,n.name);let i=n.isFile();if(n.isSymbolicLink())try{i=N(r).isFile()}catch{continue}const o=y(k(c,r));e.ignores(o)||i&&n.name.endsWith(".json")&&t.push(r)}}catch{}return t}g(ut,"collectAutoThemeEntries");function pt(c){const t=h(c,"package.json");if(f(t)){const n=L(t);if(n?.extensions?.length){const r=[];for(const i of n.extensions){const o=S(c,i);f(o)&&r.push(o)}if(r.length>0)return r}}const e=h(c,"index.ts"),s=h(c,"index.js");return f(e)?[e]:f(s)?[s]:null}g(pt,"resolveExtensionEntries");function et(c){const t=[];if(!f(c))return t;const e=pt(c);if(e)return e;const s=G();T(s,c,c);try{const n=x(c,{withFileTypes:!0});for(const r of n){if(r.name.startsWith(".")||r.name==="node_modules")continue;const i=h(c,r.name);let o=r.isDirectory(),a=r.isFile();if(r.isSymbolicLink())try{const u=N(i);o=u.isDirectory(),a=u.isFile()}catch{continue}const l=y(k(c,i)),p=o?`${l}/`:l;if(!s.ignores(p)){if(a&&(r.name.endsWith(".ts")||r.name.endsWith(".js")))t.push(i);else if(o){const u=pt(i);u&&t.push(...u)}}}}catch{}return t}g(et,"collectAutoExtensionEntries");function J(c,t){return t==="skills"?tt(c,"pi"):t==="extensions"?et(c):ct(c,_t[t])}g(J,"collectResourceFiles");function V(c,t,e){const s=y(k(e,c)),n=A(c),r=y(c),i=n==="SKILL.md",o=i?w(c):void 0,a=i?y(k(e,o)):void 0,l=i?A(o):void 0,p=i?y(o):void 0;return t.some(u=>{const m=y(u);return I(s,m)||I(n,m)||I(r,m)?!0:i?I(a,m)||I(l,m)||I(p,m):!1})}g(V,"matchesAnyPattern");function Qt(c){const t=c.startsWith("./")||c.startsWith(".\\")?c.slice(2):c;return y(t)}g(Qt,"normalizeExactPattern");function W(c,t,e){if(t.length===0)return!1;const s=y(k(e,c)),n=A(c),r=y(c),i=n==="SKILL.md",o=i?w(c):void 0,a=i?y(k(e,o)):void 0,l=i?y(o):void 0;return t.some(p=>{const u=Qt(p);return u===s||u===r?!0:i?u===a||u===l:!1})}g(W,"matchesAnyExactPattern");function ht(c){return c.filter(t=>t.startsWith("!")||t.startsWith("+")||t.startsWith("-"))}g(ht,"getOverridePatterns");function ft(c,t,e){const s=ht(t),n=s.filter(a=>a.startsWith("!")).map(a=>a.slice(1)),r=s.filter(a=>a.startsWith("+")).map(a=>a.slice(1)),i=s.filter(a=>a.startsWith("-")).map(a=>a.slice(1));let o=!0;return n.length>0&&V(c,n,e)&&(o=!1),r.length>0&&W(c,r,e)&&(o=!0),i.length>0&&W(c,i,e)&&(o=!1),o}g(ft,"isEnabledByOverrides");function K(c,t,e){const s=[],n=[],r=[],i=[];for(const a of t)a.startsWith("+")?r.push(a.slice(1)):a.startsWith("-")?i.push(a.slice(1)):a.startsWith("!")?n.push(a.slice(1)):s.push(a);let o;if(s.length===0?o=[...c]:o=c.filter(a=>V(a,s,e)),n.length>0&&(o=o.filter(a=>!V(a,n,e))),r.length>0)for(const a of c)!o.includes(a)&&W(a,r,e)&&o.push(a);return i.length>0&&(o=o.filter(a=>!W(a,i,e))),new Set(o)}g(K,"applyPatterns");function gt(c,t,e){const s=new Map;for(const n of t){const r=n.slice(n.startsWith("+")||n.startsWith("-")||n.startsWith("!")?1:0),i=!n.startsWith("-")&&!n.startsWith("!"),o=n.startsWith("+")||n.startsWith("-");for(const a of c)(o?W(a,[r],e):V(a,[r],e))&&s.set(a,i)}return s}g(gt,"applyAutoloadDisabledPatterns");class de{static{g(this,"DefaultPackageManager")}cwd;agentDir;settingsManager;builtinExtensions;globalNpmRoot;globalNpmRootCommandKey;progressCallback;constructor(t){this.cwd=_(t.cwd),this.agentDir=_(t.agentDir),this.settingsManager=t.settingsManager,this.builtinExtensions=t.builtinExtensions??[]}setProgressCallback(t){this.progressCallback=t}addSourceToSettings(t,e){const s=e?.local?"project":"user",r=(s==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],i=this.normalizePackageSourceForSettings(t,s),o=g(p=>{const u=e?.resolvedCommit;return!u&&!p?i:typeof p=="string"||p===void 0?u?{source:i,resolvedCommit:u}:i:u?{...p,source:i,resolvedCommit:u}:{...p,source:i}},"toEntry"),a=r.findIndex(p=>this.packageSourcesMatch(p,t,s));if(a!==-1){const p=r[a];if(this.getPackageSourceString(p)===i&&!e?.resolvedCommit)return!1;const u=[...r];return u[a]=o(p),s==="project"?this.settingsManager.setProjectPackages(u):this.settingsManager.setPackages(u),!0}const l=[...r,o()];return s==="project"?this.settingsManager.setProjectPackages(l):this.settingsManager.setPackages(l),!0}removeSourceFromSettings(t,e){const s=e?.local?"project":"user",r=(s==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],i=r.filter(a=>!this.packageSourcesMatch(a,t,s));return i.length!==r.length?(s==="project"?this.settingsManager.setProjectPackages(i):this.settingsManager.setPackages(i),!0):!1}getInstalledPath(t,e){const s=this.parseSource(t);if(s.type==="npm"){const n=this.getNpmInstallPath(s,e);return f(n)?n:void 0}if(s.type==="git"){const n=this.getGitInstallPath(s,e);return f(n)?n:void 0}if(s.type==="local"){const n=this.getBaseDirForScope(e),r=this.resolvePathFromBase(s.path,n);return f(r)?r:void 0}}async getRegistryIntegrity(t){const e=this.parseSource(t);if(e.type!=="npm"||!e.pinned)return;const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(["view",e.spec,"dist.integrity","--json"],this.cwd),i=(await this.runCommandCapture(s.command,[...s.args,...n],{cwd:this.cwd,timeoutMs:v})).trim();if(!i)return;const o=JSON.parse(i);return typeof o=="string"&&o.length>0?o:void 0}getRecordedIntegrity(t,e){const s=this.getNpmInstallRoot(e,!1),n=h(s,"package-lock.json");if(!f(n))return;let r;try{r=JSON.parse(X($(n,"utf-8")))}catch{return null}if(!r||typeof r!="object")return null;const o=r.packages?.[`node_modules/${t}`];if(!o||typeof o!="object")return null;const a=o.integrity;return typeof a=="string"&&a.length>0?a:null}readDeclaredPermissions(t){if(!t)return;const s=Dt(t)?.manifest.permissions;return s&&s.length>0?[...s]:void 0}async readGitHead(t){if(t)try{const s=(await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:v})).trim();return/^[0-9a-f]{7,40}$/i.test(s)?s:void 0}catch{return}}getStoredResolvedCommit(t,e){const s=e==="project"?this.settingsManager.getProjectSettings().packages??[]:this.settingsManager.getGlobalSettings().packages??[];for(const n of s)if(typeof n!="string"&&this.packageSourcesMatch(n,t,e))return n.resolvedCommit}emitProgress(t){this.progressCallback?.(t)}async withProgress(t,e,s,n){this.emitProgress({type:"start",action:t,source:e,message:s});try{await n(),this.emitProgress({type:"complete",action:t,source:e})}catch(r){const i=r instanceof Error?r.message:String(r);throw this.emitProgress({type:"error",action:t,source:e,message:i}),r}}async resolve(t){const e=this.createAccumulator(),s=this.settingsManager.getGlobalSettings(),n=this.settingsManager.getProjectSettings(),r=[];for(const l of n.packages??[])r.push({pkg:l,scope:"project"});for(const l of s.packages??[])r.push({pkg:l,scope:"user"});const i=this.dedupePackages(r);await this.resolvePackageSources(i,e,t);const o=this.agentDir,a=h(this.cwd,D);for(const l of O){const p=this.getTargetMap(e,l),u=s[l]??[],m=n[l]??[];this.resolveLocalEntries(m,l,p,{source:"local",scope:"project",origin:"top-level"},a),this.resolveLocalEntries(u,l,p,{source:"local",scope:"user",origin:"top-level"},o)}this.addAutoDiscoveredResources(e,s,n,o,a);for(const l of this.builtinExtensions){const p=`${q}${l}`,u=gt([p],ht(n.extensions??[]),a).get(p);this.addResource(e.extensions,p,{source:"builtin",scope:u===void 0?"user":"project",origin:"top-level"},u??ft(p,s.extensions??[],o))}return this.toResolvedPaths(e)}async resolveExtensionSources(t,e){const s=this.createAccumulator(),n=e?.temporary?"temporary":e?.local?"project":"user";for(const i of t.filter(o=>o.startsWith(q)))this.addResource(s.extensions,i,{source:"builtin",scope:n,origin:"top-level"},!0);const r=t.filter(i=>!i.startsWith(q)).map(i=>({pkg:i,scope:n}));return await this.resolvePackageSources(r,s),this.toResolvedPaths(s)}listConfiguredPackages(){const t=this.settingsManager.getGlobalSettings(),e=this.settingsManager.getProjectSettings(),s=[];for(const n of t.packages??[]){const r=typeof n=="string"?n:n.source,i=this.getInstalledPath(r,"user");s.push({source:r,scope:"user",filtered:typeof n=="object",installedPath:i,resolvedCommit:typeof n=="object"?n.resolvedCommit:void 0,permissions:this.readDeclaredPermissions(i)})}for(const n of e.packages??[]){const r=typeof n=="string"?n:n.source,i=this.getInstalledPath(r,"project");s.push({source:r,scope:"project",filtered:typeof n=="object",installedPath:i,resolvedCommit:typeof n=="object"?n.resolvedCommit:void 0,permissions:this.readDeclaredPermissions(i)})}return s}async install(t,e){const s=this.parseSource(t),n=e?.local?"project":"user";this.assertProjectTrustedForScope(n),await this.withProgress("install",t,`Installing ${t}...`,async()=>{if(s.type==="npm"){await this.installNpm(s,n,!1);return}if(s.type==="git"){await this.installGit(s,n);return}if(s.type==="local"){const r=this.resolvePath(s.path);if(!f(r))throw new Error(`Path does not exist: ${r}`);return}throw new Error(`Unsupported install source: ${t}`)})}async installAndPersist(t,e){await this.install(t,e);const s=e?.local?"project":"user",n=this.getInstalledPath(t,s),r=await this.readGitHead(n);this.addSourceToSettings(t,{...e,resolvedCommit:r})}async remove(t,e){const s=this.parseSource(t),n=e?.local?"project":"user";this.assertProjectTrustedForScope(n),await this.withProgress("remove",t,`Removing ${t}...`,async()=>{if(s.type==="npm"){await this.uninstallNpm(s,n);return}if(s.type==="git"){await this.removeGit(s,n);return}if(s.type!=="local")throw new Error(`Unsupported remove source: ${t}`)})}async removeAndPersist(t,e){return await this.remove(t,e),this.removeSourceFromSettings(t,e)}async update(t,e){const s=e?.latest===!0,n=this.settingsManager.getGlobalSettings(),r=this.settingsManager.getProjectSettings(),i=t?this.getPackageIdentity(t):void 0;let o=!1;const a=[];for(const l of n.packages??[]){const p=typeof l=="string"?l:l.source;i&&this.getPackageIdentity(p,"user")!==i||(o=!0,a.push({source:p,scope:"user"}))}for(const l of r.packages??[]){const p=typeof l=="string"?l:l.source;i&&this.getPackageIdentity(p,"project")!==i||(o=!0,a.push({source:p,scope:"project"}))}if(t&&!o)throw new Error(this.buildNoMatchingPackageMessage(t,[...n.packages??[],...r.packages??[]]));await this.updateConfiguredSources(a,s)}async updateConfiguredSources(t,e=!1){if(b()||t.length===0)return;const s=[],n=[];for(const p of t){const u=this.parseSource(p.source);if(u.type==="npm")u.pinned||s.push({...p,parsed:u});else if(u.type==="git"){const m=this.getStoredResolvedCommit(p.source,p.scope);if(!u.ref&&m&&!e)continue;n.push({...p,parsed:u})}}const r=s.map(p=>async()=>({entry:p,shouldUpdate:await this.shouldUpdateNpmSource(p.parsed,p.scope)})),i=await this.runWithConcurrency(r,ot),o=[],a=[];for(const p of i)p.shouldUpdate&&(p.entry.scope==="user"?o.push(p.entry):a.push(p.entry));const l=[];if(o.length>0&&l.push(this.updateNpmBatch(o,"user")),a.length>0&&l.push(this.updateNpmBatch(a,"project")),n.length>0){const p=n.map(u=>async()=>this.withProgress("update",u.source,`Updating ${u.source}...`,async()=>{if(await this.updateGit(u.parsed,u.scope),!this.getStoredResolvedCommit(u.source,u.scope))return;const P=this.getInstalledPath(u.source,u.scope),d=await this.readGitHead(P);d&&this.addSourceToSettings(u.source,{local:u.scope==="project",resolvedCommit:d})}));l.push(this.runWithConcurrency(p,Tt).then(()=>{}))}await Promise.all(l)}async shouldUpdateNpmSource(t,e){const s=this.getManagedNpmInstallPath(t,e),n=f(s)?this.getInstalledNpmVersion(s):void 0;if(!n)return!0;try{const r=await this.getLatestNpmVersion(t.version?t.spec:t.name,t.range);return nt(r,n)}catch{return!0}}async updateNpmBatch(t,e){if(t.length===0)return;const s=t.length===1?t[0].source:`${e} npm packages`,n=t.length===1?`Updating ${t[0].source}...`:`Updating ${e} npm packages...`,r=t.map(i=>i.parsed.version?i.parsed.spec:`${i.parsed.name}@latest`);await this.withProgress("update",s,n,async()=>{await this.installNpmBatch(r,e)})}async installNpmBatch(t,e){const s=this.getNpmInstallRoot(e,!1);this.ensureNpmProject(s),await this.runNpmCommand(this.getNpmInstallArgs(t,s))}async checkForAvailableUpdates(){if(b())return[];const t=this.settingsManager.getGlobalSettings(),e=this.settingsManager.getProjectSettings(),s=[];for(const o of e.packages??[])s.push({pkg:o,scope:"project"});for(const o of t.packages??[])s.push({pkg:o,scope:"user"});const r=this.dedupePackages(s).filter(o=>o.scope!=="temporary").map(o=>async()=>{const a=typeof o.pkg=="string"?o.pkg:o.pkg.source,l=this.parseSource(a);if(l.type==="local"||l.pinned)return;if(l.type==="npm"){const m=this.getNpmInstallPath(l,o.scope);return!f(m)||!await this.npmHasAvailableUpdate(l,m)?void 0:{source:a,displayName:l.name,type:"npm",scope:o.scope}}const p=this.getGitInstallPath(l,o.scope);if(!(!f(p)||!await this.gitHasAvailableUpdate(p)))return{source:a,displayName:`${l.host}/${l.path}`,type:"git",scope:o.scope}});return(await this.runWithConcurrency(r,ot)).filter(o=>o!==void 0)}async resolvePackageSources(t,e,s){for(const{pkg:n,scope:r}of t){const i=typeof n=="string"?n:n.source,o=typeof n=="object"?n:void 0,a=this.findAutoloadDeltaBase(n,r,t),l=a?.source??i,p=a?.scope??r,u=this.parseSource(l),m={source:i,scope:r,origin:"package"};if(u.type==="local"){const d=this.getBaseDirForScope(p);this.resolveLocalExtensionSource(u,e,o,m,d);continue}const P=g(async()=>{if(b())return!1;if(!s)return await this.installParsedSource(u,p),!0;const d=await s(l);if(d==="skip")return!1;if(d==="error")throw new Error(`Missing source: ${l}`);return await this.installParsedSource(u,p),!0},"installMissing");if(u.type==="npm"){let d=this.getNpmInstallPath(u,p);if(!f(d)||!await this.installedNpmMatchesConfiguredVersion(u,d)){if(!await P())continue;d=this.getNpmInstallPath(u,p)}m.baseDir=d,m.packageRoot=d,this.collectPackageResources(d,e,o,m);continue}if(u.type==="git"){const d=this.getGitInstallPath(u,p);if(f(d))p==="temporary"&&!u.pinned&&!b()&&await this.refreshTemporaryGitSource(u,l);else if(!await P())continue;m.baseDir=d,m.packageRoot=d,this.collectPackageResources(d,e,o,m)}}}findAutoloadDeltaBase(t,e,s){if(e!=="project"||typeof t!="object"||t.autoload!==!1)return;const n=this.getPackageIdentity(t.source,e),r=s.find(i=>i.scope==="user"&&this.getPackageIdentity(this.getPackageSourceString(i.pkg),"user")===n);return r?{source:this.getPackageSourceString(r.pkg),scope:"user"}:void 0}resolveLocalExtensionSource(t,e,s,n,r){const i=this.resolvePathFromBase(t.path,r);if(f(i))try{const o=N(i);if(o.isFile()){n.baseDir=w(i),this.addResource(e.extensions,i,n,!0);return}o.isDirectory()&&(n.baseDir=i,n.packageRoot=i,this.collectPackageResources(i,e,s,n)||this.addResource(e.extensions,i,n,!0))}catch{return}}async installParsedSource(t,e){if(t.type==="npm"){await this.installNpm(t,e,e==="temporary");return}if(t.type==="git"){await this.installGit(t,e);return}}getPackageSourceString(t){return typeof t=="string"?t:t.source}getSourceMatchKeyForInput(t){const e=this.parseSource(t);return e.type==="npm"?`npm:${e.name}`:e.type==="git"?`git:${e.host}/${e.path}`:`local:${this.resolvePath(e.path)}`}getSourceMatchKeyForSettings(t,e){const s=this.parseSource(t);if(s.type==="npm")return`npm:${s.name}`;if(s.type==="git")return`git:${s.host}/${s.path}`;const n=this.getBaseDirForScope(e);return`local:${this.resolvePathFromBase(s.path,n)}`}buildNoMatchingPackageMessage(t,e){const s=this.findSuggestedConfiguredSource(t,e);return s?`No matching package found for ${t}. Did you mean ${s}?`:`No matching package found for ${t}`}findSuggestedConfiguredSource(t,e){const s=t.trim(),n=new Set;for(const r of e){const i=this.getPackageSourceString(r),o=this.parseSource(i);if(o.type==="npm"){(s===o.name||s===o.spec)&&n.add(i);continue}if(o.type==="git"){const a=`${o.host}/${o.path}`,l=o.ref?`${a}@${o.ref}`:void 0;(s===a||l&&s===l)&&n.add(i)}}return n.values().next().value}packageSourcesMatch(t,e,s){const n=this.getSourceMatchKeyForSettings(this.getPackageSourceString(t),s),r=this.getSourceMatchKeyForInput(e);return n===r}normalizePackageSourceForSettings(t,e){const s=this.parseSource(t);if(s.type!=="local")return t;const n=this.getBaseDirForScope(e),r=this.resolvePath(s.path);return k(n,r)||"."}parseSource(t){if(t.startsWith("npm:")){const s=t.slice(4).trim(),{name:n,version:r}=this.parseNpmSpec(s);return{type:"npm",spec:s,name:n,version:r,range:Ut(r),pinned:Ht(r)}}if($t(t))return{type:"local",path:t};const e=It(t);return e||{type:"local",path:t}}async installedNpmMatchesConfiguredVersion(t,e){const s=this.getInstalledNpmVersion(e);return s?t.range?Et(s,t.range):!0:!1}async npmHasAvailableUpdate(t,e){if(b())return!1;const s=this.getInstalledNpmVersion(e);if(!s)return!1;try{const n=await this.getLatestNpmVersion(t.version?t.spec:t.name,t.range);return nt(n,s)}catch{return!1}}getInstalledNpmVersion(t){const e=h(t,"package.json");if(f(e))try{const s=$(e,"utf-8");return JSON.parse(X(s)).version}catch{return}}async getLatestNpmVersion(t,e){const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(["view",t,"version","--json"],this.cwd),i=(await this.runCommandCapture(s.command,[...s.args,...n],{cwd:this.cwd,timeoutMs:v})).trim();if(!i)throw new Error("Empty response from npm view");const o=JSON.parse(i);if(typeof o=="string")return o;if(Array.isArray(o)){const a=o.filter(p=>typeof p=="string"&&p.length>0),l=e?Ct(a,e):[...a].sort(Nt)[0];if(l)return l}throw new Error("Unexpected response from npm view")}async gitHasAvailableUpdate(t){if(b())return!1;try{const e=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:v}),s=await this.getRemoteGitHead(t);return e.trim()!==s.trim()}catch{return!1}}async getRemoteGitHead(t){const e=await this.getGitUpstreamRef(t);if(e){const i=(await this.runGitRemoteCommand(t,["ls-remote","origin",e])).match(/^([0-9a-f]{40})\s+/m);if(i?.[1])return i[1]}const n=(await this.runGitRemoteCommand(t,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!n?.[1])throw new Error("Failed to determine remote HEAD");return n[1]}async getLocalGitUpdateTarget(t){try{const s=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:t,timeoutMs:v})).trim();if(!s.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${s}`);const n=s.slice(7);if(!n)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:t,timeoutMs:v}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${n}:refs/remotes/origin/${n}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:t}).catch(()=>{});const e=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:t,timeoutMs:v}),n=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:t,timeoutMs:v}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return n?{ref:"origin/HEAD",head:e,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${n}:refs/remotes/origin/${n}`]}:{ref:"origin/HEAD",head:e,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(t){try{const s=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:t,timeoutMs:v})).trim();if(!s.startsWith("origin/"))return;const n=s.slice(7);return n?`refs/heads/${n}`:void 0}catch{return}}runGitRemoteCommand(t,e){return this.runCommandCapture("git",e,{cwd:t,timeoutMs:v,env:{GIT_TERMINAL_PROMPT:"0"}})}async runWithConcurrency(t,e){if(t.length===0)return[];const s=new Array(t.length);let n=0;const r=Math.max(1,Math.min(e,t.length)),i=g(async()=>{for(;;){const o=n;if(n+=1,o>=t.length)return;s[o]=await t[o]()}},"worker");return await Promise.all(Array.from({length:r},()=>i())),s}getPackageIdentity(t,e){const s=this.parseSource(t);if(s.type==="npm")return`npm:${s.name}`;if(s.type==="git")return`git:${s.host}/${s.path}`;if(e){const n=this.getBaseDirForScope(e);return`local:${this.resolvePathFromBase(s.path,n)}`}return`local:${this.resolvePath(s.path)}`}dedupePackages(t){const e=[],s=new Map;for(const n of t){const r=this.getPackageIdentity(this.getPackageSourceString(n.pkg),n.scope),i=s.get(r);if(i===void 0){s.set(r,e.length),e.push(n);continue}const o=e[i];o?.scope==="project"&&n.scope==="user"?typeof o.pkg=="object"&&o.pkg.autoload===!1&&e.push(n):n.scope==="project"&&(e[i]=n)}return e}parseNpmSpec(t){const e=t.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!e)return{name:t};const s=e[1]??t,n=e[2];return{name:s,version:n}}assertProjectTrustedForScope(t){if(t==="project"&&!this.settingsManager.isProjectTrusted())throw new Error("Project is not trusted; refusing to access project package storage")}getNpmCommand(){const t=this.settingsManager.getNpmCommand();if(!t||t.length===0)return{command:"npm",args:[]};const[e,...s]=t;if(!e)throw new Error("Invalid npmCommand: first array entry must be a non-empty command");return{command:e,args:s}}getPackageManagerName(){const t=this.getNpmCommand(),e=g(o=>A(o).replace(/\.(cmd|exe)$/i,""),"normalizeCommandName"),s=new Set(["npm","pnpm","bun"]),n=e(t.command),r=t.args.lastIndexOf("--");if(r>=0){const o=t.args[r+1];return o?e(o):n}if(s.has(n))return n;const i=[...new Set(t.args.map(e).filter(o=>s.has(o)))];if(i.length>1)throw new Error(`Ambiguous npmCommand package managers: ${i.join(", ")}`);return i[0]??n}async runNpmCommand(t,e){const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(t,e?.cwd);await this.runCommand(s.command,[...s.args,...n],e)}async applyNpmArgsHook(t,e){const s=globalThis[Wt];return typeof s!="function"?t:s(t,{cwd:e,packageManager:this.getPackageManagerName()})}getGitDependencyInstallArgs(){switch(this.getPackageManagerName()){case"bun":return["install","--omit=dev","--omit=peer"];case"pnpm":return["install","--prod","--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"];case"npm":return["install","--omit=dev","--legacy-peer-deps"];default:return["install"]}}runNpmCommandSync(t){const e=this.getNpmCommand();return this.runCommandSync(e.command,[...e.args,...t])}getNpmInstallArgs(t,e){const s=this.getPackageManagerName();return s==="bun"?["install",...t,"--cwd",e,"--omit=peer"]:s==="pnpm"?["install",...t,"--prefix",e,"--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"]:["install",...t,"--prefix",e,"--legacy-peer-deps"]}async installNpm(t,e,s){const n=this.getNpmInstallRoot(e,s);this.ensureNpmProject(n),await this.runNpmCommand(this.getNpmInstallArgs([t.spec],n))}async uninstallNpm(t,e){const s=this.getNpmInstallRoot(e,!1);if(!f(s))return;const n=this.getPackageManagerName();if(n==="bun"){await this.runNpmCommand(["uninstall",t.name,"--cwd",s]);return}const r=["uninstall",t.name,"--prefix",s];n!=="pnpm"&&r.push("--legacy-peer-deps"),await this.runNpmCommand(r)}async installGit(t,e){const s=this.getGitInstallPath(t,e);if(f(s)){if(t.ref){await this.ensureGitRef(s,["fetch","origin",t.ref],"FETCH_HEAD");return}const r=await this.getLocalGitUpdateTarget(s);await this.ensureGitRef(s,r.fetchArgs,r.ref);return}const n=this.getGitInstallRoot(e);n&&this.ensureGitIgnore(n),H(w(s),{recursive:!0}),j(this.getGitUpdateMarkerPath(s),{force:!0});try{await this.runCommand("git",["clone",t.repo,s]),t.ref&&await this.runCommand("git",["checkout",t.ref],{cwd:s});const r=h(s,"package.json");f(r)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:s})}catch(r){throw j(s,{recursive:!0,force:!0}),this.pruneEmptyGitParents(s,n),r}}async updateGit(t,e){const s=this.getGitInstallPath(t,e);if(!f(s)){await this.installGit(t,e);return}if(t.ref){await this.ensureGitRef(s,["fetch","origin",t.ref],"FETCH_HEAD");return}const n=await this.getLocalGitUpdateTarget(s);await this.ensureGitRef(s,n.fetchArgs,n.ref)}hasMissingGitDependencies(t){const e=h(t,"package.json");if(!f(e))return!1;try{const s=JSON.parse(X($(e,"utf-8")));if(!s.dependencies||typeof s.dependencies!="object"||Array.isArray(s.dependencies))return!1;const n=S(t,"node_modules");return Object.keys(s.dependencies).some(r=>{const i=S(n,r);return i.startsWith(`${n}${U}`)?!f(i):!1})}catch{return!1}}async repairMissingGitDependencies(t){this.hasMissingGitDependencies(t)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:t})}getGitUpdateMarkerPath(t){return h(w(t),`.${A(t)}.pi-update-incomplete`)}async cleanAndInstallGitDependencies(t,e){try{await this.runCommand("git",["clean","-fdx"],{cwd:t})}catch(n){throw await this.repairMissingGitDependencies(t).catch(()=>{}),n}const s=h(t,"package.json");f(s)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:t}),j(e,{force:!0})}async ensureGitRef(t,e,s){await this.runCommand("git",e,{cwd:t});const n=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:v}),r=`${s}^{commit}`,i=await this.runCommandCapture("git",["rev-parse",r],{cwd:t,timeoutMs:v}),o=this.getGitUpdateMarkerPath(t);if(n.trim()===i.trim()){f(o)?await this.cleanAndInstallGitDependencies(t,o):await this.repairMissingGitDependencies(t);return}z(o,"","utf-8"),await this.runCommand("git",["reset","--hard",r],{cwd:t}),await this.cleanAndInstallGitDependencies(t,o)}async refreshTemporaryGitSource(t,e){if(!b())try{await this.withProgress("pull",e,`Refreshing ${e}...`,async()=>{await this.updateGit(t,"temporary")})}catch{}}async removeGit(t,e){const s=this.getGitInstallPath(t,e);j(s,{recursive:!0,force:!0}),j(this.getGitUpdateMarkerPath(s),{force:!0}),this.pruneEmptyGitParents(s,this.getGitInstallRoot(e))}pruneEmptyGitParents(t,e){if(!e)return;const s=S(e);let n=w(t);for(;n.startsWith(s)&&n!==s;){if(!f(n)){n=w(n);continue}if(x(n).length>0)break;try{j(n,{recursive:!0,force:!0})}catch{break}n=w(n)}}ensureNpmProject(t){f(t)||H(t,{recursive:!0}),At(t),this.ensureGitIgnore(t);const e=h(t,"package.json");f(e)||z(e,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(t){f(t)||H(t,{recursive:!0});const e=h(t,".gitignore");f(e)||z(e,`*
2
2
  !.gitignore
3
- `,"utf-8")}getNpmInstallRoot(t,e){return e?this.getTemporaryDir("npm"):t==="project"?(this.assertProjectTrustedForScope(t),h(this.cwd,A,"npm")):h(this.agentDir,"npm")}getGlobalNpmRoot(){const t=this.getNpmCommand(),e=[t.command,...t.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===e)return this.globalNpmRoot;if(this.getPackageManagerName()==="bun"){const s=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=h(w(s),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=e,this.globalNpmRoot}getPnpmGlobalPackagePath(t){if(this.getPackageManagerName()!=="pnpm")return;const e=this.runNpmCommandSync(["list","-g","--depth","0","--json"]),s=JSON.parse(e);for(const n of s){const r=n.dependencies?.[t]?.path;if(r)return r}}getManagedNpmInstallPath(t,e){return e==="temporary"?h(this.getTemporaryDir("npm"),"node_modules",t.name):e==="project"?(this.assertProjectTrustedForScope(e),h(this.cwd,A,"npm","node_modules",t.name)):h(this.agentDir,"npm","node_modules",t.name)}getLegacyGlobalNpmInstallPath(t){try{return this.getPnpmGlobalPackagePath(t.name)??h(this.getGlobalNpmRoot(),t.name)}catch{return}}getNpmInstallPath(t,e){const s=this.getManagedNpmInstallPath(t,e);if(e!=="user"||f(s))return s;const n=this.getLegacyGlobalNpmInstallPath(t);return n&&f(n)?n:s}getGitInstallPath(t,e){if(e==="temporary")return this.getTemporaryDir(`git-${t.host}`,t.path,t.ref);const s=this.getGitInstallRoot(e);if(!s)throw new Error("Missing git install root");return this.resolveManagedPath(s,t.host,t.path)}getGitInstallRoot(t){if(t!=="temporary")return t==="project"?(this.assertProjectTrustedForScope(t),h(this.cwd,A,"git")):h(this.agentDir,"git")}getTemporaryDir(t,e,s){const n=this.resolveManagedPath(Ot(this.agentDir),t),r=kt("sha256").update(`${t}-${e??""}${s?`@${s}`:""}`).digest("hex").slice(0,8);return this.resolveManagedPath(n,r,e??"")}resolveManagedPath(t,...e){const s=S(t),n=S(s,...e);if(n!==s&&!n.startsWith(`${s}${U}`))throw new Error(`Refusing to use path outside package install root: ${n}`);return n}getBaseDirForScope(t){return t==="project"?(this.assertProjectTrustedForScope(t),h(this.cwd,A)):t==="user"?this.agentDir:this.cwd}resolvePath(t){return L(t,this.cwd,{homeDir:q(),trim:!0})}resolvePathFromBase(t,e){return L(t,e,{homeDir:q(),trim:!0})}collectPackageResources(t,e,s,n){if(xt(t))return!0;if(s){for(const o of O){const a=s[o],l=this.getTargetMap(e,o);s.autoload===!1?this.applyPackageDeltaFilter(t,a??[],o,l,n):a!==void 0?this.applyPackageFilter(t,a,o,l,n):this.collectDefaultResources(t,o,l,n)}return!0}const r=_(h(t,"package.json"));if(r){for(const o of O){const a=r[o];this.addManifestEntries(a,t,o,this.getTargetMap(e,o),n)}return!0}let i=!1;for(const o of O){const a=h(t,o);if(f(a)){const l=V(a,o);for(const p of l)this.addResource(this.getTargetMap(e,o),p,n,!0);i=!0}}return i}collectDefaultResources(t,e,s,n){const i=_(h(t,"package.json"))?.[e];if(i){this.addManifestEntries(i,t,e,s,n);return}const o=h(t,e);if(f(o)){const a=V(o,e);for(const l of a)this.addResource(s,l,n,!0)}}applyPackageFilter(t,e,s,n,r){const{allFiles:i}=this.collectManifestFiles(t,s);if(e.length===0){for(const a of i)this.addResource(n,a,r,!1);return}const o=J(i,e,t);for(const a of i){const l=o.has(a);this.addResource(n,a,r,l)}}applyPackageDeltaFilter(t,e,s,n,r){if(e.length===0)return;const{allFiles:i}=this.collectManifestFiles(t,s),o=mt(i,e,t);for(const[a,l]of o)this.addResource(n,a,r,l)}collectManifestFiles(t,e){const n=_(h(t,"package.json"))?.[e];if(n&&n.length>0){const o=this.collectFilesFromManifestEntries(n,t,e),a=n.filter(Q),l=a.length>0?J(o,a,t):new Set(o);return{allFiles:Array.from(l),enabledByManifest:l}}const r=h(t,e);if(!f(r))return{allFiles:[],enabledByManifest:new Set};const i=V(r,e);return{allFiles:i,enabledByManifest:new Set(i)}}addManifestEntries(t,e,s,n,r){if(!t)return;const i=this.collectFilesFromManifestEntries(t,e,s),o=t.filter(Q),a=J(i,o,e);for(const l of i)a.has(l)&&this.addResource(n,l,r,!0)}collectFilesFromManifestEntries(t,e,s){const r=t.filter(i=>!Q(i)).flatMap(i=>Kt(i)?Jt(i,e):[S(e,i)]);return this.collectFilesFromPaths(r,s)}resolveLocalEntries(t,e,s,n,r){if(t.length===0)return;const{plain:i,patterns:o}=zt(t),a=i.map(u=>this.resolvePathFromBase(u,r)),l=this.collectFilesFromPaths(a,e),p=J(l,o,r);for(const u of l)this.addResource(s,u,n,p.has(u))}addAutoDiscoveredResources(t,e,s,n,r){const i={source:"auto",scope:"user",origin:"top-level",baseDir:n},o={source:"auto",scope:"project",origin:"top-level",baseDir:r},a={extensions:e.extensions??[],skills:e.skills??[],prompts:e.prompts??[],themes:e.themes??[]},l={extensions:s.extensions??[],skills:s.skills??[],prompts:s.prompts??[],themes:s.themes??[]},p={extensions:h(n,"extensions"),skills:h(n,"skills"),prompts:h(n,"prompts"),themes:h(n,"themes")},u={extensions:h(r,"extensions"),skills:h(r,"skills"),prompts:h(r,"prompts"),themes:h(r,"themes")},g=Xt(),P=new Set(g.map(M=>S(M))),d=this.settingsManager.isProjectTrusted(),F=d?qt(this.cwd).filter(M=>!P.has(S(M))):[],v=m((M,E,R,gt,dt)=>{const yt=this.getTargetMap(t,M);for(const et of E){const Pt=ft(et,gt,dt);this.addResource(yt,et,R,Pt)}},"addResources");d&&(v("extensions",tt(u.extensions),o,l.extensions,r),v("skills",B(u.skills,"pi"),o,l.skills,r));for(const M of F){const E=w(M),R={...o,baseDir:E};v("skills",B(M,"agents"),R,l.skills,E)}d&&(v("prompts",lt(u.prompts),o,l.prompts,r),v("themes",ut(u.themes),o,l.themes,r)),v("extensions",tt(p.extensions),i,a.extensions,n),v("skills",B(p.skills,"pi"),i,a.skills,n);for(const M of g){const E=w(M),R={...i,baseDir:E};v("skills",B(M,"agents"),R,a.skills,E)}v("prompts",lt(p.prompts),i,a.prompts,n),v("themes",ut(p.themes),i,a.themes,n)}collectFilesFromPaths(t,e){const s=[];for(const n of t)if(f(n))try{const r=N(n);r.isFile()?s.push(n):r.isDirectory()&&s.push(...V(n,e))}catch{}return s}getTargetMap(t,e){switch(e){case"extensions":return t.extensions;case"skills":return t.skills;case"prompts":return t.prompts;case"themes":return t.themes;default:throw new Error(`Unknown resource type: ${e}`)}}addResource(t,e,s,n){e&&(t.has(e)||t.set(e,{metadata:s,enabled:n}))}createAccumulator(){return{extensions:new Map,skills:new Map,prompts:new Map,themes:new Map}}toResolvedPaths(t){const e=m(s=>{const n=Array.from(s.entries()).map(([i,{metadata:o,enabled:a}])=>({path:i,enabled:a,metadata:o}));n.sort((i,o)=>at(i.metadata)-at(o.metadata));const r=new Set;return n.filter(i=>{const o=Rt(i.path);return r.has(o)?!1:(r.add(o),!0)})},"mapToResolved");return{extensions:e(t.extensions),skills:e(t.skills),prompts:e(t.prompts),themes:e(t.themes)}}spawnCommand(t,e,s){const n=Y();return rt(t,e,{cwd:s?.cwd,stdio:At()?["ignore",2,2]:"inherit",env:n})}spawnCaptureCommand(t,e,s){const n=Y(),r=s?.env?{...n,...s.env}:n;return rt(t,e,{cwd:s?.cwd,stdio:["ignore","pipe","pipe"],env:r})}runCommandCapture(t,e,s){return new Promise((n,r)=>{const i=this.spawnCaptureCommand(t,e,s);let o="",a="",l=!1;const p=typeof s?.timeoutMs=="number"?setTimeout(()=>{l=!0,i.kill()},s.timeoutMs):void 0;i.stdout?.on("data",u=>{o+=u.toString()}),i.stderr?.on("data",u=>{a+=u.toString()}),i.once("error",u=>{p&&clearTimeout(p),r(u)}),i.once("close",(u,g)=>{if(p&&clearTimeout(p),l){r(new Error(`${t} ${e.join(" ")} timed out after ${s?.timeoutMs}ms`));return}if(u===0){n(o.trim());return}const P=u===null?`signal ${g??"unknown"}`:`code ${u}`;r(new Error(`${t} ${e.join(" ")} failed with ${P}: ${a||o}`))})})}runCommand(t,e,s){return new Promise((n,r)=>{const i=this.spawnCommand(t,e,s);i.on("error",r),i.on("exit",o=>{o===0?n():r(new Error(`${t} ${e.join(" ")} failed with code ${o}`))})})}runCommandSync(t,e){const s=Y(),n=It(t,e,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",env:s});if(n.error||n.status!==0)throw new Error(`Failed to run ${t} ${e.join(" ")}: ${n.error?.message||n.stderr||n.stdout}`);return(n.stdout||n.stderr||"").trim()}}export{de as DefaultPackageManager,Wt as NPM_ARGS_HOOK_SLOT,Ot as getExtensionTempFolder};
3
+ `,"utf-8")}getNpmInstallRoot(t,e){return e?this.getTemporaryDir("npm"):t==="project"?(this.assertProjectTrustedForScope(t),h(this.cwd,D,"npm")):h(this.agentDir,"npm")}getGlobalNpmRoot(){const t=this.getNpmCommand(),e=[t.command,...t.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===e)return this.globalNpmRoot;if(this.getPackageManagerName()==="bun"){const s=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=h(w(s),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=e,this.globalNpmRoot}getPnpmGlobalPackagePath(t){if(this.getPackageManagerName()!=="pnpm")return;const e=this.runNpmCommandSync(["list","-g","--depth","0","--json"]),s=JSON.parse(e);for(const n of s){const r=n.dependencies?.[t]?.path;if(r)return r}}getManagedNpmInstallPath(t,e){return e==="temporary"?h(this.getTemporaryDir("npm"),"node_modules",t.name):e==="project"?(this.assertProjectTrustedForScope(e),h(this.cwd,D,"npm","node_modules",t.name)):h(this.agentDir,"npm","node_modules",t.name)}getLegacyGlobalNpmInstallPath(t){try{return this.getPnpmGlobalPackagePath(t.name)??h(this.getGlobalNpmRoot(),t.name)}catch{return}}getNpmInstallPath(t,e){const s=this.getManagedNpmInstallPath(t,e);if(e!=="user"||f(s))return s;const n=this.getLegacyGlobalNpmInstallPath(t);return n&&f(n)?n:s}getGitInstallPath(t,e){if(e==="temporary")return this.getTemporaryDir(`git-${t.host}`,t.path,t.ref);const s=this.getGitInstallRoot(e);if(!s)throw new Error("Missing git install root");return this.resolveManagedPath(s,t.host,t.path)}getGitInstallRoot(t){if(t!=="temporary")return t==="project"?(this.assertProjectTrustedForScope(t),h(this.cwd,D,"git")):h(this.agentDir,"git")}getTemporaryDir(t,e,s){const n=this.resolveManagedPath(Ot(this.agentDir),t),r=kt("sha256").update(`${t}-${e??""}${s?`@${s}`:""}`).digest("hex").slice(0,8);return this.resolveManagedPath(n,r,e??"")}resolveManagedPath(t,...e){const s=S(t),n=S(s,...e);if(n!==s&&!n.startsWith(`${s}${U}`))throw new Error(`Refusing to use path outside package install root: ${n}`);return n}getBaseDirForScope(t){return t==="project"?(this.assertProjectTrustedForScope(t),h(this.cwd,D)):t==="user"?this.agentDir:this.cwd}resolvePath(t){return _(t,this.cwd,{homeDir:Q(),trim:!0})}resolvePathFromBase(t,e){return _(t,e,{homeDir:Q(),trim:!0})}collectPackageResources(t,e,s,n){if(xt(t))return!0;if(s){for(const o of O){const a=s[o],l=this.getTargetMap(e,o);s.autoload===!1?this.applyPackageDeltaFilter(t,a??[],o,l,n):a!==void 0?this.applyPackageFilter(t,a,o,l,n):this.collectDefaultResources(t,o,l,n)}return!0}const r=L(h(t,"package.json"));if(r){for(const o of O){const a=r[o];this.addManifestEntries(a,t,o,this.getTargetMap(e,o),n)}return!0}let i=!1;for(const o of O){const a=h(t,o);if(f(a)){const l=J(a,o);for(const p of l)this.addResource(this.getTargetMap(e,o),p,n,!0);i=!0}}return i}collectDefaultResources(t,e,s,n){const i=L(h(t,"package.json"))?.[e];if(i){this.addManifestEntries(i,t,e,s,n);return}const o=h(t,e);if(f(o)){const a=J(o,e);for(const l of a)this.addResource(s,l,n,!0)}}applyPackageFilter(t,e,s,n,r){const{allFiles:i}=this.collectManifestFiles(t,s);if(e.length===0){for(const a of i)this.addResource(n,a,r,!1);return}const o=K(i,e,t);for(const a of i){const l=o.has(a);this.addResource(n,a,r,l)}}applyPackageDeltaFilter(t,e,s,n,r){if(e.length===0)return;const{allFiles:i}=this.collectManifestFiles(t,s),o=gt(i,e,t);for(const[a,l]of o)this.addResource(n,a,r,l)}collectManifestFiles(t,e){const n=L(h(t,"package.json"))?.[e];if(n&&n.length>0){const o=this.collectFilesFromManifestEntries(n,t,e),a=n.filter(Z),l=a.length>0?K(o,a,t):new Set(o);return{allFiles:Array.from(l),enabledByManifest:l}}const r=h(t,e);if(!f(r))return{allFiles:[],enabledByManifest:new Set};const i=J(r,e);return{allFiles:i,enabledByManifest:new Set(i)}}addManifestEntries(t,e,s,n,r){if(!t)return;const i=this.collectFilesFromManifestEntries(t,e,s),o=t.filter(Z),a=K(i,o,e);for(const l of i)a.has(l)&&this.addResource(n,l,r,!0)}collectFilesFromManifestEntries(t,e,s){const r=t.filter(i=>!Z(i)).flatMap(i=>Vt(i)?Kt(i,e):[S(e,i)]);return this.collectFilesFromPaths(r,s)}resolveLocalEntries(t,e,s,n,r){if(t.length===0)return;const{plain:i,patterns:o}=zt(t),a=i.map(u=>this.resolvePathFromBase(u,r)),l=this.collectFilesFromPaths(a,e),p=K(l,o,r);for(const u of l)this.addResource(s,u,n,p.has(u))}addAutoDiscoveredResources(t,e,s,n,r){const i={source:"auto",scope:"user",origin:"top-level",baseDir:n},o={source:"auto",scope:"project",origin:"top-level",baseDir:r},a={extensions:e.extensions??[],skills:e.skills??[],prompts:e.prompts??[],themes:e.themes??[]},l={extensions:s.extensions??[],skills:s.skills??[],prompts:s.prompts??[],themes:s.themes??[]},p={extensions:h(n,"extensions"),skills:h(n,"skills"),prompts:h(n,"prompts"),themes:h(n,"themes")},u={extensions:h(r,"extensions"),skills:h(r,"skills"),prompts:h(r,"prompts"),themes:h(r,"themes")},m=Xt(),P=new Set(m.map(C=>S(C))),d=this.settingsManager.isProjectTrusted(),F=d?qt(this.cwd).filter(C=>!P.has(S(C))):[],M=g((C,E,R,mt,dt)=>{const yt=this.getTargetMap(t,C);for(const st of E){const Pt=ft(st,mt,dt);this.addResource(yt,st,R,Pt)}},"addResources");d&&(M("extensions",et(u.extensions),o,l.extensions,r),M("skills",B(u.skills,"pi"),o,l.skills,r));for(const C of F){const E=w(C),R={...o,baseDir:E};M("skills",B(C,"agents"),R,l.skills,E)}d&&(M("prompts",lt(u.prompts),o,l.prompts,r),M("themes",ut(u.themes),o,l.themes,r)),M("extensions",et(p.extensions),i,a.extensions,n),M("skills",B(p.skills,"pi"),i,a.skills,n);for(const C of m){const E=w(C),R={...i,baseDir:E};M("skills",B(C,"agents"),R,a.skills,E)}M("prompts",lt(p.prompts),i,a.prompts,n),M("themes",ut(p.themes),i,a.themes,n)}collectFilesFromPaths(t,e){const s=[];for(const n of t)if(f(n))try{const r=N(n);r.isFile()?s.push(n):r.isDirectory()&&s.push(...J(n,e))}catch{}return s}getTargetMap(t,e){switch(e){case"extensions":return t.extensions;case"skills":return t.skills;case"prompts":return t.prompts;case"themes":return t.themes;default:throw new Error(`Unknown resource type: ${e}`)}}addResource(t,e,s,n){e&&(t.has(e)||t.set(e,{metadata:s,enabled:n}))}createAccumulator(){return{extensions:new Map,skills:new Map,prompts:new Map,themes:new Map}}toResolvedPaths(t){const e=g(s=>{const n=Array.from(s.entries()).map(([i,{metadata:o,enabled:a}])=>({path:i,enabled:a,metadata:o}));n.sort((i,o)=>at(i.metadata)-at(o.metadata));const r=new Set;return n.filter(i=>{const o=Rt(i.path);return r.has(o)?!1:(r.add(o),!0)})},"mapToResolved");return{extensions:e(t.extensions),skills:e(t.skills),prompts:e(t.prompts),themes:e(t.themes)}}spawnCommand(t,e,s){const n=Y();return it(t,e,{cwd:s?.cwd,stdio:Gt()?["ignore",2,2]:"inherit",env:n})}spawnCaptureCommand(t,e,s){const n=Y(),r=s?.env?{...n,...s.env}:n;return it(t,e,{cwd:s?.cwd,stdio:["ignore","pipe","pipe"],env:r})}runCommandCapture(t,e,s){return new Promise((n,r)=>{const i=this.spawnCaptureCommand(t,e,s);let o="",a="",l=!1;const p=typeof s?.timeoutMs=="number"?setTimeout(()=>{l=!0,i.kill()},s.timeoutMs):void 0;i.stdout?.on("data",u=>{o+=u.toString()}),i.stderr?.on("data",u=>{a+=u.toString()}),i.once("error",u=>{p&&clearTimeout(p),r(u)}),i.once("close",(u,m)=>{if(p&&clearTimeout(p),l){r(new Error(`${t} ${e.join(" ")} timed out after ${s?.timeoutMs}ms`));return}if(u===0){n(o.trim());return}const P=u===null?`signal ${m??"unknown"}`:`code ${u}`;r(new Error(`${t} ${e.join(" ")} failed with ${P}: ${a||o}`))})})}runCommand(t,e,s){return new Promise((n,r)=>{const i=this.spawnCommand(t,e,s);i.on("error",r),i.on("exit",o=>{o===0?n():r(new Error(`${t} ${e.join(" ")} failed with code ${o}`))})})}runCommandSync(t,e){const s=Y(),n=jt(t,e,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",env:s});if(n.error||n.status!==0)throw new Error(`Failed to run ${t} ${e.join(" ")}: ${n.error?.message||n.stderr||n.stdout}`);return(n.stdout||n.stderr||"").trim()}}export{de as DefaultPackageManager,Wt as NPM_ARGS_HOOK_SLOT,Ot as getExtensionTempFolder};
@@ -1 +1 @@
1
- var m=Object.defineProperty;var t=(e,n)=>m(e,"name",{value:n,configurable:!0});import{existsSync as h,realpathSync as p}from"node:fs";import{isAbsolute as y,relative as b,resolve as v}from"node:path";import{isReadOnlyBashCommand as R}from"../tools/bash-read-only.js";import{resolveToCwd as k}from"../tools/path-utils.js";import{matchPermissionRules as S,pathPatternMatches as g,readDenyPatterns as w,targetPathOf as x}from"./rules.js";const d=Symbol.for("dal.permissions.askHandlers"),a=globalThis;a[d]instanceof Set||(a[d]=new Set);const c=a[d];function O(e){return c.add(e),()=>{c.delete(e)}}t(O,"registerPermissionAskHandler");function j(){return[...c]}t(j,"permissionAskHandlers");let u;function B(e){u=e}t(B,"setProcessReadGuard");function l(e,n){const r=b(n,e);return r===""||!r.startsWith("..")&&!y(r)}t(l,"isWithin");function f(e){try{return h(e)?p(e):e}catch{return e}}t(f,"realpathOrSelf");function P(e,n=u){if(!n)return;const r=[...new Set([v(e),f(e)])];for(const s of n.deniedPaths){const o=f(s);if(r.some(i=>l(i,s)||l(i,o)))return`Reading ${e} is blocked: it is a protected credential location (${s}). The sandbox keeps it unreadable for every tool.`}for(const{pattern:s,rule:o}of n.deniedPatterns)if(r.some(i=>g(s,i,n.cwd)))return`Reading ${e} is blocked by the permission rule ${o}.`}t(P,"readAccessDenial");const A=new Set(["read","grep","find","ls","lsp"]);function C(e,n){if(A.has(e.toolName)&&n.readGuard){const s=x(e);if(s!==void 0){const o=P(k(s,e.cwd),n.readGuard);if(o)return{behavior:"deny",reason:o}}}const r=S(n.rules,e,R);if(r?.behavior==="deny")return{behavior:"deny",reason:`Blocked by the permission rule ${r.rule} (${r.source==="user"?"~/.dal/agent/settings.json":".dal/settings.json"}).`};if(r?.behavior==="ask")return{behavior:"ask",rule:r.rule,source:r.source}}t(C,"evaluateToolPolicy");function L(e){const n=w(e.rules),r=e.protectedReads??[];if(!(r.length===0&&n.length===0))return{cwd:e.cwd,deniedPaths:r,deniedPatterns:n}}t(L,"buildReadGuard");export{L as buildReadGuard,C as evaluateToolPolicy,j as permissionAskHandlers,P as readAccessDenial,O as registerPermissionAskHandler,B as setProcessReadGuard};
1
+ var m=Object.defineProperty;var t=(e,n)=>m(e,"name",{value:n,configurable:!0});import{existsSync as p,realpathSync as h}from"node:fs";import{isAbsolute as y,relative as b,resolve as v,sep as R}from"node:path";import{isReadOnlyBashCommand as k}from"../tools/bash-read-only.js";import{resolveToCwd as S}from"../tools/path-utils.js";import{matchPermissionRules as g,pathPatternMatches as w,readDenyPatterns as x,targetPathOf as P}from"./rules.js";const d=Symbol.for("dal.permissions.askHandlers"),a=globalThis;a[d]instanceof Set||(a[d]=new Set);const c=a[d];function j(e){return c.add(e),()=>{c.delete(e)}}t(j,"registerPermissionAskHandler");function B(){return[...c]}t(B,"permissionAskHandlers");let u;function C(e){u=e}t(C,"setProcessReadGuard");function l(e,n){const r=b(n,e);return r===""||r!==".."&&!r.startsWith(`..${R}`)&&!y(r)}t(l,"isWithin");function f(e){try{return p(e)?h(e):e}catch{return e}}t(f,"realpathOrSelf");function A(e,n=u){if(!n)return;const r=[...new Set([v(e),f(e)])];for(const s of n.deniedPaths){const o=f(s);if(r.some(i=>l(i,s)||l(i,o)))return`Reading ${e} is blocked: it is a protected credential location (${s}). The sandbox keeps it unreadable for every tool.`}for(const{pattern:s,rule:o}of n.deniedPatterns)if(r.some(i=>w(s,i,n.cwd)))return`Reading ${e} is blocked by the permission rule ${o}.`}t(A,"readAccessDenial");const $=new Set(["read","grep","find","ls","lsp"]);function L(e,n){if($.has(e.toolName)&&n.readGuard){const s=P(e);if(s!==void 0){const o=A(S(s,e.cwd),n.readGuard);if(o)return{behavior:"deny",reason:o}}}const r=g(n.rules,e,k);if(r?.behavior==="deny")return{behavior:"deny",reason:`Blocked by the permission rule ${r.rule} (${r.source==="user"?"~/.dal/agent/settings.json":".dal/settings.json"}).`};if(r?.behavior==="ask")return{behavior:"ask",rule:r.rule,source:r.source}}t(L,"evaluateToolPolicy");function M(e){const n=x(e.rules),r=e.protectedReads??[];if(!(r.length===0&&n.length===0))return{cwd:e.cwd,deniedPaths:r,deniedPatterns:n}}t(M,"buildReadGuard");export{M as buildReadGuard,L as evaluateToolPolicy,B as permissionAskHandlers,A as readAccessDenial,j as registerPermissionAskHandler,C as setProcessReadGuard};
@@ -0,0 +1,16 @@
1
+ export type PackageManagerName = "npm" | "pnpm" | "yarn" | "bun";
2
+ export interface ProjectFacts {
3
+ root: string;
4
+ manager?: PackageManagerName;
5
+ managerSource?: string;
6
+ otherLockfiles: string[];
7
+ testConfigPackages: string[];
8
+ rootTestConfig: boolean;
9
+ }
10
+ export declare function findProjectRoot(cwd: string): string | undefined;
11
+ export declare function detectProjectFacts(cwd: string): ProjectFacts | undefined;
12
+ export declare function projectPackageManager(dir: string): {
13
+ manager: PackageManagerName;
14
+ source: string;
15
+ } | undefined;
16
+ export declare function describeProjectFacts(cwd: string): string | undefined;
@@ -0,0 +1,2 @@
1
+ var b=Object.defineProperty;var o=(n,e)=>b(n,"name",{value:e,configurable:!0});import{existsSync as g,readdirSync as d,readFileSync as k,statSync as F}from"node:fs";import{dirname as M,join as s,relative as T,resolve as y}from"node:path";const u=[{file:"package-lock.json",manager:"npm"},{file:"npm-shrinkwrap.json",manager:"npm"},{file:"pnpm-lock.yaml",manager:"pnpm"},{file:"yarn.lock",manager:"yarn"},{file:"bun.lock",manager:"bun"},{file:"bun.lockb",manager:"bun"}],L=/^(?:vitest|vite|jest)\.config\.(?:[cm]?[jt]s|json)$/,m=12;function h(n){try{const e=JSON.parse(k(n,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}}o(h,"readJson");function j(n){if(typeof n!="string")return;const e=n.split("@")[0];return e==="npm"||e==="pnpm"||e==="yarn"||e==="bun"?e:void 0}o(j,"managerFromField");function $(n){try{return d(n).some(e=>L.test(e))}catch{return!1}}o($,"hasTestConfig");function x(n,e){const r=[],a=e?.workspaces;if(Array.isArray(a))r.push(...a.filter(t=>typeof t=="string"));else if(a&&typeof a=="object"){const t=a.packages;Array.isArray(t)&&r.push(...t.filter(c=>typeof c=="string"))}try{const t=k(s(n,"pnpm-workspace.yaml"),"utf8");for(const c of t.matchAll(/^\s*-\s*['"]?([^'"\n#]+?)['"]?\s*$/gm))r.push(c[1])}catch{}const i=new Set;for(const t of r)if(!t.startsWith("!"))if(t.endsWith("/*")){const c=s(n,t.slice(0,-2));try{for(const p of d(c,{withFileTypes:!0}))p.isDirectory()&&i.add(s(c,p.name))}catch{}}else/[*?]/.test(t)||i.add(s(n,t));return[...i].sort()}o(x,"workspaceDirs");function v(n){return["package.json","pnpm-workspace.yaml",...u.map(e=>e.file)].map(e=>{try{return`${e}:${F(s(n,e)).mtimeMs}`}catch{return`${e}:-`}}).join("|")}o(v,"versionKey");function E(n){let e=y(n);for(;;){if(u.some(a=>g(s(e,a.file)))||j(h(s(e,"package.json"))?.packageManager))return e;if(g(s(e,".git")))return;const r=M(e);if(r===e)return;e=r}}o(E,"findProjectRoot");const w=new Map;function S(n){const e=E(n);if(!e)return;const r=v(e),a=w.get(e);if(a?.key===r)return a.facts;const i=h(s(e,"package.json")),t=u.filter(f=>g(s(e,f.file))),c=j(i?.packageManager),p=c??t[0]?.manager,P=c?"packageManager in package.json":t[0]?.file,A=t.filter(f=>f.manager!==p).map(f=>f.file),C=x(e,i).filter($).map(f=>T(e,f)),l={root:e,...p?{manager:p,managerSource:P}:{},otherLockfiles:A,testConfigPackages:C,rootTestConfig:$(e)};return w.set(e,{key:r,facts:l}),l}o(S,"detectProjectFacts");function O(n){const e=S(n);return e?.manager&&e.managerSource?{manager:e.manager,source:e.managerSource}:void 0}o(O,"projectPackageManager");function _(n){const e=S(n);if(!e)return;const r=[],a=e.root===y(n)?"":` (project root ${e.root.replace(/\\/g,"/")})`;if(e.manager&&r.push(`Package manager: ${e.manager}, from ${e.managerSource}${a}. Install and run scripts with ${e.manager} only.`),e.otherLockfiles.length>0&&r.push(`Also present, not in use: ${e.otherLockfiles.join(", ")}.`),e.testConfigPackages.length>0){const i=e.testConfigPackages.slice(0,m).join(", "),t=e.testConfigPackages.length>m?` and ${e.testConfigPackages.length-m} more`:"";r.push(`Packages with their own test config: ${i}${t}. Run a package's tests from its directory, where its config and setup files apply${e.rootTestConfig?"":"; the root has no test config of its own"}.`)}return r.length>0?r.join(`
2
+ `):void 0}o(_,"describeProjectFacts");export{_ as describeProjectFacts,S as detectProjectFacts,E as findProjectRoot,O as projectPackageManager};
@@ -1 +1 @@
1
- var A=Object.defineProperty;var i=(e,r)=>A(e,"name",{value:r,configurable:!0});import{existsSync as O,readdirSync as C,realpathSync as N}from"node:fs";import{homedir as h}from"node:os";import{isAbsolute as W,join as u,relative as T,resolve as _}from"node:path";import{packageCacheDirs as j}from"./package-managers.js";const B=["read-only","workspace-write","off"],g="DAL_SANDBOX",D={off:0,"workspace-write":1,"read-only":2};function v(e){return typeof e=="string"&&B.includes(e)}i(v,"isSandboxLevel");function I(e,r){return D[r]>D[e]?r:e}i(I,"stricterLevel");function a(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.length>0):[]}i(a,"strings");function f(e){return[...new Set(e)]}i(f,"unique");const P=process.env[g];function z(e={[g]:P}){const r=e[g];if(r)try{const t=JSON.parse(r);return v(t.level)?{level:t.level,allowedDomains:a(t.allowedDomains)}:void 0}catch{return}}i(z,"readSandboxEnvironment");function $(e){return JSON.stringify({level:e.level,allowedDomains:e.network.allowedDomains})}i($,"sandboxEnvironmentValue");function Q(e){const r=e.settings?.global??{},t=e.settings?.project??{},s=z(e.env),l=e.override??{};let o,c;return l.level?(o=l.level,c="override"):s?.level?(o=s.level,c="environment"):v(r.level)?(o=r.level,c="settings"):(o=e.defaultLevel,c="default"),!l.level&&v(t.level)&&I(o,t.level)!==o&&(o=t.level,c="project"),{level:o,levelSource:c,network:{allowedDomains:f([...a(r.network?.allowedDomains),...a(s?.allowedDomains),...a(l.allowedDomains)]),deniedDomains:f([...a(r.network?.deniedDomains),...a(t.network?.deniedDomains)]),allowLocalBinding:r.network?.allowLocalBinding===!0},filesystem:{allowWrite:a(r.filesystem?.allowWrite),denyRead:f([...a(r.filesystem?.denyRead),...a(t.filesystem?.denyRead)]),denyWrite:f([...a(r.filesystem?.denyWrite),...a(t.filesystem?.denyWrite)]),allowRead:a(r.filesystem?.allowRead)}}}i(Q,"resolveSandboxPolicy");const H=[".git/hooks",".git/config",".gitmodules",".dal",".claude",".agents",".mcp.json",".cursor",".vscode",".idea",".env"],M=[".gitconfig",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".config/fish",".dal"],V=[".ssh",".gnupg",".aws",".config/gcloud",".azure",".kube",".docker/config.json",".netrc",".npmrc",".pypirc",".git-credentials",".config/gh","Library/Keychains","Library/Application Support/Google/Chrome","Library/Application Support/Firefox","Library/Safari",".mozilla",".config/google-chrome",".config/chromium",".dal/agent/auth.json"];function m(e,r){return e==="~"?h():e.startsWith("~/")?u(h(),e.slice(2)):W(e)?e:_(r,e)}i(m,"expandPath");function w(e){try{return N(e)}catch{return e}}i(w,"realpathOrSelf");function x(e,r){const t=T(r,e);return t===""||!t.startsWith("..")&&!W(t)}i(x,"isWithin");function U(e,r,t={}){const s=h(),l=e.level==="workspace-write"?f([r,w(r),...e.filesystem.allowWrite.map(n=>m(n,r))]):[],o=e.level==="workspace-write"?t.gitDirs??[]:[],c=(t.extraWrite??[]).map(n=>m(n,r)),k=t.scratchDir?[t.scratchDir,w(t.scratchDir)]:[],E=e.level==="workspace-write"?t.packageCaches??j():[],R=f([...l,...o,...c,...k,...E]),d=[];if(e.level==="read-only"){const n=f([r,w(r)]);c.some(y=>n.some(S=>x(y,S)||x(S,y)))||d.push(...n)}for(const n of[...l,...c]){for(const p of H)d.push(u(n,p));d.push(u(n,".env.*"));for(const p of X(n))d.push(u(n,p))}for(const n of o)d.push(u(n,"hooks"),u(n,"config"));for(const n of M)d.push(u(s,n));d.push(...e.filesystem.denyWrite.map(n=>m(n,r)));const b=new Set(e.filesystem.allowRead.map(n=>m(n,r))),L=[...V.map(n=>u(s,n)).filter(n=>!b.has(n)),...e.filesystem.denyRead.map(n=>m(n,r))];return{allowWrite:R,denyWrite:f(d),denyRead:f(L)}}i(U,"filesystemRules");function X(e){if(!O(e))return[];try{return C(e).filter(r=>r.startsWith(".env."))}catch{return[]}}i(X,"listEnvFiles");function Y(e,r){const t=e.toLowerCase(),s=r.toLowerCase();return s.startsWith("*.")?t.endsWith(s.slice(1)):t===s}i(Y,"domainMatches");function Z(e){const r=e.toLowerCase().replace(/^\[|\]$/g,"");if(r==="localhost"||r.endsWith(".localhost")||r==="::1"||r==="0.0.0.0")return!0;if(r.startsWith("fe80:")||r.startsWith("fc")||r.startsWith("fd"))return r.includes(":");const t=r.split(".").map(o=>Number(o));if(t.length!==4||t.some(o=>!Number.isInteger(o)||o<0||o>255))return!1;const[s,l]=t;return s===127||s===10||s===172&&l>=16&&l<=31||s===192&&l===168||s===169&&l===254}i(Z,"isAlwaysBlockedHost");export{V as PROTECTED_HOME_READS,M as PROTECTED_HOME_WRITES,H as PROTECTED_WRITE_NAMES,g as SANDBOX_ENV,B as SANDBOX_LEVELS,Y as domainMatches,m as expandPath,U as filesystemRules,Z as isAlwaysBlockedHost,v as isSandboxLevel,z as readSandboxEnvironment,Q as resolveSandboxPolicy,$ as sandboxEnvironmentValue,I as stricterLevel};
1
+ var A=Object.defineProperty;var i=(e,r)=>A(e,"name",{value:r,configurable:!0});import{existsSync as O,readdirSync as C,realpathSync as N}from"node:fs";import{homedir as h}from"node:os";import{isAbsolute as W,join as u,relative as T,resolve as _,sep as j}from"node:path";import{packageCacheDirs as B}from"./package-managers.js";const I=["read-only","workspace-write","off"],g="DAL_SANDBOX",D={off:0,"workspace-write":1,"read-only":2};function v(e){return typeof e=="string"&&I.includes(e)}i(v,"isSandboxLevel");function P(e,r){return D[r]>D[e]?r:e}i(P,"stricterLevel");function a(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.length>0):[]}i(a,"strings");function f(e){return[...new Set(e)]}i(f,"unique");const z=process.env[g];function H(e={[g]:z}){const r=e[g];if(r)try{const t=JSON.parse(r);return v(t.level)?{level:t.level,allowedDomains:a(t.allowedDomains)}:void 0}catch{return}}i(H,"readSandboxEnvironment");function Q(e){return JSON.stringify({level:e.level,allowedDomains:e.network.allowedDomains})}i(Q,"sandboxEnvironmentValue");function U(e){const r=e.settings?.global??{},t=e.settings?.project??{},s=H(e.env),l=e.override??{};let o,c;return l.level?(o=l.level,c="override"):s?.level?(o=s.level,c="environment"):v(r.level)?(o=r.level,c="settings"):(o=e.defaultLevel,c="default"),!l.level&&v(t.level)&&P(o,t.level)!==o&&(o=t.level,c="project"),{level:o,levelSource:c,network:{allowedDomains:f([...a(r.network?.allowedDomains),...a(s?.allowedDomains),...a(l.allowedDomains)]),deniedDomains:f([...a(r.network?.deniedDomains),...a(t.network?.deniedDomains)]),allowLocalBinding:r.network?.allowLocalBinding===!0},filesystem:{allowWrite:a(r.filesystem?.allowWrite),denyRead:f([...a(r.filesystem?.denyRead),...a(t.filesystem?.denyRead)]),denyWrite:f([...a(r.filesystem?.denyWrite),...a(t.filesystem?.denyWrite)]),allowRead:a(r.filesystem?.allowRead)}}}i(U,"resolveSandboxPolicy");const M=[".git/hooks",".git/config",".gitmodules",".dal",".claude",".agents",".mcp.json",".cursor",".vscode",".idea",".env"],V=[".gitconfig",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".config/fish",".dal"],X=[".ssh",".gnupg",".aws",".config/gcloud",".azure",".kube",".docker/config.json",".netrc",".npmrc",".pypirc",".git-credentials",".config/gh","Library/Keychains","Library/Application Support/Google/Chrome","Library/Application Support/Firefox","Library/Safari",".mozilla",".config/google-chrome",".config/chromium",".dal/agent/auth.json"];function m(e,r){return e==="~"?h():e.startsWith("~/")?u(h(),e.slice(2)):W(e)?e:_(r,e)}i(m,"expandPath");function w(e){try{return N(e)}catch{return e}}i(w,"realpathOrSelf");function x(e,r){const t=T(r,e);return t===""||t!==".."&&!t.startsWith(`..${j}`)&&!W(t)}i(x,"isWithin");function Y(e,r,t={}){const s=h(),l=e.level==="workspace-write"?f([r,w(r),...e.filesystem.allowWrite.map(n=>m(n,r))]):[],o=e.level==="workspace-write"?t.gitDirs??[]:[],c=(t.extraWrite??[]).map(n=>m(n,r)),k=t.scratchDir?[t.scratchDir,w(t.scratchDir)]:[],E=e.level==="workspace-write"?t.packageCaches??B():[],R=f([...l,...o,...c,...k,...E]),d=[];if(e.level==="read-only"){const n=f([r,w(r)]);c.some(y=>n.some(S=>x(y,S)||x(S,y)))||d.push(...n)}for(const n of[...l,...c]){for(const p of M)d.push(u(n,p));d.push(u(n,".env.*"));for(const p of F(n))d.push(u(n,p))}for(const n of o)d.push(u(n,"hooks"),u(n,"config"));for(const n of V)d.push(u(s,n));d.push(...e.filesystem.denyWrite.map(n=>m(n,r)));const b=new Set(e.filesystem.allowRead.map(n=>m(n,r))),L=[...X.map(n=>u(s,n)).filter(n=>!b.has(n)),...e.filesystem.denyRead.map(n=>m(n,r))];return{allowWrite:R,denyWrite:f(d),denyRead:f(L)}}i(Y,"filesystemRules");function F(e){if(!O(e))return[];try{return C(e).filter(r=>r.startsWith(".env."))}catch{return[]}}i(F,"listEnvFiles");function Z(e,r){const t=e.toLowerCase(),s=r.toLowerCase();return s.startsWith("*.")?t.endsWith(s.slice(1)):t===s}i(Z,"domainMatches");function ee(e){const r=e.toLowerCase().replace(/^\[|\]$/g,"");if(r==="localhost"||r.endsWith(".localhost")||r==="::1"||r==="0.0.0.0")return!0;if(r.startsWith("fe80:")||r.startsWith("fc")||r.startsWith("fd"))return r.includes(":");const t=r.split(".").map(o=>Number(o));if(t.length!==4||t.some(o=>!Number.isInteger(o)||o<0||o>255))return!1;const[s,l]=t;return s===127||s===10||s===172&&l>=16&&l<=31||s===192&&l===168||s===169&&l===254}i(ee,"isAlwaysBlockedHost");export{X as PROTECTED_HOME_READS,V as PROTECTED_HOME_WRITES,M as PROTECTED_WRITE_NAMES,g as SANDBOX_ENV,I as SANDBOX_LEVELS,Z as domainMatches,m as expandPath,Y as filesystemRules,ee as isAlwaysBlockedHost,v as isSandboxLevel,H as readSandboxEnvironment,U as resolveSandboxPolicy,Q as sandboxEnvironmentValue,P as stricterLevel};
@@ -1,4 +1,4 @@
1
- var S=Object.defineProperty;var c=(e,r)=>S(e,"name",{value:r,configurable:!0});import{spawnSync as D}from"node:child_process";import{existsSync as u,mkdtempSync as I,readFileSync as v,rmSync as w,writeFileSync as p}from"node:fs";import{createRequire as y}from"node:module";import{tmpdir as L}from"node:os";import{join as d,win32 as m}from"node:path";const x="DAL_MXC_SDK_DIR",P="0.6.0-alpha",O=/^0\.6\.\d+$/,H=["Allowlisted domains are reached through dal's filtering proxy, handed to mxc as its network proxy; mxc does not enforce per-host allow or block lists on Windows.","A background process that may listen locally gets mxc's local-network access, which also reaches other machines on the private network, not only localhost.","Protected names inside a writable folder (.env, .git/hooks, .vscode, .dal, \u2026) are protected only if they already exist when the command starts; creating a missing one is not blocked.","Protected credential files (~/.ssh, cloud credentials, \u2026) are denied only if they exist when the command starts."];let h;function V(e){h=e}c(V,"setMxcRuntimeForTesting");function E(e){const r=e[x]?.trim();if(r)return u(d(r,"package.json"))?{dir:r}:{error:`${x} is set to ${r}, but there is no package there.`};try{const o=y(import.meta.url);return{dir:d(o.resolve("@microsoft/mxc-sdk/package.json"),"..")}}catch{return{error:`Microsoft eXecution Containers (mxc) is not installed. Install it with \`npm install -g @microsoft/mxc-sdk@0.6.0\`, or set ${x} to an @microsoft/mxc-sdk 0.6 package directory.`}}}c(E,"sdkDirectory");function B(e={}){if(h)return h;const r=e.env??process.env,o=E(r);if("error"in o)return o;let t;try{t=JSON.parse(v(d(o.dir,"package.json"),"utf8")).version??""}catch(n){return{error:`cannot read the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}if(!O.test(t))return{error:`dal supports @microsoft/mxc-sdk 0.6.x, but ${o.dir} is version ${t||"(unknown)"}. Install @microsoft/mxc-sdk@0.6.0.`};const a=(e.arch??process.arch)==="arm64"?"arm64":"x64",s=d(o.dir,"bin",a,"wxc-exec.exe");if(!u(s))return{error:`the mxc SDK at ${o.dir} has no ${a} wxc-exec.exe.`};let i;try{i=y(import.meta.url)(d(o.dir,"dist","index.js"))}catch(n){return{error:`cannot load the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}return{sdkDir:o.dir,sdkVersion:t,wxcExec:s,api:i}}c(B,"loadMxcRuntime");function l(e){return e.replace(/\//g,"\\")}c(l,"toWindowsPath");function f(e){return e.length>0&&!/[\s"]/.test(e)?e:`"${e.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/,"$1$1")}"`}c(f,"quoteWindowsArgument");function g(e){return`'${e.replace(/'/g,"''")}'`}c(g,"powershellQuote");function $(e){return`'${e.replace(/'/g,"'\\''")}'`}c($,"bashQuote");function T(e){const r=m.dirname(e),o=m.dirname(r);return m.basename(r).toLowerCase()==="bin"&&m.basename(o).toLowerCase()==="usr"?m.dirname(o):m.basename(r).toLowerCase()==="bin"?o:r}c(T,"shellInstallRoot");function _(e,r){const o=m.relative(r,e);return o===""||!o.startsWith("..")&&!m.isAbsolute(o)}c(_,"isWithinWindows");function C(e){const r=c(n=>[...new Set(n.map(l))],"unique"),o=r([...e.rules.allowWrite,...e.tools.readwritePaths]),t=e.rules.denyWrite.filter(n=>!/[*?]/.test(n)&&e.exists(n)&&o.some(b=>_(l(n),b))),a=r([...e.tools.readonlyPaths,e.shellRoot,e.runDir,...e.level==="read-only"?[e.cwd]:[],...t]).filter(n=>!o.includes(n)),s=r(e.rules.denyRead.filter(n=>!/[*?]/.test(n)&&e.exists(n))),i=e.proxyPort!==void 0?{proxy:{localhost:e.proxyPort}}:{allowOutbound:!1,allowLocalNetwork:e.allowLocalNetwork};return{version:P,filesystem:{readwritePaths:o,readonlyPaths:a,deniedPaths:s},network:i,ui:{allowWindows:!0,clipboard:"none",allowInputInjection:!1}}}c(C,"windowsSandboxPolicy");function R(e,r){const o={};for(const[s,i]of Object.entries(e))typeof i=="string"&&(o[s]=i);const t=c((s,i)=>{for(const n of Object.keys(o))n.toLowerCase()===s.toLowerCase()&&delete o[n];o[s]=i},"set"),a=l(r.scratchDir);if(t("TMP",a),t("TEMP",a),t("TMPDIR",a),t("DAL_SANDBOX_RUN",r.runId),r.proxyPort!==void 0){const s=`http://127.0.0.1:${r.proxyPort}`;t("HTTP_PROXY",s),t("HTTPS_PROXY",s),o.http_proxy=s,o.https_proxy=s}return Object.entries(o).map(([s,i])=>`${s}=${i}`)}c(R,"windowsSandboxEnvironment");const N="try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}";function W(e,r,o,t){return e==="powershell"?{script:`${N}
1
+ var S=Object.defineProperty;var c=(e,r)=>S(e,"name",{value:r,configurable:!0});import{spawnSync as D}from"node:child_process";import{existsSync as u,mkdtempSync as I,readFileSync as v,rmSync as w,writeFileSync as p}from"node:fs";import{createRequire as y}from"node:module";import{tmpdir as L}from"node:os";import{join as d,win32 as m}from"node:path";const x="DAL_MXC_SDK_DIR",P="0.6.0-alpha",O=/^0\.6\.\d+$/,H=["Allowlisted domains are reached through dal's filtering proxy, handed to mxc as its network proxy; mxc does not enforce per-host allow or block lists on Windows.","A background process that may listen locally gets mxc's local-network access, which also reaches other machines on the private network, not only localhost.","Protected names inside a writable folder (.env, .git/hooks, .vscode, .dal, \u2026) are protected only if they already exist when the command starts; creating a missing one is not blocked.","Protected credential files (~/.ssh, cloud credentials, \u2026) are denied only if they exist when the command starts."];let h;function V(e){h=e}c(V,"setMxcRuntimeForTesting");function E(e){const r=e[x]?.trim();if(r)return u(d(r,"package.json"))?{dir:r}:{error:`${x} is set to ${r}, but there is no package there.`};try{const o=y(import.meta.url);return{dir:d(o.resolve("@microsoft/mxc-sdk/package.json"),"..")}}catch{return{error:`Microsoft eXecution Containers (mxc) is not installed. Install it with \`npm install -g @microsoft/mxc-sdk@0.6.0\`, or set ${x} to an @microsoft/mxc-sdk 0.6 package directory.`}}}c(E,"sdkDirectory");function B(e={}){if(h)return h;const r=e.env??process.env,o=E(r);if("error"in o)return o;let t;try{t=JSON.parse(v(d(o.dir,"package.json"),"utf8")).version??""}catch(n){return{error:`cannot read the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}if(!O.test(t))return{error:`dal supports @microsoft/mxc-sdk 0.6.x, but ${o.dir} is version ${t||"(unknown)"}. Install @microsoft/mxc-sdk@0.6.0.`};const a=(e.arch??process.arch)==="arm64"?"arm64":"x64",s=d(o.dir,"bin",a,"wxc-exec.exe");if(!u(s))return{error:`the mxc SDK at ${o.dir} has no ${a} wxc-exec.exe.`};let i;try{i=y(import.meta.url)(d(o.dir,"dist","index.js"))}catch(n){return{error:`cannot load the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}return{sdkDir:o.dir,sdkVersion:t,wxcExec:s,api:i}}c(B,"loadMxcRuntime");function l(e){return e.replace(/\//g,"\\")}c(l,"toWindowsPath");function f(e){return e.length>0&&!/[\s"]/.test(e)?e:`"${e.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/,"$1$1")}"`}c(f,"quoteWindowsArgument");function g(e){return`'${e.replace(/'/g,"''")}'`}c(g,"powershellQuote");function $(e){return`'${e.replace(/'/g,"'\\''")}'`}c($,"bashQuote");function T(e){const r=m.dirname(e),o=m.dirname(r);return m.basename(r).toLowerCase()==="bin"&&m.basename(o).toLowerCase()==="usr"?m.dirname(o):m.basename(r).toLowerCase()==="bin"?o:r}c(T,"shellInstallRoot");function _(e,r){const o=m.relative(r,e);return o===""||o!==".."&&!o.startsWith("..\\")&&!m.isAbsolute(o)}c(_,"isWithinWindows");function C(e){const r=c(n=>[...new Set(n.map(l))],"unique"),o=r([...e.rules.allowWrite,...e.tools.readwritePaths]),t=e.rules.denyWrite.filter(n=>!/[*?]/.test(n)&&e.exists(n)&&o.some(b=>_(l(n),b))),a=r([...e.tools.readonlyPaths,e.shellRoot,e.runDir,...e.level==="read-only"?[e.cwd]:[],...t]).filter(n=>!o.includes(n)),s=r(e.rules.denyRead.filter(n=>!/[*?]/.test(n)&&e.exists(n))),i=e.proxyPort!==void 0?{proxy:{localhost:e.proxyPort}}:{allowOutbound:!1,allowLocalNetwork:e.allowLocalNetwork};return{version:P,filesystem:{readwritePaths:o,readonlyPaths:a,deniedPaths:s},network:i,ui:{allowWindows:!0,clipboard:"none",allowInputInjection:!1}}}c(C,"windowsSandboxPolicy");function R(e,r){const o={};for(const[s,i]of Object.entries(e))typeof i=="string"&&(o[s]=i);const t=c((s,i)=>{for(const n of Object.keys(o))n.toLowerCase()===s.toLowerCase()&&delete o[n];o[s]=i},"set"),a=l(r.scratchDir);if(t("TMP",a),t("TEMP",a),t("TMPDIR",a),t("DAL_SANDBOX_RUN",r.runId),r.proxyPort!==void 0){const s=`http://127.0.0.1:${r.proxyPort}`;t("HTTP_PROXY",s),t("HTTPS_PROXY",s),o.http_proxy=s,o.https_proxy=s}return Object.entries(o).map(([s,i])=>`${s}=${i}`)}c(R,"windowsSandboxEnvironment");const N="try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}";function W(e,r,o,t){return e==="powershell"?{script:`${N}
2
2
  ${o}
3
3
  if (-not $?) { if ($LASTEXITCODE) { exit $LASTEXITCODE } else { exit 1 } }
4
4
  `,commandLine:[f(r),"-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",f(t)].join(" ")}:{script:`${o}
@@ -2,6 +2,7 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import { type AssistantMessage, type ImageContent, type Message, type SystemMessage, type TextContent, type ToolResultMessage, type Usage, type UserMessage } from "@earendil-works/pi-ai";
3
3
  import { type BashExecutionMessage, type CustomMessage } from "./messages.ts";
4
4
  export declare const CURRENT_SESSION_VERSION = 3;
5
+ export declare function isNewerSessionFormat(header: Pick<SessionHeader, "version"> | undefined): boolean;
5
6
  export interface SessionHeader {
6
7
  type: "session";
7
8
  version?: number;
@@ -150,6 +151,7 @@ export declare class SessionManager {
150
151
  private cwd;
151
152
  private persist;
152
153
  private flushed;
154
+ private newerFormat;
153
155
  private fileEntries;
154
156
  private byId;
155
157
  private labelsById;
@@ -163,6 +165,7 @@ export declare class SessionManager {
163
165
  private _buildIndex;
164
166
  private _rewriteFile;
165
167
  isPersisted(): boolean;
168
+ isReadOnly(): boolean;
166
169
  getCwd(): string;
167
170
  getSessionDir(): string;
168
171
  usesDefaultSessionDir(): boolean;