@codeworksh/cli 0.8.0 → 0.9.0-canary.158.1.gdff28d0d

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 (151) hide show
  1. package/{acp-DodCRypZ.mjs → acp-D1X6PAQd.mjs} +16 -11
  2. package/acp-D1X6PAQd.mjs.map +1 -0
  3. package/{add-Dgy0iTEQ.mjs → add-BO0TXkKX.mjs} +8 -7
  4. package/add-BO0TXkKX.mjs.map +1 -0
  5. package/{add-31QB-o0_.mjs → add-BwC5Yb3Z.mjs} +5 -5
  6. package/add-BwC5Yb3Z.mjs.map +1 -0
  7. package/{catalog-XfqtqMDz.mjs → catalog-BhnZFkoq.mjs} +2 -2
  8. package/{catalog-XfqtqMDz.mjs.map → catalog-BhnZFkoq.mjs.map} +1 -1
  9. package/{check-BoANDJxT.mjs → check-n2oLWYrZ.mjs} +4 -4
  10. package/check-n2oLWYrZ.mjs.map +1 -0
  11. package/connect-CO-oR-Br.mjs +35 -0
  12. package/connect-CO-oR-Br.mjs.map +1 -0
  13. package/{control-CQxWGS4k.mjs → control-Clr9Xyw9.mjs} +10 -9
  14. package/control-Clr9Xyw9.mjs.map +1 -0
  15. package/devices-aPlpoGGA.mjs +29 -0
  16. package/devices-aPlpoGGA.mjs.map +1 -0
  17. package/disconnect-B7HoGP0E.mjs +21 -0
  18. package/disconnect-B7HoGP0E.mjs.map +1 -0
  19. package/disconnect-gKR8hsnU.mjs +2 -0
  20. package/{service-CjOS-xCw.mjs → discovery-D07MPnKd.mjs} +13 -37
  21. package/discovery-D07MPnKd.mjs.map +1 -0
  22. package/{entries-DpL4xhu0.mjs → entries-BzfySpSJ.mjs} +3 -3
  23. package/{entries-DpL4xhu0.mjs.map → entries-BzfySpSJ.mjs.map} +1 -1
  24. package/{error-CPyvkO4x.mjs → error-ippxl2z7.mjs} +775 -31
  25. package/error-ippxl2z7.mjs.map +1 -0
  26. package/{fork-CjZteIbk.mjs → fork-lbhh_6QP.mjs} +8 -7
  27. package/fork-lbhh_6QP.mjs.map +1 -0
  28. package/identity-DbK4fABs.mjs +26 -0
  29. package/identity-DbK4fABs.mjs.map +1 -0
  30. package/{thread-I6vNdC0y.mjs → ids-cNIRx0-c.mjs} +11 -5
  31. package/ids-cNIRx0-c.mjs.map +1 -0
  32. package/index.mjs +39 -34
  33. package/index.mjs.map +1 -1
  34. package/{install-BUfEBtrj.mjs → install-dfD5hzCS.mjs} +4 -4
  35. package/install-dfD5hzCS.mjs.map +1 -0
  36. package/jsonc-CWL4-4yz.mjs +33 -0
  37. package/jsonc-CWL4-4yz.mjs.map +1 -0
  38. package/{link-ZuzWj9qt.mjs → link-D1cicwAl.mjs} +8 -6
  39. package/link-D1cicwAl.mjs.map +1 -0
  40. package/{list-DDuzyNv0.mjs → list-BKJgNMJm.mjs} +10 -12
  41. package/list-BKJgNMJm.mjs.map +1 -0
  42. package/{list-6QTwXTKO.mjs → list-C3McEC0O.mjs} +4 -4
  43. package/list-C3McEC0O.mjs.map +1 -0
  44. package/{list-DPbF2uMB.mjs → list-CGT6jT-r.mjs} +4 -4
  45. package/list-CGT6jT-r.mjs.map +1 -0
  46. package/{list-BnIIcMI3.mjs → list-DZK016LF.mjs} +4 -4
  47. package/list-DZK016LF.mjs.map +1 -0
  48. package/{login-BtuROCPJ.mjs → login-DuFDeGH-.mjs} +4 -4
  49. package/login-DuFDeGH-.mjs.map +1 -0
  50. package/{login-CGXU21AK.mjs → login-XhIIF5Yu.mjs} +4 -4
  51. package/login-XhIIF5Yu.mjs.map +1 -0
  52. package/{logout-DUn8KSjX.mjs → logout-CA1No9_2.mjs} +4 -4
  53. package/logout-CA1No9_2.mjs.map +1 -0
  54. package/{logout-Bnk2hxfZ.mjs → logout-Dpqw8tQZ.mjs} +4 -4
  55. package/logout-Dpqw8tQZ.mjs.map +1 -0
  56. package/package-DgfSc9nY.mjs +6 -0
  57. package/package-DgfSc9nY.mjs.map +1 -0
  58. package/package.json +3 -3
  59. package/pair-BC8a_KYX.mjs +15 -0
  60. package/pair-BC8a_KYX.mjs.map +1 -0
  61. package/{providers-GEdlDJHp.mjs → providers--giKGohM.mjs} +4 -4
  62. package/providers--giKGohM.mjs.map +1 -0
  63. package/reconnect-I9-Do_DK.mjs +2 -0
  64. package/{refresh-DGJW3rSp.mjs → refresh-BIH3qn5A.mjs} +4 -4
  65. package/refresh-BIH3qn5A.mjs.map +1 -0
  66. package/{refresh-93t2pSpb.mjs → refresh-Dg8WvRcq.mjs} +4 -4
  67. package/refresh-Dg8WvRcq.mjs.map +1 -0
  68. package/{identity-LhURGrcS.mjs → registration-C6yiv31r.mjs} +27 -25
  69. package/registration-C6yiv31r.mjs.map +1 -0
  70. package/relay-CLPWErNw.mjs +319 -0
  71. package/relay-CLPWErNw.mjs.map +1 -0
  72. package/{relink-Djy5t7D2.mjs → relink-D8Koos_q.mjs} +9 -7
  73. package/relink-D8Koos_q.mjs.map +1 -0
  74. package/{reload-Dm464rPC.mjs → reload-C5-B0s9x.mjs} +6 -5
  75. package/{reload-Dm464rPC.mjs.map → reload-C5-B0s9x.mjs.map} +1 -1
  76. package/{remove-DBT19X2j.mjs → remove-6m5n17il.mjs} +4 -4
  77. package/remove-6m5n17il.mjs.map +1 -0
  78. package/{remove-f7C_vEOD.mjs → remove-VZO51J2m.mjs} +5 -5
  79. package/remove-VZO51J2m.mjs.map +1 -0
  80. package/{restart-DXMDjblc.mjs → restart-4NoPj76N.mjs} +5 -4
  81. package/restart-4NoPj76N.mjs.map +1 -0
  82. package/revoke-Gu5N3Vzy.mjs +13 -0
  83. package/revoke-Gu5N3Vzy.mjs.map +1 -0
  84. package/{run-CTFksYXE.mjs → run-RHrJN2Pv.mjs} +12 -14
  85. package/run-RHrJN2Pv.mjs.map +1 -0
  86. package/{runtime-CK2CunDw.mjs → runtime-CtLWuLd-.mjs} +48 -12
  87. package/runtime-CtLWuLd-.mjs.map +1 -0
  88. package/{serve-BntJRQed.mjs → serve-BZ5FAU3h.mjs} +586 -64
  89. package/serve-BZ5FAU3h.mjs.map +1 -0
  90. package/service-CRnqz89w.mjs +79 -0
  91. package/service-CRnqz89w.mjs.map +1 -0
  92. package/{settings-DasbTMFs.mjs → settings-DU140UBM.mjs} +3 -3
  93. package/settings-DU140UBM.mjs.map +1 -0
  94. package/{shared-CDyNsYBy.mjs → shared-CC4WukJX.mjs} +4 -4
  95. package/shared-CC4WukJX.mjs.map +1 -0
  96. package/{shared-CiSbTY59.mjs → shared-Dzwbs5Lk.mjs} +7 -9
  97. package/shared-Dzwbs5Lk.mjs.map +1 -0
  98. package/{start-CTYwK1Z4.mjs → start-COhahq2E.mjs} +5 -4
  99. package/start-COhahq2E.mjs.map +1 -0
  100. package/{status-CPKssQFk.mjs → status-Cau7bzuQ.mjs} +5 -4
  101. package/status-Cau7bzuQ.mjs.map +1 -0
  102. package/{status-CHcJyF_7.mjs → status-DJJOuCzL.mjs} +4 -4
  103. package/status-DJJOuCzL.mjs.map +1 -0
  104. package/{stop-CpQr3fUv.mjs → stop-CC--mxXp.mjs} +5 -4
  105. package/stop-CC--mxXp.mjs.map +1 -0
  106. package/{update-C3llbIB0.mjs → update-DMQLgDm3.mjs} +4 -4
  107. package/update-DMQLgDm3.mjs.map +1 -0
  108. package/acp-DodCRypZ.mjs.map +0 -1
  109. package/add-31QB-o0_.mjs.map +0 -1
  110. package/add-Dgy0iTEQ.mjs.map +0 -1
  111. package/check-BoANDJxT.mjs.map +0 -1
  112. package/control-CQxWGS4k.mjs.map +0 -1
  113. package/disconnect-BiLuV4JZ.mjs +0 -2
  114. package/error-CPyvkO4x.mjs.map +0 -1
  115. package/fork-CjZteIbk.mjs.map +0 -1
  116. package/identity-LhURGrcS.mjs.map +0 -1
  117. package/install-BUfEBtrj.mjs.map +0 -1
  118. package/jsonc-Ca0uQLm-.mjs +0 -58
  119. package/jsonc-Ca0uQLm-.mjs.map +0 -1
  120. package/link-ZuzWj9qt.mjs.map +0 -1
  121. package/list-6QTwXTKO.mjs.map +0 -1
  122. package/list-BnIIcMI3.mjs.map +0 -1
  123. package/list-DDuzyNv0.mjs.map +0 -1
  124. package/list-DPbF2uMB.mjs.map +0 -1
  125. package/login-BtuROCPJ.mjs.map +0 -1
  126. package/login-CGXU21AK.mjs.map +0 -1
  127. package/logout-Bnk2hxfZ.mjs.map +0 -1
  128. package/logout-DUn8KSjX.mjs.map +0 -1
  129. package/package-C5s94xPy.mjs +0 -6
  130. package/package-C5s94xPy.mjs.map +0 -1
  131. package/providers-GEdlDJHp.mjs.map +0 -1
  132. package/reconnect-ChE5ETwx.mjs +0 -2
  133. package/refresh-93t2pSpb.mjs.map +0 -1
  134. package/refresh-DGJW3rSp.mjs.map +0 -1
  135. package/relink-Djy5t7D2.mjs.map +0 -1
  136. package/remove-DBT19X2j.mjs.map +0 -1
  137. package/remove-f7C_vEOD.mjs.map +0 -1
  138. package/restart-DXMDjblc.mjs.map +0 -1
  139. package/run-CTFksYXE.mjs.map +0 -1
  140. package/runtime-CK2CunDw.mjs.map +0 -1
  141. package/serve-BntJRQed.mjs.map +0 -1
  142. package/service-CjOS-xCw.mjs.map +0 -1
  143. package/settings-DasbTMFs.mjs.map +0 -1
  144. package/shared-CDyNsYBy.mjs.map +0 -1
  145. package/shared-CiSbTY59.mjs.map +0 -1
  146. package/start-CTYwK1Z4.mjs.map +0 -1
  147. package/status-CHcJyF_7.mjs.map +0 -1
  148. package/status-CPKssQFk.mjs.map +0 -1
  149. package/stop-CpQr3fUv.mjs.map +0 -1
  150. package/thread-I6vNdC0y.mjs.map +0 -1
  151. package/update-C3llbIB0.mjs.map +0 -1
