alchemylab-opencode 1.0.26 → 2.0.0

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 (123) hide show
  1. package/NODE_COMPAT.md +23 -174
  2. package/dist/20260127222353_familiar_lady_ursula-KV747FJX.js +14 -0
  3. package/dist/{chunk-LTCXIXYM.js → 20260211171708_add_project_commands-GDOHPDPF.js} +3 -1
  4. package/dist/20260213144116_wakeful_the_professor-ZVDD54AK.js +14 -0
  5. package/dist/20260225215848_workspace-ZMSOZSPA.js +14 -0
  6. package/dist/20260227213759_add_session_workspace_id-ROENWPKA.js +14 -0
  7. package/dist/20260228203230_blue_harpoon-IW3Z4TQZ.js +14 -0
  8. package/dist/20260303231226_add_workspace_fields-OUVZMNAG.js +14 -0
  9. package/dist/20260309230000_move_org_to_state-NOXAPU5V.js +14 -0
  10. package/dist/20260312043431_session_message_cursor-DJ4T3T4R.js +14 -0
  11. package/dist/20260323234822_events-72GIKJ2A.js +14 -0
  12. package/dist/20260410174513_workspace-name-JXSWFBJN.js +14 -0
  13. package/dist/20260413175956_chief_energizer-4HEWZ6U3.js +14 -0
  14. package/dist/20260423070820_add_icon_url_override-X5SHFGTI.js +14 -0
  15. package/dist/20260427172553_slow_nightmare-PS5T2AH2.js +14 -0
  16. package/dist/{chunk-PWFRMDDF.js → 20260428004200_add_session_path-LGW75WYA.js} +3 -0
  17. package/dist/{valibot--1zFm7rT-FSYJNYJ6.js → 20260501142318_next_venus-J3TLVXZ6.js} +3 -1
  18. package/dist/20260504145000_add_sync_owner-3R52GB4C.js +14 -0
  19. package/dist/20260507164347_add_workspace_time-JHDRCZAR.js +14 -0
  20. package/dist/20260510033149_session_usage-UGBVOXZB.js +53 -0
  21. package/dist/20260511000411_data_migration_state-FB4LBFSE.js +14 -0
  22. package/dist/20260511173437_session-metadata-T2XHGWHS.js +14 -0
  23. package/dist/20260601010001_normalize_storage_paths-5MAY5GT3.js +14 -0
  24. package/dist/{chunk-YRY5Y3QL.js → 20260601202201_amazing_prowler-PET224YG.js} +3 -1
  25. package/dist/20260602002951_lowly_union_jack-PG6XDMGL.js +14 -0
  26. package/dist/20260602182828_add_project_directories-ZCH2ACGG.js +14 -0
  27. package/dist/20260603001617_session_message_projection_indexes-XVLJTUF2.js +14 -0
  28. package/dist/20260603040000_session_message_projection_order-XG6RACZQ.js +14 -0
  29. package/dist/20260603141458_session_input_inbox-K2VQ7V6E.js +14 -0
  30. package/dist/20260603160727_jittery_ezekiel_stane-WKJLRDO7.js +14 -0
  31. package/dist/20260604172448_event_sourced_session_input-NTXOECR7.js +14 -0
  32. package/dist/20260605003541_add_session_context_snapshot-DXMQEXMT.js +14 -0
  33. package/dist/{zod-Bwrt9trS-HVDOFWRP.js → 20260605042240_add_context_epoch_agent-W6IQYZXE.js} +3 -1
  34. package/dist/20260611035744_credential-XTMSYTJD.js +14 -0
  35. package/dist/20260611192811_lush_chimera-XPLIQMJD.js +14 -0
  36. package/dist/20260612174303_project_dir_strategy-FR2NGQKK.js +14 -0
  37. package/dist/20260622142730_simplify_session_context_epoch-NTQZR3RE.js +14 -0
  38. package/dist/20260622170816_reset_v2_session_state-5JPHJTZG.js +14 -0
  39. package/dist/20260622202450_simplify_session_input-2EXF2HMV.js +14 -0
  40. package/dist/app-runtime-6NGO2HRS.js +14 -0
  41. package/dist/chunk-4K2RXRZL.js +14 -0
  42. package/dist/chunk-BM2C7NHL.js +41 -0
  43. package/dist/chunk-E47SMIVL.js +186 -0
  44. package/dist/chunk-OMDJ6ZZ2.js +684 -0
  45. package/dist/chunk-PLQOF3WF.js +393 -0
  46. package/dist/chunk-QRABYJKL.js +14 -0
  47. package/dist/chunk-RHIWAYN5.js +14 -0
  48. package/dist/{arktype-aI7TBD0R-TFNARRIP.js → chunk-VURLSDCB.js} +3 -1
  49. package/dist/chunk-Z5TLIUAI.js +28 -0
  50. package/dist/chunk-ZMHNE2MU.js +865 -0
  51. package/dist/chunk-ZWLTE2TM.js +1455 -0
  52. package/dist/code-mode-YFX4N2VN.js +40 -0
  53. package/dist/copilot-provider-TX4YFKJZ.js +14 -0
  54. package/dist/photon-VQS5F5BI.js +14 -0
  55. package/dist/pty.node-Y3N2XKYG.js +14 -0
  56. package/dist/run.js +3 -1
  57. package/dist/serve.js +3 -1
  58. package/dist/server-TI57TGPO.js +17 -0
  59. package/dist/session-6RNXZNG6.js +14 -0
  60. package/dist/{chunk-2ANK3QEN.js → worktree-3RZQEGVC.js} +3 -1
  61. package/package.json +83 -50
  62. package/patches/@ai-sdk%2Famazon-bedrock@4.0.166.patch +164 -0
  63. package/patches/@ai-sdk%2Fanthropic@3.0.111.patch +528 -0
  64. package/patches/@ai-sdk%2Fgoogle@3.0.73.patch +69 -0
  65. package/patches/@ai-sdk%2Fgroq@3.0.31.patch +79 -0
  66. package/patches/@ai-sdk%2Fmistral@3.0.51.patch +714 -0
  67. package/patches/@ai-sdk%2Fopenai-compatible@2.0.41.patch +39 -0
  68. package/patches/@ai-sdk%2Fopenai@3.0.88.patch +280 -0
  69. package/patches/@ai-sdk%2Fxai@3.0.139.patch +296 -0
  70. package/patches/@modelcontextprotocol%2Fsdk@1.29.0.patch +647 -0
  71. package/patches/@npmcli%2Fagent@4.0.2.patch +13 -0
  72. package/patches/@silvia-odwyer%2Fphoton-node@0.3.4.patch +285 -0
  73. package/patches/effect@4.0.0-beta.83.patch +57 -0
  74. package/patches/gcp-metadata@8.1.2.patch +14 -0
  75. package/patches/pacote@21.5.0.patch +18 -0
  76. package/postinstall.cjs +146 -0
  77. package/dist/chunk-5P5WLADX.js +0 -18
  78. package/dist/chunk-7KKA6WBY.js +0 -12
  79. package/dist/chunk-A7EXZZPC.js +0 -12
  80. package/dist/chunk-CZVKIDQZ.js +0 -12
  81. package/dist/chunk-FXLFZ5DL.js +0 -12
  82. package/dist/chunk-G752V4OP.js +0 -2187
  83. package/dist/chunk-GBXMNWYD.js +0 -18
  84. package/dist/chunk-IR6PDN4W.js +0 -13
  85. package/dist/chunk-M4CB72HE.js +0 -13
  86. package/dist/chunk-MBZTOEAD.js +0 -12
  87. package/dist/default-u_dwuiYb-652AQZKX.js +0 -12
  88. package/dist/effect-QlVUlMFu-JVYEXAZL.js +0 -12
  89. package/dist/log-MVJ7H4K5.js +0 -12
  90. package/dist/pty.node-X2EITEZ4.js +0 -12
  91. package/dist/registry-ISXIFNPG.js +0 -12
  92. package/dist/run-AUCA7EKA.js +0 -20
  93. package/dist/run-service-MT3LOWLS.js +0 -12
  94. package/dist/schema-YWIVP7UR.js +0 -12
  95. package/dist/server-PIYRZLBG.js +0 -12
  96. package/dist/session-ACBIJ2VE.js +0 -12
  97. package/dist/share-next-MPGA7EO4.js +0 -12
  98. package/dist/sury-CWZTCd75-3YHH6KVI.js +0 -12
  99. package/dist/typebox-Dei93FPO-GLI7OCTY.js +0 -12
  100. package/dist/valibot-D_HTw1Gn-E5NKVIOV.js +0 -12
  101. package/dist/worktree-E4DGSBLJ.js +0 -12
  102. package/dist/zod-DSgpEGAE-DSH6V7MG.js +0 -12
  103. package/packages/opencode/migration/20260127222353_familiar_lady_ursula/migration.sql +0 -90
  104. package/packages/opencode/migration/20260127222353_familiar_lady_ursula/snapshot.json +0 -796
  105. package/packages/opencode/migration/20260211171708_add_project_commands/migration.sql +0 -1
  106. package/packages/opencode/migration/20260211171708_add_project_commands/snapshot.json +0 -806
  107. package/packages/opencode/migration/20260213144116_wakeful_the_professor/migration.sql +0 -11
  108. package/packages/opencode/migration/20260213144116_wakeful_the_professor/snapshot.json +0 -897
  109. package/packages/opencode/migration/20260225215848_workspace/migration.sql +0 -7
  110. package/packages/opencode/migration/20260225215848_workspace/snapshot.json +0 -959
  111. package/packages/opencode/migration/20260227213759_add_session_workspace_id/migration.sql +0 -2
  112. package/packages/opencode/migration/20260227213759_add_session_workspace_id/snapshot.json +0 -983
  113. package/packages/opencode/migration/20260228203230_blue_harpoon/migration.sql +0 -17
  114. package/packages/opencode/migration/20260228203230_blue_harpoon/snapshot.json +0 -1102
  115. package/packages/opencode/migration/20260303231226_add_workspace_fields/migration.sql +0 -5
  116. package/packages/opencode/migration/20260303231226_add_workspace_fields/snapshot.json +0 -1013
  117. package/packages/opencode/migration/20260309230000_move_org_to_state/migration.sql +0 -3
  118. package/packages/opencode/migration/20260309230000_move_org_to_state/snapshot.json +0 -1156
  119. package/packages/opencode/migration/20260312043431_session_message_cursor/migration.sql +0 -4
  120. package/packages/opencode/migration/20260312043431_session_message_cursor/snapshot.json +0 -1168
  121. package/packages/opencode/migration/20260323234822_events/migration.sql +0 -13
  122. package/packages/opencode/migration/20260323234822_events/snapshot.json +0 -1271
  123. package/packages/opencode/migration/20260409000000_add_session_metadata/migration.sql +0 -1
