@codeworksh/cli 0.6.0 → 0.7.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 (102) hide show
  1. package/{acp-Dr7BPHDK.mjs → acp-GGhof_w_.mjs} +4 -4
  2. package/{acp-Dr7BPHDK.mjs.map → acp-GGhof_w_.mjs.map} +1 -1
  3. package/{add-CzFz-Mfb.mjs → add-CGjQkVRs.mjs} +5 -5
  4. package/{add-CzFz-Mfb.mjs.map → add-CGjQkVRs.mjs.map} +1 -1
  5. package/{add-fJlj0O2v.mjs → add-DArbv6Op.mjs} +4 -4
  6. package/{add-fJlj0O2v.mjs.map → add-DArbv6Op.mjs.map} +1 -1
  7. package/{catalog-DCjYMhro.mjs → catalog-XfqtqMDz.mjs} +2 -2
  8. package/{catalog-DCjYMhro.mjs.map → catalog-XfqtqMDz.mjs.map} +1 -1
  9. package/{check-7oL3UVdX.mjs → check-BRHzx5p0.mjs} +4 -4
  10. package/{check-7oL3UVdX.mjs.map → check-BRHzx5p0.mjs.map} +1 -1
  11. package/{control-Bd2G-Unk.mjs → control-F0bo3rXh.mjs} +5 -5
  12. package/{control-Bd2G-Unk.mjs.map → control-F0bo3rXh.mjs.map} +1 -1
  13. package/disconnect-DemFNh2P.mjs +2 -0
  14. package/{entries-hMxcOaPm.mjs → entries-DnbFTTLU.mjs} +3 -3
  15. package/{entries-hMxcOaPm.mjs.map → entries-DnbFTTLU.mjs.map} +1 -1
  16. package/{error-BVSfzBzb.mjs → error--BWou73I.mjs} +141 -3
  17. package/error--BWou73I.mjs.map +1 -0
  18. package/{fork-BtL-68qs.mjs → fork-DlhNFPUB.mjs} +4 -4
  19. package/{fork-BtL-68qs.mjs.map → fork-DlhNFPUB.mjs.map} +1 -1
  20. package/{identity-D2pOA6eh.mjs → identity-Bcl1KlX-.mjs} +2 -2
  21. package/{identity-D2pOA6eh.mjs.map → identity-Bcl1KlX-.mjs.map} +1 -1
  22. package/index.mjs +34 -35
  23. package/index.mjs.map +1 -1
  24. package/{install-Dqx1TWtz.mjs → install-DRJ5KKyb.mjs} +4 -4
  25. package/{install-Dqx1TWtz.mjs.map → install-DRJ5KKyb.mjs.map} +1 -1
  26. package/{jsonc-BwztMdEB.mjs → jsonc-Cel7I0yd.mjs} +2 -2
  27. package/{jsonc-BwztMdEB.mjs.map → jsonc-Cel7I0yd.mjs.map} +1 -1
  28. package/{link-BilIb5jN.mjs → link-CJE1PRTf.mjs} +3 -3
  29. package/{link-BilIb5jN.mjs.map → link-CJE1PRTf.mjs.map} +1 -1
  30. package/{list-BUPm4Bsu.mjs → list-B3kSn78f.mjs} +4 -4
  31. package/{list-BUPm4Bsu.mjs.map → list-B3kSn78f.mjs.map} +1 -1
  32. package/{list-DV3VGuTp.mjs → list-Cf-zESJf.mjs} +4 -4
  33. package/{list-DV3VGuTp.mjs.map → list-Cf-zESJf.mjs.map} +1 -1
  34. package/{list-D1sa8t4P.mjs → list-Df4ngZjL.mjs} +4 -4
  35. package/{list-D1sa8t4P.mjs.map → list-Df4ngZjL.mjs.map} +1 -1
  36. package/{list-BdMdlBjQ.mjs → list-TLhgvlKp.mjs} +3 -3
  37. package/{list-BdMdlBjQ.mjs.map → list-TLhgvlKp.mjs.map} +1 -1
  38. package/{login-COjr-kTw.mjs → login-BJ3d7FM_.mjs} +4 -4
  39. package/{login-COjr-kTw.mjs.map → login-BJ3d7FM_.mjs.map} +1 -1
  40. package/{login-DC6bw2pG.mjs → login-oWLqnAQK.mjs} +4 -4
  41. package/{login-DC6bw2pG.mjs.map → login-oWLqnAQK.mjs.map} +1 -1
  42. package/{logout-CfyRsTUE.mjs → logout-ClrNQ8LO.mjs} +4 -4
  43. package/{logout-CfyRsTUE.mjs.map → logout-ClrNQ8LO.mjs.map} +1 -1
  44. package/{logout-D02BdsX6.mjs → logout-D44pgH6b.mjs} +4 -4
  45. package/{logout-D02BdsX6.mjs.map → logout-D44pgH6b.mjs.map} +1 -1
  46. package/package-CDB-uxy3.mjs +6 -0
  47. package/package-CDB-uxy3.mjs.map +1 -0
  48. package/package.json +2 -3
  49. package/{providers-8XcCtqG7.mjs → providers-ozcPo-AJ.mjs} +4 -4
  50. package/{providers-8XcCtqG7.mjs.map → providers-ozcPo-AJ.mjs.map} +1 -1
  51. package/reconnect-BcJtQx3U.mjs +2 -0
  52. package/{refresh-zDPc39tX.mjs → refresh-B6iT5eWN.mjs} +4 -4
  53. package/{refresh-zDPc39tX.mjs.map → refresh-B6iT5eWN.mjs.map} +1 -1
  54. package/{refresh-CPt2ua-n.mjs → refresh-CH7lLrF3.mjs} +4 -4
  55. package/{refresh-CPt2ua-n.mjs.map → refresh-CH7lLrF3.mjs.map} +1 -1
  56. package/{relink-Cr5T6W7K.mjs → relink-BvrynRLV.mjs} +4 -4
  57. package/{relink-Cr5T6W7K.mjs.map → relink-BvrynRLV.mjs.map} +1 -1
  58. package/{reload-xhRj21Ic.mjs → reload-qYk-KlpL.mjs} +3 -3
  59. package/{reload-xhRj21Ic.mjs.map → reload-qYk-KlpL.mjs.map} +1 -1
  60. package/{remove-DRBU8YfV.mjs → remove-Be5ytOgR.mjs} +4 -4
  61. package/{remove-DRBU8YfV.mjs.map → remove-Be5ytOgR.mjs.map} +1 -1
  62. package/{remove-BuO_0yjy.mjs → remove-CTzOWKTq.mjs} +5 -5
  63. package/{remove-BuO_0yjy.mjs.map → remove-CTzOWKTq.mjs.map} +1 -1
  64. package/{restart-B7TyHczC.mjs → restart-Dhlrvevr.mjs} +4 -4
  65. package/{restart-B7TyHczC.mjs.map → restart-Dhlrvevr.mjs.map} +1 -1
  66. package/{run-B3acSsVy.mjs → run-BX65GBq_.mjs} +4 -4
  67. package/{run-B3acSsVy.mjs.map → run-BX65GBq_.mjs.map} +1 -1
  68. package/{runtime-CwoLsQy7.mjs → runtime-CK2CunDw.mjs} +3 -18
  69. package/runtime-CK2CunDw.mjs.map +1 -0
  70. package/serve-y19CU2VR.mjs +1208 -0
  71. package/serve-y19CU2VR.mjs.map +1 -0
  72. package/{service-ClAs3abW.mjs → service-Df8gDfve.mjs} +8 -32
  73. package/service-Df8gDfve.mjs.map +1 -0
  74. package/{settings-Ct8kxLeD.mjs → settings-BzAk8lIo.mjs} +3 -3
  75. package/{settings-Ct8kxLeD.mjs.map → settings-BzAk8lIo.mjs.map} +1 -1
  76. package/{shared-CfaUYDk4.mjs → shared-BU8-Q5m8.mjs} +3 -3
  77. package/{shared-CfaUYDk4.mjs.map → shared-BU8-Q5m8.mjs.map} +1 -1
  78. package/{shared-5A9FR7Lo.mjs → shared-BnR3BFZM.mjs} +4 -4
  79. package/{shared-5A9FR7Lo.mjs.map → shared-BnR3BFZM.mjs.map} +1 -1
  80. package/{start-BPmacHoA.mjs → start-DrVnKdfd.mjs} +4 -4
  81. package/{start-BPmacHoA.mjs.map → start-DrVnKdfd.mjs.map} +1 -1
  82. package/{status-DDhz93PH.mjs → status-B-AAul1G.mjs} +4 -4
  83. package/{status-DDhz93PH.mjs.map → status-B-AAul1G.mjs.map} +1 -1
  84. package/{status-D6fIgnPp.mjs → status-BrL3Eecl.mjs} +4 -4
  85. package/{status-D6fIgnPp.mjs.map → status-BrL3Eecl.mjs.map} +1 -1
  86. package/{stop-DuDxGUsn.mjs → stop-D-OJCp9e.mjs} +4 -4
  87. package/{stop-DuDxGUsn.mjs.map → stop-D-OJCp9e.mjs.map} +1 -1
  88. package/{thread-skUkybyv.mjs → thread-BuNept5V.mjs} +2 -2
  89. package/{thread-skUkybyv.mjs.map → thread-BuNept5V.mjs.map} +1 -1
  90. package/{update-oK_209iL.mjs → update-DoS5AWg6.mjs} +4 -4
  91. package/{update-oK_209iL.mjs.map → update-DoS5AWg6.mjs.map} +1 -1
  92. package/disconnect-Dpt7LKVl.mjs +0 -2
  93. package/error-BVSfzBzb.mjs.map +0 -1
  94. package/package-D1wDsLSU.mjs +0 -6
  95. package/package-D1wDsLSU.mjs.map +0 -1
  96. package/reconnect-C4KrnFkT.mjs +0 -2
  97. package/runtime-CwoLsQy7.mjs.map +0 -1
  98. package/serve-CiiD_6i6.mjs +0 -488
  99. package/serve-CiiD_6i6.mjs.map +0 -1
  100. package/service-ClAs3abW.mjs.map +0 -1
  101. package/tui-Dp9hUjng.mjs +0 -76
  102. package/tui-Dp9hUjng.mjs.map +0 -1