@@ -1,9 +1,435 @@
1
- import { Deferred, Duration, Effect, Layer, Predicate, Schema, Stream } from "effect";
1
+ import { Context, Deferred, Duration, Effect, FileSystem, Layer, Option, Predicate, Result, Schema, Stream } from "effect";
2
2
  import { Model } from "@codeworksh/aikit";
3
- import { Control, Event, EventList, EventSchema, Location, McpError, ModelCatalog, Plugin, Project, PromptSchema, Runner, Sandbox, SandboxError, Session, SessionStore, Settings, ThreadSchema, ThreadStore, optional } from "@codeworksh/harness/effect";
3
+ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
4
+ import { Control, DaemonHost, Database, Event, EventList, EventSchema, Global, Location, McpError, ModelCatalog, Plugin, Project, PromptSchema, Runner, Sandbox, SandboxError, Session, SessionStore, Settings, SettingsFile, ThreadSchema, ThreadStore, UsageSchema, optional } from "@codeworksh/harness/effect";
4
5
  import { SandboxProvider } from "@codeworksh/harness/sandbox";
5
- import { NodeSocket } from "@effect/platform-node";
6
- import { Rpc, RpcClient, RpcGroup, RpcSerialization } from "effect/rpc";
6
+ import { Base64Url } from "effect/encoding";
7
+ import * as IpNetwork from "effect/net/IpNetwork";
8
+ import * as NetAddress from "effect/net/NetAddress";
9
+ import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSecurity } from "effect/http-api";
10
+ import { NodeServices, NodeSocket } from "@effect/platform-node";
11
+ import { Rpc, RpcClient, RpcGroup, RpcMiddleware, RpcSerialization } from "effect/rpc";
12
+ //#region \0rolldown/runtime.js
13
+ var __defProp = Object.defineProperty;
14
+ var __exportAll = (all, no_symbols) => {
15
+ let target = {};
16
+ for (var name in all) __defProp(target, name, {
17
+ get: all[name],
18
+ enumerable: true
19
+ });
20
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
21
+ return target;
22
+ };
23
+ //#endregion
24
+ //#region ../schema/src/door.ts
25
+ /** The subprotocol every client offers first, and the one a listener selects. */
26
+ const protocol = "codework";
27
+ /** The subprotocols a client offers: the fixed name, then its token; without one it is refused. */
28
+ const protocols = (token) => token === void 0 ? [protocol] : [protocol, token];
29
+ /** A token as a subprotocol can carry it: base64url, which is what {@link make} gives. */
30
+ const isToken = (value) => /^[A-Za-z0-9_-]+$/.test(value);
31
+ /** A fresh token: 32 random bytes. */
32
+ const make$1 = Effect.sync(() => Base64Url.encode(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32))));
33
+ /** The token a `Sec-WebSocket-Protocol` header offers after the fixed name, and nothing else; none otherwise. */
34
+ const offered = (header) => {
35
+ const [name, token, ...rest] = (header ?? "").split(",").map((part) => part.trim());
36
+ return name === protocol && token !== void 0 && isToken(token) && rest.length === 0 ? token : void 0;
37
+ };
38
+ /** Whether `given` is `expected`, in a time that depends on `expected`'s length alone. */
39
+ const matches = (given, expected) => {
40
+ let difference = given.length ^ expected.length;
41
+ for (let index = 0; index < expected.length; index++) difference |= expected.charCodeAt(index) ^ (given.charCodeAt(index) | 0);
42
+ return difference === 0;
43
+ };
44
+ /**
45
+ * The door on every request the listener serves, before a WebSocket upgrade: a refused one gets a
46
+ * plain HTTP status instead of 101, 403 for where it comes from and 401 for its credential.
47
+ */
48
+ const layer$1 = (options) => HttpRouter.middleware((app) => Effect.gen(function* () {
49
+ const request = yield* HttpServerRequest.HttpServerRequest;
50
+ const origin = request.headers.origin;
51
+ if (origin !== void 0 && !options.origins.includes(origin)) return HttpServerResponse.empty({ status: 403 });
52
+ const admitted = yield* options.admit(offered(request.headers["sec-websocket-protocol"]), request);
53
+ if (admitted === void 0) return HttpServerResponse.empty({ status: 401 });
54
+ return yield* Effect.provideService(app, HttpServerRequest.HttpServerRequest, admitted);
55
+ }), { global: true });
56
+ //#endregion
57
+ //#region ../schema/src/forwarded.ts
58
+ /** The address `request` came from, by its socket, canonical; none when it has none. */
59
+ const peer = (request) => Option.match(request.remoteAddress, {
60
+ onNone: () => void 0,
61
+ onSome: (address) => Result.getOrUndefined(Result.map(NetAddress.ipFromString(address), (ip) => NetAddress.toCanonical(ip)))
62
+ });
63
+ /** Whether `request` reached the proxy in front of this listener over TLS, by a proxy on loopback or in `trusted`. */
64
+ const encrypted = (request, trusted) => {
65
+ const from = peer(request);
66
+ if (from === void 0 || !(NetAddress.isLoopback(from) || trusted.some((network) => IpNetwork.contains(network, from)))) return false;
67
+ return request.headers["x-forwarded-proto"]?.split(",")[0]?.trim().toLowerCase() === "https";
68
+ };
69
+ //#endregion
70
+ //#region ../schema/src/jws.ts
71
+ const PublicKey = Schema.Struct({
72
+ kty: Schema.Literal("OKP"),
73
+ crv: Schema.Literal("Ed25519"),
74
+ x: Schema.String
75
+ });
76
+ const PrivateKey = Schema.Struct({
77
+ ...PublicKey.fields,
78
+ d: Schema.String
79
+ });
80
+ const Header = Schema.Struct({
81
+ alg: Schema.Literal("EdDSA"),
82
+ /** The signing key's thumbprint, for a key the verifier already holds. */
83
+ kid: Schema.optional(Schema.String),
84
+ /** The signing key itself, for a request that registers it. */
85
+ jwk: Schema.optional(PublicKey)
86
+ });
87
+ var JwsError = class extends Schema.TaggedError()("Jws.JwsError", { reason: Schema.Literals([
88
+ "malformed",
89
+ "signature",
90
+ "crypto"
91
+ ]) }) {};
92
+ const algorithm = { name: "Ed25519" };
93
+ const decodeHeader = Schema.decodeUnknownEffect(Schema.fromJsonString(Header));
94
+ const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
95
+ const crypto$1 = (evaluate) => Effect.tryPromise({
96
+ try: evaluate,
97
+ catch: () => new JwsError({ reason: "crypto" })
98
+ });
99
+ const bytes = (part) => Result.match(Base64Url.decode(part), {
100
+ onFailure: () => Effect.fail(new JwsError({ reason: "malformed" })),
101
+ onSuccess: (decoded) => Effect.succeed(Uint8Array.from(decoded))
102
+ });
103
+ /** The public half of a private key. */
104
+ const publicOf = (key) => ({
105
+ kty: key.kty,
106
+ crv: key.crv,
107
+ x: key.x
108
+ });
109
+ /** A fresh Ed25519 keypair as a private JWK; its public half is {@link publicOf}. */
110
+ const generate = Effect.fn("Jws.generate")(function* () {
111
+ const pair = yield* crypto$1(() => globalThis.crypto.subtle.generateKey("Ed25519", true, ["sign", "verify"]));
112
+ if (!("privateKey" in pair)) return yield* new JwsError({ reason: "crypto" });
113
+ const jwk = yield* crypto$1(() => globalThis.crypto.subtle.exportKey("jwk", pair.privateKey));
114
+ return yield* Schema.decodeUnknownEffect(PrivateKey)(jwk).pipe(Effect.mapError(() => new JwsError({ reason: "crypto" })));
115
+ });
116
+ /** The RFC 7638 thumbprint of a public key: base64url SHA-256 of its required members, in order. */
117
+ const thumbprint = Effect.fn("Jws.thumbprint")(function* (key) {
118
+ const canonical = `{"crv":"${key.crv}","kty":"${key.kty}","x":"${key.x}"}`;
119
+ const digest = yield* crypto$1(() => globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical)));
120
+ return Base64Url.encode(new Uint8Array(digest));
121
+ });
122
+ /** A key's thumbprint as people compare it, `SHA256:<thumbprint>`. */
123
+ const fingerprintOf = (thumbprint) => `SHA256:${thumbprint}`;
124
+ /** A public key as people compare it: {@link fingerprintOf} its thumbprint. */
125
+ const fingerprint = (key) => Effect.map(thumbprint(key), fingerprintOf);
126
+ /** Signs `claims` with `key`, naming it by `kid` or embedding its public half. */
127
+ const sign = Effect.fn("Jws.sign")(function* (claims, key, name) {
128
+ const header = "kid" in name ? {
129
+ alg: "EdDSA",
130
+ kid: name.kid
131
+ } : {
132
+ alg: "EdDSA",
133
+ jwk: publicOf(key)
134
+ };
135
+ const input = `${Base64Url.encode(JSON.stringify(header))}.${Base64Url.encode(JSON.stringify(claims))}`;
136
+ const signer = yield* crypto$1(() => globalThis.crypto.subtle.importKey("jwk", key, algorithm, false, ["sign"]));
137
+ const signature = yield* crypto$1(() => globalThis.crypto.subtle.sign(algorithm, signer, new TextEncoder().encode(input)));
138
+ return `${input}.${Base64Url.encode(new Uint8Array(signature))}`;
139
+ });
140
+ const parts = (token) => {
141
+ const [header, claims, signature, extra] = token.split(".");
142
+ return header === void 0 || claims === void 0 || signature === void 0 || extra !== void 0 ? Effect.fail(new JwsError({ reason: "malformed" })) : Effect.succeed({
143
+ header,
144
+ claims,
145
+ signature
146
+ });
147
+ };
148
+ const decodeClaims = (part) => Effect.flatMap(bytes(part), (decoded) => decodeJson(new TextDecoder().decode(decoded)).pipe(Effect.mapError(() => new JwsError({ reason: "malformed" }))));
149
+ /** A token's header, read before its signature is checked, to find the key that checks it. */
150
+ const peek = Effect.fn("Jws.peek")(function* (token) {
151
+ const { header } = yield* parts(token);
152
+ return yield* decodeHeader(new TextDecoder().decode(yield* bytes(header))).pipe(Effect.mapError(() => new JwsError({ reason: "malformed" })));
153
+ });
154
+ /** A token's claims, still undecoded, read without checking its signature: for echoing, never for trusting. */
155
+ const peekClaims = Effect.fn("Jws.peekClaims")(function* (token) {
156
+ return yield* decodeClaims((yield* parts(token)).claims);
157
+ });
158
+ /** Checks `token`'s signature against `key` and returns its claims, still undecoded. */
159
+ const verify = Effect.fn("Jws.verify")(function* (token, key) {
160
+ const { header, claims, signature } = yield* parts(token);
161
+ const signed = yield* bytes(signature);
162
+ const verifier = yield* crypto$1(() => globalThis.crypto.subtle.importKey("jwk", key, algorithm, false, ["verify"]));
163
+ if (!(yield* crypto$1(() => globalThis.crypto.subtle.verify(algorithm, verifier, signed, new TextEncoder().encode(`${header}.${claims}`))))) return yield* new JwsError({ reason: "signature" });
164
+ return yield* decodeClaims(claims);
165
+ });
166
+ //#endregion
167
+ //#region ../schema/src/relay.ts
168
+ const Role = Schema.Literals([
169
+ "owner",
170
+ "admin",
171
+ "member"
172
+ ]);
173
+ /** A workspace's id, which the relay assigns; anything else is refused at the wire. */
174
+ const WorkspaceId = Schema.String.check(Schema.isUUID());
175
+ /** A machine's id: generated (a UUID) or set with `--machine-id`, lowercase letters, digits and dashes. */
176
+ const MachineId = Schema.String.check(Schema.isPattern(/^[a-z0-9][a-z0-9-]{0,63}$/));
177
+ var Account = class extends Schema.Class("Relay.Account")({
178
+ id: Schema.String,
179
+ email: Schema.String,
180
+ name: Schema.NullOr(Schema.String)
181
+ }) {};
182
+ var Workspace = class extends Schema.Class("Relay.Workspace")({
183
+ id: WorkspaceId,
184
+ name: Schema.String,
185
+ role: Role
186
+ }) {};
187
+ var Me = class extends Schema.Class("Relay.Me")({
188
+ account: Account,
189
+ workspaces: Schema.Array(Workspace)
190
+ }) {};
191
+ /** How a machine got its id: generated on first run, or set with `--machine-id`. */
192
+ const IdSource = Schema.Literals(["generated", "flag"]);
193
+ /** What a machine says about itself when it pairs and on every heartbeat. */
194
+ const MachineInfo = Schema.Struct({
195
+ id: MachineId,
196
+ source: IdSource,
197
+ localHostName: Schema.String,
198
+ givenName: Schema.NullOr(Schema.String),
199
+ os: Schema.String,
200
+ arch: Schema.String,
201
+ version: Schema.String
202
+ });
203
+ var Machine = class extends Schema.Class("Relay.Machine")({
204
+ ...MachineInfo.fields,
205
+ workspaceId: WorkspaceId,
206
+ /** The thumbprint of the key the link is live under; a home holds that key for this workspace. */
207
+ keyId: Schema.String,
208
+ /** The thumbprint of the home's identity key: links with the same one, in any workspace, are one machine. */
209
+ identityKeyId: Schema.String,
210
+ ownerId: Schema.String,
211
+ online: Schema.Boolean,
212
+ lastSeenAt: Schema.NullOr(Schema.String)
213
+ }) {};
214
+ const SignedRequest = Schema.Struct({ jws: Schema.String });
215
+ Schema.Struct({
216
+ op: Schema.Literal("pairing.create"),
217
+ iat: Schema.Number,
218
+ machine: MachineInfo,
219
+ /** The workspace the connect started from; the approver may pick another when it is null. */
220
+ workspaceId: Schema.NullOr(WorkspaceId),
221
+ /** An {@link IdentityClaims} JWS by the home's identity key, naming this request's key. */
222
+ identity: Schema.String
223
+ });
224
+ Schema.Struct({
225
+ op: Schema.Literal("identity.bind"),
226
+ iat: Schema.Number,
227
+ keyId: Schema.String
228
+ });
229
+ Schema.Struct({
230
+ op: Schema.Literal("pairing.poll"),
231
+ iat: Schema.Number
232
+ });
233
+ Schema.Struct({
234
+ op: Schema.Literal("machine.heartbeat"),
235
+ iat: Schema.Number,
236
+ workspaceId: WorkspaceId,
237
+ machine: MachineInfo
238
+ });
239
+ Schema.Struct({
240
+ op: Schema.Literal("machine.revoke"),
241
+ iat: Schema.Number,
242
+ /** Used once: a replayed revoke is refused. */
243
+ jti: Schema.String,
244
+ workspaceId: WorkspaceId,
245
+ machineId: MachineId
246
+ });
247
+ const PairingCreated = Schema.Struct({
248
+ userCode: Schema.String,
249
+ expiresIn: Schema.Int,
250
+ interval: Schema.Int
251
+ });
252
+ const Connected$1 = Schema.Struct({
253
+ machineId: MachineId,
254
+ workspace: Schema.Struct({
255
+ id: WorkspaceId,
256
+ name: Schema.String
257
+ }),
258
+ owner: Schema.Struct({
259
+ id: Schema.String,
260
+ name: Schema.NullOr(Schema.String)
261
+ })
262
+ });
263
+ const PairingStatus = Schema.Union([Schema.Struct({ status: Schema.Literals([
264
+ "pending",
265
+ "expired",
266
+ "declined",
267
+ "superseded"
268
+ ]) }), Schema.Struct({
269
+ status: Schema.Literal("approved"),
270
+ connected: Connected$1
271
+ })]);
272
+ var Unauthorized$1 = class extends Schema.TaggedError()("Relay.Unauthorized", { message: Schema.String }, { httpApiStatus: 401 }) {};
273
+ /** The relay couldn't check the request just now (its auth vendor is unreachable): try again shortly. */
274
+ var Unavailable = class extends Schema.TaggedError()("Relay.Unavailable", { message: Schema.String }, { httpApiStatus: 503 }) {};
275
+ /** The machine's link to the workspace is gone: revoked, replaced, or its owner left. Reconnect to restore it. */
276
+ var MachineRevoked = class extends Schema.TaggedError()("Relay.MachineRevoked", { message: Schema.String }, { httpApiStatus: 401 }) {};
277
+ var Forbidden$1 = class extends Schema.TaggedError()("Relay.Forbidden", { message: Schema.String }, { httpApiStatus: 403 }) {};
278
+ var NotFound = class extends Schema.TaggedError()("Relay.NotFound", { message: Schema.String }, { httpApiStatus: 404 }) {};
279
+ Context.Service()("relay/Person");
280
+ /** Verifies a person's bearer session token and provides {@link Person}. */
281
+ var PersonAuth = class extends HttpApiMiddleware.Service()("relay/PersonAuth", {
282
+ security: { bearer: HttpApiSecurity.bearer },
283
+ error: [Unauthorized$1, Unavailable]
284
+ }) {};
285
+ var MeGroup = class extends HttpApiGroup.make("me").add(HttpApiEndpoint.get("get", "/v1/me", { success: Me })).middleware(PersonAuth) {};
286
+ /** A machine that ran `codework connect` for a workspace and waits for a member to approve its code. */
287
+ var PendingPairing = class extends Schema.Class("Relay.PendingPairing")({
288
+ userCode: Schema.String,
289
+ machine: MachineInfo,
290
+ /** `approved`: a member approved it and the machine's next poll links it. */
291
+ status: Schema.Literals(["pending", "approved"]),
292
+ /** A machine with this id is already in the workspace; approving replaces its link. */
293
+ replaces: Schema.Boolean,
294
+ createdAt: Schema.String,
295
+ expiresAt: Schema.String
296
+ }) {};
297
+ const WorkspaceName = Schema.Trimmed.check(Schema.isNonEmpty(), Schema.isMaxLength(64));
298
+ /** People create workspaces, and manage pairings and machines in a workspace they belong to. */
299
+ var WorkspaceGroup = class extends HttpApiGroup.make("workspace").add(
300
+ HttpApiEndpoint.post("create", "/v1/workspaces", {
301
+ payload: Schema.Struct({ name: WorkspaceName }),
302
+ success: Workspace
303
+ }),
304
+ /** Approves a code; the machine's next poll links it, so it answers with what the machine said. */
305
+ HttpApiEndpoint.post("approve", "/v1/workspaces/:workspaceId/pairings/approve", {
306
+ params: { workspaceId: WorkspaceId },
307
+ payload: Schema.Struct({ userCode: Schema.String }),
308
+ success: Schema.Struct({ machine: MachineInfo }),
309
+ error: [NotFound, Forbidden$1]
310
+ }),
311
+ HttpApiEndpoint.get("machines", "/v1/workspaces/:workspaceId/machines", {
312
+ params: { workspaceId: WorkspaceId },
313
+ success: Schema.Array(Machine),
314
+ error: Forbidden$1
315
+ }),
316
+ /** The workspace's pending connects, each with the code its machine shows. */
317
+ HttpApiEndpoint.get("pairings", "/v1/workspaces/:workspaceId/pairings", {
318
+ params: { workspaceId: WorkspaceId },
319
+ success: Schema.Array(PendingPairing),
320
+ error: Forbidden$1
321
+ }),
322
+ /** Turns a pending connect away; the waiting machine hears it was declined. */
323
+ HttpApiEndpoint.post("decline", "/v1/workspaces/:workspaceId/pairings/decline", {
324
+ params: { workspaceId: WorkspaceId },
325
+ payload: Schema.Struct({ userCode: Schema.String }),
326
+ error: [NotFound, Forbidden$1]
327
+ }),
328
+ /** Disconnects a machine from the workspace: its owner, or a workspace owner or admin, may. */
329
+ HttpApiEndpoint.post("remove", "/v1/workspaces/:workspaceId/machines/:machineId/remove", {
330
+ params: {
331
+ workspaceId: WorkspaceId,
332
+ machineId: MachineId
333
+ },
334
+ payload: Schema.Struct({ keyId: Schema.String }),
335
+ error: [NotFound, Forbidden$1]
336
+ })
337
+ ).middleware(PersonAuth) {};
338
+ /** Machines authenticate each request with a signature, not a session. */
339
+ var MachineGroup = class extends HttpApiGroup.make("machine").add(HttpApiEndpoint.post("pair", "/v1/pairings", {
340
+ payload: SignedRequest,
341
+ success: PairingCreated,
342
+ error: [Unauthorized$1, NotFound]
343
+ }), HttpApiEndpoint.post("poll", "/v1/pairings/poll", {
344
+ payload: SignedRequest,
345
+ success: PairingStatus,
346
+ error: [Unauthorized$1, NotFound]
347
+ }), HttpApiEndpoint.post("heartbeat", "/v1/machines/heartbeat", {
348
+ payload: SignedRequest,
349
+ error: [Unauthorized$1, MachineRevoked]
350
+ }), HttpApiEndpoint.post("revoke", "/v1/machines/revoke", {
351
+ payload: SignedRequest,
352
+ error: [Unauthorized$1, MachineRevoked]
353
+ })) {};
354
+ var Api$1 = class extends HttpApi.make("relay").add(MeGroup).add(WorkspaceGroup).add(MachineGroup) {};
355
+ //#endregion
356
+ //#region ../schema/src/machine.ts
357
+ /** This machine and the workspaces it is connected to, from its `machine.json`. */
358
+ const Status = Schema.Struct({
359
+ /** None before the machine's first connect gives it an identity. */
360
+ id: Schema.NullOr(Schema.String),
361
+ /** The OS's name for the host, read fresh. */
362
+ localHostName: Schema.String,
363
+ /** The user's own name for it, shown in place of `localHostName` when set. */
364
+ givenName: Schema.NullOr(Schema.String),
365
+ /**
366
+ * Each link with the thumbprint of its key: a relay row under another key is not this machine's. A
367
+ * leaving link was ended here while the relay couldn't be reached; it is revoked once it can. Older
368
+ * machines don't report it.
369
+ */
370
+ workspaces: Schema.Array(Schema.Struct({
371
+ id: Schema.String,
372
+ name: Schema.String,
373
+ keyId: Schema.String,
374
+ leaving: Schema.optionalKey(Schema.Boolean)
375
+ }))
376
+ });
377
+ const Disconnect = Schema.Struct({
378
+ workspaceId: Schema.String,
379
+ keyId: Schema.String
380
+ });
381
+ /** A disconnect: this machine afterwards, and whether the relay confirmed; if not, the link is left leaving. */
382
+ const Disconnected = Schema.Struct({
383
+ status: Status,
384
+ revoked: Schema.Boolean
385
+ });
386
+ /** A connect's progress: the code to approve, then the link once a member approved it. */
387
+ const ConnectEvent = Schema.Union([Schema.TaggedStruct("Code", { userCode: Schema.String }), Schema.TaggedStruct("Connected", { connected: Connected$1 })]);
388
+ var ConnectError = class extends Schema.TaggedError()("Machine.ConnectError", { message: Schema.String }) {};
389
+ //#endregion
390
+ //#region ../schema/src/pairing.ts
391
+ /** `POST` with {@link Exchange} creates a device: answers 201 with {@link Device}. */
392
+ const devicesPath = "/api/v1/devices";
393
+ /**
394
+ * `POST` with a {@link Signed} {@link Proof} creates a ticket: answers 201 with a {@link Signed} {@link Grant},
395
+ * or 401 with a {@link Signed} {@link Refusal} (empty when the body names no nonce).
396
+ */
397
+ const ticketsPath = "/api/v1/tickets";
398
+ /** What `POST /api/v1/devices` takes: the code a person read, a name for the computer offering it, and its key. */
399
+ const Exchange = Schema.Struct({
400
+ code: Schema.String,
401
+ label: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(100), Schema.isPattern(/^[^\p{Cc}]*$/u)),
402
+ key: PublicKey
403
+ });
404
+ Schema.Struct({
405
+ id: Schema.String,
406
+ machine: PublicKey
407
+ });
408
+ /** A compact JWS, as both ticket routes carry one. */
409
+ const Signed = Schema.Struct({ jws: Schema.String });
410
+ /** How long a {@link Proof} is good for, either side of the machine's clock; its nonce is held as long. */
411
+ const proofWindow = 3e5;
412
+ /** A device asking for a ticket, signed with its key and named by the key's thumbprint; each nonce is taken once. */
413
+ const Proof = Schema.Struct({
414
+ op: Schema.Literal("ticket.create"),
415
+ /** The thumbprint of the machine key it is for: one device key is paired with every machine. */
416
+ aud: Schema.String,
417
+ device: Schema.String,
418
+ /** Epoch milliseconds. */
419
+ iat: Schema.Finite,
420
+ nonce: Schema.String
421
+ });
422
+ Schema.Struct({
423
+ op: Schema.Literal("ticket.grant"),
424
+ ticket: Schema.String,
425
+ nonce: Schema.String
426
+ });
427
+ Schema.Struct({
428
+ op: Schema.Literal("ticket.refuse"),
429
+ nonce: Schema.String,
430
+ at: Schema.Finite
431
+ });
432
+ //#endregion
7
433
  //#region src/server/envelope.ts