@@ -0,0 +1,186 @@
1
+ // Built by esbuild from opencode-server source
2
+ if (typeof globalThis.Bun === 'undefined') {
3
+ globalThis.Bun = {
4
+ version: '0.0.0-node-compat',
5
+ stdin: { async text() { const chunks = []; for await (const c of process.stdin) chunks.push(c); return Buffer.concat(chunks).toString(); } },
6
+ which(cmd) { try { return require('child_process').execFileSync('which', [cmd], { encoding: 'utf8' }).trim(); } catch { return null; } },
7
+ };
8
+ }
9
+ if (typeof globalThis.__name === 'undefined') { globalThis.__name = (t, n) => { Object.defineProperty(t, 'name', { value: n, configurable: true }); return t; }; }
10
+ if (typeof globalThis.__export === 'undefined') { globalThis.__export = (t, a) => { for (const k in a) Object.defineProperty(t, k, { get: a[k], enumerable: true }); }; }
11
+ import { createRequire as __alchemyCreateRequire } from 'node:module';
12
+ const require = __alchemyCreateRequire(import.meta.url);
13
+
14
+ import{D as Ye,s as yt,w as ze}from"./chunk-ZMHNE2MU.js";import{b as ut}from"./chunk-QRABYJKL.js";import{C as Ge,Ea as $e,Sa as Me,Va as te,Wa as Oe,Xa as qe,Ya as Be,oa as Le,ra as Ve,s as Ne,sa as mt,v as ae,va as U}from"./chunk-OMDJ6ZZ2.js";import{Ia as lt,K as at,L as dt,Ma as O,Na as ft,P as le,Qa as ve,U as Se,a as ee,b as rt,d as ot,h as Q,i as nt,qb as Z,r as it,s as st,t as Ee,ub as y,vb as _e,wb as Ae,xb as _,y as ct,zc as pt}from"./chunk-BM2C7NHL.js";import{a as m,d as ce}from"./chunk-RHIWAYN5.js";var et={};ce(et,{CreateFailedError:()=>Fe,CreateInput:()=>ir,Event:()=>Re,Info:()=>nr,ListFailedError:()=>Ue,NameGenerationFailedError:()=>Te,NotGitError:()=>ye,RemoveFailedError:()=>ne,RemoveInput:()=>sr,ResetFailedError:()=>N,ResetInput:()=>cr,Service:()=>ge,StartCommandFailedError:()=>Je,Worktree:()=>et,node:()=>fr});var me={};ce(me,{InstanceStore:()=>me,Service:()=>de,bootstrapNode:()=>vt,node:()=>Qt,use:()=>Xt});import{Context as Bt,Deferred as X,Duration as zt,Effect as d,Exit as Ce,Layer as Yt,Scope as Ht}from"effect";var fe={};ce(fe,{InstanceBootstrap:()=>fe,Service:()=>He});import{Context as Et}from"effect";var He=class extends Et.Service()("@opencode/InstanceBootstrap"){static{m(this,"Service")}};var oe={};ce(oe,{Event:()=>wt,Info:()=>Vt,NotFoundError:()=>Pe,Project:()=>oe,Service:()=>J,UpdateInput:()=>$t,UpdatePayload:()=>Mt,fromRow:()=>re,node:()=>Qe,use:()=>qt});import{and as Ut,eq as T,sql as Wt}from"drizzle-orm";var ue={};ce(ue,{Command:()=>ue,Default:()=>Ie,Event:()=>Ct,Info:()=>Rt,Service:()=>pe,hints:()=>je,node:()=>Ft});import jt from"path";import{Effect as be,Layer as Dt,Context as Pt,Schema as A}from"effect";var Xe=`Create or update \`AGENTS.md\` for this repository.
15
+
16
+ The goal is a compact instruction file that helps future OpenCode sessions avoid mistakes and ramp up quickly. Every line should answer: "Would an agent likely miss this without help?" If not, leave it out.
17
+
18
+ User-provided focus or constraints (honor these):
19
+ $ARGUMENTS
20
+
21
+ ## How to investigate
22
+
23
+ Read the highest-value sources first:
24
+ - \`README*\`, root manifests, workspace config, lockfiles
25
+ - build, test, lint, formatter, typecheck, and codegen config
26
+ - CI workflows and pre-commit / task runner config
27
+ - existing instruction files (\`AGENTS.md\`, \`CLAUDE.md\`, \`.cursor/rules/\`, \`.cursorrules\`, \`.github/copilot-instructions.md\`)
28
+ - repo-local OpenCode config such as \`opencode.json\`
29
+
30
+ If architecture is still unclear after reading config and docs, inspect a small number of representative code files to find the real entrypoints, package boundaries, and execution flow. Prefer reading the files that explain how the system is wired together over random leaf files.
31
+
32
+ Prefer executable sources of truth over prose. If docs conflict with config or scripts, trust the executable source and only keep what you can verify.
33
+
34
+ ## What to extract
35
+
36
+ Look for the highest-signal facts for an agent working in this repo:
37
+ - exact developer commands, especially non-obvious ones
38
+ - how to run a single test, a single package, or a focused verification step
39
+ - required command order when it matters, such as \`lint -> typecheck -> test\`
40
+ - monorepo or multi-package boundaries, ownership of major directories, and the real app/library entrypoints
41
+ - framework or toolchain quirks: generated code, migrations, codegen, build artifacts, special env loading, dev servers, infra deploy flow
42
+ - repo-specific style or workflow conventions that differ from defaults
43
+ - testing quirks: fixtures, integration test prerequisites, snapshot workflows, required services, flaky or expensive suites
44
+ - important constraints from existing instruction files worth preserving
45
+
46
+ Good \`AGENTS.md\` content is usually hard-earned context that took reading multiple files to infer.
47
+
48
+ ## Questions
49
+
50
+ Only ask the user questions if the repo cannot answer something important. Use the \`question\` tool for one short batch at most.
51
+
52
+ Good questions:
53
+ - undocumented team conventions
54
+ - branch / PR / release expectations
55
+ - missing setup or test prerequisites that are known but not written down
56
+
57
+ Do not ask about anything the repo already makes clear.
58
+
59
+ ## Writing rules
60
+
61
+ Include only high-signal, repo-specific guidance such as:
62
+ - exact commands and shortcuts the agent would otherwise guess wrong
63
+ - architecture notes that are not obvious from filenames
64
+ - conventions that differ from language or framework defaults
65
+ - setup requirements, environment quirks, and operational gotchas
66
+ - references to existing instruction sources that matter
67
+
68
+ Exclude:
69
+ - generic software advice
70
+ - long tutorials or exhaustive file trees
71
+ - obvious language conventions
72
+ - speculative claims or anything you could not verify
73
+ - content better stored in another file referenced via \`opencode.json\` \`instructions\`
74
+
75
+ When in doubt, omit.
76
+
77
+ Prefer short sections and bullets. If the repo is simple, keep the file simple. If the repo is large, summarize the few structural facts that actually change how an agent should work.
78
+
79
+ If \`AGENTS.md\` already exists at \`\${path}\`, improve it in place rather than rewriting blindly. Preserve verified useful guidance, delete fluff or stale claims, and reconcile it with the current codebase.
80
+ `;var Ke=`You are a code reviewer. Your job is to review code changes and provide actionable feedback.
81
+
82
+ ---
83
+
84
+ Input: $ARGUMENTS
85
+
86
+ ---
87
+
88
+ ## Determining What to Review
89
+
90
+ Based on the input provided, determine which type of review to perform:
91
+
92
+ 1. **No arguments (default)**: Review all uncommitted changes
93
+ - Run: \`git diff\` for unstaged changes
94
+ - Run: \`git diff --cached\` for staged changes
95
+ - Run: \`git status --short\` to identify untracked (net new) files
96
+
97
+ 2. **Commit hash** (40-char SHA or short hash): Review that specific commit
98
+ - Run: \`git show $ARGUMENTS\`
99
+
100
+ 3. **Branch name**: Compare current branch to the specified branch
101
+ - Run: \`git diff $ARGUMENTS...HEAD\`
102
+
103
+ 4. **PR URL or number** (contains "github.com" or "pull" or looks like a PR number): Review the pull request
104
+ - Run: \`gh pr view $ARGUMENTS\` to get PR context
105
+ - Run: \`gh pr diff $ARGUMENTS\` to get the diff
106
+
107
+ Use best judgement when processing input.
108
+
109
+ ---
110
+
111
+ ## Gathering Context
112
+
113
+ **Diffs alone are not enough.** After getting the diff, read the entire file(s) being modified to understand the full context. Code that looks wrong in isolation may be correct given surrounding logic\u2014and vice versa.
114
+
115
+ - Use the diff to identify which files changed
116
+ - Use \`git status --short\` to identify untracked files, then read their full contents
117
+ - Read the full file to understand existing patterns, control flow, and error handling
118
+ - Check for existing style guide or conventions files (CONVENTIONS.md, AGENTS.md, .editorconfig, etc.)
119
+
120
+ ---
121
+
122
+ ## What to Look For
123
+
124
+ **Bugs** - Your primary focus.
125
+ - Logic errors, off-by-one mistakes, incorrect conditionals
126
+ - If-else guards: missing guards, incorrect branching, unreachable code paths
127
+ - Edge cases: null/empty/undefined inputs, error conditions, race conditions
128
+ - Security issues: injection, auth bypass, data exposure
129
+ - Broken error handling that swallows failures, throws unexpectedly or returns error types that are not caught.
130
+
131
+ **Structure** - Does the code fit the codebase?
132
+ - Does it follow existing patterns and conventions?
133
+ - Are there established abstractions it should use but doesn't?
134
+ - Excessive nesting that could be flattened with early returns or extraction
135
+
136
+ **Performance** - Only flag if obviously problematic.
137
+ - O(n\xB2) on unbounded data, N+1 queries, blocking I/O on hot paths
138
+
139
+ **Behavior Changes** - If a behavioral change is introduced, raise it (especially if it's possibly unintentional).
140
+
141
+ ---
142
+
143
+ ## Before You Flag Something
144
+
145
+ **Be certain.** If you're going to call something a bug, you need to be confident it actually is one.
146
+
147
+ - Only review the changes - do not review pre-existing code that wasn't modified
148
+ - Don't flag something as a bug if you're unsure - investigate first
149
+ - Don't invent hypothetical problems - if an edge case matters, explain the realistic scenario where it breaks
150
+ - If you need more context to be sure, use the tools below to get it
151
+
152
+ **Don't be a zealot about style.** When checking code against conventions:
153
+
154
+ - Verify the code is *actually* in violation. Don't complain about else statements if early returns are already being used correctly.
155
+ - Some "violations" are acceptable when they're the simplest option. A \`let\` statement is fine if the alternative is convoluted.
156
+ - Excessive nesting is a legitimate concern regardless of other style choices.
157
+ - Don't flag style preferences as issues unless they clearly violate established project conventions.
158
+
159
+ ---
160
+
161
+ ## Tools
162
+
163
+ Use these to inform your review:
164
+
165
+ - **Explore agent** - Find how existing code handles similar problems. Check patterns, conventions, and prior art before claiming something doesn't fit.
166
+ - **Exa Code Context** - Verify correct usage of libraries/APIs before flagging something as wrong.
167
+ - **Web Search** - Research best practices if you're unsure about a pattern.
168
+
169
+ If you're uncertain about something and can't verify it with these tools, say "I'm not sure about X" rather than flagging it as a definite issue.
170
+
171
+ ---
172
+
173
+ ## Output
174
+
175
+ 1. If there is a bug, be direct and clear about why it is a bug.
176
+ 2. Clearly communicate severity of issues. Do not overstate severity.
177
+ 3. Critiques should clearly and explicitly communicate the scenarios, environments, or inputs that are necessary for the bug to arise. The comment should immediately indicate that the issue's severity depends on these factors.
178
+ 4. Your tone should be matter-of-fact and not accusatory or overly positive. It should read as a helpful AI assistant suggestion without sounding too much like a human reviewer.
179
+ 5. Write so the reader can quickly understand the issue without reading too closely.
180
+ 6. AVOID flattery, do not give any comments that are not helpful to the reader. Avoid phrasing like "Great job ...", "Thanks for ...".
181
+ `;var xe={};ce(xe,{CommandExecuted:()=>ht,Definitions:()=>St,LegacyEvent:()=>xe});import{Schema as gt}from"effect";var ht=it({type:"command.executed",schema:{name:gt.String,sessionID:ct,arguments:gt.String,messageID:pt.MessageID}}),St=st(ht);var Ct={Executed:xe.CommandExecuted},Rt=A.Struct({name:A.String,description:A.optional(A.String),agent:A.optional(A.String),model:A.optional(A.String),source:A.optional(A.Literals(["command","mcp","skill"])),template:A.Unknown,subtask:A.optional(A.Boolean),hints:A.Array(A.String)}).annotate({identifier:"Command"});function je(a){let S=[],x=a.match(/\$\d+/g);if(x)for(let I of[...new Set(x)].sort())S.push(I);return a.includes("$ARGUMENTS")&&S.push("$ARGUMENTS"),S}m(je,"hints");var Ie={INIT:"init",REVIEW:"review"},pe=class extends Pt.Service()("@opencode/Command"){static{m(this,"Service")}},Tt=Dt.effect(pe,be.gen(function*(){let a=yield*Me.Service,S=yield*Ye.Service,x=yield*ze.Service,I=be.fn("Command.state")(function*(R){let b=yield*a.get(),H=yield*yt.make(),G={};G[Ie.INIT]={name:Ie.INIT,description:"guided AGENTS.md setup",source:"command",get template(){return Xe.replace("${path}",R.worktree)},hints:je(Xe)},G[Ie.REVIEW]={name:Ie.REVIEW,description:"review changes [commit|branch|pr], defaults to uncommitted",source:"command",get template(){return Ke.replace("${path}",R.worktree)},subtask:!0,hints:je(Ke)};for(let[j,k]of Object.entries(b.command??{}))G[j]={name:j,agent:k.agent,model:k.model,description:k.description,source:"command",get template(){return k.template},subtask:k.subtask,hints:je(k.template)};for(let[j,k]of Object.entries(yield*S.prompts()))G[j]={name:j,source:"mcp",description:k.description,get template(){return H.promise(S.getPrompt(k.client,k.name,k.arguments?Object.fromEntries(k.arguments.map((B,L)=>[B.name,`$${L+1}`])):{}).pipe(be.map(B=>B?.messages.map(L=>L.content.type==="text"?L.content.text:"").join(`
182
+ `)||"")))},hints:k.arguments?.map((B,L)=>`$${L+1}`)??[]};for(let j of yield*x.all()){if(G[j.name])continue;let k=j.location==="<built-in>"?void 0:jt.dirname(j.location);G[j.name]={name:j.name,description:j.description,source:"skill",get template(){return k?[j.content,"",`Base directory for this skill: ${k}`,"Relative paths in this skill (e.g., scripts/, references/) are relative to this base directory."].join(`
183
+ `):j.content},hints:[]}}return{commands:G}}),q=yield*U.make(R=>I(R)),Y=be.fn("Command.get")(function*(R){return(yield*U.get(q)).commands[R]}),D=be.fn("Command.list")(function*(){let R=yield*U.get(q);return Object.values(R.commands)});return pe.of({get:Y,list:D})})),Ft=ee.make({service:pe,layer:Tt,deps:[Me.node,Ye.node,ze.node]});import{Effect as i,Layer as _t,Scope as At,Context as Nt,Stream as De,Schema as $}from"effect";import{ChildProcess as Gt,ChildProcessSpawner as Lt}from"effect/unstable/process";var Vt=Z.Info,wt={Updated:Z.Event.Updated};function re(a){let S=a.icon_url||a.icon_url_override||a.icon_color?{url:a.icon_url??void 0,override:a.icon_url_override??void 0,color:a.icon_color??void 0}:void 0;return{id:a.id,worktree:a.worktree,vcs:a.vcs?$.decodeUnknownSync(Z.Vcs)(a.vcs):void 0,name:a.name??void 0,icon:S,time:{created:a.time_created,updated:a.time_updated,initialized:a.time_initialized??void 0},sandboxes:a.sandboxes,commands:a.commands??void 0}}m(re,"fromRow");var $t=$.Struct({projectID:_.ID,name:$.optional($.String),icon:$.optional(Z.Icon),commands:$.optional(Z.Commands)}),Mt=$.Struct({name:$.optional($.String),icon:$.optional(Z.Icon),commands:$.optional(Z.Commands)}).annotate({identifier:"ProjectUpdateInput"}),Pe=class extends $.TaggedErrorClass()("Project.NotFoundError",{projectID:_.ID}){static{m(this,"NotFoundError")}},J=class extends Nt.Service()("@opencode/Project"){static{m(this,"Service")}},Ot=_t.effect(J,i.gen(function*(){let a=yield*O.Service,S=yield*Lt.ChildProcessSpawner,x=yield*_.Service,I=yield*Ae.Service,q=yield*Oe.Service,Y=yield*Be.Service,{db:D}=yield*le.Service,R=i.fnUntraced(function*(o,c){let p=yield*S.spawn(Gt.make("git",o,{cwd:c?.cwd,extendEnv:!0,stdin:"ignore"})),[g,P]=yield*i.all([De.mkString(De.decodeText(p.stdout)),De.mkString(De.decodeText(p.stderr))],{concurrency:2});return{code:yield*p.exitCode,text:g,stderr:P}},i.scoped,i.catch(()=>i.succeed({code:1,text:"",stderr:""}))),b=m(o=>i.sync(()=>te.emit("event",{directory:"global",project:o.id,payload:{type:wt.Updated.type,properties:o}})),"emitUpdated"),H=$.decodeUnknownSync($.optional(Z.Vcs))(at.OPENCODE_FAKE_VCS),G=yield*At.Scope,j=i.fn("Project.migrateProjectId")(function*(o,c){o&&o!==_.ID.global&&o!==c&&(yield*D.transaction(p=>i.gen(function*(){let g=yield*p.select().from(y).where(T(y.id,o)).get(),P=yield*p.select().from(y).where(T(y.id,c)).get();g&&!P&&(yield*p.insert(y).values({...g,id:c,time_updated:Date.now()}).run()),yield*p.delete(_e).where(T(_e.project_id,o)).run(),yield*p.update(ae).set({project_id:c,time_updated:Wt`${ae.time_updated}`}).where(T(ae.project_id,o)).run(),yield*p.update(Ne).set({project_id:c}).where(T(Ne.project_id,o)).run(),g&&(yield*p.delete(y).where(T(y.id,o)).run())}),{behavior:"immediate"}).pipe(i.orDie))}),k=i.fn("Project.saveProjectDirectory")(function*(o){if(o.projectID===_.ID.global)return;let c=Q.make(O.resolve(o.directory));yield*I.create({directory:c,projectID:o.projectID}).pipe(i.catchCause(p=>i.logWarning("project directory persistence failed",{projectID:o.projectID,cause:p})))}),B=i.fn("Project.fromDirectory")(function*(o){yield*i.logInfo("fromDirectory",{directory:o});let c=yield*x.resolve(Q.make(o)),p=c.id===_.ID.make("global")&&!c.vcs?"/":c.directory,g=_.ID.make(c.id);yield*j(c.previous?_.ID.make(c.previous):void 0,g);let P=yield*D.select().from(y).where(T(y.id,g)).get().pipe(i.orDie),t=P?re(P):{id:g,worktree:p,vcs:c.vcs?.type??H,sandboxes:[],time:{created:Date.now(),updated:Date.now()}};Y.experimentalIconDiscovery&&(yield*L(t).pipe(i.ignore,i.forkIn(G)));let e={...t,worktree:g===_.ID.global?p:t.worktree,vcs:c.vcs?.type??H,time:{...t.time,updated:Date.now()}};return g!==_.ID.global&&c.directory!==e.worktree&&!e.sandboxes.includes(c.directory)&&e.sandboxes.push(c.directory),e.sandboxes=yield*i.forEach(e.sandboxes,r=>a.exists(r).pipe(i.orDie,i.map(l=>l?r:void 0)),{concurrency:"unbounded"}).pipe(i.map(r=>r.filter(l=>l!==void 0))),yield*D.insert(y).values({id:e.id,worktree:Q.make(e.worktree),vcs:e.vcs??null,name:e.name,icon_url:e.icon?.url,icon_url_override:e.icon?.override,icon_color:e.icon?.color,time_created:e.time.created,time_updated:e.time.updated,time_initialized:e.time.initialized,sandboxes:e.sandboxes.map(r=>Q.make(r)),commands:e.commands}).onConflictDoUpdate({target:y.id,set:{worktree:Q.make(e.worktree),vcs:e.vcs??null,name:e.name,icon_url:e.icon?.url,icon_url_override:e.icon?.override,icon_color:e.icon?.color,time_updated:e.time.updated,time_initialized:e.time.initialized,sandboxes:e.sandboxes.map(r=>Q.make(r)),commands:e.commands}}).run().pipe(i.orDie),g!==_.ID.global&&(yield*D.update(ae).set({project_id:g}).where(Ut(T(ae.project_id,_.ID.global),T(ae.directory,c.directory))).run().pipe(i.orDie)),yield*k({projectID:g,directory:c.directory}),yield*b(e),g!==_.ID.global&&c.vcs?.type==="git"&&(yield*x.commit({store:c.vcs.store,id:c.id})),{project:e,sandbox:c.vcs?c.directory:p}}),L=i.fn("Project.discover")(function*(o){if(o.vcs!=="git"||o.icon?.override||o.icon?.url)return;let p=(yield*a.glob("**/favicon.{ico,png,svg,jpg,jpeg,webp}",{cwd:o.worktree,absolute:!0,include:"file"}).pipe(i.orDie)).sort((r,l)=>r.length-l.length)[0];if(!p)return;let g=yield*a.readFile(p).pipe(i.orDie),P=Buffer.from(g).toString("base64"),e=`data:${O.mimeType(p)};base64,${P}`;yield*K({projectID:o.id,icon:{url:e}}).pipe(i.catchTag("Project.NotFoundError",()=>i.void))}),he=i.fn("Project.list")(function*(){return(yield*D.select().from(y).all().pipe(i.orDie)).map(re)}),V=i.fn("Project.get")(function*(o){let c=yield*D.select().from(y).where(T(y.id,o)).get().pipe(i.orDie);return c?re(c):void 0}),K=i.fn("Project.update")(function*(o){let c=yield*D.update(y).set({name:o.name,icon_url:o.icon?.url,icon_url_override:o.icon?.override,icon_color:o.icon?.color,commands:o.commands,time_updated:Date.now()}).where(T(y.id,o.projectID)).returning().get().pipe(i.orDie);if(!c)return yield*new Pe({projectID:o.projectID});let p=re(c);return yield*b(p),p}),n=i.fn("Project.initGit")(function*(o){if(o.project.vcs==="git")return o.project;if(!(yield*i.sync(()=>ut("git"))))throw new Error("Git is not installed");let c=yield*R(["init","--quiet"],{cwd:o.directory});if(c.code!==0)throw new Error(c.stderr.trim()||c.text.trim()||"Failed to initialize git repository");let{project:p}=yield*B(o.directory);return p}),f=i.fn("Project.setInitialized")(function*(o){yield*D.update(y).set({time_initialized:Date.now()}).where(T(y.id,o)).run().pipe(i.orDie)}),w=yield*U.make(i.fn("Project.initState")(function*(o){let c=yield*q.listen(p=>p.type!==ue.Event.Executed.type||p.location?.directory!==o.directory?i.void:p.data.name===ue.Default.INIT?f(o.project.id):i.void);yield*i.addFinalizer(()=>c)})),F=i.fn("Project.init")(function*(){yield*U.get(w)}),z=i.fn("Project.sandboxes")(function*(o){let c=yield*D.select().from(y).where(T(y.id,o)).get().pipe(i.orDie);if(!c)return[];let p=re(c);return yield*i.forEach(p.sandboxes,g=>a.isDir(g).pipe(i.orDie,i.map(P=>P?g:void 0)),{concurrency:"unbounded"}).pipe(i.map(g=>g.filter(P=>P!==void 0)))}),ie=i.fn("Project.addSandbox")(function*(o,c){let p=yield*D.select().from(y).where(T(y.id,o)).get().pipe(i.orDie);if(!p)throw new Error(`Project not found: ${o}`);let g=Q.make(c),P=[...p.sandboxes];P.includes(g)||P.push(g);let t=yield*D.update(y).set({sandboxes:P,time_updated:Date.now()}).where(T(y.id,o)).returning().get().pipe(i.orDie);if(!t)throw new Error(`Project not found: ${o}`);yield*b(re(t))}),We=i.fn("Project.removeSandbox")(function*(o,c){let p=yield*D.select().from(y).where(T(y.id,o)).get().pipe(i.orDie);if(!p)throw new Error(`Project not found: ${o}`);let g=Q.make(c),P=p.sandboxes.filter(e=>e!==g),t=yield*D.update(y).set({sandboxes:P,time_updated:Date.now()}).where(T(y.id,o)).returning().get().pipe(i.orDie);if(!t)throw new Error(`Project not found: ${o}`);yield*b(re(t))});return J.of({init:F,fromDirectory:B,discover:L,list:he,get:V,update:K,initGit:n,setInitialized:f,sandboxes:z,addSandbox:ie,removeSandbox:We})})),qt=Se(J),Qe=ee.make({service:J,layer:Ot,deps:[O.node,ve.node,ft.node,_.node,Ae.node,Oe.node,Be.node,le.node]});var de=class extends Bt.Service()("@opencode/InstanceStore"){static{m(this,"Service")}},Xt=Se(de),Kt=Yt.effect(de,d.gen(function*(){let a=yield*J,S=yield*fe.Service,x=yield*Ht.Scope,I=new Map,q=m(n=>d.gen(function*(){let f=n.project&&n.worktree?{directory:n.directory,worktree:n.worktree,project:n.project}:yield*a.fromDirectory(n.directory).pipe(d.map(w=>({directory:n.directory,worktree:w.sandbox,project:w.project})));return yield*S.run.pipe(d.provideService(Le,f)),f}).pipe(d.withSpan("InstanceStore.boot")),"boot"),Y=m((n,f)=>d.sync(()=>I.get(n)!==f?!1:(I.delete(n),!0)),"removeEntry"),D=m((n,f,w)=>d.gen(function*(){let F=yield*d.exit(q({...f,directory:n}));Ce.isFailure(F)&&(yield*Y(n,w)),yield*X.done(w.deferred,F).pipe(d.asVoid)}),"completeLoad"),R=m(n=>d.sync(()=>te.emit("event",{directory:n.directory,project:n.project,workspace:mt.workspaceID,payload:{type:"server.instance.disposed",properties:{directory:n.directory}}})),"emitDisposed"),b=d.fn("InstanceStore.disposeContext")(function*(n){yield*d.logInfo("disposing instance",{directory:n.directory}),yield*d.promise(()=>Ve(n.directory)),yield*R({directory:n.directory,project:n.project.id})}),H=d.fnUntraced(function*(n,f,w){return I.get(n)!==f||(yield*b(w),I.get(n)!==f)?!1:(I.delete(n),!0)}),G=m(n=>{let f=O.resolve(n.directory);return d.uninterruptibleMask(w=>d.gen(function*(){let F=I.get(f);if(F)return yield*w(X.await(F.deferred));let z={deferred:X.makeUnsafe()};return I.set(f,z),yield*d.gen(function*(){yield*d.logInfo("creating instance",{directory:f}),yield*D(f,n,z)}).pipe(d.forkIn(x,{startImmediately:!0})),yield*w(X.await(z.deferred))})).pipe(d.withSpan("InstanceStore.load"))},"load"),j=m(n=>{let f=O.resolve(n.directory);return d.uninterruptibleMask(w=>d.gen(function*(){let F=I.get(f),z={deferred:X.makeUnsafe()};return I.set(f,z),yield*d.gen(function*(){yield*d.logInfo("reloading instance",{directory:f}),F&&(yield*X.await(F.deferred).pipe(d.ignore),yield*d.promise(()=>Ve(f)),yield*R({directory:f,project:n.project?.id})),yield*D(f,n,z)}).pipe(d.forkIn(x,{startImmediately:!0})),yield*w(X.await(z.deferred))})).pipe(d.withSpan("InstanceStore.reload"))},"reload"),k=d.fn("InstanceStore.dispose")(function*(n){let f=I.get(n.directory);if(!f)return yield*b(n);let w=yield*X.await(f.deferred).pipe(d.exit);if(Ce.isFailure(w))return yield*Y(n.directory,f).pipe(d.asVoid);w.value===n&&(yield*H(n.directory,f,n).pipe(d.asVoid))}),B=d.fn("InstanceStore.disposeDirectory")(function*(n){let f=O.resolve(n),w=I.get(f);if(!w)return;let F=yield*X.await(w.deferred).pipe(d.exit);if(Ce.isFailure(F))return yield*Y(f,w).pipe(d.asVoid);yield*H(f,w,F.value).pipe(d.asVoid)}),L=d.fnUntraced(function*(){yield*d.logInfo("disposing all instances"),yield*d.forEach([...I.entries()],n=>d.gen(function*(){let f=yield*X.await(n[1].deferred).pipe(d.exit);if(Ce.isFailure(f)){yield*d.logWarning("instance dispose failed",{key:n[0],cause:f.cause}),yield*Y(n[0],n[1]);return}yield*H(n[0],n[1],f.value)}),{discard:!0})}),he=yield*d.cachedWithTTL(L(),zt.zero),V=d.fn("InstanceStore.disposeAll")(function*(){return yield*he}),K=m((n,f)=>G(n).pipe(d.flatMap(w=>f.pipe(d.provideService(Le,w)))),"provide");return yield*d.addFinalizer(()=>V().pipe(d.ignore)),de.of({load:G,reload:j,dispose:k,disposeDirectory:B,disposeAll:V,provide:K})})),vt=ee.unbound(fe.Service,ot.tags.values.global),Qt=rt({service:de,layer:Kt,deps:[Qe,vt]});import{eq as Jt}from"drizzle-orm";import{Effect as s,Layer as er,Path as tr,Schema as h,Scope as rr,Context as or}from"effect";import{ChildProcess as It}from"effect/unstable/process";var ke={};ce(ke,{Definitions:()=>Zt,Failed:()=>bt,Ready:()=>xt,WorktreeEvent:()=>ke});import{Schema as Ze}from"effect";var xt=Ee.define({type:"worktree.ready",schema:{name:Ze.String,branch:nt(Ze.String)}}),bt=Ee.define({type:"worktree.failed",schema:{message:Ze.String}}),Zt=Ee.inventory(xt,bt);var Re=ke,nr=h.Struct({name:h.String,branch:h.optional(h.String),directory:h.String}).annotate({identifier:"Worktree"}),ir=h.Struct({name:h.optional(h.String),startCommand:h.optional(h.String.annotate({description:"Additional startup script to run after the project's start command"}))}).annotate({identifier:"WorktreeCreateInput"}),sr=h.Struct({directory:h.String}).annotate({identifier:"WorktreeRemoveInput"}),cr=h.Struct({directory:h.String}).annotate({identifier:"WorktreeResetInput"}),ye=class extends h.TaggedErrorClass()("WorktreeNotGitError",{message:h.String}){static{m(this,"NotGitError")}},Te=class extends h.TaggedErrorClass()("WorktreeNameGenerationFailedError",{message:h.String}){static{m(this,"NameGenerationFailedError")}},Fe=class extends h.TaggedErrorClass()("WorktreeCreateFailedError",{message:h.String}){static{m(this,"CreateFailedError")}},Je=class extends h.TaggedErrorClass()("WorktreeStartCommandFailedError",{message:h.String}){static{m(this,"StartCommandFailedError")}},ne=class extends h.TaggedErrorClass()("WorktreeRemoveFailedError",{message:h.String}){static{m(this,"RemoveFailedError")}},N=class extends h.TaggedErrorClass()("WorktreeResetFailedError",{message:h.String}){static{m(this,"ResetFailedError")}},Ue=class extends h.TaggedErrorClass()("WorktreeListFailedError",{message:h.String}){static{m(this,"ListFailedError")}};function ar(a){return a.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").replace(/-+$/,"")}m(ar,"slugify");function dr(...a){return a.filter(Boolean).flatMap(S=>S.split(`
184
+ `).map(x=>x.trim()).flatMap(x=>{let I=x.match(/^warning:\s+failed to remove\s+(.+):\s+/i);if(!I)return[];let q=I[1]?.trim().replace(/^['"]|['"]$/g,"");return q?[q]:[]}))}m(dr,"failedRemoves");var ge=class extends or.Service()("@opencode/Worktree"){static{m(this,"Service")}},lr=er.effect(ge,s.gen(function*(){let a=yield*rr.Scope,S=yield*O.Service,x=yield*tr.Path,I=yield*ve.Service,{db:q}=yield*le.Service,Y=yield*qe.Service,D=yield*oe.Service,R=yield*me.Service,b=s.fnUntraced(function*(t,e){let r=yield*I.run(It.make("git",t,{cwd:e?.cwd,extendEnv:!0,stdin:"ignore"}));return{code:r.exitCode,text:r.stdout.toString("utf8"),stderr:r.stderr.toString("utf8")}},s.catch(t=>s.succeed({code:1,text:"",stderr:t instanceof Error?t.message:String(t)}))),H=26,G=s.fn("Worktree.candidate")(function*(t){let e=yield*U.context;for(let r of Array.from({length:H},(l,u)=>u)){let l=t.name?r===0?t.name:`${t.name}-${Ge.create()}`:Ge.create(),u=t.detached?void 0:`opencode/${l}`,v=x.join(t.root,l);if(!(yield*S.exists(v).pipe(s.orDie))){if(u){let E=`refs/heads/${u}`;if((yield*b(["show-ref","--verify","--quiet",E],{cwd:e.worktree})).code===0)continue}return{name:l,directory:v,...u?{branch:u}:{}}}}return yield*new Te({message:"Failed to generate a unique worktree name"})}),j=s.fn("Worktree.makeWorktreeInfo")(function*(t){let e=yield*U.context;if(e.project.vcs!=="git")return yield*new ye({message:"Worktrees are only supported for git projects"});let r=x.join(dt.Path.data,"worktree",e.project.id);return yield*S.makeDirectory(r,{recursive:!0}).pipe(s.orDie),yield*G({root:r,name:t?.name?ar(t.name):"",detached:t?.detached})}),k=s.fnUntraced(function*(t){let e=yield*U.context,r=yield*b(t.branch?["worktree","add","--no-checkout","-b",t.branch,t.directory]:["worktree","add","--no-checkout","--detach",t.directory,"HEAD"],{cwd:e.worktree});if(r.code!==0)return yield*new Fe({message:r.stderr||r.text||"Failed to create git worktree"});yield*D.addSandbox(e.project.id,t.directory).pipe(s.catch(()=>s.void))}),B=s.fnUntraced(function*(t,e){let r=yield*U.context,l=yield*U.workspaceID,u=r.project.id,v=e?.trim(),E=yield*b(["reset","--hard"],{cwd:t.directory});if(E.code!==0){let C=E.stderr||E.text||"Failed to populate worktree";yield*s.logError("worktree checkout failed",{directory:t.directory,message:C}),te.emit("event",{directory:t.directory,project:r.project.id,workspace:l,payload:{type:Re.Failed.type,properties:{message:C}}});return}(yield*R.load({directory:t.directory}).pipe(s.as(!0),s.catch(C=>s.gen(function*(){let se=$e(C);return yield*s.logError("worktree bootstrap failed",{directory:t.directory,message:se}),te.emit("event",{directory:t.directory,project:r.project.id,workspace:l,payload:{type:Re.Failed.type,properties:{message:se}}}),!1}))))&&(te.emit("event",{directory:t.directory,project:r.project.id,workspace:l,payload:{type:Re.Ready.type,properties:{name:t.name,...t.branch?{branch:t.branch}:{}}}}),yield*c(t.directory,{projectID:u,extra:v}))}),L=s.fn("Worktree.createFromInfo")(function*(t,e){yield*k(t),yield*B(t,e).pipe(s.catchCause(r=>s.logError("worktree bootstrap failed",{cause:r})),s.forkIn(a))}),he=s.fn("Worktree.create")(function*(t){let e=yield*j({name:t?.name});return yield*L(e,t?.startCommand),e}),V=s.fnUntraced(function*(t){let e=x.resolve(t),r=yield*S.realPath(e).pipe(s.catch(()=>s.succeed(e))),l=x.normalize(r);return process.platform==="win32"?l.toLowerCase():l});function K(t){return t.split(`
185
+ `).map(e=>e.trim()).reduce((e,r)=>{if(!r)return e;if(r.startsWith("worktree "))return e.push({path:r.slice(9).trim()}),e;let l=e[e.length-1];return l&&r.startsWith("branch ")&&(l.branch=r.slice(7).trim()),e},[])}m(K,"parseWorktreeList");let n=s.fnUntraced(function*(t,e){for(let r of t){if(!r.path)continue;if((yield*V(r.path))===e)return r}}),f=s.fn("Worktree.list")(function*(){let t=yield*U.context;if(t.project.vcs!=="git")return[];let e=yield*b(["worktree","list","--porcelain"],{cwd:t.worktree});if(e.code!==0)return yield*new Ue({message:e.stderr||e.text||"Failed to read git worktrees"});let r=yield*V(t.project.worktree),l=x.basename(r).toLowerCase();return yield*s.forEach(K(e.text),u=>s.gen(function*(){if(!u.path)return;let v=yield*V(u.path);if(v===r)return;let E=x.basename(v).toLowerCase();return{name:E===l?x.basename(x.dirname(v)):E,directory:v,...u.branch?{branch:u.branch.replace(/^refs\/heads\//,"")}:{}}})).pipe(s.map(u=>u.filter(v=>v!==void 0)))});function w(t){return S.exists(t).pipe(s.orDie,s.flatMap(e=>e?b(["fsmonitor--daemon","stop"],{cwd:t}):s.void))}m(w,"stopFsmonitor");function F(t){return s.tryPromise({try:m(async()=>{let e=await import("fs/promises"),r=process.platform==="win32"?50:5;for(let l of Array.from({length:r},(u,v)=>v))try{await e.rm(t,{recursive:!0,force:!0});return}catch(u){if(l===r-1)throw u;await new Promise(v=>setTimeout(v,100))}},"try"),catch:m(e=>new ne({message:$e(e)||"Failed to remove git worktree directory"}),"catch")})}m(F,"cleanDirectory");let z=s.fn("Worktree.remove")(function*(t){let e=yield*U.context;if(e.project.vcs!=="git")return yield*new ye({message:"Worktrees are only supported for git projects"});let r=yield*V(t.directory);r!==(yield*V(e.worktree))&&(yield*R.disposeDirectory(t.directory));let l=yield*b(["worktree","list","--porcelain"],{cwd:e.worktree});if(l.code!==0)return yield*new ne({message:l.stderr||l.text||"Failed to read git worktrees"});let u=K(l.text),v=yield*n(u,r);if(!v?.path)return(yield*S.exists(r).pipe(s.orDie))&&(yield*w(r),yield*F(r)),!0;yield*R.disposeDirectory(v.path),yield*w(v.path);let E=yield*b(["worktree","remove","--force",v.path],{cwd:e.worktree});if(E.code!==0){let C=yield*b(["worktree","list","--porcelain"],{cwd:e.worktree});if(C.code!==0)return yield*new ne({message:E.stderr||E.text||C.stderr||C.text||"Failed to remove git worktree"});if((yield*n(K(C.text),r))?.path)return yield*new ne({message:E.stderr||E.text||"Failed to remove git worktree"})}yield*F(v.path);let M=v.branch?.replace(/^refs\/heads\//,"");if(M){let C=yield*b(["branch","-D",M],{cwd:e.worktree});if(C.code!==0)return yield*new ne({message:C.stderr||C.text||"Failed to delete worktree branch"})}return!0}),ie=s.fnUntraced(function*(t,e,r){let l=yield*b(t,e);return l.code!==0?yield*r(l):l}),We=s.fnUntraced(function*(t,e){let[r,l]=process.platform==="win32"?["cmd",["/c",e]]:["bash",["-lc",e]],u=yield*I.run(It.make(r,l,{cwd:t,extendEnv:!0,stdin:"ignore"}));return{code:u.exitCode,stderr:u.stderr.toString("utf8")}},s.catch(()=>s.succeed({code:1,stderr:""}))),o=s.fnUntraced(function*(t,e,r){let l=e.trim();if(!l)return!0;let u=yield*We(t,l);return u.code===0?!0:(yield*s.logError("worktree start command failed",{kind:r,directory:t,message:u.stderr}),!1)}),c=s.fnUntraced(function*(t,e){let r=yield*q.select().from(y).where(Jt(y.id,e.projectID)).get().pipe(s.orDie),u=(r?oe.fromRow(r):void 0)?.commands?.start?.trim()??"";return(yield*o(t,u,"project"))?(yield*o(t,e.extra??"","worktree"),!0):!1}),p=s.fnUntraced(function*(t,e){let r=yield*V(t);yield*s.forEach(e,l=>s.gen(function*(){let u=yield*V(x.resolve(t,l));u!==r&&u.startsWith(`${r}${x.sep}`)&&(yield*S.remove(u,{recursive:!0}).pipe(s.ignore))}),{concurrency:"unbounded"})}),g=s.fnUntraced(function*(t){let e=yield*b(["clean","-ffdx"],{cwd:t});if(e.code===0)return e;let r=dr(e.stderr,e.text);return r.length?(yield*p(t,r),yield*b(["clean","-ffdx"],{cwd:t})):e}),P=s.fn("Worktree.reset")(function*(t){let e=yield*U.context;if(e.project.vcs!=="git")return yield*new ye({message:"Worktrees are only supported for git projects"});let r=yield*V(t.directory),l=yield*V(e.worktree);if(r===l)return yield*new N({message:"Cannot reset the primary workspace"});let u=yield*b(["worktree","list","--porcelain"],{cwd:e.worktree});if(u.code!==0)return yield*new N({message:u.stderr||u.text||"Failed to read git worktrees"});let v=yield*n(K(u.text),r);if(!v?.path)return yield*new N({message:"Worktree not found"});let E=v.path,M=yield*Y.defaultBranch(e.worktree);if(!M)return yield*new N({message:"Default branch not found"});let C=M.ref.indexOf("/");if(M.ref!==M.name&&C>0){let W=M.ref.slice(0,C),kt=M.ref.slice(C+1);yield*ie(["fetch",W,kt],{cwd:e.worktree},tt=>new N({message:tt.stderr||tt.text||`Failed to fetch ${M.ref}`}))}yield*ie(["reset","--hard",M.ref],{cwd:E},W=>new N({message:W.stderr||W.text||"Failed to reset worktree to target"}));let se=yield*g(E);if(se.code!==0)return yield*new N({message:se.stderr||se.text||"Failed to clean worktree"});yield*ie(["submodule","update","--init","--recursive","--force"],{cwd:E},W=>new N({message:W.stderr||W.text||"Failed to update submodules"})),yield*ie(["submodule","foreach","--recursive","git","reset","--hard"],{cwd:E},W=>new N({message:W.stderr||W.text||"Failed to reset submodules"})),yield*ie(["submodule","foreach","--recursive","git","clean","-fdx"],{cwd:E},W=>new N({message:W.stderr||W.text||"Failed to clean submodules"}));let we=yield*b(["-c","core.fsmonitor=false","status","--porcelain=v1"],{cwd:E});return we.code!==0?yield*new N({message:we.stderr||we.text||"Failed to read git status"}):we.text.trim()?yield*new N({message:`Worktree reset left local changes:
186
+ ${we.text.trim()}`}):(yield*c(E,{projectID:e.project.id}).pipe(s.catchCause(W=>s.logError("worktree start task failed",{cause:W})),s.forkIn(a)),!0)});return ge.of({makeWorktreeInfo:j,createFromInfo:L,create:he,list:f,remove:z,reset:P})})),fr=ee.make({service:ge,layer:lr,deps:[O.node,lt,ve.node,qe.node,oe.node,me.node,le.node]});export{xe as a,ue as b,He as c,J as d,Qe as e,oe as f,me as g,ke as h,Re as i,nr as j,ir as k,sr as l,cr as m,ye as n,Te as o,Fe as p,Je as q,ne as r,N as s,Ue as t,ge as u,fr as v,et as w};