@codeworksh/cli 0.9.0-canary.157.1.g0c59cb43 → 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 (126) hide show
  1. package/{acp-8-tGD7v8.mjs → acp-D1X6PAQd.mjs} +4 -4
  2. package/{acp-8-tGD7v8.mjs.map → acp-D1X6PAQd.mjs.map} +1 -1
  3. package/{add-DHMnQW99.mjs → add-BO0TXkKX.mjs} +8 -7
  4. package/add-BO0TXkKX.mjs.map +1 -0
  5. package/{add-zUESl6ET.mjs → add-BwC5Yb3Z.mjs} +5 -5
  6. package/{add-zUESl6ET.mjs.map → add-BwC5Yb3Z.mjs.map} +1 -1
  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-DaAohHQB.mjs → check-n2oLWYrZ.mjs} +4 -4
  10. package/{check-DaAohHQB.mjs.map → check-n2oLWYrZ.mjs.map} +1 -1
  11. package/connect-CO-oR-Br.mjs +35 -0
  12. package/connect-CO-oR-Br.mjs.map +1 -0
  13. package/{control-Bumzv5lJ.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-utTS2IQu.mjs → discovery-D07MPnKd.mjs} +13 -37
  21. package/discovery-D07MPnKd.mjs.map +1 -0
  22. package/{entries-DEIZstjm.mjs → entries-BzfySpSJ.mjs} +3 -3
  23. package/{entries-DEIZstjm.mjs.map → entries-BzfySpSJ.mjs.map} +1 -1
  24. package/{error-CDGBK9Du.mjs → error-ippxl2z7.mjs} +552 -9
  25. package/error-ippxl2z7.mjs.map +1 -0
  26. package/{fork-D9G8UFMP.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-oH9PJv_L.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-B3Jrv5qY.mjs → install-dfD5hzCS.mjs} +4 -4
  35. package/{install-B3Jrv5qY.mjs.map → install-dfD5hzCS.mjs.map} +1 -1
  36. package/{jsonc-CwZ1q4tQ.mjs → jsonc-CWL4-4yz.mjs} +2 -2
  37. package/{jsonc-CwZ1q4tQ.mjs.map → jsonc-CWL4-4yz.mjs.map} +1 -1
  38. package/{link-XTnNYTMG.mjs → link-D1cicwAl.mjs} +8 -6
  39. package/link-D1cicwAl.mjs.map +1 -0
  40. package/{list-CkcQPdvs.mjs → list-BKJgNMJm.mjs} +10 -12
  41. package/list-BKJgNMJm.mjs.map +1 -0
  42. package/{list-BWMsbeuT.mjs → list-C3McEC0O.mjs} +4 -4
  43. package/{list-BWMsbeuT.mjs.map → list-C3McEC0O.mjs.map} +1 -1
  44. package/{list-B56MDFRg.mjs → list-CGT6jT-r.mjs} +4 -4
  45. package/{list-B56MDFRg.mjs.map → list-CGT6jT-r.mjs.map} +1 -1
  46. package/{list-2wagSRhT.mjs → list-DZK016LF.mjs} +4 -4
  47. package/{list-2wagSRhT.mjs.map → list-DZK016LF.mjs.map} +1 -1
  48. package/{login-DEDr2Vyx.mjs → login-DuFDeGH-.mjs} +4 -4
  49. package/{login-DEDr2Vyx.mjs.map → login-DuFDeGH-.mjs.map} +1 -1
  50. package/{login-k_5cpvOg.mjs → login-XhIIF5Yu.mjs} +4 -4
  51. package/{login-k_5cpvOg.mjs.map → login-XhIIF5Yu.mjs.map} +1 -1
  52. package/{logout-CuhgmxyS.mjs → logout-CA1No9_2.mjs} +4 -4
  53. package/{logout-CuhgmxyS.mjs.map → logout-CA1No9_2.mjs.map} +1 -1
  54. package/{logout-DgfjJ4Qs.mjs → logout-Dpqw8tQZ.mjs} +4 -4
  55. package/{logout-DgfjJ4Qs.mjs.map → logout-Dpqw8tQZ.mjs.map} +1 -1
  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-DFBL85KS.mjs → providers--giKGohM.mjs} +4 -4
  62. package/{providers-DFBL85KS.mjs.map → providers--giKGohM.mjs.map} +1 -1
  63. package/reconnect-I9-Do_DK.mjs +2 -0
  64. package/{refresh-BevzQTKE.mjs → refresh-BIH3qn5A.mjs} +4 -4
  65. package/{refresh-BevzQTKE.mjs.map → refresh-BIH3qn5A.mjs.map} +1 -1
  66. package/{refresh-D1ikVUxv.mjs → refresh-Dg8WvRcq.mjs} +4 -4
  67. package/{refresh-D1ikVUxv.mjs.map → refresh-Dg8WvRcq.mjs.map} +1 -1
  68. package/{identity-jiAiU7Z0.mjs → registration-C6yiv31r.mjs} +27 -36
  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-D-74aBQZ.mjs → relink-D8Koos_q.mjs} +9 -7
  73. package/relink-D8Koos_q.mjs.map +1 -0
  74. package/{reload-DQDThDsu.mjs → reload-C5-B0s9x.mjs} +6 -5
  75. package/reload-C5-B0s9x.mjs.map +1 -0
  76. package/{remove-DbGeM1mo.mjs → remove-6m5n17il.mjs} +4 -4
  77. package/{remove-DbGeM1mo.mjs.map → remove-6m5n17il.mjs.map} +1 -1
  78. package/{remove-C5Cdkluk.mjs → remove-VZO51J2m.mjs} +5 -5
  79. package/{remove-C5Cdkluk.mjs.map → remove-VZO51J2m.mjs.map} +1 -1
  80. package/{restart-B41PrPeq.mjs → restart-4NoPj76N.mjs} +5 -4
  81. package/{restart-B41PrPeq.mjs.map → restart-4NoPj76N.mjs.map} +1 -1
  82. package/revoke-Gu5N3Vzy.mjs +13 -0
  83. package/revoke-Gu5N3Vzy.mjs.map +1 -0
  84. package/{run-tgTFwaz6.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-u3l-ZR4V.mjs → serve-BZ5FAU3h.mjs} +397 -35
  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-DIqNg65Q.mjs → settings-DU140UBM.mjs} +3 -3
  93. package/{settings-DIqNg65Q.mjs.map → settings-DU140UBM.mjs.map} +1 -1
  94. package/{shared-DasNo1nI.mjs → shared-CC4WukJX.mjs} +4 -4
  95. package/{shared-DasNo1nI.mjs.map → shared-CC4WukJX.mjs.map} +1 -1
  96. package/{shared-D9lJX6cL.mjs → shared-Dzwbs5Lk.mjs} +7 -9
  97. package/shared-Dzwbs5Lk.mjs.map +1 -0
  98. package/{start-DaHslind.mjs → start-COhahq2E.mjs} +5 -4
  99. package/{start-DaHslind.mjs.map → start-COhahq2E.mjs.map} +1 -1
  100. package/{status-CvPbXQCn.mjs → status-Cau7bzuQ.mjs} +5 -4
  101. package/{status-CvPbXQCn.mjs.map → status-Cau7bzuQ.mjs.map} +1 -1
  102. package/{status-B1V5lctj.mjs → status-DJJOuCzL.mjs} +4 -4
  103. package/{status-B1V5lctj.mjs.map → status-DJJOuCzL.mjs.map} +1 -1
  104. package/{stop-BSy13mZw.mjs → stop-CC--mxXp.mjs} +5 -4
  105. package/{stop-BSy13mZw.mjs.map → stop-CC--mxXp.mjs.map} +1 -1
  106. package/{update-DKaDSMmZ.mjs → update-DMQLgDm3.mjs} +4 -4
  107. package/{update-DKaDSMmZ.mjs.map → update-DMQLgDm3.mjs.map} +1 -1
  108. package/add-DHMnQW99.mjs.map +0 -1
  109. package/control-Bumzv5lJ.mjs.map +0 -1
  110. package/disconnect-DyZh1VIG.mjs +0 -2
  111. package/error-CDGBK9Du.mjs.map +0 -1
  112. package/fork-D9G8UFMP.mjs.map +0 -1
  113. package/identity-jiAiU7Z0.mjs.map +0 -1
  114. package/link-XTnNYTMG.mjs.map +0 -1
  115. package/list-CkcQPdvs.mjs.map +0 -1
  116. package/package-CKwlCT6j.mjs +0 -6
  117. package/package-CKwlCT6j.mjs.map +0 -1
  118. package/reconnect-CfSVaPkd.mjs +0 -2
  119. package/relink-D-74aBQZ.mjs.map +0 -1
  120. package/reload-DQDThDsu.mjs.map +0 -1
  121. package/run-tgTFwaz6.mjs.map +0 -1
  122. package/runtime-CK2CunDw.mjs.map +0 -1
  123. package/serve-u3l-ZR4V.mjs.map +0 -1
  124. package/service-utTS2IQu.mjs.map +0 -1
  125. package/shared-D9lJX6cL.mjs.map +0 -1
  126. package/thread-oH9PJv_L.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, DaemonHost, Database, Event, EventList, EventSchema, Location, McpError, ModelCatalog, Plugin, Project, PromptSchema, Runner, Sandbox, SandboxError, Session, SessionStore, Settings, SettingsFile, ThreadSchema, ThreadStore, UsageSchema, 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,