8
434
  /**
9
435
  * The wire form of an `EventSchema.Payload`. `data` is carried in its encoded
@@ -122,9 +548,49 @@ const Part = Schema.Union([
122
548
  /** A stored part row's JSON, or none when it is not a part a client renders. */
123
549
  const decode = Schema.decodeUnknownOption(Schema.fromJsonString(Part));
124
550
  //#endregion
551
+ //#region src/server/principal.ts
552
+ var Current = class extends Context.Service()("@codeworksh/cli/server/principal/Current") {};
553
+ var Unauthorized = class extends Schema.TaggedError()("Server.Unauthorized", { message: Schema.String }) {};
554
+ /** A call this caller may not make: only this computer manages who is paired, and only a device leaves. */
555
+ var Forbidden = class extends Schema.TaggedError()("Server.Forbidden", { message: Schema.String }) {};
556
+ /**
557
+ * Decides the caller of every RPC from the connection it comes on. The contract carries the tag; each
558
+ * listener provides its own implementation where it is built.
559
+ */
560
+ var Door = class extends RpcMiddleware.Service()("@codeworksh/cli/server/principal/Door", { error: Unauthorized }) {};
561
+ /** `effect`, for a local caller only; a device is refused. */
562
+ const local = (effect) => Effect.gen(function* () {
563
+ if ((yield* Current).kind !== "local") return yield* new Forbidden({ message: "Only this computer manages its paired devices" });
564
+ return yield* effect;
565
+ });
566
+ /** The home's token for the life of the server, which every local client sends. */
567
+ var Token = class extends Context.Service()("@codeworksh/cli/server/principal/Token") {};
568
+ /**
569
+ * A fresh token per start, published in `service.json` alone. A `<home>/token` an earlier build kept
570
+ * is deleted, so no stale copy of a credential stays behind.
571
+ */
572
+ const layerToken = Layer.effect(Token, Effect.gen(function* () {
573
+ const global = yield* Global.Service;
574
+ yield* (yield* FileSystem.FileSystem).remove(`${global.home}/token`).pipe(Effect.ignore);
575
+ return yield* make$1;
576
+ }).pipe(Effect.provide(NodeServices.layer)));
577
+ //#endregion
125
578
  //#region src/server/contract.ts