@@ -0,0 +1,1208 @@
1
+ import { i as Cmd, t as handler } from "./runtime-CK2CunDw.mjs";
2
+ import { C as Core, S as Connected, T as ofThread, _ as HostError, b as path, g as Api, r as renderError, u as writeError, v as OAuthError, w as encode, x as decode } from "./error--BWou73I.mjs";
3
+ import { t as harnessOptions } from "./harness-6d8TlAVk.mjs";
4
+ import { c as register, r as layer$6, s as log, t as Service$4 } from "./identity-Bcl1KlX-.mjs";
5
+ import { Cause, Clock, Context, Data, DateTime, Effect, Exit, Fiber, FileSystem, Layer, Logger, Option, Path, PubSub, Queue, Ref, Schedule, Schema, Scope, Semaphore, Stream } from "effect";
6
+ import { Model } from "@codeworksh/aikit";
7
+ import { HttpRouter, HttpServer } from "effect/http";
8
+ import { Control, Event, EventList, EventRegistry, EventSchema, Git, Global, Harness, Mcp, ModelCatalog, Project, PromptSchema, Sandbox, Session, SessionStore, Settings, State, ThreadSchema, ThreadStore, expandTilde } from "@codeworksh/harness/effect";
9
+ import { NodeHttpServer } from "@effect/platform-node";
10
+ import { RpcSerialization, RpcServer } from "effect/rpc";
11
+ import { summarizeGitHubCopilot, summarizeOpenAICodex } from "@codeworksh/aikit/oauth/summary";
12
+ import { GitHubCopilotOAuthClient, JsonGitHubCopilotAuthStorage } from "@codeworksh/aikit/oauth/github/copilot";
13
+ import { JsonOpenAICodexAuthStorage, OpenAICodexOAuthClient } from "@codeworksh/aikit/oauth/openai/codex";
14
+ import * as NetAddress from "effect/net/NetAddress";
15
+ import { createServer } from "node:http";
16
+ import { ChildProcess, ChildProcessSpawner } from "effect/process";
17
+ import { readdir } from "node:fs/promises";
18
+ import { homedir } from "node:os";
19
+ //#region src/server/clones.ts
20
+ /**
21
+ * Background clones into host folders. Each is tracked by its destination from start until 30 seconds
22
+ * after it is done (a failed or cancelled one stays until retried or discarded), and git's progress
23
+ * is streamed as it arrives. Tracking is in memory: a restart forgets every clone.
24
+ */
25
+ var Service$3 = class extends Context.Service()("@codeworksh/cli/server/clones/Service") {};
26
+ const DONE_RETENTION = "30 seconds";
27
+ const STALL_AFTER = "20 seconds";
28
+ const DETAIL_MAX = 200;
29
+ const ERROR_MAX = 1e3;
30
+ const MAX_OUTPUT_BYTES = 262144;
31
+ const MAX_PENDING_LINE = 65536;
32
+ const NOT_CLONED = "The repository could not be cloned.";
33
+ const UNCOMPLETED = "The source control operation could not be completed.";
34
+ const CLONE_ENV = {
35
+ GIT_PROGRESS_DELAY: "0",
36
+ GIT_TERMINAL_PROMPT: "0",
37
+ LANGUAGE: "C"
38
+ };
39
+ const clampText = (text, maxLength) => text.length <= maxLength ? text : `${text.slice(0, maxLength - 1)}…`;
40
+ const fail$1 = (message) => new HostError({ message });
41
+ var CloneError = class extends Data.TaggedError("CloneError") {};
42
+ const STAGE_PREFIXES = [
43
+ [/^remote: Enumerating objects/, "counting"],
44
+ [/^remote: Counting objects/, "counting"],
45
+ [/^remote: Compressing objects/, "counting"],
46
+ [/^Receiving objects/, "receiving"],
47
+ [/^Resolving deltas/, "resolving"],
48
+ [/^Updating files/, "checkout"],
49
+ [/^Checking out files/, "checkout"]
50
+ ];
51
+ const PERCENT = /:\s+(\d+)%\s+\((\d+)\/(\d+)\)(?:,\s*(.*?))?\s*(?:,\s*done\.)?\s*$/;
52
+ /** One progress redraw; git separates them with a bare CR. */
53
+ const parseProgress = (line) => {
54
+ const trimmed = line.trim();
55
+ const stageEntry = STAGE_PREFIXES.find(([pattern]) => pattern.test(trimmed));
56
+ if (!stageEntry) return null;
57
+ const stage = stageEntry[1];
58
+ const match = PERCENT.exec(trimmed);
59
+ if (!match) return {
60
+ stage,
61
+ percent: null,
62
+ detail: null
63
+ };
64
+ const percent = Number(match[1]);
65
+ const rawDetail = match[4]?.trim() ?? "";
66
+ const detail = rawDetail.length > 0 && rawDetail !== "done." ? rawDetail : null;
67
+ return {
68
+ stage,
69
+ percent: Number.isFinite(percent) ? Math.max(0, Math.min(100, percent)) : null,
70
+ detail
71
+ };
72
+ };
73
+ const SCP_LIKE_URL = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/;
74
+ const SSH_URL = /^ssh:\/\/(?:[^/\s]*@)?([^@:/\s]+)(:\d+)?\/(.+)$/;
75
+ const HTTPS_URL = /^https?:\/\/(?:[^/\s]*@)?([^@:/\s]+)(:\d+)?\/(.+)$/;
76
+ const parseCloneUrl = (url) => {
77
+ const trimmed = url.trim();
78
+ const ssh = SSH_URL.exec(trimmed);
79
+ if (ssh) return {
80
+ protocol: "ssh",
81
+ host: ssh[1],
82
+ path: ssh[3],
83
+ customPort: !!ssh[2]
84
+ };
85
+ const https = HTTPS_URL.exec(trimmed);
86
+ if (https) return {
87
+ protocol: "https",
88
+ host: https[1],
89
+ path: https[3],
90
+ customPort: !!https[2]
91
+ };
92
+ const scp = SCP_LIKE_URL.exec(trimmed);
93
+ if (scp) return {
94
+ protocol: "ssh",
95
+ host: scp[1],
96
+ path: scp[2],
97
+ customPort: false
98
+ };
99
+ return null;
100
+ };
101
+ /**
102
+ * A clone URL in the other protocol, as the host may only have SSH keys or only an HTTPS credential
103
+ * helper; null when it cannot be rewritten safely, such as with a custom port.
104
+ */
105
+ const cloneUrlForProtocol = (url, protocol) => {
106
+ const parsed = parseCloneUrl(url);
107
+ if (!parsed) return null;
108
+ if (parsed.protocol === protocol) return url.trim();
109
+ if (parsed.customPort) return null;
110
+ if (parsed.protocol === "ssh" && parsed.host.toLowerCase() === "ssh.dev.azure.com") {
111
+ const azure = /^v3\/([^/?#]+)\/([^/?#]+)\/([^/?#]+)$/.exec(parsed.path);
112
+ return azure ? `https://dev.azure.com/${azure[1]}/${azure[2]}/_git/${azure[3]}` : null;
113
+ }
114
+ if (parsed.protocol === "https" && parsed.host.toLowerCase() === "dev.azure.com") {
115
+ const azure = /^([^/?#]+)\/([^/?#]+)\/_git\/([^/?#]+)$/.exec(parsed.path);
116
+ return azure ? `git@ssh.dev.azure.com:v3/${azure[1]}/${azure[2]}/${azure[3]}` : null;
117
+ }
118
+ return protocol === "ssh" ? `git@${parsed.host}:${parsed.path}` : `https://${parsed.host}/${parsed.path}`;
119
+ };
120
+ /** An SSH rejection is retried over HTTPS; other URL shapes are never guessed. */
121
+ const httpsFallbackUrl = (cloneUrl) => parseCloneUrl(cloneUrl)?.protocol === "ssh" ? cloneUrlForProtocol(cloneUrl, "https") : null;
122
+ /** The remote as clients see it: git still gets the credentials. */
123
+ const redactRemoteUrl = (remoteUrl) => {
124
+ const url = URL.parse(remoteUrl);
125
+ if (url === null || url.username.length === 0 && url.password.length === 0 && url.search.length === 0) return remoteUrl;
126
+ url.username = "";
127
+ url.password = "";
128
+ url.search = "";
129
+ return url.toString();
130
+ };
131
+ const URL_WITH_USERINFO = /\b([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]+@/gi;
132
+ const QUOTED_URL_QUERY = /(['"])([a-z][a-z0-9+.-]*:\/\/[^\s?]*)\?.*\1(?=[\s:]|$)/gi;
133
+ const URL_QUERY = /\b([a-z][a-z0-9+.-]*:\/\/[^\s?]*)\?[^\s]*/gi;
134
+ const redactUrlCredentials = (text) => text.replace(QUOTED_URL_QUERY, "$1$2$1").replace(URL_QUERY, "$1").replace(URL_WITH_USERINFO, "$1");
135
+ const FAILURE_PATTERNS = [
136
+ [/would clobber existing tag/i, "conflict"],
137
+ [/is already (?:used by worktree at|checked out at)/i, "conflict"],
138
+ [/a branch named .+ already exists/i, "conflict"],
139
+ [/could not lock config file .+: File exists/i, "conflict"],
140
+ [/(?:authentication failed|could not read Username|could not read Password|permission denied \([a-z-]+(?:,[a-z-]+)*\)|permission denied, please try again)/i, "authentication_failed"],
141
+ [/host key verification failed/i, "host_key_unverified"]
142
+ ];
143
+ const DIAGNOSTIC_LINE = /^(?:fatal|error):|^!\s|^\s+!\s/;
144
+ const SSH_TRANSPORT_REFUSAL = /Permission denied \((?:publickey|password|keyboard-interactive)|Permission denied, please try again|Host key verification failed/i;
145
+ const classify = (stderr) => {
146
+ const diagnostics = stderr.split(/\r?\n/).filter((line) => DIAGNOSTIC_LINE.test(line) || !line.startsWith("remote:") && SSH_TRANSPORT_REFUSAL.test(line)).join("\n");
147
+ if (diagnostics.length === 0) return null;
148
+ if (diagnostics.toLowerCase().includes("not a git repository")) return "not_a_repository";
149
+ return FAILURE_PATTERNS.find(([pattern]) => pattern.test(diagnostics))?.[1] ?? null;
150
+ };
151
+ const isSshRejection = (error) => error.reason === "authentication_failed" || error.reason === "host_key_unverified";
152
+ /**
153
+ * Appends a git config entry through the environment, after any inherited ones, without touching
154
+ * argv or the user's config; an invalid inherited count is left for git to report.
155
+ */
156
+ const gitConfigEnv = (env, key, value) => {
157
+ const inherited = env.GIT_CONFIG_COUNT;
158
+ if (inherited !== void 0 && inherited !== "" && /^[ \t\r\n\v\f]*(?:\+?\d+|-0+)/.exec(inherited)?.[0] !== inherited) return {};
159
+ const count = inherited === void 0 || inherited === "" ? 0 : Number.parseInt(inherited, 10);
160
+ return {
161
+ GIT_CONFIG_COUNT: String(count + 1),
162
+ [`GIT_CONFIG_KEY_${count}`]: key,
163
+ [`GIT_CONFIG_VALUE_${count}`]: value
164
+ };
165
+ };
166
+ const LINE_SEPARATOR = /\r\n|\r|\n/;
167
+ /** Reads a git output stream, keeping its first 256 KiB as text and passing every non-empty line on. */
168
+ const collect = Effect.fnUntraced(function* (stream, onLine) {
169
+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
170
+ const lineDecoder = new TextDecoder();
171
+ let bytes = 0;
172
+ let text = "";
173
+ let pending = "";
174
+ let truncated = false;
175
+ const emit = Effect.fnUntraced(function* (flush) {
176
+ if (onLine === void 0) return;
177
+ let separator = LINE_SEPARATOR.exec(pending);
178
+ while (separator) {
179
+ const line = pending.slice(0, separator.index);
180
+ pending = pending.slice(separator.index + separator[0].length);
181
+ if (line.length > 0) yield* onLine(line);
182
+ separator = LINE_SEPARATOR.exec(pending);
183
+ }
184
+ if (flush) {
185
+ const trailing = pending;
186
+ pending = "";
187
+ if (trailing.length > 0) yield* onLine(trailing);
188
+ }
189
+ });
190
+ yield* Stream.runForEach(stream, Effect.fnUntraced(function* (chunk) {
191
+ if (!truncated) {
192
+ const room = MAX_OUTPUT_BYTES - bytes;
193
+ const kept = chunk.byteLength > room ? chunk.subarray(0, Math.max(0, room)) : chunk;
194
+ bytes += kept.byteLength;
195
+ truncated = chunk.byteLength > room;
196
+ text += decoder.decode(kept, { stream: !truncated });
197
+ }
198
+ if (onLine === void 0) return;
199
+ pending += lineDecoder.decode(chunk, { stream: true });
200
+ yield* emit(false);
201
+ if (truncated && pending.length > MAX_PENDING_LINE) pending = "";
202
+ }));
203
+ if (!truncated) text += decoder.decode();
204
+ pending += lineDecoder.decode();
205
+ yield* emit(true);
206
+ return text;
207
+ });
208
+ const make$2 = Effect.gen(function* () {
209
+ const fs = yield* FileSystem.FileSystem;
210
+ const path = yield* Path.Path;
211
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
212
+ const clones = yield* Ref.make(/* @__PURE__ */ new Map());
213
+ const changes = yield* PubSub.unbounded();
214
+ const retentionFibers = /* @__PURE__ */ new Map();
215
+ let sequence = 0;
216
+ const cloneScope = yield* Scope.make("parallel");
217
+ yield* Effect.addFinalizer(() => Scope.close(cloneScope, Exit.void));
218
+ const actionLock = yield* Semaphore.make(1);
219
+ const locked = (effect) => actionLock.withPermits(1)(effect);
220
+ const resolve = (value) => path.resolve(expandTilde(value.trim(), path));
221
+ const failed = () => fail$1(UNCOMPLETED);
222
+ const normalizeDestination = Effect.fn("Clones.normalizeDestination")(function* (destination) {
223
+ if (destination.trim().length === 0) return yield* fail$1("Choose a destination path before cloning.");
224
+ return resolve(destination);
225
+ });
226
+ const prepareDestination = Effect.fn("Clones.prepareDestination")(function* (input) {
227
+ const destination = yield* normalizeDestination(input);
228
+ if (yield* fs.exists(destination).pipe(Effect.mapError(failed))) {
229
+ if ((yield* fs.readDirectory(destination).pipe(Effect.mapError(() => fail$1("Destination path already exists and is not a directory.")))).length > 0) return yield* fail$1("Destination path already exists and is not empty.");
230
+ } else {
231
+ const parent = path.dirname(destination);
232
+ if (!(yield* fs.exists(parent).pipe(Effect.mapError(failed)))) yield* fs.makeDirectory(parent, { recursive: true }).pipe(Effect.mapError(failed));
233
+ }
234
+ return destination;
235
+ });
236
+ const prepare = Effect.fn("Clones.prepare")(function* (input) {
237
+ const destination = yield* prepareDestination(input.path);
238
+ const cloneUrl = input.remote.trim();
239
+ if (cloneUrl.length === 0) return yield* fail$1("Enter a repository path or clone URL before cloning.");
240
+ return {
241
+ destination,
242
+ cloneUrl,
243
+ remote: redactRemoteUrl(cloneUrl)
244
+ };
245
+ });
246
+ /** Empties a partial clone's folder, keeping the folder; refuses one holding files git did not write. */
247
+ const discardClone = Effect.fn("Clones.discardClone")(function* (input) {
248
+ const destination = yield* normalizeDestination(input);
249
+ const entries = yield* fs.readDirectory(destination).pipe(Effect.catchIf((error) => error.reason._tag === "NotFound", () => Effect.succeed([])), Effect.mapError(() => fail$1("The clone destination could not be inspected.")));
250
+ if (entries.length > 0 && !entries.includes(".git")) return yield* fail$1("Destination path contains files that are not from the clone.");
251
+ yield* fs.remove(destination, {
252
+ recursive: true,
253
+ force: true
254
+ }).pipe(Effect.andThen(fs.makeDirectory(destination, { recursive: true })), Effect.retry({
255
+ schedule: Schedule.spaced("200 millis"),
256
+ times: 5
257
+ }), Effect.mapError(() => fail$1("The partial clone could not be removed.")));
258
+ });
259
+ const attempt = Effect.fn("Clones.attempt")(function* (destination, cloneUrl, onProgress) {
260
+ const tail = [];
261
+ const onLine = (line) => {
262
+ const parsed = parseProgress(line);
263
+ if (parsed) return onProgress(parsed);
264
+ return Effect.sync(() => {
265
+ const trimmed = line.trim();
266
+ if (trimmed.length === 0 || trimmed.startsWith("Cloning into")) return;
267
+ tail.push(redactUrlCredentials(trimmed));
268
+ if (tail.length > 4) tail.shift();
269
+ });
270
+ };
271
+ const normalized = cloneUrl.replace(/^([a-z][a-z0-9+.-]*:\/\/[^/?#]+)\?/i, "$1/?");
272
+ const base = {
273
+ ...process.env,
274
+ GIT_OPTIONAL_LOCKS: "0",
275
+ ...CLONE_ENV
276
+ };
277
+ const env = {
278
+ ...base,
279
+ ...gitConfigEnv(base, "safe.bareRepository", "explicit")
280
+ };
281
+ yield* Effect.gen(function* () {
282
+ const handle = yield* spawner.spawn(ChildProcess.make("git", [
283
+ "clone",
284
+ "--progress",
285
+ "--",
286
+ normalized,
287
+ path.basename(destination)
288
+ ], {
289
+ cwd: path.dirname(destination),
290
+ env,
291
+ extendEnv: false,
292
+ stdin: "ignore",
293
+ stdout: "pipe",
294
+ stderr: "pipe"
295
+ }));
296
+ const [, stderr, exitCode] = yield* Effect.all([
297
+ collect(handle.stdout),
298
+ collect(handle.stderr, onLine),
299
+ handle.exitCode
300
+ ], { concurrency: "unbounded" });
301
+ if (exitCode !== 0) return yield* new CloneError({
302
+ message: "",
303
+ reason: classify(stderr)
304
+ });
305
+ }).pipe(Effect.scoped, Effect.mapError((error) => new CloneError({
306
+ message: tail.length > 0 ? tail.join(" ") : NOT_CLONED,
307
+ reason: error instanceof CloneError ? error.reason : null
308
+ })));
309
+ });
310
+ /** Clones over the URL as given, then over HTTPS when SSH was refused; the folder is not emptied in between. */
311
+ const cloneRepository = Effect.fn("Clones.cloneRepository")(function* (input, cloneUrl, onProgress) {
312
+ const destination = yield* prepareDestination(input);
313
+ const httpsUrl = httpsFallbackUrl(cloneUrl);
314
+ const first = attempt(destination, cloneUrl, onProgress);
315
+ if (httpsUrl === null) return yield* first;
316
+ yield* first.pipe(Effect.catchIf(isSshRejection, (sshError) => attempt(destination, httpsUrl, onProgress).pipe(Effect.mapError((httpsError) => new CloneError({
317
+ message: `${sshError.message} Cloning over HTTPS instead also failed: ${httpsError.message}`,
318
+ reason: httpsError.reason
319
+ })))));
320
+ });
321
+ const list = Ref.get(clones).pipe(Effect.map((current) => Array.from(current.values(), (tracked) => tracked.snapshot)));
322
+ const publish = list.pipe(Effect.flatMap((snapshots) => PubSub.publish(changes, snapshots)));
323
+ const modify = (id, mutate) => Ref.modify(clones, (current) => {
324
+ const existing = current.get(id);
325
+ if (!existing) return [null, current];
326
+ const nextTracked = mutate(existing);
327
+ const nextSnapshot = {
328
+ ...nextTracked.snapshot,
329
+ sequence: ++sequence
330
+ };
331
+ const next = new Map(current);
332
+ next.set(id, {
333
+ ...nextTracked,
334
+ snapshot: nextSnapshot
335
+ });
336
+ return [nextSnapshot, next];
337
+ }).pipe(Effect.tap((snapshot) => snapshot ? publish : Effect.void));
338
+ const clearRetention = (id) => {
339
+ const fiber = retentionFibers.get(id);
340
+ retentionFibers.delete(id);
341
+ return fiber ? Fiber.interrupt(fiber).pipe(Effect.ignore) : Effect.void;
342
+ };
343
+ const remove = (id) => Ref.update(clones, (current) => {
344
+ if (!current.has(id)) return current;
345
+ const next = new Map(current);
346
+ next.delete(id);
347
+ return next;
348
+ }).pipe(Effect.andThen(publish));
349
+ const scheduleRemoval = Effect.fn("Clones.scheduleRemoval")(function* (id) {
350
+ yield* clearRetention(id);
351
+ const fiber = yield* remove(id).pipe(Effect.delay(DONE_RETENTION), Effect.ensuring(Effect.sync(() => {
352
+ if (retentionFibers.get(id) === fiber) retentionFibers.delete(id);
353
+ })), Effect.forkDetach);
354
+ retentionFibers.set(id, fiber);
355
+ });
356
+ const progress = (id, update) => modify(id, (tracked) => ({
357
+ ...tracked,
358
+ snapshot: {
359
+ ...tracked.snapshot,
360
+ stage: update.stage,
361
+ percent: update.percent,
362
+ detail: update.detail === null ? null : clampText(update.detail, DETAIL_MAX),
363
+ stalled: false
364
+ }
365
+ })).pipe(Effect.asVoid);
366
+ const markStalled = (id) => modify(id, (tracked) => ({
367
+ ...tracked,
368
+ snapshot: {
369
+ ...tracked.snapshot,
370
+ stalled: true
371
+ }
372
+ })).pipe(Effect.asVoid);
373
+ /** Marks the clone stalled once, then waits for git to speak again. */
374
+ const watchForStall = (id, pulses) => Queue.take(pulses).pipe(Effect.timeoutOption(STALL_AFTER), Effect.flatMap((pulse) => Option.isSome(pulse) ? Effect.void : markStalled(id).pipe(Effect.andThen(Queue.take(pulses)))), Effect.forever);
375
+ const finish = Effect.fn("Clones.finish")(function* (id, phase, error) {
376
+ const endedAt = yield* Clock.currentTimeMillis;
377
+ yield* modify(id, (tracked) => ({
378
+ ...tracked,
379
+ fiber: null,
380
+ snapshot: {
381
+ ...tracked.snapshot,
382
+ phase,
383
+ endedAt,
384
+ percent: phase === "done" ? 100 : tracked.snapshot.percent,
385
+ stalled: false,
386
+ error: error === null ? null : clampText(error, ERROR_MAX)
387
+ }
388
+ }));
389
+ if (phase === "done") yield* scheduleRemoval(id);
390
+ });
391
+ const cloneWatchingForStall = Effect.fn("Clones.cloneWatchingForStall")(function* (id, tracked) {
392
+ const pulses = yield* Queue.sliding(1);
393
+ yield* watchForStall(id, pulses).pipe(Effect.forkScoped);
394
+ return yield* cloneRepository(id, tracked.cloneUrl, (update) => Queue.offer(pulses, void 0).pipe(Effect.andThen(progress(id, update))));
395
+ }, Effect.scoped);
396
+ const describeFailure = (cause) => {
397
+ const error = Cause.squash(cause);
398
+ return error instanceof Error && error.message.trim().length > 0 ? error.message : NOT_CLONED;
399
+ };
400
+ const runClone = (id, tracked) => cloneWatchingForStall(id, tracked).pipe(Effect.onExit((exit) => Exit.isSuccess(exit) ? finish(id, "done", null) : Cause.hasInterruptsOnly(exit.cause) ? finish(id, "cancelled", null) : finish(id, "failed", describeFailure(exit.cause))), Effect.ignoreCause());
401
+ const launch = Effect.fn("Clones.launch")(function* (id) {
402
+ const tracked = (yield* Ref.get(clones)).get(id);
403
+ if (!tracked) return;
404
+ const fiber = yield* runClone(id, tracked).pipe(Effect.forkIn(cloneScope));
405
+ yield* Ref.update(clones, (map) => {
406
+ const existing = map.get(id);
407
+ if (!existing) return map;
408
+ const next = new Map(map);
409
+ next.set(id, {
410
+ ...existing,
411
+ fiber
412
+ });
413
+ return next;
414
+ });
415
+ });
416
+ const get = (id) => Ref.get(clones).pipe(Effect.map((current) => current.get(id)?.snapshot ?? null));
417
+ const start = Effect.fn("Clones.start")(function* (input) {
418
+ const prepared = yield* prepare(input);
419
+ const id = prepared.destination;
420
+ const snapshot = {
421
+ path: id,
422
+ remote: prepared.remote,
423
+ phase: "running",
424
+ stage: "connecting",
425
+ percent: null,
426
+ detail: null,
427
+ stalled: false,
428
+ error: null,
429
+ startedAt: yield* Clock.currentTimeMillis,
430
+ endedAt: null,
431
+ sequence: ++sequence
432
+ };
433
+ if (!(yield* Ref.modify(clones, (current) => {
434
+ if (current.has(id)) return [false, current];
435
+ const next = new Map(current);
436
+ next.set(id, {
437
+ snapshot,
438
+ fiber: null,
439
+ cloneUrl: prepared.cloneUrl
440
+ });
441
+ return [true, next];
442
+ }))) return yield* fail$1("A clone into this destination is already in progress.");
443
+ yield* Effect.uninterruptible(Effect.gen(function* () {
444
+ yield* clearRetention(id);
445
+ const created = () => fail$1("Failed to create the clone destination.");
446
+ if (!(yield* fs.exists(id).pipe(Effect.mapError(created)))) yield* fs.makeDirectory(id, { recursive: true }).pipe(Effect.mapError(created));
447
+ yield* publish;
448
+ yield* launch(id);
449
+ }).pipe(Effect.tapError(() => remove(id))));
450
+ return {
451
+ path: id,
452
+ remote: prepared.remote
453
+ };
454
+ });
455
+ const cancel = Effect.fn("Clones.cancel")(function* (input) {
456
+ const id = resolve(input);
457
+ const tracked = (yield* Ref.get(clones)).get(id);
458
+ if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) return false;
459
+ const fiber = tracked.fiber;
460
+ yield* Effect.uninterruptible(Effect.gen(function* () {
461
+ yield* Fiber.interrupt(fiber);
462
+ const after = yield* get(id);
463
+ if (after?.phase === "done") return;
464
+ if (after?.phase === "running") yield* finish(id, "cancelled", null);
465
+ yield* discardClone(id).pipe(Effect.ignore);
466
+ }));
467
+ return true;
468
+ });
469
+ const retry = Effect.fn("Clones.retry")(function* (input) {
470
+ const id = resolve(input);
471
+ const tracked = (yield* Ref.get(clones)).get(id);
472
+ if (!tracked || tracked.snapshot.phase !== "failed" && tracked.snapshot.phase !== "cancelled") return false;
473
+ yield* discardClone(id);
474
+ const startedAt = yield* Clock.currentTimeMillis;
475
+ yield* modify(id, (entry) => ({
476
+ ...entry,
477
+ snapshot: {
478
+ ...entry.snapshot,
479
+ phase: "running",
480
+ stage: "connecting",
481
+ percent: null,
482
+ detail: null,
483
+ stalled: false,
484
+ error: null,
485
+ startedAt,
486
+ endedAt: null
487
+ }
488
+ }));
489
+ yield* launch(id);
490
+ return true;
491
+ });
492
+ const discard = Effect.fn("Clones.discard")(function* (input) {
493
+ const id = resolve(input);
494
+ const tracked = (yield* Ref.get(clones)).get(id);
495
+ if (!tracked) return;
496
+ if (tracked.fiber) yield* Fiber.interrupt(tracked.fiber);
497
+ if ((yield* get(id))?.phase !== "done") yield* discardClone(id).pipe(Effect.ignore);
498
+ yield* clearRetention(id);
499
+ yield* remove(id);
500
+ });
501
+ const guard = Effect.fn("Clones.guard")(function* (input) {
502
+ const clone = yield* get(resolve(input));
503
+ if (clone === null || clone.phase === "done") return;
504
+ return yield* fail$1(clone.phase === "running" ? "The repository is still being cloned." : "The repository was not cloned. Retry the clone first.");
505
+ });
506
+ const stream = Stream.callback((mailbox) => Effect.gen(function* () {
507
+ const subscription = yield* PubSub.subscribe(changes);
508
+ Queue.offerUnsafe(mailbox, yield* list);
509
+ yield* Stream.fromSubscription(subscription).pipe(Stream.runForEach((snapshots) => Effect.sync(() => Queue.offerUnsafe(mailbox, snapshots))), Effect.forkScoped);
510
+ }), {
511
+ bufferSize: 1,
512
+ strategy: "sliding"
513
+ });
514
+ return Service$3.of({
515
+ start: (input) => locked(start(input)),
516
+ cancel: (path) => locked(cancel(path)),
517
+ retry: (path) => locked(retry(path)),
518
+ discard: (path) => locked(discard(path)),
519
+ guard,
520
+ stream
521
+ });
522
+ });
523
+ const layer$5 = Layer.effect(Service$3, make$2);
524
+ var Service$2 = class extends Context.Service()("@codeworksh/cli/server/feed/Service") {};
525
+ /**
526
+ * Fan-out for `event.subscribe`. One listener on the event bus encodes each
527
+ * event once and hands the same envelope to every client, rather than every
528
+ * client re-encoding the same payload.
529
+ *
530
+ * Failure is per-cause, not per-feed: a client that cannot keep up fails alone
531
+ * with its own overflow, while an event that cannot be encoded is a server bug
532
+ * that disconnects everyone currently attached -- the feed stays usable for
533
+ * whoever connects next. Types outside the server's registry are dropped
534
+ * before they can consume a client's capacity.
535
+ */
536
+ const make$1 = Effect.fn("EventFeed.make")(function* (listen, options) {
537
+ const capacity = options?.capacity ?? 4096;
538
+ const registry = options?.registry ?? Core;
539
+ const subscribers = /* @__PURE__ */ new Set();
540
+ const failAll = (error) => Effect.sync(() => {
541
+ const current = Array.from(subscribers);
542
+ subscribers.clear();
543
+ for (const subscriber of current) Queue.failCauseUnsafe(subscriber, Cause.fail(error));
544
+ });
545
+ const deliver = Effect.fnUntraced(function* (event) {
546
+ if (subscribers.size === 0) return;
547
+ if (registry(event.type) === void 0) return;
548
+ const envelope = yield* encode(event, registry);
549
+ for (const subscriber of subscribers) {
550
+ if (Queue.offerUnsafe(subscriber, envelope)) continue;
551
+ subscribers.delete(subscriber);
552
+ Queue.failCauseUnsafe(subscriber, Cause.fail(new Event.SubscriptionOverflowError({ capacity })));
553
+ }
554
+ });
555
+ const publish = (event) => deliver(event).pipe(Effect.catchTags({
556
+ EventEncodingError: (error) => Effect.logError("Failed to encode public event", {
557
+ type: error.type,
558
+ cause: error.cause
559
+ }).pipe(Effect.andThen(failAll(error))),
560
+ UnknownEventTypeError: Effect.die
561
+ }));
562
+ const unsubscribe = yield* listen(publish);
563
+ yield* Effect.addFinalizer(() => unsubscribe);
564
+ return Service$2.of({ subscribe: Effect.acquireRelease(Queue.dropping(capacity).pipe(Effect.tap((queue) => Effect.sync(() => subscribers.add(queue)))), (queue) => Effect.sync(() => subscribers.delete(queue)).pipe(Effect.andThen(Queue.shutdown(queue)))).pipe(Effect.map(Stream.fromQueue)) });
565
+ });
566
+ const layer$4 = Layer.effect(Service$2, Effect.gen(function* () {
567
+ const events = yield* Event.Service;
568
+ const registered = yield* EventRegistry.Service;
569
+ return yield* make$1(events.listen, { registry: registered.get });
570
+ }));
571
+ //#endregion
572
+ //#region src/server/host.ts
573
+ /**
574
+ * Host folders for adding a project: browsing directories, creating and adding one, and looking
575
+ * repositories up through the GitHub CLI. Everything here runs on the server's host.
576
+ */
577
+ var Service$1 = class extends Context.Service()("@codeworksh/cli/server/host/Service") {};
578
+ const MAX_NAME = 200;
579
+ const MAX_ATTEMPTS = 100;
580
+ const INSTALL_GH = "Install the GitHub CLI (gh) to clone GitHub repositories.";
581
+ const LOGIN_GH = "Run `gh auth login` to sign in to GitHub.";
582
+ const NOT_FOUND = "Repository not found. Check the owner and name and try again.";
583
+ const NOT_NAMED = "Repositories are named owner/name.";
584
+ const fail = (message) => new HostError({ message });
585
+ const describe = (error, target) => error.reason._tag === "NotFound" ? `${target} does not exist.` : error.reason._tag === "PermissionDenied" ? `Permission denied: ${target}` : error.message;
586
+ /** The folder `host.create` claims for a project name: a slug that is never empty or a reserved Windows name. */
587
+ const folderName = (name) => {
588
+ const slug = name.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+/, "").slice(0, 64).replace(/-+$/, "");
589
+ if (slug.length === 0) return "project";
590
+ return /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(slug) ? `${slug}-project` : slug;
591
+ };
592
+ const commitFailure = (stderr) => {
593
+ if (/identity unknown|tell me who you are|no (name|email) was given|unable to auto-detect email|empty ident/i.test(stderr)) return "Git has no name or email set, so the first commit was skipped.";
594
+ return `The first commit was skipped: ${stderr.split("\n").map((text) => text.trim()).filter(Boolean).at(-1) ?? "git could not make it."}`;
595
+ };
596
+ const SEGMENT = /^[A-Za-z0-9_.-]+$/;
597
+ const isGitHubHost = (host) => host === "github.com" || host.includes("github");
598
+ /** `owner/name`, `host/owner/name`, an http(s) URL, or a bare `name`; undefined for anything else. */
599
+ const parseRepository = (selector) => {
600
+ const segments = (value) => value.replace(/\.git\/*$/i, "").split("/").filter(Boolean);
601
+ const named = (host, owner, name) => name !== void 0 && SEGMENT.test(name) && (owner === void 0 || SEGMENT.test(owner)) ? {
602
+ host,
603
+ name,
604
+ ...owner === void 0 ? {} : { owner }
605
+ } : void 0;
606
+ const trimmed = selector.trim();
607
+ if (/^https?:\/\//i.test(trimmed)) {
608
+ const url = URL.parse(trimmed);
609
+ const parts = url === null ? [] : segments(url.pathname);
610
+ return url !== null && parts.length === 2 ? named(url.host.toLowerCase(), parts[0], parts[1]) : void 0;
611
+ }
612
+ const parts = segments(trimmed);
613
+ const [first, second, third] = parts;
614
+ if (parts.length === 1) return named("github.com", void 0, first);
615
+ if (parts.length === 2) return named("github.com", first, second);
616
+ const host = first?.toLowerCase();
617
+ return parts.length === 3 && host !== void 0 && isGitHubHost(host) ? named(host, second, third) : void 0;
618
+ };
619
+ const decodeRepository = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Struct({
620
+ full_name: Schema.String,
621
+ html_url: Schema.String,
622
+ ssh_url: Schema.String
623
+ })));
624
+ const make = Effect.gen(function* () {
625
+ const fs = yield* FileSystem.FileSystem;
626
+ const path = yield* Path.Path;
627
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
628
+ const git = yield* Git.Service;
629
+ const home = homedir();
630
+ const info = {
631
+ home,
632
+ projects: path.join(home, "codework", "projects")
633
+ };
634
+ const resolve = (value) => path.resolve(expandTilde(value, path));
635
+ const failed = (target) => (error) => fail(describe(error, target));
636
+ const stat = (target) => fs.stat(target).pipe(Effect.asSome, Effect.catchIf((error) => error.reason._tag === "NotFound", () => Effect.succeedNone), Effect.mapError(failed(target)));
637
+ const browse = Effect.fn("Host.browse")(function* (input) {
638
+ const directory = resolve(input);
639
+ return {
640
+ path: directory,
641
+ entries: (yield* Effect.tryPromise({
642
+ try: () => readdir(directory, { withFileTypes: true }),
643
+ catch: (cause) => cause instanceof Error && "code" in cause ? String(cause.code) : void 0
644
+ }).pipe(Effect.catchIf((code) => code === "EACCES" || code === "EPERM", () => Effect.succeed([])), Effect.mapError((code) => fail(code === "ENOENT" ? `${directory} does not exist.` : code === "ENOTDIR" ? `${directory} is not a directory.` : `Could not read ${directory}.`)))).filter((entry) => entry.isDirectory()).map((entry) => ({
645
+ name: entry.name,
646
+ path: path.join(directory, entry.name)
647
+ })).toSorted((a, b) => a.name.localeCompare(b.name))
648
+ };
649
+ });
650
+ const add = Effect.fn("Host.add")(function* (input) {
651
+ const directory = resolve(input);
652
+ const found = yield* stat(directory);
653
+ if (Option.isNone(found)) yield* fs.makeDirectory(directory, { recursive: true }).pipe(Effect.mapError(failed(directory)));
654
+ else if (found.value.type !== "Directory") return yield* fail(`${directory} is not a directory.`);
655
+ return { path: directory };
656
+ });
657
+ const claim = Effect.fn("Host.claim")(function* (slug) {
658
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
659
+ const folder = path.join(info.projects, attempt === 1 ? slug : `${slug}-${attempt}`);
660
+ if (yield* fs.makeDirectory(folder).pipe(Effect.as(true), Effect.catchIf((error) => error.reason._tag === "AlreadyExists", () => Effect.succeed(false)), Effect.mapError(failed(folder)))) return folder;
661
+ }
662
+ return yield* fail(`Every folder name for "${slug}" is taken in ${info.projects}.`);
663
+ });
664
+ /** A repository with a README; answers why the first commit was skipped, if it was. */
665
+ const scaffold = Effect.fn("Host.scaffold")(function* (folder, name) {
666
+ const configured = yield* git.exec(folder, [
667
+ "config",
668
+ "--get",
669
+ "init.defaultBranch"
670
+ ]).pipe(Effect.map((result) => result.exitCode === 0 ? result.text.trim() : ""), Effect.orElseSucceed(() => ""));
671
+ yield* git.init(folder, { branch: configured || "main" }).pipe(Effect.mapError((error) => fail(error.message)));
672
+ const readme = path.join(folder, "README.md");
673
+ yield* fs.writeFileString(readme, `# ${name}\n`).pipe(Effect.mapError(failed(readme)));
674
+ const added = yield* git.exec(folder, [
675
+ "add",
676
+ "--force",
677
+ "--",
678
+ "README.md"
679
+ ]).pipe(Effect.mapError(() => fail("Could not run git add.")));
680
+ if (added.exitCode !== 0) return yield* fail(added.stderr.trim() || "git add failed.");
681
+ const committed = yield* git.exec(folder, [
682
+ "commit",
683
+ "--message",
684
+ "Initial commit"
685
+ ]).pipe(Effect.option);
686
+ if (Option.isNone(committed)) return "Could not run git commit, so the first commit was skipped.";
687
+ return committed.value.exitCode === 0 ? void 0 : commitFailure(committed.value.stderr);
688
+ });
689
+ const create = Effect.fn("Host.create")(function* (input) {
690
+ const name = input.trim();
691
+ if (name.length === 0) return yield* fail("A project needs a name.");
692
+ if (name.length > MAX_NAME) return yield* fail(`A project name is at most ${MAX_NAME} characters.`);
693
+ yield* fs.makeDirectory(info.projects, { recursive: true }).pipe(Effect.mapError(failed(info.projects)));
694
+ const folder = yield* claim(folderName(name));
695
+ const commitError = yield* scaffold(folder, name).pipe(Effect.onError(() => fs.remove(folder, { recursive: true }).pipe(Effect.ignore)));
696
+ return {
697
+ path: folder,
698
+ ...commitError === void 0 ? {} : { commitError }
699
+ };
700
+ });
701
+ const gh = Effect.fn("Host.gh")(function* (args) {
702
+ const handle = yield* spawner.spawn(ChildProcess.make("gh", [...args], {
703
+ env: {
704
+ GH_PROMPT_DISABLED: "1",
705
+ NO_COLOR: "1"
706
+ },
707
+ extendEnv: true,
708
+ stdin: "ignore",
709
+ stdout: "pipe",
710
+ stderr: "pipe"
711
+ }));
712
+ return yield* Effect.all({
713
+ exitCode: handle.exitCode,
714
+ stdout: handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
715
+ stderr: handle.stderr.pipe(Stream.decodeText(), Stream.mkString)
716
+ }, { concurrency: "unbounded" });
717
+ }, Effect.scoped);
718
+ const status = Effect.fn("Host.status")(function* () {
719
+ const version = yield* gh(["--version"]).pipe(Effect.option);
720
+ if (Option.isNone(version) || version.value.exitCode !== 0) return {
721
+ ready: false,
722
+ hint: INSTALL_GH
723
+ };
724
+ const auth = yield* gh(["auth", "status"]).pipe(Effect.option);
725
+ if (Option.isNone(auth) || auth.value.exitCode !== 0) return {
726
+ ready: false,
727
+ hint: LOGIN_GH
728
+ };
729
+ return { ready: true };
730
+ });
731
+ const lookup = Effect.fn("Host.lookup")(function* (repository) {
732
+ const selector = parseRepository(repository);
733
+ if (selector === void 0) return yield* fail(NOT_NAMED);
734
+ const hostname = selector.host === "github.com" ? [] : ["--hostname", selector.host];
735
+ const api = (args) => gh([
736
+ "api",
737
+ ...hostname,
738
+ ...args
739
+ ]).pipe(Effect.mapError(() => fail(INSTALL_GH)));
740
+ let owner = selector.owner;
741
+ if (owner === void 0) {
742
+ const user = yield* api([
743
+ "user",
744
+ "--jq",
745
+ ".login"
746
+ ]);
747
+ owner = user.stdout.trim();
748
+ if (user.exitCode !== 0 || owner.length === 0) return yield* fail(user.stderr.trim() || "Could not read the signed-in GitHub user.");
749
+ }
750
+ const result = yield* api([`repos/${owner}/${selector.name}`]);
751
+ if (result.exitCode !== 0) return yield* fail(/HTTP 404|Not Found/i.test(result.stderr) ? NOT_FOUND : result.stderr.trim() || "gh api failed.");
752
+ const found = yield* decodeRepository(result.stdout).pipe(Effect.mapError(() => fail("GitHub answered with something other than a repository.")));
753
+ return {
754
+ nameWithOwner: found.full_name,
755
+ url: found.html_url,
756
+ sshUrl: found.ssh_url
757
+ };
758
+ });
759
+ return Service$1.of({
760
+ info,
761
+ browse,
762
+ add,
763
+ create,
764
+ status,
765
+ lookup
766
+ });
767
+ });
768
+ const layer$3 = Layer.effect(Service$1, make).pipe(Layer.provide(Git.defaultLayer("/")));
769
+ //#endregion
770
+ //#region src/server/oauth.ts
771
+ /**
772
+ * Server-side OAuth credential storage.
773
+ *
774
+ * The CLI runs the interactive part of every login locally — a browser
775
+ * callback or a device code cannot travel over RPC — and sends the resulting
776
+ * credentials here, so this service only ever reads, writes, refreshes and
777
+ * clears the server home's `auth.json`.
778
+ */
779
+ var Service = class extends Context.Service()("@codeworksh/cli/server/oauth/Service") {};
780
+ const message = (cause) => cause instanceof Error && cause.message.trim().length > 0 ? cause.message : String(cause);
781
+ /**
782
+ * Re-exported so the server, the CLI and aikit all describe a login the same
783
+ * way; `Contract.OAuthInfo` is the wire shape of {@link OAuthSummary}.
784
+ */
785
+ const codexInfo = summarizeOpenAICodex;
786
+ const copilotInfo = summarizeGitHubCopilot;
787
+ const layer$2 = (options = {}) => Layer.effect(Service, Effect.gen(function* () {
788
+ const global = yield* Global.Service;
789
+ const authFile = Global.authFile(options.home === void 0 ? void 0 : global.home);
790
+ const file = authFile === void 0 ? {} : { path: authFile };
791
+ const codex = new OpenAICodexOAuthClient({ storage: new JsonOpenAICodexAuthStorage(file) });
792
+ const copilot = new GitHubCopilotOAuthClient({ storage: new JsonGitHubCopilotAuthStorage(file) });
793
+ const attempt = (run) => Effect.tryPromise({
794
+ try: run,
795
+ catch: (cause) => new OAuthError({ message: message(cause) })
796
+ });
797
+ const optional = (run, info) => attempt(run).pipe(Effect.map((value) => value === void 0 ? null : info(value)));
798
+ return Service.of({
799
+ save: (wire) => {
800
+ if (wire.provider === "openai-codex") {
801
+ const credentials = {
802
+ access: wire.access,
803
+ refresh: wire.refresh,
804
+ expires: wire.expires,
805
+ accountId: wire.accountId
806
+ };
807
+ return attempt(() => codex.storage.set(credentials)).pipe(Effect.as(codexInfo(credentials)));
808
+ }
809
+ const credentials = {
810
+ access: wire.access,
811
+ refresh: wire.refresh,
812
+ expires: wire.expires,
813
+ ...wire.enterpriseUrl === void 0 ? {} : { enterpriseUrl: wire.enterpriseUrl },
814
+ ...wire.apiEndpoint === void 0 ? {} : { apiEndpoint: wire.apiEndpoint },
815
+ ...wire.availableModelIds === void 0 ? {} : { availableModelIds: [...wire.availableModelIds] }
816
+ };
817
+ return attempt(() => copilot.storage.set(credentials)).pipe(Effect.as(copilotInfo(credentials)));
818
+ },
819
+ status: (provider) => provider === "openai-codex" ? optional(() => codex.storage.get(), codexInfo) : optional(() => copilot.storage.get(), copilotInfo),
820
+ refresh: (provider) => provider === "openai-codex" ? optional(() => codex.getCredentials(), codexInfo) : optional(() => copilot.getCredentials(), copilotInfo),
821
+ logout: (provider) => attempt(() => provider === "openai-codex" ? codex.logout() : copilot.logout())
822
+ });
823
+ }));
824
+ //#endregion
825
+ //#region src/server/handlers.ts
826
+ const toSandboxInfo = (info) => ({
827
+ id: info.id,
828
+ driver: info.driver,
829
+ kind: info.kind,
830
+ providerResourceId: info.providerResourceId,
831
+ ownership: info.ownership,
832
+ status: info.status,
833
+ usage: info.usage,
834
+ refCount: info.refCount,
835
+ createdAt: info.createdAt,
836
+ updatedAt: info.updatedAt
837
+ });
838
+ const toSessionInfo = (info) => ({
839
+ id: info.id,
840
+ directory: info.directory,
841
+ ...info.hostDir === void 0 ? {} : { hostDir: info.hostDir },
842
+ ...info.sandbox === void 0 ? {} : { sandbox: toSandboxInfo(info.sandbox) },
843
+ ...info.project === void 0 ? {} : { project: info.project },
844
+ updatedAt: info.updatedAt,
845
+ mainThreadId: info.mainThreadId
846
+ });
847
+ const toThreadInfo = (info) => ({
848
+ id: info.id,
849
+ origin: info.origin,
850
+ ...info.title === void 0 ? {} : { title: info.title },
851
+ updatedAt: info.updatedAt,
852
+ ...info.model === void 0 ? {} : { model: info.model },
853
+ ...info.thinkingLevel === void 0 ? {} : { thinkingLevel: info.thinkingLevel },
854
+ ...info.foundation === void 0 ? {} : { foundation: info.foundation },
855
+ ...info.placement === void 0 ? {} : { placement: info.placement },
856
+ usage: info.usage,
857
+ session: toSessionInfo(info.session)
858
+ });
859
+ const runtimeInput = (runtime) => ({
860
+ ...runtime?.model == null ? {} : { model: runtime.model },
861
+ ...runtime?.thinkingLevel == null ? {} : { thinkingLevel: runtime.thinkingLevel },
862
+ ...runtime?.foundation == null ? {} : { foundation: runtime.foundation }
863
+ });
864
+ const decodeFailedReply = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Struct({
865
+ stopReason: Schema.Literal("error"),
866
+ errorMessage: Schema.String,
867
+ provider: Schema.Struct({ id: Schema.String }),
868
+ model: Schema.String
869
+ })));
870
+ const replyError = (data) => Option.map(decodeFailedReply(data), (reply) => `${reply.provider.id}/${reply.model}: ${reply.errorMessage}`);
871
+ const threadInfo = (threadId) => Session.threadInfo(threadId).pipe(Effect.map(toThreadInfo));
872
+ const exported = (name, self) => self.pipe(Effect.withSpan(name, {
873
+ level: "Info",
874
+ root: true
875
+ }));
876
+ const releaseOnFailure = (selection) => selection?.created && selection.info !== void 0 ? Sandbox.stop(selection.info.id).pipe(Effect.catchCause(Effect.logError)) : Effect.void;
877
+ /** A `session.log` item for the wire: a stored event as its envelope, or the replay marker. */
878
+ const toLogItem = (registry) => (item) => Event.isSynced(item) ? Effect.succeed(item) : encode(item, registry).pipe(Effect.catchTag("UnknownEventTypeError", Effect.die));
879
+ const layer$1 = Api.toLayer(Effect.gen(function* () {
880
+ const control = yield* Control.Service;
881
+ const feed = yield* Service$2;
882
+ const sessions = yield* SessionStore.Service;
883
+ const threads = yield* ThreadStore.Service;
884
+ const resolve = (ref) => control.resolve(ref).pipe(Effect.map((thread) => ThreadSchema.ID.make(thread.id)));
885
+ const state = yield* State.Service;
886
+ const oauth = yield* Service;
887
+ const identity = yield* Service$4;
888
+ const events = yield* Event.Service;
889
+ const registry = yield* EventRegistry.Service;
890
+ const mcp = yield* Mcp.Service;
891
+ const host = yield* Service$1;
892
+ const clones = yield* Service$3;
893
+ const mcpControl = (operation) => Effect.fnUntraced(function* ({ server, ...ref }) {
894
+ return yield* mcp[operation](yield* resolve(ref), server);
895
+ });
896
+ return Api.of({
897
+ "server.info": () => Effect.succeed({
898
+ pid: identity.pid,
899
+ version: identity.version
900
+ }),
901
+ "auth.save": ({ credentials }) => oauth.save(credentials),
902
+ "auth.status": ({ provider }) => oauth.status(provider),
903
+ "auth.refresh": ({ provider }) => oauth.refresh(provider),
904
+ "auth.logout": ({ provider }) => oauth.logout(provider),
905
+ "session.create": Effect.fnUntraced(function* ({ title, directory, hostDir, sandbox, runtime, project }) {
906
+ if (hostDir !== void 0) yield* clones.guard(hostDir);
907
+ const selection = sandbox === void 0 ? void 0 : yield* exported("Server.session.create", Sandbox.resolve(sandbox));
908
+ const selected = selection?.info;
909
+ const handle = yield* Session.create({
910
+ ...title === void 0 ? {} : { title },
911
+ ...directory === void 0 ? {} : { directory },
912
+ ...hostDir === void 0 ? {} : { hostDir },
913
+ ...selected === void 0 ? {} : { sandbox: selected },
914
+ ...project === void 0 ? {} : { project },
915
+ ...runtimeInput(runtime)
916
+ }).pipe(Effect.onError(() => releaseOnFailure(selection)));
917
+ return toThreadInfo(yield* handle.main.info);
918
+ }),
919
+ "model.list": Effect.fnUntraced(function* ({ hostDir }) {
920
+ const filter = hostDir === void 0 ? {} : { hostDir };
921
+ const loaded = yield* (yield* Settings.Service).load(hostDir);
922
+ const { model } = loaded;
923
+ const providers = yield* ModelCatalog.available(filter);
924
+ const entry = (yield* ModelCatalog.effective(loaded.models))[model.provider]?.[model.id];
925
+ return {
926
+ providers: providers.flatMap((provider) => {
927
+ const models = Object.values(provider.models);
928
+ const first = models[0];
929
+ return first === void 0 ? [] : [{
930
+ id: provider.id,
931
+ name: first.provider.name,
932
+ models: models.map((info) => ({
933
+ id: info.id,
934
+ name: info.name,
935
+ thinkingLevels: Model.getSupportedThinkingLevels(info)
936
+ }))
937
+ }];
938
+ }),
939
+ default: {
940
+ provider: model.provider,
941
+ id: model.id,
942
+ thinkingLevel: model.thinkingLevel,
943
+ ...entry === void 0 ? {} : {
944
+ name: entry.name,
945
+ providerName: entry.provider.name
946
+ }
947
+ }
948
+ };
949
+ }),
950
+ "project.rename": Effect.fnUntraced(function* ({ projectId, name }) {
951
+ const renamed = yield* Project.rename({
952
+ projectId,
953
+ name
954
+ });
955
+ return {
956
+ id: renamed.id,
957
+ name: renamed.name
958
+ };
959
+ }),
960
+ "plugin.reload": Effect.fnUntraced(function* () {
961
+ return yield* state.reload;
962
+ }),
963
+ "session.link": Effect.fnUntraced(function* ({ sessionId, hostDir }) {
964
+ const handle = yield* Session.link({
965
+ sessionId,
966
+ hostDir: hostDir ?? null
967
+ });
968
+ return toSessionInfo(yield* handle.info);
969
+ }),
970
+ "session.relink": Effect.fnUntraced(function* ({ sessionId, threadId, sandbox, directory }) {
971
+ const selection = sandbox === void 0 ? void 0 : yield* exported("Server.session.relink", Sandbox.resolve(sandbox));
972
+ const selected = selection?.info;
973
+ const thread = yield* (yield* Session.relink({
974
+ sessionId,
975
+ ...threadId === void 0 ? {} : { threadId },
976
+ ...selected === void 0 ? {} : { sandbox: selected },
977
+ ...directory === void 0 ? {} : { directory }
978
+ }).pipe(Effect.onError(() => releaseOnFailure(selection)))).thread(threadId ?? ThreadSchema.MAIN);
979
+ return toThreadInfo(yield* thread.info);
980
+ }),
981
+ "session.delete": Effect.fnUntraced(function* ({ sessionId }) {
982
+ return { deleted: yield* Session.remove(sessionId) };
983
+ }),
984
+ "session.interrupt": Effect.fnUntraced(function* ({ sessionId }) {
985
+ return { interrupted: yield* control.interruptSession(sessionId, { reason: "user" }) };
986
+ }),
987
+ "session.log": ({ sessionId, threadId, after, follow }) => Stream.unwrap(Effect.gen(function* () {
988
+ if (Option.isNone(yield* sessions.get(sessionId))) return yield* new SessionStore.SessionNotFoundError({ sessionId });
989
+ return events.log({
990
+ aggregateId: sessionId,
991
+ follow: follow ?? false,
992
+ ...after === void 0 ? {} : { after }
993
+ }).pipe(Stream.filter((item) => threadId === void 0 || Event.isSynced(item) || ofThread(threadId)(item)), Stream.mapEffect(toLogItem(registry.get)));
994
+ })),
995
+ "thread.list": Effect.fnUntraced(function* ({ sessionId }) {
996
+ const rows = yield* threads.list(sessionId);
997
+ return yield* Effect.forEach(rows, (row) => threadInfo(ThreadSchema.ID.make(row.id)).pipe(Effect.orDie));
998
+ }),
999
+ "thread.info": Effect.fnUntraced(function* (ref) {
1000
+ return yield* threadInfo(yield* resolve(ref));
1001
+ }),
1002
+ "thread.configure": Effect.fnUntraced(function* ({ runtime, ...ref }) {
1003
+ const threadId = yield* resolve(ref);
1004
+ const change = {
1005
+ ...runtime.model === void 0 ? {} : { model: runtime.model },
1006
+ ...runtime.thinkingLevel === void 0 ? {} : { thinkingLevel: runtime.thinkingLevel },
1007
+ ...runtime.foundation === void 0 ? {} : { foundation: runtime.foundation }
1008
+ };
1009
+ if (Object.keys(change).length > 0) yield* events.publish(EventList.ThreadConfigured, {
1010
+ sessionId: ref.sessionId,
1011
+ threadId,
1012
+ timestamp: yield* DateTime.now,
1013
+ change
1014
+ });
1015
+ return yield* threadInfo(threadId);
1016
+ }),
1017
+ "thread.fork": Effect.fnUntraced(function* ({ entryId, mode, ...ref }) {
1018
+ const forked = yield* threads.fork({
1019
+ threadId: yield* resolve(ref),
1020
+ entryId,
1021
+ ...mode === void 0 ? {} : { mode }
1022
+ });
1023
+ return {
1024
+ thread: yield* threadInfo(ThreadSchema.ID.make(forked.thread.id)),
1025
+ ...forked.text === void 0 ? {} : { text: forked.text }
1026
+ };
1027
+ }),
1028
+ "thread.history": Effect.fnUntraced(function* (ref) {
1029
+ return { entries: (yield* threads.line(yield* resolve(ref))).flatMap(({ entry, parts }) => entry.type === "user" || entry.type === "assistant" ? [{
1030
+ id: entry.id,
1031
+ threadId: entry.threadId,
1032
+ seq: entry.seq,
1033
+ role: entry.type,
1034
+ state: entry.state,
1035
+ createdAt: DateTime.toEpochMillis(entry.createdAt),
1036
+ updatedAt: DateTime.toEpochMillis(entry.updatedAt),
1037
+ parts: parts.flatMap((part) => Option.toArray(decode(part.data))),
1038
+ ...Option.match(entry.type === "assistant" ? replyError(entry.data) : Option.none(), {
1039
+ onNone: () => ({}),
1040
+ onSome: (error) => ({ error })
1041
+ })
1042
+ }] : []) };
1043
+ }),
1044
+ "thread.queue": Effect.fnUntraced(function* (ref) {
1045
+ return { entries: (yield* control.pending(yield* resolve(ref))).map((input) => ({
1046
+ id: input.id,
1047
+ delivery: input.delivery,
1048
+ text: PromptSchema.Prompt.text(input.prompt),
1049
+ createdAt: DateTime.toEpochMillis(input.timeCreated)
1050
+ })) };
1051
+ }),
1052
+ "thread.prompt": Effect.fnUntraced(function* ({ text, delivery, id, ...ref }) {
1053
+ return { threadId: (yield* control.prompt({
1054
+ ...ref,
1055
+ prompt: PromptSchema.Prompt.fromText(text),
1056
+ ...delivery === void 0 ? {} : { delivery },
1057
+ ...id === void 0 ? {} : { id }
1058
+ })).threadId };
1059
+ }),
1060
+ "thread.interrupt": Effect.fnUntraced(function* (ref) {
1061
+ return { interrupted: yield* control.interrupt(yield* resolve(ref), { reason: "user" }) };
1062
+ }),
1063
+ "thread.cancel": Effect.fnUntraced(function* ({ messageId, ...ref }) {
1064
+ return { cancelled: yield* control.cancel(yield* resolve(ref), messageId) };
1065
+ }),
1066
+ "thread.update": Effect.fnUntraced(function* ({ messageId, delivery, text, ...ref }) {
1067
+ return { updated: yield* control.update(yield* resolve(ref), messageId, {
1068
+ ...delivery === void 0 ? {} : { delivery },
1069
+ ...text === void 0 ? {} : { prompt: PromptSchema.Prompt.fromText(text) }
1070
+ }) };
1071
+ }),
1072
+ "thread.message": Effect.fnUntraced(function* ({ messageId, ...ref }) {
1073
+ return { found: (yield* threads.line(yield* resolve(ref))).some(({ entry }) => entry.id === messageId) };
1074
+ }),
1075
+ "thread.wait": Effect.fnUntraced(function* (ref) {
1076
+ yield* control.wait(yield* resolve(ref));
1077
+ }),
1078
+ "mcp.connect": mcpControl("connect"),
1079
+ "mcp.disconnect": mcpControl("disconnect"),
1080
+ "host.info": () => Effect.succeed(host.info),
1081
+ "host.browse": ({ path }) => host.browse(path),
1082
+ "host.create": ({ name }) => host.create(name),
1083
+ "host.add": ({ path }) => host.add(path),
1084
+ "host.clone": (input) => clones.start(input),
1085
+ "host.clones": () => clones.stream,
1086
+ "host.cancel": ({ path }) => clones.cancel(path).pipe(Effect.map((applied) => ({ applied }))),
1087
+ "host.retry": ({ path }) => clones.retry(path).pipe(Effect.map((applied) => ({ applied }))),
1088
+ "host.discard": ({ path }) => clones.discard(path),
1089
+ "github.status": () => host.status(),
1090
+ "github.lookup": ({ repository }) => host.lookup(repository),
1091
+ "sandbox.drivers": Effect.fnUntraced(function* () {
1092
+ return (yield* Sandbox.drivers()).map(({ name, kind }) => ({
1093
+ name,
1094
+ kind
1095
+ }));
1096
+ }),
1097
+ "sandbox.list": Effect.fnUntraced(function* () {
1098
+ return (yield* Sandbox.list()).map(toSandboxInfo);
1099
+ }),
1100
+ "sandbox.create": Effect.fnUntraced(function* ({ driver }) {
1101
+ return toSandboxInfo(yield* exported("Server.sandbox.create", Sandbox.create({ driver })));
1102
+ }),
1103
+ "sandbox.register": Effect.fnUntraced(function* ({ driver, providerResourceId }) {
1104
+ return toSandboxInfo(yield* Sandbox.register({
1105
+ driver,
1106
+ providerResourceId
1107
+ }));
1108
+ }),
1109
+ "sandbox.stop": Effect.fnUntraced(function* ({ sandboxId }) {
1110
+ yield* Sandbox.stop(sandboxId);
1111
+ }),
1112
+ "event.subscribe": ({ threadId }) => Stream.unwrap(feed.subscribe.pipe(Effect.map((events) => Stream.make({
1113
+ id: EventSchema.ID.create(),
1114
+ type: Connected.type,
1115
+ data: {}
1116
+ }).pipe(Stream.concat(threadId === void 0 ? events : events.pipe(Stream.filter(ofThread(threadId))))))))
1117
+ });
1118
+ }));
1119
+ //#endregion
1120
+ //#region src/server/server.ts
1121
+ const managedShutdown = Layer.unwrap(Effect.gen(function* () {
1122
+ const control = yield* Control.Service;
1123
+ yield* Effect.addFinalizer(() => Effect.gen(function* () {
1124
+ yield* Effect.forEach(yield* control.active, (id) => control.interrupt(id, {
1125
+ reason: "shutdown",
1126
+ awaitSettlement: true
1127
+ }).pipe(Effect.timeout("10 seconds"), Effect.ignore), {
1128
+ concurrency: "unbounded",
1129
+ discard: true
1130
+ });
1131
+ const infos = yield* Sandbox.list();
1132
+ yield* Effect.forEach(infos.filter((info) => info.ownership === "managed"), (info) => Sandbox.stop(info.id).pipe(Effect.timeout("10 seconds"), Effect.catchCause((cause) => Effect.logError("Failed to stop managed sandbox during shutdown", cause).pipe(Effect.annotateLogs({ sandboxInstanceId: info.id })))), {
1133
+ concurrency: "unbounded",
1134
+ discard: true
1135
+ });
1136
+ }));
1137
+ return Layer.empty;
1138
+ }));
1139
+ /**
1140
+ * Resumes the runs the last server left unfinished, whether it crashed or shut down: the session
1141
+ * table records them as they start, so this needs nothing from the previous process.
1142
+ */
1143
+ const resumeUnfinished = Layer.effectDiscard(Effect.gen(function* () {
1144
+ const control = yield* Control.Service;
1145
+ yield* Effect.forkScoped(control.resumeUnfinished);
1146
+ }));
1147
+ /**
1148
+ * Advertises the listener once it has an address: logs the endpoint and files
1149
+ * the registration later invocations discover it through.
1150
+ */
1151
+ const announce = Layer.unwrap(Effect.gen(function* () {
1152
+ const server = yield* HttpServer.HttpServer;
1153
+ const global = yield* Global.Service;
1154
+ const identity = yield* Service$4;
1155
+ const address = server.address;
1156
+ const url = `${NetAddress.formatUrlUnsafe(address, "ws")}${path}`;
1157
+ yield* Effect.log(`codework serve listening on ${url}`);
1158
+ if (!NetAddress.isInetAddress(address)) return Layer.empty;
1159
+ return register({
1160
+ home: global.home,
1161
+ info: {
1162
+ pid: identity.pid,
1163
+ version: identity.version,
1164
+ url,
1165
+ port: address.port
1166
+ }
1167
+ });
1168
+ }));
1169
+ const layer = (options) => {
1170
+ const rpc = RpcServer.layerHttp({
1171
+ group: Api,
1172
+ path,
1173
+ protocol: "websocket"
1174
+ }).pipe(Layer.provide(layer$1.pipe(Layer.provide(layer$4))));
1175
+ return HttpRouter.serve(rpc, { disableListenLog: true }).pipe(Layer.provideMerge(managedShutdown), Layer.provideMerge(resumeUnfinished), Layer.provide(layer$2(options.harness.home === void 0 ? {} : { home: options.harness.home })), Layer.provide(layer$3), Layer.provide(layer$5)).pipe(Layer.provideMerge(announce), Layer.provideMerge(NodeHttpServer.layer(createServer, {
1176
+ host: options.host,
1177
+ port: options.port
1178
+ })), Layer.provide(RpcSerialization.layerNdjson), Layer.provide(layer$6), Layer.provide(Harness.layer(options.harness)));
1179
+ };
1180
+ //#endregion
1181
+ //#region src/cli/cmd/handlers/serve.ts
1182
+ const failed = Effect.sync(() => {
1183
+ process.exitCode = 1;
1184
+ });
1185
+ const report = (error) => writeError(renderError(error)).pipe(Effect.andThen(failed));
1186
+ var serve_default = handler(Cmd.commands.serve, Effect.fn("CLI.serve", { level: "Info" })(function* ({ host, port, service }) {
1187
+ const shared = yield* Cmd.spec;
1188
+ const harness = {
1189
+ ...harnessOptions(shared),
1190
+ watchModels: true
1191
+ };
1192
+ const serve = Layer.launch(layer({
1193
+ host,
1194
+ port,
1195
+ harness
1196
+ }));
1197
+ if (!service) return yield* serve.pipe(Effect.catch(report));
1198
+ yield* Effect.gen(function* () {
1199
+ const paths = yield* Global.resolve(harness.home === void 0 ? {} : { home: harness.home });
1200
+ yield* (yield* FileSystem.FileSystem).makeDirectory(paths.log, { recursive: true });
1201
+ const logger = Logger.formatSimple.pipe(Logger.toFile(log(paths.log), { flag: "w" }));
1202
+ yield* serve.pipe(Effect.catch((error) => Effect.logError(renderError(error).trim()).pipe(Effect.andThen(failed))), Effect.provide(Logger.layer([logger])));
1203
+ }).pipe(Effect.catch(report));
1204
+ }));
1205
+ //#endregion
1206
+ export { serve_default as default };
1207
+
1208
+ //# sourceMappingURL=serve-y19CU2VR.mjs.map