@codeworksh/cli 0.6.0 → 0.7.0-dev.20261103153533
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.
- package/{acp-Dr7BPHDK.mjs → acp-DByNLz1o.mjs} +4 -4
- package/{acp-Dr7BPHDK.mjs.map → acp-DByNLz1o.mjs.map} +1 -1
- package/{add-CzFz-Mfb.mjs → add-CGjQkVRs.mjs} +5 -5
- package/{add-CzFz-Mfb.mjs.map → add-CGjQkVRs.mjs.map} +1 -1
- package/{add-fJlj0O2v.mjs → add-DArbv6Op.mjs} +4 -4
- package/{add-fJlj0O2v.mjs.map → add-DArbv6Op.mjs.map} +1 -1
- package/{catalog-DCjYMhro.mjs → catalog-XfqtqMDz.mjs} +2 -2
- package/{catalog-DCjYMhro.mjs.map → catalog-XfqtqMDz.mjs.map} +1 -1
- package/{check-7oL3UVdX.mjs → check-BRHzx5p0.mjs} +4 -4
- package/{check-7oL3UVdX.mjs.map → check-BRHzx5p0.mjs.map} +1 -1
- package/{control-Bd2G-Unk.mjs → control-F0bo3rXh.mjs} +5 -5
- package/{control-Bd2G-Unk.mjs.map → control-F0bo3rXh.mjs.map} +1 -1
- package/disconnect-DemFNh2P.mjs +2 -0
- package/{entries-hMxcOaPm.mjs → entries-DnbFTTLU.mjs} +3 -3
- package/{entries-hMxcOaPm.mjs.map → entries-DnbFTTLU.mjs.map} +1 -1
- package/{error-BVSfzBzb.mjs → error--BWou73I.mjs} +141 -3
- package/error--BWou73I.mjs.map +1 -0
- package/{fork-BtL-68qs.mjs → fork-DlhNFPUB.mjs} +4 -4
- package/{fork-BtL-68qs.mjs.map → fork-DlhNFPUB.mjs.map} +1 -1
- package/{identity-D2pOA6eh.mjs → identity-DZ9fJ4gS.mjs} +2 -2
- package/{identity-D2pOA6eh.mjs.map → identity-DZ9fJ4gS.mjs.map} +1 -1
- package/index.mjs +34 -35
- package/index.mjs.map +1 -1
- package/{install-Dqx1TWtz.mjs → install-DRJ5KKyb.mjs} +4 -4
- package/{install-Dqx1TWtz.mjs.map → install-DRJ5KKyb.mjs.map} +1 -1
- package/{jsonc-BwztMdEB.mjs → jsonc-Cel7I0yd.mjs} +2 -2
- package/{jsonc-BwztMdEB.mjs.map → jsonc-Cel7I0yd.mjs.map} +1 -1
- package/{link-BilIb5jN.mjs → link-CJE1PRTf.mjs} +3 -3
- package/{link-BilIb5jN.mjs.map → link-CJE1PRTf.mjs.map} +1 -1
- package/{list-BUPm4Bsu.mjs → list-B3kSn78f.mjs} +4 -4
- package/{list-BUPm4Bsu.mjs.map → list-B3kSn78f.mjs.map} +1 -1
- package/{list-DV3VGuTp.mjs → list-Cf-zESJf.mjs} +4 -4
- package/{list-DV3VGuTp.mjs.map → list-Cf-zESJf.mjs.map} +1 -1
- package/{list-D1sa8t4P.mjs → list-Df4ngZjL.mjs} +4 -4
- package/{list-D1sa8t4P.mjs.map → list-Df4ngZjL.mjs.map} +1 -1
- package/{list-BdMdlBjQ.mjs → list-TLhgvlKp.mjs} +3 -3
- package/{list-BdMdlBjQ.mjs.map → list-TLhgvlKp.mjs.map} +1 -1
- package/{login-COjr-kTw.mjs → login-BJ3d7FM_.mjs} +4 -4
- package/{login-COjr-kTw.mjs.map → login-BJ3d7FM_.mjs.map} +1 -1
- package/{login-DC6bw2pG.mjs → login-oWLqnAQK.mjs} +4 -4
- package/{login-DC6bw2pG.mjs.map → login-oWLqnAQK.mjs.map} +1 -1
- package/{logout-CfyRsTUE.mjs → logout-ClrNQ8LO.mjs} +4 -4
- package/{logout-CfyRsTUE.mjs.map → logout-ClrNQ8LO.mjs.map} +1 -1
- package/{logout-D02BdsX6.mjs → logout-D44pgH6b.mjs} +4 -4
- package/{logout-D02BdsX6.mjs.map → logout-D44pgH6b.mjs.map} +1 -1
- package/package-kQk1S4c4.mjs +6 -0
- package/package-kQk1S4c4.mjs.map +1 -0
- package/package.json +3 -4
- package/{providers-8XcCtqG7.mjs → providers-ozcPo-AJ.mjs} +4 -4
- package/{providers-8XcCtqG7.mjs.map → providers-ozcPo-AJ.mjs.map} +1 -1
- package/reconnect-BcJtQx3U.mjs +2 -0
- package/{refresh-zDPc39tX.mjs → refresh-B6iT5eWN.mjs} +4 -4
- package/{refresh-zDPc39tX.mjs.map → refresh-B6iT5eWN.mjs.map} +1 -1
- package/{refresh-CPt2ua-n.mjs → refresh-CH7lLrF3.mjs} +4 -4
- package/{refresh-CPt2ua-n.mjs.map → refresh-CH7lLrF3.mjs.map} +1 -1
- package/{relink-Cr5T6W7K.mjs → relink-BvrynRLV.mjs} +4 -4
- package/{relink-Cr5T6W7K.mjs.map → relink-BvrynRLV.mjs.map} +1 -1
- package/{reload-xhRj21Ic.mjs → reload-qYk-KlpL.mjs} +3 -3
- package/{reload-xhRj21Ic.mjs.map → reload-qYk-KlpL.mjs.map} +1 -1
- package/{remove-DRBU8YfV.mjs → remove-Be5ytOgR.mjs} +4 -4
- package/{remove-DRBU8YfV.mjs.map → remove-Be5ytOgR.mjs.map} +1 -1
- package/{remove-BuO_0yjy.mjs → remove-CTzOWKTq.mjs} +5 -5
- package/{remove-BuO_0yjy.mjs.map → remove-CTzOWKTq.mjs.map} +1 -1
- package/{restart-B7TyHczC.mjs → restart-Bgg85KbX.mjs} +4 -4
- package/{restart-B7TyHczC.mjs.map → restart-Bgg85KbX.mjs.map} +1 -1
- package/{run-B3acSsVy.mjs → run-BX65GBq_.mjs} +4 -4
- package/{run-B3acSsVy.mjs.map → run-BX65GBq_.mjs.map} +1 -1
- package/{runtime-CwoLsQy7.mjs → runtime-CK2CunDw.mjs} +3 -18
- package/runtime-CK2CunDw.mjs.map +1 -0
- package/serve-DGKuRC1e.mjs +1208 -0
- package/serve-DGKuRC1e.mjs.map +1 -0
- package/{service-ClAs3abW.mjs → service-Bi5LhlKj.mjs} +8 -32
- package/service-Bi5LhlKj.mjs.map +1 -0
- package/{settings-Ct8kxLeD.mjs → settings-BzAk8lIo.mjs} +3 -3
- package/{settings-Ct8kxLeD.mjs.map → settings-BzAk8lIo.mjs.map} +1 -1
- package/{shared-CfaUYDk4.mjs → shared-BU8-Q5m8.mjs} +3 -3
- package/{shared-CfaUYDk4.mjs.map → shared-BU8-Q5m8.mjs.map} +1 -1
- package/{shared-5A9FR7Lo.mjs → shared-BnR3BFZM.mjs} +4 -4
- package/{shared-5A9FR7Lo.mjs.map → shared-BnR3BFZM.mjs.map} +1 -1
- package/{start-BPmacHoA.mjs → start-B1HNadNT.mjs} +4 -4
- package/{start-BPmacHoA.mjs.map → start-B1HNadNT.mjs.map} +1 -1
- package/{status-DDhz93PH.mjs → status-B-AAul1G.mjs} +4 -4
- package/{status-DDhz93PH.mjs.map → status-B-AAul1G.mjs.map} +1 -1
- package/{status-D6fIgnPp.mjs → status-CDnnxcCO.mjs} +4 -4
- package/{status-D6fIgnPp.mjs.map → status-CDnnxcCO.mjs.map} +1 -1
- package/{stop-DuDxGUsn.mjs → stop-C6QOtS6O.mjs} +4 -4
- package/{stop-DuDxGUsn.mjs.map → stop-C6QOtS6O.mjs.map} +1 -1
- package/{thread-skUkybyv.mjs → thread-BuNept5V.mjs} +2 -2
- package/{thread-skUkybyv.mjs.map → thread-BuNept5V.mjs.map} +1 -1
- package/{update-oK_209iL.mjs → update-DoS5AWg6.mjs} +4 -4
- package/{update-oK_209iL.mjs.map → update-DoS5AWg6.mjs.map} +1 -1
- package/disconnect-Dpt7LKVl.mjs +0 -2
- package/error-BVSfzBzb.mjs.map +0 -1
- package/package-D1wDsLSU.mjs +0 -6
- package/package-D1wDsLSU.mjs.map +0 -1
- package/reconnect-C4KrnFkT.mjs +0 -2
- package/runtime-CwoLsQy7.mjs.map +0 -1
- package/serve-CiiD_6i6.mjs +0 -488
- package/serve-CiiD_6i6.mjs.map +0 -1
- package/service-ClAs3abW.mjs.map +0 -1
- package/tui-Dp9hUjng.mjs +0 -76
- package/tui-Dp9hUjng.mjs.map +0 -1
package/serve-CiiD_6i6.mjs
DELETED
|
@@ -1,488 +0,0 @@
|
|
|
1
|
-
import { i as Cmd, t as handler } from "./runtime-CwoLsQy7.mjs";
|
|
2
|
-
import { C as encode, S as Core, _ as OAuthError, b as decode, g as Api, r as renderError, u as writeError, w as ofThread, x as Connected, y as path } from "./error-BVSfzBzb.mjs";
|
|
3
|
-
import { t as harnessOptions } from "./harness-6d8TlAVk.mjs";
|
|
4
|
-
import { c as register, r as layer$4, s as log, t as Service$2 } from "./identity-D2pOA6eh.mjs";
|
|
5
|
-
import { Cause, Context, DateTime, Effect, FileSystem, Layer, Logger, Option, Queue, Schema, Stream } from "effect";
|
|
6
|
-
import { Model } from "@codeworksh/aikit";
|
|
7
|
-
import { HttpRouter, HttpServer } from "effect/http";
|
|
8
|
-
import { Control, Event, EventList, EventRegistry, EventSchema, Global, Harness, Mcp, ModelCatalog, Project, PromptSchema, Sandbox, Session, SessionStore, Settings, State, ThreadSchema, ThreadStore } 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
|
-
var Service$1 = class extends Context.Service()("@codeworksh/cli/server/feed/Service") {};
|
|
17
|
-
/**
|
|
18
|
-
* Fan-out for `event.subscribe`. One listener on the event bus encodes each
|
|
19
|
-
* event once and hands the same envelope to every client, rather than every
|
|
20
|
-
* client re-encoding the same payload.
|
|
21
|
-
*
|
|
22
|
-
* Failure is per-cause, not per-feed: a client that cannot keep up fails alone
|
|
23
|
-
* with its own overflow, while an event that cannot be encoded is a server bug
|
|
24
|
-
* that disconnects everyone currently attached -- the feed stays usable for
|
|
25
|
-
* whoever connects next. Types outside the server's registry are dropped
|
|
26
|
-
* before they can consume a client's capacity.
|
|
27
|
-
*/
|
|
28
|
-
const make = Effect.fn("EventFeed.make")(function* (listen, options) {
|
|
29
|
-
const capacity = options?.capacity ?? 4096;
|
|
30
|
-
const registry = options?.registry ?? Core;
|
|
31
|
-
const subscribers = /* @__PURE__ */ new Set();
|
|
32
|
-
const failAll = (error) => Effect.sync(() => {
|
|
33
|
-
const current = Array.from(subscribers);
|
|
34
|
-
subscribers.clear();
|
|
35
|
-
for (const subscriber of current) Queue.failCauseUnsafe(subscriber, Cause.fail(error));
|
|
36
|
-
});
|
|
37
|
-
const deliver = Effect.fnUntraced(function* (event) {
|
|
38
|
-
if (subscribers.size === 0) return;
|
|
39
|
-
if (registry(event.type) === void 0) return;
|
|
40
|
-
const envelope = yield* encode(event, registry);
|
|
41
|
-
for (const subscriber of subscribers) {
|
|
42
|
-
if (Queue.offerUnsafe(subscriber, envelope)) continue;
|
|
43
|
-
subscribers.delete(subscriber);
|
|
44
|
-
Queue.failCauseUnsafe(subscriber, Cause.fail(new Event.SubscriptionOverflowError({ capacity })));
|
|
45
|
-
}
|
|
46
|
-
});
|
|
47
|
-
const publish = (event) => deliver(event).pipe(Effect.catchTags({
|
|
48
|
-
EventEncodingError: (error) => Effect.logError("Failed to encode public event", {
|
|
49
|
-
type: error.type,
|
|
50
|
-
cause: error.cause
|
|
51
|
-
}).pipe(Effect.andThen(failAll(error))),
|
|
52
|
-
UnknownEventTypeError: Effect.die
|
|
53
|
-
}));
|
|
54
|
-
const unsubscribe = yield* listen(publish);
|
|
55
|
-
yield* Effect.addFinalizer(() => unsubscribe);
|
|
56
|
-
return Service$1.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)) });
|
|
57
|
-
});
|
|
58
|
-
const layer$3 = Layer.effect(Service$1, Effect.gen(function* () {
|
|
59
|
-
const events = yield* Event.Service;
|
|
60
|
-
const registered = yield* EventRegistry.Service;
|
|
61
|
-
return yield* make(events.listen, { registry: registered.get });
|
|
62
|
-
}));
|
|
63
|
-
//#endregion
|
|
64
|
-
//#region src/server/oauth.ts
|
|
65
|
-
/**
|
|
66
|
-
* Server-side OAuth credential storage.
|
|
67
|
-
*
|
|
68
|
-
* The CLI runs the interactive part of every login locally — a browser
|
|
69
|
-
* callback or a device code cannot travel over RPC — and sends the resulting
|
|
70
|
-
* credentials here, so this service only ever reads, writes, refreshes and
|
|
71
|
-
* clears the server home's `auth.json`.
|
|
72
|
-
*/
|
|
73
|
-
var Service = class extends Context.Service()("@codeworksh/cli/server/oauth/Service") {};
|
|
74
|
-
const message = (cause) => cause instanceof Error && cause.message.trim().length > 0 ? cause.message : String(cause);
|
|
75
|
-
/**
|
|
76
|
-
* Re-exported so the server, the CLI and aikit all describe a login the same
|
|
77
|
-
* way; `Contract.OAuthInfo` is the wire shape of {@link OAuthSummary}.
|
|
78
|
-
*/
|
|
79
|
-
const codexInfo = summarizeOpenAICodex;
|
|
80
|
-
const copilotInfo = summarizeGitHubCopilot;
|
|
81
|
-
const layer$2 = (options = {}) => Layer.effect(Service, Effect.gen(function* () {
|
|
82
|
-
const global = yield* Global.Service;
|
|
83
|
-
const authFile = Global.authFile(options.home === void 0 ? void 0 : global.home);
|
|
84
|
-
const file = authFile === void 0 ? {} : { path: authFile };
|
|
85
|
-
const codex = new OpenAICodexOAuthClient({ storage: new JsonOpenAICodexAuthStorage(file) });
|
|
86
|
-
const copilot = new GitHubCopilotOAuthClient({ storage: new JsonGitHubCopilotAuthStorage(file) });
|
|
87
|
-
const attempt = (run) => Effect.tryPromise({
|
|
88
|
-
try: run,
|
|
89
|
-
catch: (cause) => new OAuthError({ message: message(cause) })
|
|
90
|
-
});
|
|
91
|
-
const optional = (run, info) => attempt(run).pipe(Effect.map((value) => value === void 0 ? null : info(value)));
|
|
92
|
-
return Service.of({
|
|
93
|
-
save: (wire) => {
|
|
94
|
-
if (wire.provider === "openai-codex") {
|
|
95
|
-
const credentials = {
|
|
96
|
-
access: wire.access,
|
|
97
|
-
refresh: wire.refresh,
|
|
98
|
-
expires: wire.expires,
|
|
99
|
-
accountId: wire.accountId
|
|
100
|
-
};
|
|
101
|
-
return attempt(() => codex.storage.set(credentials)).pipe(Effect.as(codexInfo(credentials)));
|
|
102
|
-
}
|
|
103
|
-
const credentials = {
|
|
104
|
-
access: wire.access,
|
|
105
|
-
refresh: wire.refresh,
|
|
106
|
-
expires: wire.expires,
|
|
107
|
-
...wire.enterpriseUrl === void 0 ? {} : { enterpriseUrl: wire.enterpriseUrl },
|
|
108
|
-
...wire.apiEndpoint === void 0 ? {} : { apiEndpoint: wire.apiEndpoint },
|
|
109
|
-
...wire.availableModelIds === void 0 ? {} : { availableModelIds: [...wire.availableModelIds] }
|
|
110
|
-
};
|
|
111
|
-
return attempt(() => copilot.storage.set(credentials)).pipe(Effect.as(copilotInfo(credentials)));
|
|
112
|
-
},
|
|
113
|
-
status: (provider) => provider === "openai-codex" ? optional(() => codex.storage.get(), codexInfo) : optional(() => copilot.storage.get(), copilotInfo),
|
|
114
|
-
refresh: (provider) => provider === "openai-codex" ? optional(() => codex.getCredentials(), codexInfo) : optional(() => copilot.getCredentials(), copilotInfo),
|
|
115
|
-
logout: (provider) => attempt(() => provider === "openai-codex" ? codex.logout() : copilot.logout())
|
|
116
|
-
});
|
|
117
|
-
}));
|
|
118
|
-
//#endregion
|
|
119
|
-
//#region src/server/handlers.ts
|
|
120
|
-
const toSandboxInfo = (info) => ({
|
|
121
|
-
id: info.id,
|
|
122
|
-
driver: info.driver,
|
|
123
|
-
kind: info.kind,
|
|
124
|
-
providerResourceId: info.providerResourceId,
|
|
125
|
-
ownership: info.ownership,
|
|
126
|
-
status: info.status,
|
|
127
|
-
usage: info.usage,
|
|
128
|
-
refCount: info.refCount,
|
|
129
|
-
createdAt: info.createdAt,
|
|
130
|
-
updatedAt: info.updatedAt
|
|
131
|
-
});
|
|
132
|
-
const toSessionInfo = (info) => ({
|
|
133
|
-
id: info.id,
|
|
134
|
-
directory: info.directory,
|
|
135
|
-
...info.hostDir === void 0 ? {} : { hostDir: info.hostDir },
|
|
136
|
-
...info.sandbox === void 0 ? {} : { sandbox: toSandboxInfo(info.sandbox) },
|
|
137
|
-
...info.project === void 0 ? {} : { project: info.project },
|
|
138
|
-
updatedAt: info.updatedAt,
|
|
139
|
-
mainThreadId: info.mainThreadId
|
|
140
|
-
});
|
|
141
|
-
const toThreadInfo = (info) => ({
|
|
142
|
-
id: info.id,
|
|
143
|
-
origin: info.origin,
|
|
144
|
-
...info.title === void 0 ? {} : { title: info.title },
|
|
145
|
-
updatedAt: info.updatedAt,
|
|
146
|
-
...info.model === void 0 ? {} : { model: info.model },
|
|
147
|
-
...info.thinkingLevel === void 0 ? {} : { thinkingLevel: info.thinkingLevel },
|
|
148
|
-
...info.foundation === void 0 ? {} : { foundation: info.foundation },
|
|
149
|
-
...info.placement === void 0 ? {} : { placement: info.placement },
|
|
150
|
-
usage: info.usage,
|
|
151
|
-
session: toSessionInfo(info.session)
|
|
152
|
-
});
|
|
153
|
-
const runtimeInput = (runtime) => ({
|
|
154
|
-
...runtime?.model == null ? {} : { model: runtime.model },
|
|
155
|
-
...runtime?.thinkingLevel == null ? {} : { thinkingLevel: runtime.thinkingLevel },
|
|
156
|
-
...runtime?.foundation == null ? {} : { foundation: runtime.foundation }
|
|
157
|
-
});
|
|
158
|
-
const decodeFailedReply = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Struct({
|
|
159
|
-
stopReason: Schema.Literal("error"),
|
|
160
|
-
errorMessage: Schema.String,
|
|
161
|
-
provider: Schema.Struct({ id: Schema.String }),
|
|
162
|
-
model: Schema.String
|
|
163
|
-
})));
|
|
164
|
-
const replyError = (data) => Option.map(decodeFailedReply(data), (reply) => `${reply.provider.id}/${reply.model}: ${reply.errorMessage}`);
|
|
165
|
-
const threadInfo = (threadId) => Session.threadInfo(threadId).pipe(Effect.map(toThreadInfo));
|
|
166
|
-
const exported = (name, self) => self.pipe(Effect.withSpan(name, {
|
|
167
|
-
level: "Info",
|
|
168
|
-
root: true
|
|
169
|
-
}));
|
|
170
|
-
const releaseOnFailure = (selection) => selection?.created && selection.info !== void 0 ? Sandbox.stop(selection.info.id).pipe(Effect.catchCause(Effect.logError)) : Effect.void;
|
|
171
|
-
/** A `session.log` item for the wire: a stored event as its envelope, or the replay marker. */
|
|
172
|
-
const toLogItem = (registry) => (item) => Event.isSynced(item) ? Effect.succeed(item) : encode(item, registry).pipe(Effect.catchTag("UnknownEventTypeError", Effect.die));
|
|
173
|
-
const layer$1 = Api.toLayer(Effect.gen(function* () {
|
|
174
|
-
const control = yield* Control.Service;
|
|
175
|
-
const feed = yield* Service$1;
|
|
176
|
-
const sessions = yield* SessionStore.Service;
|
|
177
|
-
const threads = yield* ThreadStore.Service;
|
|
178
|
-
const resolve = (ref) => control.resolve(ref).pipe(Effect.map((thread) => ThreadSchema.ID.make(thread.id)));
|
|
179
|
-
const state = yield* State.Service;
|
|
180
|
-
const oauth = yield* Service;
|
|
181
|
-
const identity = yield* Service$2;
|
|
182
|
-
const events = yield* Event.Service;
|
|
183
|
-
const registry = yield* EventRegistry.Service;
|
|
184
|
-
const mcp = yield* Mcp.Service;
|
|
185
|
-
const mcpControl = (operation) => Effect.fnUntraced(function* ({ server, ...ref }) {
|
|
186
|
-
return yield* mcp[operation](yield* resolve(ref), server);
|
|
187
|
-
});
|
|
188
|
-
return Api.of({
|
|
189
|
-
"server.info": () => Effect.succeed({
|
|
190
|
-
pid: identity.pid,
|
|
191
|
-
version: identity.version
|
|
192
|
-
}),
|
|
193
|
-
"auth.save": ({ credentials }) => oauth.save(credentials),
|
|
194
|
-
"auth.status": ({ provider }) => oauth.status(provider),
|
|
195
|
-
"auth.refresh": ({ provider }) => oauth.refresh(provider),
|
|
196
|
-
"auth.logout": ({ provider }) => oauth.logout(provider),
|
|
197
|
-
"session.create": Effect.fnUntraced(function* ({ title, directory, hostDir, sandbox, runtime, project }) {
|
|
198
|
-
const selection = sandbox === void 0 ? void 0 : yield* exported("Server.session.create", Sandbox.resolve(sandbox));
|
|
199
|
-
const selected = selection?.info;
|
|
200
|
-
const handle = yield* Session.create({
|
|
201
|
-
...title === void 0 ? {} : { title },
|
|
202
|
-
...directory === void 0 ? {} : { directory },
|
|
203
|
-
...hostDir === void 0 ? {} : { hostDir },
|
|
204
|
-
...selected === void 0 ? {} : { sandbox: selected },
|
|
205
|
-
...project === void 0 ? {} : { project },
|
|
206
|
-
...runtimeInput(runtime)
|
|
207
|
-
}).pipe(Effect.onError(() => releaseOnFailure(selection)));
|
|
208
|
-
return toThreadInfo(yield* handle.main.info);
|
|
209
|
-
}),
|
|
210
|
-
"model.list": Effect.fnUntraced(function* ({ hostDir }) {
|
|
211
|
-
const filter = hostDir === void 0 ? {} : { hostDir };
|
|
212
|
-
const loaded = yield* (yield* Settings.Service).load(hostDir);
|
|
213
|
-
const { model } = loaded;
|
|
214
|
-
const providers = yield* ModelCatalog.available(filter);
|
|
215
|
-
const entry = (yield* ModelCatalog.effective(loaded.models))[model.provider]?.[model.id];
|
|
216
|
-
return {
|
|
217
|
-
providers: providers.flatMap((provider) => {
|
|
218
|
-
const models = Object.values(provider.models);
|
|
219
|
-
const first = models[0];
|
|
220
|
-
return first === void 0 ? [] : [{
|
|
221
|
-
id: provider.id,
|
|
222
|
-
name: first.provider.name,
|
|
223
|
-
models: models.map((info) => ({
|
|
224
|
-
id: info.id,
|
|
225
|
-
name: info.name,
|
|
226
|
-
thinkingLevels: Model.getSupportedThinkingLevels(info)
|
|
227
|
-
}))
|
|
228
|
-
}];
|
|
229
|
-
}),
|
|
230
|
-
default: {
|
|
231
|
-
provider: model.provider,
|
|
232
|
-
id: model.id,
|
|
233
|
-
thinkingLevel: model.thinkingLevel,
|
|
234
|
-
...entry === void 0 ? {} : {
|
|
235
|
-
name: entry.name,
|
|
236
|
-
providerName: entry.provider.name
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
};
|
|
240
|
-
}),
|
|
241
|
-
"project.rename": Effect.fnUntraced(function* ({ projectId, name }) {
|
|
242
|
-
const renamed = yield* Project.rename({
|
|
243
|
-
projectId,
|
|
244
|
-
name
|
|
245
|
-
});
|
|
246
|
-
return {
|
|
247
|
-
id: renamed.id,
|
|
248
|
-
name: renamed.name
|
|
249
|
-
};
|
|
250
|
-
}),
|
|
251
|
-
"plugin.reload": Effect.fnUntraced(function* () {
|
|
252
|
-
return yield* state.reload;
|
|
253
|
-
}),
|
|
254
|
-
"session.link": Effect.fnUntraced(function* ({ sessionId, hostDir }) {
|
|
255
|
-
const handle = yield* Session.link({
|
|
256
|
-
sessionId,
|
|
257
|
-
hostDir: hostDir ?? null
|
|
258
|
-
});
|
|
259
|
-
return toSessionInfo(yield* handle.info);
|
|
260
|
-
}),
|
|
261
|
-
"session.relink": Effect.fnUntraced(function* ({ sessionId, threadId, sandbox, directory }) {
|
|
262
|
-
const selection = sandbox === void 0 ? void 0 : yield* exported("Server.session.relink", Sandbox.resolve(sandbox));
|
|
263
|
-
const selected = selection?.info;
|
|
264
|
-
const thread = yield* (yield* Session.relink({
|
|
265
|
-
sessionId,
|
|
266
|
-
...threadId === void 0 ? {} : { threadId },
|
|
267
|
-
...selected === void 0 ? {} : { sandbox: selected },
|
|
268
|
-
...directory === void 0 ? {} : { directory }
|
|
269
|
-
}).pipe(Effect.onError(() => releaseOnFailure(selection)))).thread(threadId ?? ThreadSchema.MAIN);
|
|
270
|
-
return toThreadInfo(yield* thread.info);
|
|
271
|
-
}),
|
|
272
|
-
"session.delete": Effect.fnUntraced(function* ({ sessionId }) {
|
|
273
|
-
return { deleted: yield* Session.remove(sessionId) };
|
|
274
|
-
}),
|
|
275
|
-
"session.interrupt": Effect.fnUntraced(function* ({ sessionId }) {
|
|
276
|
-
return { interrupted: yield* control.interruptSession(sessionId, { reason: "user" }) };
|
|
277
|
-
}),
|
|
278
|
-
"session.log": ({ sessionId, threadId, after, follow }) => Stream.unwrap(Effect.gen(function* () {
|
|
279
|
-
if (Option.isNone(yield* sessions.get(sessionId))) return yield* new SessionStore.SessionNotFoundError({ sessionId });
|
|
280
|
-
return events.log({
|
|
281
|
-
aggregateId: sessionId,
|
|
282
|
-
follow: follow ?? false,
|
|
283
|
-
...after === void 0 ? {} : { after }
|
|
284
|
-
}).pipe(Stream.filter((item) => threadId === void 0 || Event.isSynced(item) || ofThread(threadId)(item)), Stream.mapEffect(toLogItem(registry.get)));
|
|
285
|
-
})),
|
|
286
|
-
"thread.list": Effect.fnUntraced(function* ({ sessionId }) {
|
|
287
|
-
const rows = yield* threads.list(sessionId);
|
|
288
|
-
return yield* Effect.forEach(rows, (row) => threadInfo(ThreadSchema.ID.make(row.id)).pipe(Effect.orDie));
|
|
289
|
-
}),
|
|
290
|
-
"thread.info": Effect.fnUntraced(function* (ref) {
|
|
291
|
-
return yield* threadInfo(yield* resolve(ref));
|
|
292
|
-
}),
|
|
293
|
-
"thread.configure": Effect.fnUntraced(function* ({ runtime, ...ref }) {
|
|
294
|
-
const threadId = yield* resolve(ref);
|
|
295
|
-
const change = {
|
|
296
|
-
...runtime.model === void 0 ? {} : { model: runtime.model },
|
|
297
|
-
...runtime.thinkingLevel === void 0 ? {} : { thinkingLevel: runtime.thinkingLevel },
|
|
298
|
-
...runtime.foundation === void 0 ? {} : { foundation: runtime.foundation }
|
|
299
|
-
};
|
|
300
|
-
if (Object.keys(change).length > 0) yield* events.publish(EventList.ThreadConfigured, {
|
|
301
|
-
sessionId: ref.sessionId,
|
|
302
|
-
threadId,
|
|
303
|
-
timestamp: yield* DateTime.now,
|
|
304
|
-
change
|
|
305
|
-
});
|
|
306
|
-
return yield* threadInfo(threadId);
|
|
307
|
-
}),
|
|
308
|
-
"thread.fork": Effect.fnUntraced(function* ({ entryId, mode, ...ref }) {
|
|
309
|
-
const forked = yield* threads.fork({
|
|
310
|
-
threadId: yield* resolve(ref),
|
|
311
|
-
entryId,
|
|
312
|
-
...mode === void 0 ? {} : { mode }
|
|
313
|
-
});
|
|
314
|
-
return {
|
|
315
|
-
thread: yield* threadInfo(ThreadSchema.ID.make(forked.thread.id)),
|
|
316
|
-
...forked.text === void 0 ? {} : { text: forked.text }
|
|
317
|
-
};
|
|
318
|
-
}),
|
|
319
|
-
"thread.history": Effect.fnUntraced(function* (ref) {
|
|
320
|
-
return { entries: (yield* threads.line(yield* resolve(ref))).flatMap(({ entry, parts }) => entry.type === "user" || entry.type === "assistant" ? [{
|
|
321
|
-
id: entry.id,
|
|
322
|
-
threadId: entry.threadId,
|
|
323
|
-
seq: entry.seq,
|
|
324
|
-
role: entry.type,
|
|
325
|
-
state: entry.state,
|
|
326
|
-
createdAt: DateTime.toEpochMillis(entry.createdAt),
|
|
327
|
-
updatedAt: DateTime.toEpochMillis(entry.updatedAt),
|
|
328
|
-
parts: parts.flatMap((part) => Option.toArray(decode(part.data))),
|
|
329
|
-
...Option.match(entry.type === "assistant" ? replyError(entry.data) : Option.none(), {
|
|
330
|
-
onNone: () => ({}),
|
|
331
|
-
onSome: (error) => ({ error })
|
|
332
|
-
})
|
|
333
|
-
}] : []) };
|
|
334
|
-
}),
|
|
335
|
-
"thread.queue": Effect.fnUntraced(function* (ref) {
|
|
336
|
-
return { entries: (yield* control.pending(yield* resolve(ref))).map((input) => ({
|
|
337
|
-
id: input.id,
|
|
338
|
-
delivery: input.delivery,
|
|
339
|
-
text: PromptSchema.Prompt.text(input.prompt),
|
|
340
|
-
createdAt: DateTime.toEpochMillis(input.timeCreated)
|
|
341
|
-
})) };
|
|
342
|
-
}),
|
|
343
|
-
"thread.prompt": Effect.fnUntraced(function* ({ text, delivery, id, ...ref }) {
|
|
344
|
-
return { threadId: (yield* control.prompt({
|
|
345
|
-
...ref,
|
|
346
|
-
prompt: PromptSchema.Prompt.fromText(text),
|
|
347
|
-
...delivery === void 0 ? {} : { delivery },
|
|
348
|
-
...id === void 0 ? {} : { id }
|
|
349
|
-
})).threadId };
|
|
350
|
-
}),
|
|
351
|
-
"thread.interrupt": Effect.fnUntraced(function* (ref) {
|
|
352
|
-
return { interrupted: yield* control.interrupt(yield* resolve(ref), { reason: "user" }) };
|
|
353
|
-
}),
|
|
354
|
-
"thread.cancel": Effect.fnUntraced(function* ({ messageId, ...ref }) {
|
|
355
|
-
return { cancelled: yield* control.cancel(yield* resolve(ref), messageId) };
|
|
356
|
-
}),
|
|
357
|
-
"thread.update": Effect.fnUntraced(function* ({ messageId, delivery, text, ...ref }) {
|
|
358
|
-
return { updated: yield* control.update(yield* resolve(ref), messageId, {
|
|
359
|
-
...delivery === void 0 ? {} : { delivery },
|
|
360
|
-
...text === void 0 ? {} : { prompt: PromptSchema.Prompt.fromText(text) }
|
|
361
|
-
}) };
|
|
362
|
-
}),
|
|
363
|
-
"thread.message": Effect.fnUntraced(function* ({ messageId, ...ref }) {
|
|
364
|
-
return { found: (yield* threads.line(yield* resolve(ref))).some(({ entry }) => entry.id === messageId) };
|
|
365
|
-
}),
|
|
366
|
-
"thread.wait": Effect.fnUntraced(function* (ref) {
|
|
367
|
-
yield* control.wait(yield* resolve(ref));
|
|
368
|
-
}),
|
|
369
|
-
"mcp.connect": mcpControl("connect"),
|
|
370
|
-
"mcp.disconnect": mcpControl("disconnect"),
|
|
371
|
-
"sandbox.drivers": Effect.fnUntraced(function* () {
|
|
372
|
-
return (yield* Sandbox.drivers()).map(({ name, kind }) => ({
|
|
373
|
-
name,
|
|
374
|
-
kind
|
|
375
|
-
}));
|
|
376
|
-
}),
|
|
377
|
-
"sandbox.list": Effect.fnUntraced(function* () {
|
|
378
|
-
return (yield* Sandbox.list()).map(toSandboxInfo);
|
|
379
|
-
}),
|
|
380
|
-
"sandbox.create": Effect.fnUntraced(function* ({ driver }) {
|
|
381
|
-
return toSandboxInfo(yield* exported("Server.sandbox.create", Sandbox.create({ driver })));
|
|
382
|
-
}),
|
|
383
|
-
"sandbox.register": Effect.fnUntraced(function* ({ driver, providerResourceId }) {
|
|
384
|
-
return toSandboxInfo(yield* Sandbox.register({
|
|
385
|
-
driver,
|
|
386
|
-
providerResourceId
|
|
387
|
-
}));
|
|
388
|
-
}),
|
|
389
|
-
"sandbox.stop": Effect.fnUntraced(function* ({ sandboxId }) {
|
|
390
|
-
yield* Sandbox.stop(sandboxId);
|
|
391
|
-
}),
|
|
392
|
-
"event.subscribe": ({ threadId }) => Stream.unwrap(feed.subscribe.pipe(Effect.map((events) => Stream.make({
|
|
393
|
-
id: EventSchema.ID.create(),
|
|
394
|
-
type: Connected.type,
|
|
395
|
-
data: {}
|
|
396
|
-
}).pipe(Stream.concat(threadId === void 0 ? events : events.pipe(Stream.filter(ofThread(threadId))))))))
|
|
397
|
-
});
|
|
398
|
-
}));
|
|
399
|
-
//#endregion
|
|
400
|
-
//#region src/server/server.ts
|
|
401
|
-
const managedShutdown = Layer.unwrap(Effect.gen(function* () {
|
|
402
|
-
const control = yield* Control.Service;
|
|
403
|
-
yield* Effect.addFinalizer(() => Effect.gen(function* () {
|
|
404
|
-
yield* Effect.forEach(yield* control.active, (id) => control.interrupt(id, {
|
|
405
|
-
reason: "shutdown",
|
|
406
|
-
awaitSettlement: true
|
|
407
|
-
}).pipe(Effect.timeout("10 seconds"), Effect.ignore), {
|
|
408
|
-
concurrency: "unbounded",
|
|
409
|
-
discard: true
|
|
410
|
-
});
|
|
411
|
-
const infos = yield* Sandbox.list();
|
|
412
|
-
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 })))), {
|
|
413
|
-
concurrency: "unbounded",
|
|
414
|
-
discard: true
|
|
415
|
-
});
|
|
416
|
-
}));
|
|
417
|
-
return Layer.empty;
|
|
418
|
-
}));
|
|
419
|
-
/**
|
|
420
|
-
* Resumes the runs the last server left unfinished, whether it crashed or shut down: the session
|
|
421
|
-
* table records them as they start, so this needs nothing from the previous process.
|
|
422
|
-
*/
|
|
423
|
-
const resumeUnfinished = Layer.effectDiscard(Effect.gen(function* () {
|
|
424
|
-
const control = yield* Control.Service;
|
|
425
|
-
yield* Effect.forkScoped(control.resumeUnfinished);
|
|
426
|
-
}));
|
|
427
|
-
/**
|
|
428
|
-
* Advertises the listener once it has an address: logs the endpoint and files
|
|
429
|
-
* the registration later invocations discover it through.
|
|
430
|
-
*/
|
|
431
|
-
const announce = Layer.unwrap(Effect.gen(function* () {
|
|
432
|
-
const server = yield* HttpServer.HttpServer;
|
|
433
|
-
const global = yield* Global.Service;
|
|
434
|
-
const identity = yield* Service$2;
|
|
435
|
-
const address = server.address;
|
|
436
|
-
const url = `${NetAddress.formatUrlUnsafe(address, "ws")}${path}`;
|
|
437
|
-
yield* Effect.log(`codework serve listening on ${url}`);
|
|
438
|
-
if (!NetAddress.isInetAddress(address)) return Layer.empty;
|
|
439
|
-
return register({
|
|
440
|
-
home: global.home,
|
|
441
|
-
info: {
|
|
442
|
-
pid: identity.pid,
|
|
443
|
-
version: identity.version,
|
|
444
|
-
url,
|
|
445
|
-
port: address.port
|
|
446
|
-
}
|
|
447
|
-
});
|
|
448
|
-
}));
|
|
449
|
-
const layer = (options) => {
|
|
450
|
-
const rpc = RpcServer.layerHttp({
|
|
451
|
-
group: Api,
|
|
452
|
-
path,
|
|
453
|
-
protocol: "websocket"
|
|
454
|
-
}).pipe(Layer.provide(layer$1.pipe(Layer.provide(layer$3))));
|
|
455
|
-
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 }))).pipe(Layer.provideMerge(announce), Layer.provideMerge(NodeHttpServer.layer(createServer, {
|
|
456
|
-
host: options.host,
|
|
457
|
-
port: options.port
|
|
458
|
-
})), Layer.provide(RpcSerialization.layerNdjson), Layer.provide(layer$4), Layer.provide(Harness.layer(options.harness)));
|
|
459
|
-
};
|
|
460
|
-
//#endregion
|
|
461
|
-
//#region src/cli/cmd/handlers/serve.ts
|
|
462
|
-
const failed = Effect.sync(() => {
|
|
463
|
-
process.exitCode = 1;
|
|
464
|
-
});
|
|
465
|
-
const report = (error) => writeError(renderError(error)).pipe(Effect.andThen(failed));
|
|
466
|
-
var serve_default = handler(Cmd.commands.serve, Effect.fn("CLI.serve", { level: "Info" })(function* ({ host, port, service }) {
|
|
467
|
-
const shared = yield* Cmd.spec;
|
|
468
|
-
const harness = {
|
|
469
|
-
...harnessOptions(shared),
|
|
470
|
-
watchModels: true
|
|
471
|
-
};
|
|
472
|
-
const serve = Layer.launch(layer({
|
|
473
|
-
host,
|
|
474
|
-
port,
|
|
475
|
-
harness
|
|
476
|
-
}));
|
|
477
|
-
if (!service) return yield* serve.pipe(Effect.catch(report));
|
|
478
|
-
yield* Effect.gen(function* () {
|
|
479
|
-
const paths = yield* Global.resolve(harness.home === void 0 ? {} : { home: harness.home });
|
|
480
|
-
yield* (yield* FileSystem.FileSystem).makeDirectory(paths.log, { recursive: true });
|
|
481
|
-
const logger = Logger.formatSimple.pipe(Logger.toFile(log(paths.log), { flag: "w" }));
|
|
482
|
-
yield* serve.pipe(Effect.catch((error) => Effect.logError(renderError(error).trim()).pipe(Effect.andThen(failed))), Effect.provide(Logger.layer([logger])));
|
|
483
|
-
}).pipe(Effect.catch(report));
|
|
484
|
-
}));
|
|
485
|
-
//#endregion
|
|
486
|
-
export { serve_default as default };
|
|
487
|
-
|
|
488
|
-
//# sourceMappingURL=serve-CiiD_6i6.mjs.map
|
package/serve-CiiD_6i6.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"serve-CiiD_6i6.mjs","names":["Service","Envelope.Core","Envelope.encode","layer","layer","Contract.OAuthError","Envelope.encode","layer","EventFeed.Service","OAuth.Service","Identity.Service","Envelope.ofThread","MessagePart.decode","Identity.Service","Contract.path","Registration.register","Contract.Api","EventFeed.layer","OAuth.layer","Identity.layer","Runtime.handler","Server.layer","Registration.log"],"sources":["../../src/server/feed.ts","../../src/server/oauth.ts","../../src/server/handlers.ts","../../src/server/server.ts","../../src/cli/cmd/handlers/serve.ts"],"sourcesContent":["import { Event, EventRegistry, EventSchema } from \"@codeworksh/harness/effect\";\nimport { Cause, Context, Effect, Layer, Queue, Scope, Stream } from \"effect\";\nimport { EncodingError, type EventEnvelope, Envelope } from \"./envelope.ts\";\n\nexport const SubscriberCapacity = 4096;\n\nexport type Error = Event.SubscriptionOverflowError | EncodingError;\n\nexport interface Interface {\n\t/** A live envelope stream for one client; releasing the scope unregisters it. */\n\treadonly subscribe: Effect.Effect<Stream.Stream<EventEnvelope, Error>, never, Scope.Scope>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/cli/server/feed/Service\") {}\n\n/**\n * Fan-out for `event.subscribe`. One listener on the event bus encodes each\n * event once and hands the same envelope to every client, rather than every\n * client re-encoding the same payload.\n *\n * Failure is per-cause, not per-feed: a client that cannot keep up fails alone\n * with its own overflow, while an event that cannot be encoded is a server bug\n * that disconnects everyone currently attached -- the feed stays usable for\n * whoever connects next. Types outside the server's registry are dropped\n * before they can consume a client's capacity.\n */\nexport const make = Effect.fn(\"EventFeed.make\")(function* (\n\tlisten: (subscriber: Event.Subscriber) => Effect.Effect<Event.Unsubscribe>,\n\toptions?: { readonly capacity?: number; readonly registry?: Envelope.Registry },\n) {\n\tconst capacity = options?.capacity ?? SubscriberCapacity;\n\t// Whatever this server knows how to describe, plugin registrations included.\n\tconst registry = options?.registry ?? Envelope.Core;\n\tconst subscribers = new Set<Queue.Queue<EventEnvelope, Error>>();\n\n\tconst failAll = (error: Error) =>\n\t\tEffect.sync(() => {\n\t\t\tconst current = Array.from(subscribers);\n\t\t\tsubscribers.clear();\n\t\t\tfor (const subscriber of current) Queue.failCauseUnsafe(subscriber, Cause.fail(error));\n\t\t});\n\n\tconst deliver = Effect.fnUntraced(function* (event: EventSchema.Payload) {\n\t\tif (subscribers.size === 0) return;\n\t\t// Dropped here rather than after the queue: a burst of events this server\n\t\t// cannot describe must not spend a client's capacity on its way to nowhere.\n\t\tif (registry(event.type) === undefined) return;\n\t\tconst envelope = yield* Envelope.encode(event, registry);\n\t\tfor (const subscriber of subscribers) {\n\t\t\tif (Queue.offerUnsafe(subscriber, envelope)) continue;\n\t\t\tsubscribers.delete(subscriber);\n\t\t\tQueue.failCauseUnsafe(subscriber, Cause.fail(new Event.SubscriptionOverflowError({ capacity })));\n\t\t}\n\t});\n\n\tconst publish = (event: EventSchema.Payload) =>\n\t\tdeliver(event).pipe(\n\t\t\tEffect.catchTags({\n\t\t\t\tEventEncodingError: (error) =>\n\t\t\t\t\tEffect.logError(\"Failed to encode public event\", { type: error.type, cause: error.cause }).pipe(\n\t\t\t\t\t\tEffect.andThen(failAll(error)),\n\t\t\t\t\t),\n\t\t\t\t// The registry guard in `deliver` already returned for unknown types.\n\t\t\t\tUnknownEventTypeError: Effect.die,\n\t\t\t}),\n\t\t);\n\n\tconst unsubscribe = yield* listen(publish);\n\tyield* Effect.addFinalizer(() => unsubscribe);\n\n\treturn Service.of({\n\t\tsubscribe: Effect.acquireRelease(\n\t\t\tQueue.dropping<EventEnvelope, Error>(capacity).pipe(\n\t\t\t\tEffect.tap((queue) => Effect.sync(() => subscribers.add(queue))),\n\t\t\t),\n\t\t\t(queue) => Effect.sync(() => subscribers.delete(queue)).pipe(Effect.andThen(Queue.shutdown(queue))),\n\t\t).pipe(Effect.map(Stream.fromQueue)),\n\t});\n});\n\nexport const layer = Layer.effect(\n\tService,\n\tEffect.gen(function* () {\n\t\tconst events = yield* Event.Service;\n\t\tconst registered = yield* EventRegistry.Service;\n\t\treturn yield* make(events.listen, { registry: registered.get });\n\t}),\n);\n\nexport * as EventFeed from \"./feed.ts\";\n","/**\n * Server-side OAuth credential storage.\n *\n * The CLI runs the interactive part of every login locally — a browser\n * callback or a device code cannot travel over RPC — and sends the resulting\n * credentials here, so this service only ever reads, writes, refreshes and\n * clears the server home's `auth.json`.\n */\nimport {\n\tGitHubCopilotOAuthClient,\n\tJsonGitHubCopilotAuthStorage,\n\ttype GitHubCopilotOAuthCredentials,\n} from \"@codeworksh/aikit/oauth/github/copilot\";\nimport {\n\tJsonOpenAICodexAuthStorage,\n\tOpenAICodexOAuthClient,\n\ttype OpenAICodexOAuthCredentials,\n} from \"@codeworksh/aikit/oauth/openai/codex\";\nimport { summarizeGitHubCopilot, summarizeOpenAICodex } from \"@codeworksh/aikit/oauth/summary\";\nimport { Global } from \"@codeworksh/harness/effect\";\nimport { Context, Effect, Layer } from \"effect\";\nimport { Contract } from \"./contract.ts\";\n\ninterface Interface {\n\treadonly save: (credentials: Contract.OAuthCredentials) => Effect.Effect<Contract.OAuthInfo, Contract.OAuthError>;\n\treadonly status: (provider: Contract.OAuthProvider) => Effect.Effect<Contract.OAuthInfo | null, Contract.OAuthError>;\n\treadonly refresh: (\n\t\tprovider: Contract.OAuthProvider,\n\t) => Effect.Effect<Contract.OAuthInfo | null, Contract.OAuthError>;\n\treadonly logout: (provider: Contract.OAuthProvider) => Effect.Effect<void, Contract.OAuthError>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/cli/server/oauth/Service\") {}\n\nconst message = (cause: unknown): string =>\n\tcause instanceof Error && cause.message.trim().length > 0 ? cause.message : String(cause);\n\n/**\n * Re-exported so the server, the CLI and aikit all describe a login the same\n * way; `Contract.OAuthInfo` is the wire shape of {@link OAuthSummary}.\n */\nexport const codexInfo = summarizeOpenAICodex;\nexport const copilotInfo = summarizeGitHubCopilot;\n\nexport const layer = (options: { readonly home?: string | undefined } = {}) =>\n\tLayer.effect(\n\t\tService,\n\t\tEffect.gen(function* () {\n\t\t\tconst global = yield* Global.Service;\n\t\t\tconst authFile = Global.authFile(options.home === undefined ? undefined : global.home);\n\t\t\tconst file = authFile === undefined ? {} : { path: authFile };\n\t\t\tconst codex = new OpenAICodexOAuthClient({ storage: new JsonOpenAICodexAuthStorage(file) });\n\t\t\tconst copilot = new GitHubCopilotOAuthClient({ storage: new JsonGitHubCopilotAuthStorage(file) });\n\t\t\tconst attempt = <A>(run: () => Promise<A>) =>\n\t\t\t\tEffect.tryPromise({\n\t\t\t\t\ttry: run,\n\t\t\t\t\tcatch: (cause) => new Contract.OAuthError({ message: message(cause) }),\n\t\t\t\t});\n\t\t\tconst optional = <A>(run: () => Promise<A | undefined>, info: (value: A) => Contract.OAuthInfo) =>\n\t\t\t\tattempt(run).pipe(Effect.map((value) => (value === undefined ? null : info(value))));\n\n\t\t\treturn Service.of({\n\t\t\t\t// The `provider` tag is routing, not a credential: it never reaches disk.\n\t\t\t\tsave: (wire) => {\n\t\t\t\t\tif (wire.provider === \"openai-codex\") {\n\t\t\t\t\t\tconst credentials: OpenAICodexOAuthCredentials = {\n\t\t\t\t\t\t\taccess: wire.access,\n\t\t\t\t\t\t\trefresh: wire.refresh,\n\t\t\t\t\t\t\texpires: wire.expires,\n\t\t\t\t\t\t\taccountId: wire.accountId,\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn attempt(() => codex.storage.set(credentials)).pipe(Effect.as(codexInfo(credentials)));\n\t\t\t\t\t}\n\t\t\t\t\tconst credentials: GitHubCopilotOAuthCredentials = {\n\t\t\t\t\t\taccess: wire.access,\n\t\t\t\t\t\trefresh: wire.refresh,\n\t\t\t\t\t\texpires: wire.expires,\n\t\t\t\t\t\t...(wire.enterpriseUrl === undefined ? {} : { enterpriseUrl: wire.enterpriseUrl }),\n\t\t\t\t\t\t...(wire.apiEndpoint === undefined ? {} : { apiEndpoint: wire.apiEndpoint }),\n\t\t\t\t\t\t...(wire.availableModelIds === undefined ? {} : { availableModelIds: [...wire.availableModelIds] }),\n\t\t\t\t\t};\n\t\t\t\t\treturn attempt(() => copilot.storage.set(credentials)).pipe(Effect.as(copilotInfo(credentials)));\n\t\t\t\t},\n\t\t\t\tstatus: (provider) =>\n\t\t\t\t\tprovider === \"openai-codex\"\n\t\t\t\t\t\t? optional(() => codex.storage.get(), codexInfo)\n\t\t\t\t\t\t: optional(() => copilot.storage.get(), copilotInfo),\n\t\t\t\t// GitHub OAuth tokens never expire, so a Copilot \"refresh\" is a read.\n\t\t\t\trefresh: (provider) =>\n\t\t\t\t\tprovider === \"openai-codex\"\n\t\t\t\t\t\t? optional(() => codex.getCredentials(), codexInfo)\n\t\t\t\t\t\t: optional(() => copilot.getCredentials(), copilotInfo),\n\t\t\t\tlogout: (provider) => attempt(() => (provider === \"openai-codex\" ? codex.logout() : copilot.logout())),\n\t\t\t});\n\t\t}),\n\t);\n\nexport * as OAuth from \"./oauth.ts\";\n","import { Model } from \"@codeworksh/aikit\";\nimport {\n\tControl,\n\tEvent,\n\tEventList,\n\tEventRegistry,\n\tEventSchema,\n\tMcp,\n\tModelCatalog,\n\tProject,\n\tPromptSchema,\n\tSandbox,\n\tSession,\n\tSessionStore,\n\tSettings,\n\tState,\n\tThreadSchema,\n\tThreadStore,\n} from \"@codeworksh/harness/effect\";\nimport { DateTime, Effect, Option, Schema, Stream } from \"effect\";\nimport {\n\tContract,\n\ttype HistoryEntry,\n\ttype LogSynced,\n\ttype RuntimeConfig,\n\ttype SandboxInfo,\n\ttype SessionInfo,\n\ttype ThreadInfo,\n} from \"./contract.ts\";\nimport { type EncodingError, Envelope, type EventEnvelope } from \"./envelope.ts\";\nimport { EventFeed } from \"./feed.ts\";\nimport { Identity } from \"./identity.ts\";\nimport { OAuth } from \"./oauth.ts\";\nimport { MessagePart } from \"./part.ts\";\n\nconst toSandboxInfo = (info: Sandbox.Info): SandboxInfo => ({\n\tid: info.id,\n\tdriver: info.driver,\n\tkind: info.kind,\n\tproviderResourceId: info.providerResourceId,\n\townership: info.ownership,\n\tstatus: info.status,\n\tusage: info.usage,\n\trefCount: info.refCount,\n\tcreatedAt: info.createdAt,\n\tupdatedAt: info.updatedAt,\n});\n\nconst toSessionInfo = (info: Session.Info): SessionInfo => ({\n\tid: info.id,\n\tdirectory: info.directory,\n\t...(info.hostDir === undefined ? {} : { hostDir: info.hostDir }),\n\t...(info.sandbox === undefined ? {} : { sandbox: toSandboxInfo(info.sandbox) }),\n\t...(info.project === undefined ? {} : { project: info.project }),\n\tupdatedAt: info.updatedAt,\n\tmainThreadId: info.mainThreadId,\n});\n\nconst toThreadInfo = (info: Session.ThreadInfo): ThreadInfo => ({\n\tid: info.id,\n\torigin: info.origin,\n\t...(info.title === undefined ? {} : { title: info.title }),\n\tupdatedAt: info.updatedAt,\n\t...(info.model === undefined ? {} : { model: info.model }),\n\t...(info.thinkingLevel === undefined ? {} : { thinkingLevel: info.thinkingLevel }),\n\t...(info.foundation === undefined ? {} : { foundation: info.foundation }),\n\t...(info.placement === undefined ? {} : { placement: info.placement }),\n\tusage: info.usage,\n\tsession: toSessionInfo(info.session),\n});\n\n// Wire configs name only the keys they set, so `undefined` never reaches the harness under\n// exactOptionalPropertyTypes. Creating takes choices only; `null` clears nothing there.\nconst runtimeInput = (runtime: RuntimeConfig | undefined): Session.RuntimeInput => ({\n\t...(runtime?.model == null ? {} : { model: runtime.model }),\n\t...(runtime?.thinkingLevel == null ? {} : { thinkingLevel: runtime.thinkingLevel }),\n\t...(runtime?.foundation == null ? {} : { foundation: runtime.foundation }),\n});\n\n// A failed reply's envelope keeps the provider's reason; it reads as the live failure does.\nconst decodeFailedReply = Schema.decodeUnknownOption(\n\tSchema.fromJsonString(\n\t\tSchema.Struct({\n\t\t\tstopReason: Schema.Literal(\"error\"),\n\t\t\terrorMessage: Schema.String,\n\t\t\tprovider: Schema.Struct({ id: Schema.String }),\n\t\t\tmodel: Schema.String,\n\t\t}),\n\t),\n);\nconst replyError = (data: string) =>\n\tOption.map(decodeFailedReply(data), (reply) => `${reply.provider.id}/${reply.model}: ${reply.errorMessage}`);\n\nconst threadInfo = (threadId: ThreadSchema.ID) => Session.threadInfo(threadId).pipe(Effect.map(toThreadInfo));\n\n// RpcServer's request span has no level, so it is Debug and drops every Info span under it.\n// Provisioning a sandbox is worth exporting, so it starts a trace of its own.\nconst exported = <A, E, R>(name: string, self: Effect.Effect<A, E, R>) =>\n\tself.pipe(Effect.withSpan(name, { level: \"Info\", root: true }));\n\nconst releaseOnFailure = (selection: Effect.Success<ReturnType<typeof Sandbox.resolve>> | undefined) =>\n\tselection?.created && selection.info !== undefined\n\t\t? Sandbox.stop(selection.info.id).pipe(Effect.catchCause(Effect.logError))\n\t\t: Effect.void;\n\n/** A `session.log` item for the wire: a stored event as its envelope, or the replay marker. */\nconst toLogItem =\n\t(registry: Envelope.Registry) =>\n\t(item: Event.LogItem): Effect.Effect<EventEnvelope | LogSynced, EncodingError> =>\n\t\tEvent.isSynced(item)\n\t\t\t? Effect.succeed(item)\n\t\t\t: Envelope.encode(item, registry).pipe(\n\t\t\t\t\t// Every stored type is a kernel durable one, which the registry always knows.\n\t\t\t\t\tEffect.catchTag(\"UnknownEventTypeError\", Effect.die),\n\t\t\t\t);\n\nexport const layer = Contract.Api.toLayer(\n\tEffect.gen(function* () {\n\t\tconst control = yield* Control.Service;\n\t\tconst feed = yield* EventFeed.Service;\n\t\tconst sessions = yield* SessionStore.Service;\n\t\tconst threads = yield* ThreadStore.Service;\n\t\tconst resolve = (ref: Control.ThreadRef) =>\n\t\t\tcontrol.resolve(ref).pipe(Effect.map((thread) => ThreadSchema.ID.make(thread.id)));\n\t\tconst state = yield* State.Service;\n\t\tconst oauth = yield* OAuth.Service;\n\t\tconst identity = yield* Identity.Service;\n\t\tconst events = yield* Event.Service;\n\t\tconst registry = yield* EventRegistry.Service;\n\t\tconst mcp = yield* Mcp.Service;\n\t\tconst mcpControl = (operation: \"connect\" | \"disconnect\") =>\n\t\t\tEffect.fnUntraced(function* ({ server, ...ref }: Control.ThreadRef & { readonly server: string }) {\n\t\t\t\treturn yield* mcp[operation](yield* resolve(ref), server);\n\t\t\t});\n\n\t\treturn Contract.Api.of({\n\t\t\t\"server.info\": () => Effect.succeed({ pid: identity.pid, version: identity.version }),\n\t\t\t\"auth.save\": ({ credentials }) => oauth.save(credentials),\n\t\t\t\"auth.status\": ({ provider }) => oauth.status(provider),\n\t\t\t\"auth.refresh\": ({ provider }) => oauth.refresh(provider),\n\t\t\t\"auth.logout\": ({ provider }) => oauth.logout(provider),\n\t\t\t\"session.create\": Effect.fnUntraced(function* ({ title, directory, hostDir, sandbox, runtime, project }) {\n\t\t\t\tconst selection =\n\t\t\t\t\tsandbox === undefined ? undefined : yield* exported(\"Server.session.create\", Sandbox.resolve(sandbox));\n\t\t\t\tconst selected = selection?.info;\n\t\t\t\tconst handle = yield* Session.create({\n\t\t\t\t\t...(title === undefined ? {} : { title }),\n\t\t\t\t\t...(directory === undefined ? {} : { directory }),\n\t\t\t\t\t// Passed through as given, never defaulted to the server's own directory: a\n\t\t\t\t\t// session the client did not place has no project, which is a normal state.\n\t\t\t\t\t...(hostDir === undefined ? {} : { hostDir }),\n\t\t\t\t\t...(selected === undefined ? {} : { sandbox: selected }),\n\t\t\t\t\t...(project === undefined ? {} : { project }),\n\t\t\t\t\t...runtimeInput(runtime),\n\t\t\t\t}).pipe(Effect.onError(() => releaseOnFailure(selection)));\n\t\t\t\treturn toThreadInfo(yield* handle.main.info);\n\t\t\t}),\n\t\t\t\"model.list\": Effect.fnUntraced(function* ({ hostDir }) {\n\t\t\t\tconst filter = hostDir === undefined ? {} : { hostDir };\n\t\t\t\tconst settings = yield* Settings.Service;\n\t\t\t\tconst loaded = yield* settings.load(hostDir);\n\t\t\t\tconst { model } = loaded;\n\t\t\t\tconst providers = yield* ModelCatalog.available(filter);\n\t\t\t\t// Named from the whole catalog, so a default without credentials still reads as itself.\n\t\t\t\tconst entry = (yield* ModelCatalog.effective(loaded.models))[model.provider]?.[model.id];\n\t\t\t\treturn {\n\t\t\t\t\tproviders: providers.flatMap((provider) => {\n\t\t\t\t\t\tconst models = Object.values(provider.models);\n\t\t\t\t\t\tconst first = models[0];\n\t\t\t\t\t\treturn first === undefined\n\t\t\t\t\t\t\t? []\n\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tid: provider.id,\n\t\t\t\t\t\t\t\t\t\tname: first.provider.name,\n\t\t\t\t\t\t\t\t\t\tmodels: models.map((info) => ({\n\t\t\t\t\t\t\t\t\t\t\tid: info.id,\n\t\t\t\t\t\t\t\t\t\t\tname: info.name,\n\t\t\t\t\t\t\t\t\t\t\tthinkingLevels: Model.getSupportedThinkingLevels(info),\n\t\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t];\n\t\t\t\t\t}),\n\t\t\t\t\tdefault: {\n\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\tid: model.id,\n\t\t\t\t\t\tthinkingLevel: model.thinkingLevel,\n\t\t\t\t\t\t...(entry === undefined ? {} : { name: entry.name, providerName: entry.provider.name }),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}),\n\t\t\t\"project.rename\": Effect.fnUntraced(function* ({ projectId, name }) {\n\t\t\t\tconst renamed = yield* Project.rename({ projectId, name });\n\t\t\t\treturn { id: renamed.id, name: renamed.name };\n\t\t\t}),\n\t\t\t\"plugin.reload\": Effect.fnUntraced(function* () {\n\t\t\t\treturn yield* state.reload;\n\t\t\t}),\n\t\t\t\"session.link\": Effect.fnUntraced(function* ({ sessionId, hostDir }) {\n\t\t\t\tconst handle = yield* Session.link({ sessionId, hostDir: hostDir ?? null });\n\t\t\t\treturn toSessionInfo(yield* handle.info);\n\t\t\t}),\n\t\t\t\"session.relink\": Effect.fnUntraced(function* ({ sessionId, threadId, sandbox, directory }) {\n\t\t\t\tconst selection =\n\t\t\t\t\tsandbox === undefined ? undefined : yield* exported(\"Server.session.relink\", Sandbox.resolve(sandbox));\n\t\t\t\tconst selected = selection?.info;\n\t\t\t\tconst handle = yield* Session.relink({\n\t\t\t\t\tsessionId,\n\t\t\t\t\t...(threadId === undefined ? {} : { threadId }),\n\t\t\t\t\t...(selected === undefined ? {} : { sandbox: selected }),\n\t\t\t\t\t...(directory === undefined ? {} : { directory }),\n\t\t\t\t}).pipe(Effect.onError(() => releaseOnFailure(selection)));\n\t\t\t\tconst thread = yield* handle.thread(threadId ?? ThreadSchema.MAIN);\n\t\t\t\treturn toThreadInfo(yield* thread.info);\n\t\t\t}),\n\t\t\t\"session.delete\": Effect.fnUntraced(function* ({ sessionId }) {\n\t\t\t\treturn { deleted: yield* Session.remove(sessionId) };\n\t\t\t}),\n\t\t\t\"session.interrupt\": Effect.fnUntraced(function* ({ sessionId }) {\n\t\t\t\t// Ack only: the wire answers \"was there work to stop\", and the caller\n\t\t\t\t// uses `thread.wait` when it needs cleanup to have finished.\n\t\t\t\treturn { interrupted: yield* control.interruptSession(sessionId, { reason: \"user\" }) };\n\t\t\t}),\n\t\t\t\"session.log\": ({ sessionId, threadId, after, follow }) =>\n\t\t\t\tStream.unwrap(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tif (Option.isNone(yield* sessions.get(sessionId))) {\n\t\t\t\t\t\t\treturn yield* new SessionStore.SessionNotFoundError({ sessionId });\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn events\n\t\t\t\t\t\t\t.log({\n\t\t\t\t\t\t\t\taggregateId: sessionId,\n\t\t\t\t\t\t\t\tfollow: follow ?? false,\n\t\t\t\t\t\t\t\t...(after === undefined ? {} : { after }),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.pipe(\n\t\t\t\t\t\t\t\tStream.filter(\n\t\t\t\t\t\t\t\t\t(item) =>\n\t\t\t\t\t\t\t\t\t\tthreadId === undefined || Event.isSynced(item) || Envelope.ofThread(threadId)(item),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tStream.mapEffect(toLogItem(registry.get)),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\"thread.list\": Effect.fnUntraced(function* ({ sessionId }) {\n\t\t\t\tconst rows = yield* threads.list(sessionId);\n\t\t\t\treturn yield* Effect.forEach(rows, (row) => threadInfo(ThreadSchema.ID.make(row.id)).pipe(Effect.orDie));\n\t\t\t}),\n\t\t\t\"thread.info\": Effect.fnUntraced(function* (ref) {\n\t\t\t\treturn yield* threadInfo(yield* resolve(ref));\n\t\t\t}),\n\t\t\t\"thread.configure\": Effect.fnUntraced(function* ({ runtime, ...ref }) {\n\t\t\t\tconst threadId = yield* resolve(ref);\n\t\t\t\tconst change = {\n\t\t\t\t\t...(runtime.model === undefined ? {} : { model: runtime.model }),\n\t\t\t\t\t...(runtime.thinkingLevel === undefined ? {} : { thinkingLevel: runtime.thinkingLevel }),\n\t\t\t\t\t...(runtime.foundation === undefined ? {} : { foundation: runtime.foundation }),\n\t\t\t\t};\n\t\t\t\tif (Object.keys(change).length > 0) {\n\t\t\t\t\tyield* events.publish(EventList.ThreadConfigured, {\n\t\t\t\t\t\tsessionId: ref.sessionId,\n\t\t\t\t\t\tthreadId,\n\t\t\t\t\t\ttimestamp: yield* DateTime.now,\n\t\t\t\t\t\tchange,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn yield* threadInfo(threadId);\n\t\t\t}),\n\t\t\t\"thread.fork\": Effect.fnUntraced(function* ({ entryId, mode, ...ref }) {\n\t\t\t\tconst forked = yield* threads.fork({\n\t\t\t\t\tthreadId: yield* resolve(ref),\n\t\t\t\t\tentryId,\n\t\t\t\t\t...(mode === undefined ? {} : { mode }),\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tthread: yield* threadInfo(ThreadSchema.ID.make(forked.thread.id)),\n\t\t\t\t\t...(forked.text === undefined ? {} : { text: forked.text }),\n\t\t\t\t};\n\t\t\t}),\n\t\t\t\"thread.history\": Effect.fnUntraced(function* (ref) {\n\t\t\t\tconst line = yield* threads.line(yield* resolve(ref));\n\t\t\t\tconst entries = line.flatMap(({ entry, parts }): ReadonlyArray<HistoryEntry> =>\n\t\t\t\t\tentry.type === \"user\" || entry.type === \"assistant\"\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tid: entry.id,\n\t\t\t\t\t\t\t\t\tthreadId: entry.threadId,\n\t\t\t\t\t\t\t\t\tseq: entry.seq,\n\t\t\t\t\t\t\t\t\trole: entry.type,\n\t\t\t\t\t\t\t\t\tstate: entry.state,\n\t\t\t\t\t\t\t\t\tcreatedAt: DateTime.toEpochMillis(entry.createdAt),\n\t\t\t\t\t\t\t\t\tupdatedAt: DateTime.toEpochMillis(entry.updatedAt),\n\t\t\t\t\t\t\t\t\t// A part this schema does not render (a future aikit type) is skipped, not fatal.\n\t\t\t\t\t\t\t\t\tparts: parts.flatMap((part) => Option.toArray(MessagePart.decode(part.data))),\n\t\t\t\t\t\t\t\t\t...Option.match(entry.type === \"assistant\" ? replyError(entry.data) : Option.none(), {\n\t\t\t\t\t\t\t\t\t\tonNone: () => ({}),\n\t\t\t\t\t\t\t\t\t\tonSome: (error) => ({ error }),\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: [],\n\t\t\t\t);\n\t\t\t\treturn { entries };\n\t\t\t}),\n\t\t\t\"thread.queue\": Effect.fnUntraced(function* (ref) {\n\t\t\t\tconst pending = yield* control.pending(yield* resolve(ref));\n\t\t\t\treturn {\n\t\t\t\t\tentries: pending.map((input) => ({\n\t\t\t\t\t\tid: input.id,\n\t\t\t\t\t\tdelivery: input.delivery,\n\t\t\t\t\t\ttext: PromptSchema.Prompt.text(input.prompt),\n\t\t\t\t\t\tcreatedAt: DateTime.toEpochMillis(input.timeCreated),\n\t\t\t\t\t})),\n\t\t\t\t};\n\t\t\t}),\n\t\t\t\"thread.prompt\": Effect.fnUntraced(function* ({ text, delivery, id, ...ref }) {\n\t\t\t\tconst admitted = yield* control.prompt({\n\t\t\t\t\t...ref,\n\t\t\t\t\tprompt: PromptSchema.Prompt.fromText(text),\n\t\t\t\t\t...(delivery === undefined ? {} : { delivery }),\n\t\t\t\t\t...(id === undefined ? {} : { id }),\n\t\t\t\t});\n\t\t\t\treturn { threadId: admitted.threadId };\n\t\t\t}),\n\t\t\t\"thread.interrupt\": Effect.fnUntraced(function* (ref) {\n\t\t\t\t// Ack only: the wire answers \"was there work to stop\", and the caller\n\t\t\t\t// uses `thread.wait` when it needs cleanup to have finished.\n\t\t\t\treturn { interrupted: yield* control.interrupt(yield* resolve(ref), { reason: \"user\" }) };\n\t\t\t}),\n\t\t\t\"thread.cancel\": Effect.fnUntraced(function* ({ messageId, ...ref }) {\n\t\t\t\treturn { cancelled: yield* control.cancel(yield* resolve(ref), messageId) };\n\t\t\t}),\n\t\t\t\"thread.update\": Effect.fnUntraced(function* ({ messageId, delivery, text, ...ref }) {\n\t\t\t\tconst updated = yield* control.update(yield* resolve(ref), messageId, {\n\t\t\t\t\t...(delivery === undefined ? {} : { delivery }),\n\t\t\t\t\t...(text === undefined ? {} : { prompt: PromptSchema.Prompt.fromText(text) }),\n\t\t\t\t});\n\t\t\t\treturn { updated };\n\t\t\t}),\n\t\t\t\"thread.message\": Effect.fnUntraced(function* ({ messageId, ...ref }) {\n\t\t\t\t// Scoped to the thread's line: an entry id is global, and a client should not learn\n\t\t\t\t// about conversations it did not ask for. An inherited prompt is in the thread's.\n\t\t\t\tconst line = yield* threads.line(yield* resolve(ref));\n\t\t\t\treturn { found: line.some(({ entry }) => entry.id === messageId) };\n\t\t\t}),\n\t\t\t\"thread.wait\": Effect.fnUntraced(function* (ref) {\n\t\t\t\tyield* control.wait(yield* resolve(ref));\n\t\t\t}),\n\t\t\t\"mcp.connect\": mcpControl(\"connect\"),\n\t\t\t\"mcp.disconnect\": mcpControl(\"disconnect\"),\n\t\t\t\"sandbox.drivers\": Effect.fnUntraced(function* () {\n\t\t\t\tconst drivers = yield* Sandbox.drivers();\n\t\t\t\treturn drivers.map(({ name, kind }) => ({ name, kind }));\n\t\t\t}),\n\t\t\t\"sandbox.list\": Effect.fnUntraced(function* () {\n\t\t\t\treturn (yield* Sandbox.list()).map(toSandboxInfo);\n\t\t\t}),\n\t\t\t\"sandbox.create\": Effect.fnUntraced(function* ({ driver }) {\n\t\t\t\treturn toSandboxInfo(yield* exported(\"Server.sandbox.create\", Sandbox.create({ driver })));\n\t\t\t}),\n\t\t\t\"sandbox.register\": Effect.fnUntraced(function* ({ driver, providerResourceId }) {\n\t\t\t\treturn toSandboxInfo(yield* Sandbox.register({ driver, providerResourceId }));\n\t\t\t}),\n\t\t\t\"sandbox.stop\": Effect.fnUntraced(function* ({ sandboxId }) {\n\t\t\t\tyield* Sandbox.stop(sandboxId);\n\t\t\t}),\n\t\t\t// Acquiring the feed subscription is the readiness barrier: `server.connected`\n\t\t\t// is only emitted once this client is registered, so a prompt admitted after\n\t\t\t// it cannot land in the gap.\n\t\t\t\"event.subscribe\": ({ threadId }) =>\n\t\t\t\tStream.unwrap(\n\t\t\t\t\tfeed.subscribe.pipe(\n\t\t\t\t\t\tEffect.map((events) =>\n\t\t\t\t\t\t\tStream.make({ id: EventSchema.ID.create(), type: Envelope.Connected.type, data: {} }).pipe(\n\t\t\t\t\t\t\t\tStream.concat(\n\t\t\t\t\t\t\t\t\tthreadId === undefined ? events : events.pipe(Stream.filter(Envelope.ofThread(threadId))),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t});\n\t}),\n);\n\nexport * as Handlers from \"./handlers.ts\";\n","import { Control, Global, Harness, Sandbox } from \"@codeworksh/harness/effect\";\nimport { NodeHttpServer } from \"@effect/platform-node\";\nimport { Effect, Layer } from \"effect\";\nimport { HttpRouter, HttpServer } from \"effect/http\";\nimport * as NetAddress from \"effect/net/NetAddress\";\nimport { RpcSerialization, RpcServer } from \"effect/rpc\";\n/* @effect-diagnostics nodeBuiltinImport:off -- the RPC listener needs a raw node server. */\nimport { createServer } from \"node:http\";\nimport { Contract } from \"./contract.ts\";\nimport { EventFeed } from \"./feed.ts\";\nimport { Handlers } from \"./handlers.ts\";\nimport { Identity } from \"./identity.ts\";\nimport { OAuth } from \"./oauth.ts\";\nimport { Registration } from \"./registration.ts\";\n\n// Managed instances outlive any single RPC; the serve scope is what stops them.\nconst managedShutdown = Layer.unwrap(\n\tEffect.gen(function* () {\n\t\tconst control = yield* Control.Service;\n\t\tyield* Effect.addFinalizer(() =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\t// Release drain leases before stopping the server's managed sandboxes.\n\t\t\t\t// Both phases are best effort and bounded so a provider cannot prevent\n\t\t\t\t// process shutdown; an interrupted stop is persisted as faulted and can\n\t\t\t\t// recover the next time that sandbox is mounted.\n\t\t\t\tyield* Effect.forEach(\n\t\t\t\t\tyield* control.active,\n\t\t\t\t\t(id) =>\n\t\t\t\t\t\tcontrol\n\t\t\t\t\t\t\t.interrupt(id, { reason: \"shutdown\", awaitSettlement: true })\n\t\t\t\t\t\t\t.pipe(Effect.timeout(\"10 seconds\"), Effect.ignore),\n\t\t\t\t\t{ concurrency: \"unbounded\", discard: true },\n\t\t\t\t);\n\t\t\t\tconst infos = yield* Sandbox.list();\n\t\t\t\tyield* Effect.forEach(\n\t\t\t\t\tinfos.filter((info) => info.ownership === \"managed\"),\n\t\t\t\t\t(info) =>\n\t\t\t\t\t\tSandbox.stop(info.id).pipe(\n\t\t\t\t\t\t\tEffect.timeout(\"10 seconds\"),\n\t\t\t\t\t\t\tEffect.catchCause((cause) =>\n\t\t\t\t\t\t\t\tEffect.logError(\"Failed to stop managed sandbox during shutdown\", cause).pipe(\n\t\t\t\t\t\t\t\t\tEffect.annotateLogs({ sandboxInstanceId: info.id }),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t{ concurrency: \"unbounded\", discard: true },\n\t\t\t\t);\n\t\t\t}),\n\t\t);\n\t\treturn Layer.empty;\n\t}),\n);\n\n/**\n * Resumes the runs the last server left unfinished, whether it crashed or shut down: the session\n * table records them as they start, so this needs nothing from the previous process.\n */\nconst resumeUnfinished = Layer.effectDiscard(\n\tEffect.gen(function* () {\n\t\tconst control = yield* Control.Service;\n\t\tyield* Effect.forkScoped(control.resumeUnfinished);\n\t}),\n);\n\n/**\n * Advertises the listener once it has an address: logs the endpoint and files\n * the registration later invocations discover it through.\n */\nconst announce = Layer.unwrap(\n\tEffect.gen(function* () {\n\t\tconst server = yield* HttpServer.HttpServer;\n\t\tconst global = yield* Global.Service;\n\t\tconst identity = yield* Identity.Service;\n\t\t// A ws server always binds TCP; the guard keeps the logger honest if that ever changes.\n\t\tconst address = server.address;\n\t\tconst url = `${NetAddress.formatUrlUnsafe(address, \"ws\")}${Contract.path}`;\n\t\tyield* Effect.log(`codework serve listening on ${url}`);\n\t\tif (!NetAddress.isInetAddress(address)) return Layer.empty;\n\t\treturn Registration.register({\n\t\t\thome: global.home,\n\t\t\tinfo: { pid: identity.pid, version: identity.version, url, port: address.port },\n\t\t});\n\t}),\n);\n\nexport const layer = (options: { host: string; port: number; harness: Harness.Options }) => {\n\tconst rpc = RpcServer.layerHttp({ group: Contract.Api, path: Contract.path, protocol: \"websocket\" }).pipe(\n\t\tLayer.provide(Handlers.layer.pipe(Layer.provide(EventFeed.layer))),\n\t);\n\tconst app = HttpRouter.serve(rpc, { disableListenLog: true }).pipe(\n\t\tLayer.provideMerge(managedShutdown),\n\t\tLayer.provideMerge(resumeUnfinished),\n\t\tLayer.provide(OAuth.layer(options.harness.home === undefined ? {} : { home: options.harness.home })),\n\t);\n\treturn app.pipe(\n\t\tLayer.provideMerge(announce),\n\t\tLayer.provideMerge(NodeHttpServer.layer(createServer, { host: options.host, port: options.port })),\n\t\tLayer.provide(RpcSerialization.layerNdjson),\n\t\tLayer.provide(Identity.layer),\n\t\tLayer.provide(Harness.layer(options.harness)),\n\t);\n};\n\nexport * as Server from \"./server.ts\";\n","import { Global } from \"@codeworksh/harness/effect\";\nimport { Effect, FileSystem, Layer, Logger } from \"effect\";\nimport { Runtime } from \"../../../framework/runtime.ts\";\nimport { Registration } from \"../../../server/registration.ts\";\nimport { Server } from \"../../../server/server.ts\";\nimport { renderError } from \"../../error.ts\";\nimport { harnessOptions } from \"../../harness.ts\";\nimport { writeError } from \"../../output.ts\";\nimport { Cmd } from \"../cmd.ts\";\n\nconst failed = Effect.sync(() => {\n\tprocess.exitCode = 1;\n});\n\nconst report = (error: unknown) => writeError(renderError(error)).pipe(Effect.andThen(failed));\n\nexport default Runtime.handler(\n\tCmd.commands.serve,\n\tEffect.fn(\"CLI.serve\", { level: \"Info\" })(function* ({ host, port, service }) {\n\t\tconst shared = yield* Cmd.spec;\n\t\tconst harness = { ...harnessOptions(shared), watchModels: true };\n\t\tconst serve = Layer.launch(Server.layer({ host, port, harness }));\n\t\tif (!service) return yield* serve.pipe(Effect.catch(report));\n\n\t\t// A background server has no terminal: its log, and the reason it stopped, go to a\n\t\t// file the CLI that started it reads back when startup fails.\n\t\tconst background = Effect.gen(function* () {\n\t\t\tconst paths = yield* Global.resolve(harness.home === undefined ? {} : { home: harness.home });\n\t\t\tconst fs = yield* FileSystem.FileSystem;\n\t\t\tyield* fs.makeDirectory(paths.log, { recursive: true });\n\t\t\tconst logger = Logger.formatSimple.pipe(Logger.toFile(Registration.log(paths.log), { flag: \"w\" }));\n\t\t\tyield* serve.pipe(\n\t\t\t\tEffect.catch((error) => Effect.logError(renderError(error).trim()).pipe(Effect.andThen(failed))),\n\t\t\t\tEffect.provide(Logger.layer([logger])),\n\t\t\t);\n\t\t});\n\t\tyield* background.pipe(Effect.catch(report));\n\t}),\n);\n"],"mappings":";;;;;;;;;;;;;;;AAaA,IAAaA,YAAb,cAA6B,QAAQ,QAA4B,CAAC,CAAC,qCAAqC,CAAC,CAAC,CAAC;;;;;;;;;;;;AAa3G,MAAa,OAAO,OAAO,GAAG,gBAAgB,CAAC,CAAC,WAC/C,QACA,SACC;CACD,MA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ED,MAAM,UAAU,UAAmB,WAAW,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,MAAM,CAAC;AAE7F,IAAA,gBAAeC,QACd,IAAI,SAAS,OACb,OAAO,GAAG,aAAa,EAAE,OAAO,OAAO,CAAC,CAAC,CAAC,WAAW,EAAE,MAAM,MAAM,WAAW;CAC7E,MAAM,SAAS,OAAO,IAAI;CAC1B,MAAM,UAAU;EAAE,GAAG,eAAe,MAAM;EAAG,aAAa;CAAK;CAC/D,MAAM,QAAQ,MAAM,OAAOC,MAAa;EAAE;EAAM;EAAM;CAAQ,CAAC,CAAC;CAChE,IAAI,CAAC,SAAS,OAAO,OAAO,MAAM,KAAK,OAAO,MAAM,MAAM,CAAC;CAc3D,OAVmB,OAAO,IAAI,aAAa;EAC1C,MAAM,QAAQ,OAAO,OAAO,QAAQ,QAAQ,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,KAAK,CAAC;EAE5F,QAAO,OADW,WAAW,WAAA,CACnB,cAAc,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC;EACtD,MAAM,SAAS,OAAO,aAAa,KAAK,OAAO,OAAOC,IAAiB,MAAM,GAAG,GAAG,EAAE,MAAM,IAAI,CAAC,CAAC;EACjG,OAAO,MAAM,KACZ,OAAO,OAAO,UAAU,OAAO,SAAS,YAAY,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,MAAM,CAAC,CAAC,GAC/F,OAAO,QAAQ,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,CACtC;CACD,CACgB,CAAC,CAAC,KAAK,OAAO,MAAM,MAAM,CAAC;AAC5C,CAAC,CACF"}
|
package/service-ClAs3abW.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"service-ClAs3abW.mjs","names":["Client.layer","Client.make","Registration.infoJson","Health.probe","Registration.file","log","Registration.log","Registration.command"],"sources":["../../src/server/health.ts","../../src/server/discovery.ts","../../src/cli/service.ts"],"sourcesContent":["import { Effect, Layer } from \"effect\";\nimport { Client } from \"./client.ts\";\n\n/**\n * One `server.info` call, with the answer normalized to `undefined` for every\n * way a server can fail to answer: unreachable, slow, or speaking a different\n * protocol. A health check that throws where it should say \"no\" would make\n * every caller wrap it in a catch.\n */\nexport const probe = (url: string) =>\n\tEffect.gen(function* () {\n\t\tconst context = yield* Layer.build(Client.layer(url)).pipe(Effect.orElseSucceed(() => undefined));\n\t\tif (context === undefined) return undefined;\n\t\treturn yield* Effect.gen(function* () {\n\t\t\tconst rpc = yield* Client.make;\n\t\t\treturn yield* rpc[\"server.info\"]({}).pipe(Effect.timeout(\"1 second\"));\n\t\t}).pipe(\n\t\t\tEffect.provideContext(context),\n\t\t\tEffect.orElseSucceed(() => undefined),\n\t\t);\n\t}).pipe(Effect.scoped);\n\nexport * as Health from \"./health.ts\";\n","import { type Duration, Effect, FileSystem, Option, Ref, Schedule, Schema } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\nimport { Health } from \"./health.ts\";\nimport { Identity } from \"./identity.ts\";\nimport { Registration } from \"./registration.ts\";\n\n/** A server a client can connect to, and the process and port behind it. */\nexport interface Endpoint {\n\treadonly url: string;\n\treadonly pid: number;\n\treadonly port: number;\n}\n\n/** A managed server could not be produced, in the words the CLI prints. */\nexport class ServerStartError extends Schema.TaggedError<ServerStartError>()(\"Discovery.ServerStartError\", {\n\tmessage: Schema.String,\n}) {}\n\nexport interface Options {\n\t/** The CodeWork home whose `service.json` names the server. */\n\treadonly home: string;\n\t/** The home's log directory, where a background server writes `server.log`. */\n\treadonly log: string;\n\treadonly host: string;\n\treadonly port: number;\n\t/** Server-owned flags placed before `serve`. */\n\treadonly args: ReadonlyArray<string>;\n}\n\nconst START_TIMEOUT = \"20 seconds\";\nconst RACE_GRACE = \"2 seconds\";\nconst STOP_TIMEOUT = \"5 seconds\";\n\nconst decode = Schema.decodeUnknownEffect(Registration.infoJson);\n\nconst read = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst fs = yield* FileSystem.FileSystem;\n\t\tconst text = yield* fs.readFileString(path).pipe(Effect.option);\n\t\tif (Option.isNone(text)) return undefined;\n\t\treturn yield* decode(text.value).pipe(Effect.option, Effect.map(Option.getOrUndefined));\n\t});\n\nconst remove = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst fs = yield* FileSystem.FileSystem;\n\t\tyield* fs.remove(path);\n\t}).pipe(Effect.ignore);\n\n/** Whether `pid` is a running process. EPERM means it exists but belongs to someone else. */\nconst alive = (pid: number) =>\n\tEffect.try({ try: () => process.kill(pid, 0), catch: (error) => (error as NodeJS.ErrnoException).code }).pipe(\n\t\tEffect.as(true),\n\t\tEffect.catch((code) => Effect.succeed(code === \"EPERM\")),\n\t);\n\n/** Whether `pid` exits within `timeout`. */\nconst exits = (pid: number, timeout: typeof STOP_TIMEOUT) =>\n\talive(pid).pipe(\n\t\tEffect.repeat({ while: (running) => running, schedule: Schedule.spaced(\"50 millis\") }),\n\t\tEffect.timeoutOption(timeout),\n\t\tEffect.map(Option.isSome),\n\t);\n\n/**\n * The registered server, with `live` set when the process answering its endpoint\n * is the one that registered. The file is a hint, never proof: a different server\n * on a reused port must not pass for it.\n */\nconst registered = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst info = yield* read(path);\n\t\tif (info === undefined) return undefined;\n\t\tconst live = yield* Health.probe(info.url);\n\t\treturn { info, live: live?.pid === info.pid ? live : undefined };\n\t});\n\nconst endpoint = (info: Registration.Info): Endpoint => ({ url: info.url, pid: info.pid, port: info.port });\n\n/** The running server registered for `home`, with the build it reports. */\nexport const discover = (home: string) =>\n\tregistered(Registration.file(home)).pipe(\n\t\tEffect.map((found) =>\n\t\t\tfound?.live === undefined ? undefined : { ...endpoint(found.info), version: found.live.version },\n\t\t),\n\t);\n\n/**\n * Stop the server registered for `home`, returning it, or undefined when none\n * answers. Only a server that confirms it is the registrant is signalled: a pid\n * on file may since have been reused by an unrelated process.\n */\nexport const stop = (home: string) =>\n\tEffect.gen(function* () {\n\t\tconst path = Registration.file(home);\n\t\tconst found = yield* registered(path);\n\t\tif (found === undefined) return undefined;\n\t\tif (found.live === undefined) {\n\t\t\tif (!(yield* alive(found.info.pid))) yield* remove(path);\n\t\t\treturn undefined;\n\t\t}\n\t\tyield* terminate(path, found.info.pid);\n\t\treturn endpoint(found.info);\n\t});\n\n/**\n * Ensure a healthy local server for `home`: reuse the registered one, replace it\n * when `replace` is set and it runs a different build, or start a background one.\n *\n * The background server is detached and outlives this caller, so the next\n * invocation reuses it. When two callers race, only the contender that binds the\n * port registers; the loser exits and both adopt the winner, because a caller\n * only ever believes a registration it can confirm over the wire.\n */\nexport const ensure = (\n\toptions: Options & {\n\t\treadonly replace: boolean;\n\t\treadonly onStart?: (reason: \"missing\" | \"version-mismatch\") => void;\n\t},\n) =>\n\tEffect.gen(function* () {\n\t\tconst path = Registration.file(options.home);\n\t\tconst found = yield* registered(path);\n\t\tif (found?.live !== undefined) {\n\t\t\tif (!options.replace || found.live.version === Identity.current.version) return endpoint(found.info);\n\t\t\tyield* Effect.sync(() => options.onStart?.(\"version-mismatch\"));\n\t\t\tyield* terminate(path, found.info.pid);\n\t\t} else {\n\t\t\t// A file nothing answers for, left by a crash, must not mislead the next caller.\n\t\t\tif (found !== undefined && !(yield* alive(found.info.pid))) yield* remove(path);\n\t\t\tyield* Effect.sync(() => options.onStart?.(\"missing\"));\n\t\t}\n\t\treturn yield* start(path, options);\n\t});\n\n/** The registered server once it answers, polled every 200ms for up to `timeout`. */\nconst ready = (path: string, timeout: Duration.Input, pending: Effect.Effect<boolean>) =>\n\tEffect.gen(function* () {\n\t\tconst next = yield* registered(path);\n\t\tif (next?.live !== undefined) return Option.some(endpoint(next.info));\n\t\t// A live registrant that does not answer yet is another caller's server starting up.\n\t\tconst waiting = (yield* pending) || (next !== undefined && (yield* alive(next.info.pid)));\n\t\treturn waiting ? Option.none() : yield* Effect.fail(\"exited\" as const);\n\t}).pipe(\n\t\tEffect.repeat({ until: Option.isSome, schedule: Schedule.spaced(\"200 millis\") }),\n\t\tEffect.timeoutOption(timeout),\n\t\tEffect.map(Option.flatten),\n\t\tEffect.orElseSucceed(() => Option.none<Endpoint>()),\n\t);\n\n/**\n * Start a background server and wait for it to register, quoting the reason\n * from its log when it cannot.\n *\n * The contender stays tied to this scope until it is the server adopted: a\n * timeout, an interrupt, or another caller winning the race stops it rather than\n * leaving an unmanaged server behind.\n */\nconst start = (path: string, options: Options) =>\n\tEffect.gen(function* () {\n\t\tconst contender = yield* spawn(options);\n\t\tconst won = yield* ready(path, START_TIMEOUT, contender.isRunning.pipe(Effect.orElseSucceed(() => false)));\n\t\t// A contender that lost the bind race exits before the winner may have filed its\n\t\t// registration; give the winner a moment before calling the start a failure.\n\t\tconst server = Option.isSome(won) ? won : yield* ready(path, RACE_GRACE, Effect.succeed(true));\n\t\tif (Option.isSome(server)) {\n\t\t\tif (server.value.pid === contender.pid) yield* contender.unref.pipe(Effect.asVoid);\n\t\t\treturn server.value;\n\t\t}\n\n\t\tconst log = Registration.log(options.log);\n\t\tconst reason = yield* lastLine(log);\n\t\treturn yield* new ServerStartError({\n\t\t\tmessage: [\n\t\t\t\t`could not start a CodeWork server on ${options.host}:${options.port}`,\n\t\t\t\t...(reason === undefined ? [] : [`reason: ${reason}`]),\n\t\t\t\t`log: ${log}`,\n\t\t\t\t\"hint: pass --port to use another port, or point `codework tui --server` at a running server\",\n\t\t\t].join(\"\\n\"),\n\t\t});\n\t}).pipe(Effect.scoped);\n\n/**\n * Keep the session's server running for as long as the caller lives.\n *\n * The TUI only reconnects; it cannot start a server. If the one it uses goes\n * away, this brings one back on the same port so the reconnect lands. It never\n * replaces a running server: another invocation may have just upgraded it.\n */\nexport const keepAlive = (initial: Endpoint, options: Options) =>\n\tEffect.gen(function* () {\n\t\tconst current = yield* Ref.make(initial);\n\t\tyield* Effect.gen(function* () {\n\t\t\tconst server = yield* Ref.get(current);\n\t\t\tif (yield* alive(server.pid)) return;\n\t\t\tconst next = yield* ensure({ ...options, port: server.port, replace: false }).pipe(\n\t\t\t\tEffect.orElseSucceed(() => server),\n\t\t\t);\n\t\t\tyield* Ref.set(current, next);\n\t\t}).pipe(Effect.repeat(Schedule.spaced(\"1 second\")));\n\t});\n\n/** Ask `pid` to shut down, escalating to SIGKILL, and retire its registration. */\nconst terminate = (path: string, pid: number) =>\n\tEffect.gen(function* () {\n\t\tconst signal = (name: NodeJS.Signals) => Effect.try(() => process.kill(pid, name)).pipe(Effect.ignore);\n\t\tyield* signal(\"SIGTERM\");\n\t\tif (!(yield* exits(pid, STOP_TIMEOUT))) {\n\t\t\tyield* signal(\"SIGKILL\");\n\t\t\tyield* exits(pid, STOP_TIMEOUT);\n\t\t}\n\t\t// A server removes its own file on a clean exit; this covers the SIGKILL path.\n\t\tconst info = yield* read(path);\n\t\tif (info?.pid === pid) yield* remove(path);\n\t});\n\nconst lastLine = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst fs = yield* FileSystem.FileSystem;\n\t\tconst text = yield* fs.readFileString(path).pipe(Effect.orElseSucceed(() => \"\"));\n\t\treturn text\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trim())\n\t\t\t.findLast((line) => line.length > 0);\n\t});\n\n/**\n * Spawn `codework serve --service` detached, inheriting this environment so it\n * resolves the same home, catalog and credentials. It writes its own log, so no\n * stdio is tied to this short-lived caller. It stays referenced, and so stopped\n * with the scope, until `start` adopts it.\n */\nconst spawn = (options: Options) =>\n\tEffect.gen(function* () {\n\t\tconst [file, ...base] = Registration.command();\n\t\tif (file === undefined) return yield* Effect.die(new Error(\"could not resolve the codework entrypoint\"));\n\t\tconst spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n\t\tconst handle = yield* spawner.spawn(\n\t\t\tChildProcess.make(\n\t\t\t\tfile,\n\t\t\t\t[...base, ...options.args, \"serve\", \"--service\", \"--host\", options.host, \"--port\", String(options.port)],\n\t\t\t\t{ detached: true, stdin: \"ignore\", stdout: \"ignore\", stderr: \"ignore\" },\n\t\t\t),\n\t\t);\n\t\treturn handle;\n\t});\n\nexport * as Discovery from \"./discovery.ts\";\n","import { Global } from \"@codeworksh/harness/effect\";\nimport { Effect, Option } from \"effect\";\nimport type { Discovery } from \"../server/discovery.ts\";\n\ninterface Shared {\n\treadonly userConfigDir: Option.Option<string>;\n\treadonly home: Option.Option<string>;\n\treadonly database: Option.Option<string>;\n}\n\n/** The CodeWork home the shared flags name, resolved the way the harness resolves it. */\nexport const home = (shared: Shared) => Global.resolve(Option.isSome(shared.home) ? { home: shared.home.value } : {});\n\n/**\n * How `tui` and `service` find or start the background server: the home whose\n * `service.json` names it, and the server-owned flags it is started with, in the\n * order `serve` parses them.\n */\nexport const options = (shared: Shared, server: { readonly host: string; readonly port: number }) =>\n\thome(shared).pipe(\n\t\tEffect.map((paths): Discovery.Options => ({\n\t\t\thome: paths.home,\n\t\t\tlog: paths.log,\n\t\t\t...server,\n\t\t\targs: [\n\t\t\t\t...(Option.isSome(shared.home) ? [\"--home\", shared.home.value] : []),\n\t\t\t\t...(Option.isSome(shared.database) ? [\"--database\", shared.database.value] : []),\n\t\t\t\t...(Option.isSome(shared.userConfigDir) ? [\"--user-config-dir\", shared.userConfigDir.value] : []),\n\t\t\t],\n\t\t})),\n\t);\n\nexport * as Service from \"./service.ts\";\n"],"mappings":";;;;;;;;;;;;AASA,MAAa,SAAS,QACrB,OAAO,IAAI,aAAa;CACvB,MAAM,UAAU,OAAO,MAAM,MAAMA,MAAa,GAAG,CAAC,CAAC,CAAC,KAAK,OAAO,oBAAoB,KAAA,CAAS,CAAC;CAChG,IAAI,YAAY,KAAA,GAAW,OAAO,KAAA;CAClC,OAAO,OAAO,OAAO,IAAI,aAAa;EAErC,OAAO,QAAO,OADKC,KAAAA,CACD,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,UAAU,CAAC;CACrE,CAAC,CAAC,CAAC,KACF,OAAO,eAAe,OA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