126
579
  /** The HTTP path the RPC endpoint is served on; the version moves with breaking wire changes. */
127
580
  const path = "/rpc/v1";
581
+ /** A computer paired with this machine. */
582
+ const DeviceInfo = Schema.Struct({
583
+ id: Schema.String,
584
+ label: Schema.String,
585
+ /** Its key's fingerprint, `SHA256:<thumbprint>`. */
586
+ fingerprint: Schema.String,
587
+ /** Epoch milliseconds. */
588
+ createdAt: Schema.Finite,
589
+ /** When it last took a ticket, epoch milliseconds; a device unseen for 30 days is refused. */
590
+ seenAt: Schema.Finite,
591
+ /** Whether it last paired or took a ticket over TLS, which ends at a proxy in front of this server. */
592
+ encrypted: Schema.optional(Schema.Boolean)
593
+ });
128
594
  const SandboxInfo = Schema.Struct({
129
595
  id: Sandbox.SandboxInstance.ID,
130
596
  driver: Schema.String,
@@ -250,6 +716,8 @@ const ThreadFields = {
250
716
  runStateAt: optional(Schema.Finite),
251
717
  /** Absent before the first run. */
252
718
  lastRun: optional(ThreadRun),
719
+ /** Whether it holds queued prompts that wait for its next prompt instead of running by themselves. */
720
+ parked: Schema.Boolean,
253
721
  /** Automatic restarts of the current run. */
254
722
  restarts: Schema.Int,
255
723
  /** The 1-based provider request in flight; absent when none is. */
@@ -294,7 +762,64 @@ const IndexItem = Schema.Union([
294
762
  }),
295
763
  Schema.TaggedStruct("Synced", {
296
764
  storeId: Schema.String,
765
+ rev: Schema.Int,
766
+ boot: Schema.String,
767
+ reset: optional(Schema.Literal(true))
768
+ })
769
+ ]);
770
+ UsageSchema.edges;
771
+ /** Where a `usage.sync` row belongs: a thread's UTC hour. */
772
+ const UsageOwner = {
773
+ /** Start of the UTC hour, epoch milliseconds. */
774
+ hour: Schema.Int,
775
+ threadId: ThreadSchema.ID,
776
+ /** The thread's session and project when the row was first written. */
777
+ sessionId: Session.SessionSchema.ID,
778
+ projectId: Schema.String
779
+ };
780
+ /** A `usage.sync` item: a rollup row with the revision that last wrote it, or progress. */
781
+ const UsageItem = Schema.Union([
782
+ Schema.TaggedStruct("Usage", {
783
+ ...UsageOwner,
784
+ provider: Schema.String,
785
+ model: Schema.String,
786
+ thinking: Schema.String,
787
+ requests: Schema.Int,
788
+ /** `reasoning` is part of `output`. */
789
+ tokens: Schema.Struct({
790
+ input: Schema.Int,
791
+ output: Schema.Int,
792
+ cacheRead: Schema.Int,
793
+ cacheWrite: Schema.Int,
794
+ reasoning: Schema.Int
795
+ }),
796
+ /** US dollars, from the catalog's prices. */
797
+ cost: Schema.Struct({
798
+ total: Schema.Finite,
799
+ input: Schema.Finite,
800
+ output: Schema.Finite,
801
+ cacheRead: Schema.Finite,
802
+ cacheWrite: Schema.Finite
803
+ }),
804
+ /** Total ms of the `timed` requests: the committed ones; aborted requests are never timed. */
805
+ duration: Schema.Finite,
806
+ timed: Schema.Int,
807
+ /** The `timed` requests per bucket of `edges`, one more than there are edges. */
808
+ durations: Schema.Array(Schema.Int),
297
809
  rev: Schema.Int
810
+ }),
811
+ Schema.TaggedStruct("Tally", {
812
+ ...UsageOwner,
813
+ kind: Schema.Literals(UsageSchema.tallyKinds),
814
+ name: Schema.String,
815
+ count: Schema.Int,
816
+ rev: Schema.Int
817
+ }),
818
+ Schema.TaggedStruct("Synced", {
819
+ storeId: Schema.String,
820
+ rev: Schema.Int,
821
+ boot: Schema.String,
822
+ reset: optional(Schema.Literal(true))
298
823
  })
299
824
  ]);
300
825
  /** A thread of a session: `threadId`, or the session's `main` thread when absent. */
@@ -525,6 +1050,21 @@ const McpStatus = Schema.Struct({
525
1050
  skipped: optional(EventList.McpSkipped)
526
1051
  });
527
1052
  const McpErrors = Schema.Union([ThreadErrors, McpError.UnknownServerError]);
1053
+ const SettingsFileRef = {
1054
+ projectId: optional(Schema.String),
1055
+ file: Schema.Literals(["settings", "mcp"])
1056
+ };
1057
+ /** The settings a project's `settings.jsonc` falls back to, as the page shows them. */
1058
+ const Inherited = Schema.Struct({ retry: Schema.Struct({
1059
+ maxRetries: Schema.Int,
1060
+ baseDelayMs: Schema.Int,
1061
+ maxDelayMs: Schema.Int
1062
+ }) });
1063
+ const SettingsFileErrors = Schema.Union([
1064
+ Settings.SettingsError,
1065
+ Project.ProjectNotFoundError,
1066
+ Project.ProjectCheckoutError
1067
+ ]);
528
1068
  const Api = RpcGroup.make(
529
1069
  /**
530
1070
  * The server's own identity: the process and build a client is talking to.
@@ -542,20 +1082,45 @@ const Api = RpcGroup.make(
542
1082
  /** The harness store this server serves; a sync cursor is only valid against it. */
543
1083
  storeId: Schema.String,
544
1084
  /** The store's head: the last revision taken. */
545
- rev: Schema.Int
1085
+ rev: Schema.Int,
1086
+ /** The machine it runs on, by the name its user knows it; absent when the OS names it nothing. */
1087
+ host: optional(Schema.Struct({ name: Schema.String })),
1088
+ /** The id in the home's `machine.json`; absent until the home has one. */
1089
+ machineId: optional(Schema.String)
546
1090
  })