@@ -618,7 +1084,9 @@ const Api = RpcGroup.make(
618
1084
  /** The store's head: the last revision taken. */
619
1085
  rev: Schema.Int,
620
1086
  /** The machine it runs on, by the name its user knows it; absent when the OS names it nothing. */
621
- host: optional(Schema.Struct({ name: Schema.String }))
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)
622
1090
  })
623
1091
  }),
624
1092
  /**
@@ -1049,6 +1517,67 @@ const Api = RpcGroup.make(
1049
1517
  success: McpStatus,
1050
1518
  error: McpErrors
1051
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
+ }),
1052
1581
  /** The OS home directory, and the folder `host.create` makes projects in. */
1053
1582
  Rpc.make("host.info", {
1054
1583
  payload: {},
@@ -1199,11 +1728,11 @@ const Api = RpcGroup.make(
1199
1728
  error: Schema.Union([Event.SubscriptionOverflowError, EncodingError]),
1200
1729
  stream: true
1201
1730
  })
1202
- );
1731
+ ).middleware(Door);
1203
1732
  //#endregion
1204
1733
  //#region src/server/client.ts
1205
1734
  const make = RpcClient.make(Api);
1206
- 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));
1207
1736
  /** A server-side failure as the client sees it: the category, not the cause. */
1208
1737
  var ExecutionError = class extends Schema.TaggedError()("Client.ExecutionError", {
1209
1738
  type: Schema.String,
@@ -1349,10 +1878,24 @@ const usage = (summary, columns) => {
1349
1878
  const writeOut = (value) => Effect.sync(() => void process.stdout.write(value));
1350
1879
  /** A value in its wire form, as indented JSON. */
1351
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
+ };
1352
1889
  const writeError = (value) => Effect.sync(() => void process.stderr.write(value));
1353
1890
  const terminalColumns = () => process.stderr.isTTY ? process.stderr.columns ?? 72 : 72;
1354
1891
  //#endregion
1355
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
+ });
1356
1899
  /** Bad flag or argument combinations the parser cannot express on its own. */
1357
1900
  var InvalidInputError = class extends Schema.TaggedError()("CLI.InvalidInputError", { message: Schema.String }) {};
1358
1901
  var OAuthError = class extends Schema.TaggedError()("CLI.OAuthError", {
@@ -1515,6 +2058,6 @@ const reportFailure = (error) => writeError(renderError(error)).pipe(Effect.andT
1515
2058
  process.exitCode = 1;
1516
2059
  })));
1517
2060
  //#endregion
1518
- 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 };
1519
2062
 
1520
- //# sourceMappingURL=error-CDGBK9Du.mjs.map
2063
+ //# sourceMappingURL=error-ippxl2z7.mjs.map