547
1091
  }),
548
1092
  /**
549
1093
  * The index of this machine: every project, space, session and thread whose revision is past
550
1094
  * `after`, in revision order, then `Synced` at the head read when the call began; then the same
551
1095
  * live after each commit. `after: 0` reads the whole index. A row written again moves to a later
552
- * revision and is sent again; the latest wins. A deleted session arrives as `Removed`.
1096
+ * revision and is sent again; the latest wins. A deleted session arrives as `Removed`. `boot` is
1097
+ * the one the last `Synced` carried: when the store left that line (a restored backup), it reads
1098
+ * from zero instead.
553
1099
  */
554
1100
  Rpc.make("index.sync", {
555
- payload: { after: Schema.Int },
1101
+ payload: {
1102
+ after: Schema.Int,
1103
+ boot: optional(Schema.String)
1104
+ },
556
1105
  success: IndexItem,
557
1106
  stream: true
558
1107
  }),
1108
+ /**
1109
+ * The usage rollup of this machine: every `usage` and `tally` row whose revision is past `after`,
1110
+ * in revision order, then `Synced` at the head read when the call began; then the same live after
1111
+ * each commit. `after: 0` reads every row. A row written again moves to a later revision and is
1112
+ * sent again in full; the latest wins. Rows carry running totals, not deltas: a client replaces a
1113
+ * row by its key, never adds to it. A deleted session's rows stay. `boot` is the one the last
1114
+ * `Synced` carried: when the store left that line (a restored backup), it reads from zero instead.
1115
+ */
1116
+ Rpc.make("usage.sync", {
1117
+ payload: {
1118
+ after: Schema.Int,
1119
+ boot: optional(Schema.String)
1120
+ },
1121
+ success: UsageItem,
1122
+ stream: true
1123
+ }),
559
1124
  Rpc.make("auth.save", {
560
1125
  payload: { credentials: OAuthCredentials },
561
1126
  success: OAuthInfo,
@@ -610,6 +1175,12 @@ const Api = RpcGroup.make(
610
1175
  HostError
611
1176
  ])
612
1177
  }),
1178
+ /** The `origin` URL of a project's main checkout on the host, credentials taken out; null when there is none. */
1179
+ Rpc.make("project.remote", {
1180
+ payload: { projectId: Schema.String },
1181
+ success: Schema.Struct({ url: Schema.NullOr(Schema.String) }),
1182
+ error: Project.ProjectNotFoundError
1183
+ }),
613
1184
  Rpc.make("project.rename", {
614
1185
  payload: {
615
1186
  projectId: Schema.String,
@@ -622,16 +1193,72 @@ const Api = RpcGroup.make(
622
1193
  error: Project.ProjectNotFoundError
623
1194
  }),
624
1195
  /**
1196
+ * A settings file as written: the project's when `projectId` is given -- the one sessions in its
1197
+ * main checkout read -- otherwise the user's. `version` is what `settings.write` is held to;
1198
+ * `error` is what the runtime would reject in the file as it stands.
1199
+ */
1200
+ Rpc.make("settings.read", {
1201
+ payload: SettingsFileRef,
1202
+ success: Schema.Struct({
1203
+ path: Schema.String,
1204
+ source: Schema.String,
1205
+ exists: Schema.Boolean,
1206
+ version: Schema.String,
1207
+ /** The file's JSONC as a value; absent when it does not parse. */
1208
+ value: optional(Schema.Unknown),
1209
+ error: optional(Schema.String),
1210
+ /**
1211
+ * For `settings.jsonc`: what applies where this file sets nothing -- the user's settings over the
1212
+ * defaults for a project's file, the defaults for the user's. Absent when a lower file is broken.
1213
+ */
1214
+ inherited: optional(Inherited),
1215
+ /**
1216
+ * For `mcp.json`: the servers as sessions use them, user and project merged; entries the runtime
1217
+ * skips are left out. `from` is the file that defines the server, not one that only overrides it.
1218
+ */
1219
+ servers: optional(Schema.Array(Schema.Struct({
1220
+ name: Schema.String,
1221
+ from: Schema.Literals(["user", "project"]),
1222
+ enabled: Schema.Boolean
1223
+ })))
1224
+ }),
1225
+ error: SettingsFileErrors
1226
+ }),
1227
+ /** The whole file, written only when it is still at `version` and the runtime would accept it. */
1228
+ Rpc.make("settings.write", {
1229
+ payload: {
1230
+ ...SettingsFileRef,
1231
+ source: Schema.String,
1232
+ version: Schema.String
1233
+ },
1234
+ success: Schema.Struct({ version: Schema.String }),
1235
+ error: Schema.Union([SettingsFileErrors, SettingsFile.SettingsConflictError])
1236
+ }),
1237
+ /**
1238
+ * One value at `at` set in place, keeping the rest of the file as written; no `value` removes it.
1239
+ * Refused when the result would not be accepted.
1240
+ */
1241
+ Rpc.make("settings.set", {
1242
+ payload: {
1243
+ ...SettingsFileRef,
1244
+ at: Schema.NonEmptyArray(Schema.Union([Schema.String, Schema.Int])),
1245
+ value: optional(Schema.Unknown)
1246
+ },
1247
+ success: Schema.Struct({ version: Schema.String }),
1248
+ error: SettingsFileErrors
1249
+ }),
1250
+ /**
625
1251
  * The models a session anchored at `hostDir` can use: providers this server holds credentials
626
- * for, in the catalog plus that project's settings, and the model settings pick when a session
627
- * names none. Without `hostDir`, only the user's settings apply. Credentials are checked for
628
- * presence, not validity.
1252
+ * for, in the catalog plus that project's settings, and the model a session runs when it names
1253
+ * none: the one settings name, else one picked from those providers. `default` is absent when
1254
+ * neither gives one. Without `hostDir`, only the user's settings apply. Credentials are checked
1255
+ * for presence, not validity.
629
1256
  */
630
1257
  Rpc.make("model.list", {
631
1258
  payload: { hostDir: optional(Session.AbsolutePath) },
632
1259
  success: Schema.Struct({
633
1260
  providers: Schema.Array(ModelProvider),
634
- default: Schema.Struct({
1261
+ default: optional(Schema.Struct({
635
1262
  provider: Schema.String,
636
1263
  id: Schema.String,
637
1264
  /** As settings name it; a run clamps it to what the model supports. */
@@ -639,7 +1266,7 @@ const Api = RpcGroup.make(
639
1266
  /** Display names from the catalog, present even when its provider is not listed. */
640
1267
  name: optional(Schema.String),
641
1268
  providerName: optional(Schema.String)
642
- })
1269
+ }))
643
1270
  }),
644
1271
  error: Schema.Union([Settings.SettingsError, Runner.ModelCatalogError])
645
1272
  }),
@@ -890,6 +1517,67 @@ const Api = RpcGroup.make(
890
1517
  success: McpStatus,
891
1518
  error: McpErrors
892
1519
  }),
1520
+ /** This machine and the workspaces it is connected to. */
1521
+ Rpc.make("machine.info", {
1522
+ payload: {},
1523
+ success: Status
1524
+ }),
1525
+ /** Names this machine for people; an empty name goes back to the OS's. */
1526
+ Rpc.make("machine.rename", {
1527
+ payload: { givenName: Schema.String },
1528
+ success: Status
1529
+ }),
1530
+ /** Leaves a workspace: the relay revokes this machine's link, and the machine forgets it. */
1531
+ Rpc.make("machine.disconnect", {
1532
+ payload: Disconnect,
1533
+ success: Disconnected,
1534
+ error: ConnectError
1535
+ }),
1536
+ /**
1537
+ * Connects this machine to a workspace: the code a member approves, then the link once they have.
1538
+ * `workspaceId` is the workspace it is meant for; without one the approver picks it.
1539
+ */
1540
+ Rpc.make("machine.connect", {
1541
+ payload: { workspaceId: Schema.optional(Schema.String) },
1542
+ success: ConnectEvent,
1543
+ error: ConnectError,
1544
+ stream: true
1545
+ }),
1546
+ /**
1547
+ * A one-time code another computer exchanges at `POST /api/v1/devices` to pair its key, and the
1548
+ * fingerprint of this machine's key, which that computer keeps. Valid 10 minutes, once; held in
1549
+ * memory, so a restart forgets it. Local callers only.
1550
+ */
1551
+ Rpc.make("device.pair", {
1552
+ payload: {},
1553
+ success: Schema.Struct({
1554
+ code: Schema.String,
1555
+ expiresAt: Schema.Finite,
1556
+ fingerprint: Schema.String
1557
+ }),
1558
+ error: Forbidden
1559
+ }),
1560
+ /** Every paired device, oldest first. Local callers only. */
1561
+ Rpc.make("device.list", {
1562
+ payload: {},
1563
+ success: Schema.Array(DeviceInfo),
1564
+ error: Forbidden
1565
+ }),
1566
+ /** Forgets a device and ends its open connections; `applied` is false when none has `id`. Local callers only. */
1567
+ Rpc.make("device.revoke", {
1568
+ payload: { id: Schema.String },
1569
+ success: Schema.Struct({ applied: Schema.Boolean }),
1570
+ error: Forbidden
1571
+ }),
1572
+ /**
1573
+ * Ends the calling device's own pairing, as `device.revoke` would. Its sockets end with it, this one
1574
+ * too, so the reply may never arrive: the connection dropping after the call is sent means it left.
1575
+ * Devices only; a local caller has no pairing to leave.
1576
+ */
1577
+ Rpc.make("device.leave", {
1578
+ payload: {},
1579
+ error: Forbidden
1580
+ }),
893
1581
  /** The OS home directory, and the folder `host.create` makes projects in. */
894
1582
  Rpc.make("host.info", {
895
1583
  payload: {},
@@ -1009,20 +1697,42 @@ const Api = RpcGroup.make(
1009
1697
  error: SandboxErrors
1010
1698
  }),
1011
1699
  /**
1700
+ * Calls a method of a space daemon running in `spaceId`, such as `git.diff`. Never starts a daemon
1701
+ * and never wakes a sandbox: `unavailable` when none runs there, `detached` when the space is not
1702
+ * mounted.
1703
+ */
1704
+ Rpc.make("daemon.call", {
1705
+ payload: {
1706
+ plugin: Schema.String,
1707
+ spaceId: Schema.String,
1708
+ method: Schema.String,
1709
+ input: optional(Schema.Unknown)
1710
+ },
1711
+ success: Schema.Unknown,
1712
+ error: DaemonHost.DaemonCallError
1713
+ }),
1714
+ /**
1012
1715
  * Every event the server publishes, live, after a `server.connected` frame. With `threadId`,
1013
1716
  * only the events naming that thread; the frame still comes first.
1014
1717
  */
1015
1718
  Rpc.make("event.subscribe", {
1016
- payload: { threadId: optional(ThreadSchema.ID) },
1719
+ payload: {
1720
+ threadId: optional(ThreadSchema.ID),
1721
+ /**
1722
+ * Only these event types. The last event of each type that a space daemon published is sent
1723
+ * first, after `server.connected`: a client that was away catches up without a change.
1724
+ */
1725
+ types: optional(Schema.Array(Schema.String))
1726
+ },
1017
1727
  success: EventEnvelope,
1018
1728
  error: Schema.Union([Event.SubscriptionOverflowError, EncodingError]),
1019
1729
  stream: true
1020
1730
  })
1021
- );
1731
+ ).middleware(Door);
1022
1732
  //#endregion
1023
1733
  //#region src/server/client.ts
1024
1734
  const make = RpcClient.make(Api);
1025
- const layer = (url) => RpcClient.layerProtocolSocket().pipe(Layer.provide(NodeSocket.layerWebSocket(url)), Layer.provide(RpcSerialization.layerNdjson));
1735
+ const layer = (server) => RpcClient.layerProtocolSocket().pipe(Layer.provide(NodeSocket.layerWebSocket(server.url, { protocols: protocols(server.token) })), Layer.provide(RpcSerialization.layerNdjson));
1026
1736
  /** A server-side failure as the client sees it: the category, not the cause. */
1027
1737
  var ExecutionError = class extends Schema.TaggedError()("Client.ExecutionError", {
1028
1738
  type: Schema.String,
@@ -1045,13 +1755,24 @@ const run = Effect.fn("Client.run")(function* (rpc, input, render) {
1045
1755
  let admitted = false;
1046
1756
  let promoted = false;
1047
1757
  let settled = false;
1048
- let unattributed;
1758
+ let admittedAt;
1759
+ const starts = [];
1760
+ const ends = [];
1761
+ const ours = () => ends.findLast(({ at, error }) => {
1762
+ const start = Math.max(...starts.filter((seq) => seq < at));
1763
+ return error !== void 0 && admittedAt !== void 0 && start > admittedAt;
1764
+ })?.error;
1049
1765
  const stalled = yield* Deferred.make();
1050
- const terminal = (event) => {
1766
+ /** How a run ended, as this client reports it; `undefined` for a success. */
1767
+ const failure = (event) => {
1051
1768
  if (Schema.is(EventList.ExecutionInterrupted)(event)) return new ExecutionError({
1052
1769
  type: "aborted",
1053
1770
  message: event.data.reason === "shutdown" ? "Server stopped the session" : "Session interrupted"
1054
1771
  });
1772
+ if (Schema.is(EventList.RunFailed)(event)) return new ExecutionError({
1773
+ type: `run.${event.data.reason}`,
1774
+ message: event.data.message
1775
+ });
1055
1776
  if (Schema.is(EventList.ExecutionFailed)(event)) return new ExecutionError({
1056
1777
  type: event.data.error.type,
1057
1778
  message: event.data.error.message,
@@ -1069,21 +1790,25 @@ const run = Effect.fn("Client.run")(function* (rpc, input, render) {
1069
1790
  }
1070
1791
  const event = yield* decode$1(envelope).pipe(Effect.catchTag("UnknownEventTypeError", () => Effect.void));
1071
1792
  if (event === void 0) return;
1072
- if (Schema.is(EventList.PromptAdmitted)(event) && event.data.messageId === id) admitted = true;
1073
- if (Schema.is(EventList.Prompted)(event) && event.data.messageId === id) {
1074
- promoted = true;
1075
- unattributed = void 0;
1793
+ const seq = event.durable?.seq;
1794
+ if (Schema.is(EventList.ExecutionStarted)(event) && seq !== void 0) starts.push(seq);
1795
+ if (Schema.is(EventList.PromptAdmitted)(event) && event.data.messageId === id) {
1796
+ admitted = true;
1797
+ admittedAt = seq;
1076
1798
  }
1077
- if (!admitted) return;
1078
- const ended = terminal(event);
1079
- const succeeded = Schema.is(EventList.ExecutionSucceeded)(event);
1799
+ if (Schema.is(EventList.Prompted)(event) && event.data.messageId === id) promoted = true;
1800
+ const ended = EventList.isRunEnded(event);
1801
+ const error = ended ? failure(event) : void 0;
1080
1802
  if (!promoted) {
1081
- if (ended !== void 0) unattributed = ended;
1082
- if (ended !== void 0 || succeeded) yield* Deferred.succeed(stalled, void 0);
1803
+ if (ended && seq !== void 0) ends.push({
1804
+ at: seq,
1805
+ error
1806
+ });
1807
+ if (admitted && ends.some(({ at }) => admittedAt === void 0 || at > admittedAt)) yield* Deferred.succeed(stalled, void 0);
1083
1808
  return;
1084
1809
  }
1085
- if (ended !== void 0) return yield* ended;
1086
- if (succeeded) {
1810
+ if (error !== void 0) return yield* error;
1811
+ if (ended) {
1087
1812
  settled = true;
1088
1813
  return;
1089
1814
  }
@@ -1102,7 +1827,7 @@ const run = Effect.fn("Client.run")(function* (rpc, input, render) {
1102
1827
  })));
1103
1828
  yield* Effect.raceFirst(consume, reconcile);
1104
1829
  if (settled) return;
1105
- if (abandoned) return yield* unattributed ?? new ExecutionError({
1830
+ if (abandoned) return yield* ours() ?? new ExecutionError({
1106
1831
  type: "unknown",
1107
1832
  message: "Prompt was not promoted"
1108
1833
  });
@@ -1153,10 +1878,24 @@ const usage = (summary, columns) => {
1153
1878
  const writeOut = (value) => Effect.sync(() => void process.stdout.write(value));
1154
1879
  /** A value in its wire form, as indented JSON. */
1155
1880
  const writeJson = (schema, value) => Schema.encodeEffect(schema)(value).pipe(Effect.orDie, Effect.flatMap((encoded) => writeOut(`${JSON.stringify(encoded, null, " ")}\n`)));
1881
+ /** Rows as plain columns, two spaces apart; the last column is not padded. */
1882
+ const table = (rows) => {
1883
+ const widths = rows[0]?.map((_, column) => Math.max(...rows.map((row) => row[column]?.length ?? 0))) ?? [];
1884
+ return rows.map((row) => {
1885
+ const last = row.length - 1;
1886
+ return `${row.map((cell, column) => column === last ? cell : cell.padEnd(widths[column] ?? 0)).join(" ")}\n`;
1887
+ }).join("");
1888
+ };
1156
1889
  const writeError = (value) => Effect.sync(() => void process.stderr.write(value));
1157
1890
  const terminalColumns = () => process.stderr.isTTY ? process.stderr.columns ?? 72 : 72;
1158
1891
  //#endregion
1159
1892
  //#region src/cli/error.ts
1893
+ var error_exports = /* @__PURE__ */ __exportAll({
1894
+ InvalidInputError: () => InvalidInputError,
1895
+ OAuthError: () => OAuthError,
1896
+ renderError: () => renderError,
1897
+ reportFailure: () => reportFailure
1898
+ });
1160
1899
  /** Bad flag or argument combinations the parser cannot express on its own. */
1161
1900
  var InvalidInputError = class extends Schema.TaggedError()("CLI.InvalidInputError", { message: Schema.String }) {};
1162
1901
  var OAuthError = class extends Schema.TaggedError()("CLI.OAuthError", {
@@ -1169,6 +1908,7 @@ const isProviderError = Schema.is(Runner.ProviderError);
1169
1908
  const isModelCatalogError = Schema.is(Runner.ModelCatalogError);
1170
1909
  const isModelCatalogRefreshError = Schema.is(ModelCatalog.RefreshError);
1171
1910
  const isModelNotFoundError = Schema.is(Runner.ModelNotFoundError);
1911
+ const isNoModelError = Schema.is(Runner.NoModelError);
1172
1912
  const isLLMStreamError = Schema.is(Runner.LLMStreamError);
1173
1913
  const isSandboxProviderError = Schema.is(SandboxProvider.SandboxProviderError);
1174
1914
  const isPluginInstallError = Schema.is(Plugin.InstallError);
@@ -1180,6 +1920,7 @@ const isSettingsError = Schema.is(Settings.SettingsError);
1180
1920
  const isSandboxDriverNotRegisteredError = Schema.is(SandboxError.SandboxDriverNotRegisteredError);
1181
1921
  const isSandboxDriverRegistrationError = Schema.is(SandboxError.SandboxDriverRegistrationError);
1182
1922
  const isExecutionError = Schema.is(ExecutionError);
1923
+ const isDatabaseOutdatedError = Schema.is(Database.OutdatedError);
1183
1924
  const credentialHint = (provider) => {
1184
1925
  switch (provider) {
1185
1926
  case "openrouter": return "set OPENROUTER_API_KEY and retry";
@@ -1259,6 +2000,7 @@ const pluginReasonHint = (reason) => {
1259
2000
  const settingsHint = (reason) => {
1260
2001
  switch (reason) {
1261
2002
  case "read": return "the file exists but could not be read; check that it is a file and readable";
2003
+ case "write": return "the file could not be written; check that its directory is writable";
1262
2004
  case "parse": return "the file is not valid JSON; the location above is where parsing stopped";
1263
2005
  case "decode": return "the key above holds a value this setting does not accept";
1264
2006
  }
@@ -1268,6 +2010,7 @@ const renderError = (error) => {
1268
2010
  if (isSandboxDriverNotRegisteredError(error)) return `error: sandbox driver "${error.driver}" is not registered (available: ${error.registered?.join(", ") ?? "none"})\n`;
1269
2011
  if (isSandboxDriverRegistrationError(error)) return `error: ${error.reason}\n`;
1270
2012
  if (isInvalidInputError(error)) return `error: ${error.message}\n`;
2013
+ if (isDatabaseOutdatedError(error)) return `error[database-outdated]: ${error.message}\n`;
1271
2014
  if (isOAuthError(error)) return [`error[oauth-credential-error]: ${error.message}`, ...error.cause === void 0 ? [] : [`detail: ${unknownMessage(error.cause)}`]].join("\n") + "\n";
1272
2015
  if (isSandboxProviderError(error)) return [
1273
2016
  `error: SandboxProviderError - ${error.sanitized.message}`,
@@ -1306,6 +2049,7 @@ const renderError = (error) => {
1306
2049
  if (isModelCatalogError(error)) return [`error[model-catalog-${error.reason}]: ${error.message}`, "hint: run `codework models refresh`"].join("\n") + "\n";
1307
2050
  if (isModelCatalogRefreshError(error)) return [`error[catalog-refresh-failed]: ${error.message}`, "hint: check the network connection and retry"].join("\n") + "\n";
1308
2051
  if (isModelNotFoundError(error)) return [`error[model-not-found-error]: ${error.message}`, "hint: check the provider/model IDs in models.gen.json or regenerate the catalog"].join("\n") + "\n";
2052
+ if (isNoModelError(error)) return [`error[no-model-error]: ${error.message}`, "hint: set a provider API key, run `codework auth login`, or set model.provider and model.id in settings"].join("\n") + "\n";
1309
2053
  if (isLLMStreamError(error)) return `error[llm-stream-error]: ${error.message}\n`;
1310
2054
  if (isExecutionError(error)) return [error.type === "aborted" ? `error: ${error.message}` : `error[${error.type}]: ${error.message}`, ...error.status === void 0 ? [] : [`status: ${error.status}`]].join("\n") + "\n";
1311
2055
  return `error: ${unknownMessage(error)}\n`;
@@ -1314,6 +2058,6 @@ const reportFailure = (error) => writeError(renderError(error)).pipe(Effect.andT
1314
2058
  process.exitCode = 1;
1315
2059
  })));
1316
2060
  //#endregion
1317
- export { Core as C, Connected as S, ofThread as T, HostError as _, addUsage as a, path as b, terminalColumns as c, writeJson as d, writeOut as f, Api as g, run as h, reportFailure as i, usage as l, make as m, OAuthError as n, emptyUsage as o, layer as p, renderError as r, header as s, InvalidInputError as t, writeError as u, OAuthError$1 as v, encode as w, decode as x, ThreadInfo as y };
2061
+ export { sign as $, decode as A, ticketsPath as B, Current as C, Unauthorized as D, Token as E, Exchange as F, WorkspaceId as G, Api$1 as H, Proof as I, fingerprint as J, PrivateKey as K, Signed as L, Core as M, encode as N, layerToken as O, ofThread as P, publicOf as Q, devicesPath as R, path as S, Forbidden as T, IdSource as U, ConnectError as V, MachineId as W, peek as X, generate as Y, peekClaims as Z, run as _, reportFailure as a, make$1 as at, OAuthError$1 as b, header as c, usage as d, thumbprint as et, writeError as f, make as g, layer as h, renderError as i, layer$1 as it, Connected as j, local as k, table as l, writeOut as m, OAuthError as n, encrypted as nt, addUsage as o, matches as ot, writeJson as p, PublicKey as q, error_exports as r, peer as rt, emptyUsage as s, protocols as st, InvalidInputError as t, verify as tt, terminalColumns as u, Api as v, Door as w, ThreadInfo as x, HostError as y, proofWindow as z };
1318
2062
 
1319
- //# sourceMappingURL=error-CPyvkO4x.mjs.map
2063
+ //# sourceMappingURL=error-ippxl2z7.mjs.map