hinacode 0.3.0-alpha.17 → 0.3.0-alpha.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/out/server/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __createRequire } from "node:module";
2
2
  globalThis.require ??= __createRequire(import.meta.url);
3
- import { d as dual, r as runFork, t as tapCause, h as hasInterruptsOnly, v as void_, s as squash, l as logError, c as constVoid, i as isEffect, a as isSuccess, w as withFiber, C as ConsoleRef, b as sync, T as TaggedError, A as ArraySchema, S as String$6, U as Union, e as hasProperty, o as optional$3, L as Literal, f as optionalKey, D as Defect, g as format, j as toCodecStringTree, k as decodeUnknownEffect, m as identity, n as succeed$2, p as fail, q as is, u as TrueLiterals, F as FalseLiterals, x as mapError, B as BooleanLiterals, I as Int$4, R as Reference, y as fnUntraced, z as scoped, Q as QuitError, E as Terminal, G as cached, H as suspend, P as Prototype, J as getOrElse, K as some, M as match, N as none, O as make$2, V as map$2, W as taggedEnum, X as match$1, Y as map$3, Z as isSome, _ as flatMap$1, $ as sync$1, a0 as empty, a1 as reduce, a2 as pipe, a3 as match$2, a4 as findFirstIndex, a5 as findFirst, a6 as findLast, a7 as isReadonlyArrayNonEmpty, a8 as ensuring, a9 as orDie, aa as take, ab as raceFirst, ac as round, ad as pipeArguments, ae as catchTags, af as fromUndefinedOr, ag as isNotUndefined, ah as getOrUndefined, ai as assignProperty, aj as Service, ak as empty$1, al as exists, am as gen, an as isNone, ao as succeed$3, ap as value, aq as provideService, ar as Stdio, as as catchFilter, at as isQuitError, au as succeed$4, av as fail$1, aw as interrupt, ax as andThen, ay as catchTag, az as result, aA as make$3, aB as provideContext, aC as MinimumLogLevel, aD as Struct, aE as ApprovalRequest, aF as QuestionRequest, aG as SecretRequest, aH as Thread, aI as TaggedError$1, aJ as seconds, aK as decodeUnknownExit, aL as fromJsonString, aM as ServerFrame, aN as acquireRelease, aO as unbounded, aP as endUnsafe, aQ as encodeUnknownEffect, aR as RpcMethods, aS as timeoutOrElse, aT as callback, aU as methodKind, aV as offerUnsafe, aW as WebSocket, aX as REMOTE_PATH, aY as REMOTE_MAX_FRAME_BYTES, aZ as succeedNone, a_ as cliSocketPath, a$ as all, b0 as fromResult, b1 as Number$2, b2 as forEach, b3 as NullOr, b4 as Routine, b5 as AccessMode, b6 as ProviderId, b7 as promise, b8 as isFailure, b9 as toCheckoutTarget, ba as noticeEvents, bb as PushEvent, bc as ThreadStatus, bd as try_, be as as, bf as isThreadBusy, bg as tryPromise, bh as map$4, bi as isAlive, bj as packageJson, bk as tapError, bl as provide, bm as layer$1 } from "./chunks/dataDir-D7GgMeKc.js";
3
+ import { d as dual, r as runFork, t as tapCause, h as hasInterruptsOnly, v as void_, s as squash, l as logError, c as constVoid, i as isEffect, a as isSuccess, w as withFiber, C as ConsoleRef, b as sync, T as TaggedError, A as ArraySchema, S as String$6, U as Union, e as hasProperty, o as optional$3, L as Literal, f as optionalKey, D as Defect, g as format, j as toCodecStringTree, k as decodeUnknownEffect, m as identity, n as succeed$2, p as fail, q as is, u as TrueLiterals, F as FalseLiterals, x as mapError, B as BooleanLiterals, I as Int$4, R as Reference, y as fnUntraced, z as scoped, Q as QuitError, E as Terminal, G as cached, H as suspend, P as Prototype, J as getOrElse, K as some, M as match, N as none, O as make$2, V as map$2, W as taggedEnum, X as match$1, Y as map$3, Z as isSome, _ as flatMap$1, $ as sync$1, a0 as empty, a1 as reduce, a2 as pipe, a3 as match$2, a4 as findFirstIndex, a5 as findFirst, a6 as findLast, a7 as isReadonlyArrayNonEmpty, a8 as ensuring, a9 as orDie, aa as take, ab as raceFirst, ac as round, ad as pipeArguments, ae as catchTags, af as fromUndefinedOr, ag as isNotUndefined, ah as getOrUndefined, ai as assignProperty, aj as Service, ak as empty$1, al as exists, am as gen, an as isNone, ao as succeed$3, ap as value, aq as provideService, ar as Stdio, as as catchFilter, at as isQuitError, au as succeed$4, av as fail$1, aw as interrupt, ax as andThen, ay as catchTag, az as result, aA as make$3, aB as provideContext, aC as MinimumLogLevel, aD as TaggedError$1, aE as seconds, aF as decodeUnknownExit, aG as fromJsonString, aH as ServerFrame, aI as LegacyChallenge, aJ as acquireRelease, aK as unbounded, aL as endUnsafe, aM as encodeUnknownEffect, aN as RpcMethods, aO as timeoutOrElse, aP as callback, aQ as methodKind, aR as offerUnsafe, aS as WebSocket, aT as REMOTE_PATH, aU as REMOTE_MAX_FRAME_BYTES, aV as succeedNone, aW as cliSocketPath, aX as all, aY as fromResult, aZ as Struct, a_ as ApprovalRequest, a$ as QuestionRequest, b0 as SecretRequest, b1 as Thread, b2 as Number$2, b3 as forEach, b4 as NullOr, b5 as Routine, b6 as AccessMode, b7 as ProviderId, b8 as promise, b9 as isFailure, ba as toCheckoutTarget, bb as noticeEvents, bc as PushEvent, bd as ThreadStatus, be as try_, bf as as, bg as isThreadBusy, bh as tryPromise, bi as map$4, bj as isAlive, bk as packageJson, bl as tapError, bm as provide, bn as layer$1 } from "./chunks/dataDir-kSsTIMx3.js";
4
4
  import { homedir, userInfo } from "node:os";
5
5
  import { resolve, sep, join, dirname } from "node:path";
6
6
  import { randomUUID } from "node:crypto";
@@ -5146,24 +5146,6 @@ const runWith = (command, config) => {
5146
5146
  yield* provideContext(program, services);
5147
5147
  }, catchFilter((error2) => isCliError(error2) && error2._tag === "ShowHelp" ? succeed$4(error2) : fail$1(error2), (error2) => andThen(showHelp(command, error2, config.renderErrors !== false), fail(error2))), catchFilter((error2) => config.renderErrors !== false && isCliError(error2) && error2._tag === "UserError" ? succeed$4(error2) : fail$1(error2), (error2) => andThen(showUserError(error2), fail(error2))), catchFilter((e) => isQuitError(e) ? succeed$4(e) : fail$1(e), (_) => interrupt));
5148
5148
  };
5149
- const Ask = Union([
5150
- Struct({ kind: Literal("approval"), threadId: String$6, request: ApprovalRequest }),
5151
- Struct({ kind: Literal("question"), threadId: String$6, request: QuestionRequest }),
5152
- Struct({ kind: Literal("secret"), threadId: String$6, request: SecretRequest }),
5153
- Struct({ kind: Literal("interrupted"), thread: Thread }),
5154
- Struct({ kind: Literal("limited"), thread: Thread })
5155
- ]);
5156
- const pendingAsks = (threadId, pending) => [
5157
- ...pending.approvals.map((request) => ({ kind: "approval", threadId, request })),
5158
- ...pending.questions.map((request) => ({ kind: "question", threadId, request })),
5159
- ...pending.secretRequests.map((request) => ({ kind: "secret", threadId, request }))
5160
- ];
5161
- const asksFrom = (threads, transcripts) => threads.flatMap((thread) => {
5162
- if (thread.status === "interrupted") return [{ kind: "interrupted", thread }];
5163
- if (thread.status === "limited") return [{ kind: "limited", thread }];
5164
- const pending = transcripts.get(thread.id);
5165
- return thread.status === "awaiting_approval" && pending !== void 0 ? pendingAsks(thread.id, pending) : [];
5166
- });
5167
5149
  const EXIT = {
5168
5150
  done: 0,
5169
5151
  failed: 1,
@@ -5198,22 +5180,25 @@ class RpcError extends TaggedError$1("RpcError") {
5198
5180
  class NoSocket extends TaggedError$1("NoSocket") {
5199
5181
  }
5200
5182
  const decodeServerFrame = decodeUnknownExit(fromJsonString(ServerFrame));
5183
+ const decodeFirstFrame = decodeUnknownExit(fromJsonString(Union([ServerFrame, LegacyChallenge])));
5201
5184
  const forwardTo = (queue) => (event) => event === null ? endUnsafe(queue) : offerUnsafe(queue, event);
5202
5185
  const disconnected = () => unreachableError("lost the connection to HinaCode");
5203
- const open$1 = (socketPath) => callback((resume) => {
5204
- const socket = new WebSocket(`ws+unix://${socketPath}:${REMOTE_PATH}`, { maxPayload: REMOTE_MAX_FRAME_BYTES });
5205
- socket.once("error", () => resume(fail(new NoSocket({ socketPath }))));
5206
- socket.once("close", () => resume(fail(new NoSocket({ socketPath }))));
5207
- socket.once("message", (raw) => {
5208
- const decoded = decodeServerFrame(String(raw));
5209
- resume(
5210
- decoded._tag === "Success" ? succeed$2({ socket, first: decoded.value }) : fail(
5211
- new CliFailure({ code: EXIT.unreachable, message: `${socketPath} sent a frame the CLI can't read` })
5212
- )
5213
- );
5214
- });
5215
- return sync$1(() => socket.terminate());
5216
- });
5186
+ const open$1 = (socketPath) => callback(
5187
+ (resume) => {
5188
+ const socket = new WebSocket(`ws+unix://${socketPath}:${REMOTE_PATH}`, { maxPayload: REMOTE_MAX_FRAME_BYTES });
5189
+ socket.once("error", () => resume(fail(new NoSocket({ socketPath }))));
5190
+ socket.once("close", () => resume(fail(new NoSocket({ socketPath }))));
5191
+ socket.once("message", (raw) => {
5192
+ const decoded = decodeFirstFrame(String(raw));
5193
+ resume(
5194
+ decoded._tag === "Success" ? succeed$2({ socket, first: decoded.value }) : fail(
5195
+ new CliFailure({ code: EXIT.unreachable, message: `${socketPath} sent a frame the CLI can't read` })
5196
+ )
5197
+ );
5198
+ });
5199
+ return sync$1(() => socket.terminate());
5200
+ }
5201
+ );
5217
5202
  const handshake = (socketPath) => gen(function* () {
5218
5203
  const { socket, first } = yield* open$1(socketPath).pipe(
5219
5204
  timeoutOrElse({ duration: READY_TIMEOUT, orElse: () => fail(new NoSocket({ socketPath })) })
@@ -5404,6 +5389,87 @@ const writeLine = (value2) => sync$1(() => void process.stdout.write(`${JSON.str
5404
5389
  `));
5405
5390
  const emit = (output) => flatMap$1(output, ({ value: value2, code }) => andThen(writeLine(value2), exitWith(code)));
5406
5391
  const succeed = (value2) => ({ value: value2, code: EXIT.done });
5392
+ const MIN_KEY_PREFIX = 4;
5393
+ const resolveDevice = (raw, devices2) => {
5394
+ const named = devices2.filter((device) => device.name.toLowerCase() === raw.toLowerCase());
5395
+ const matches = named.length > 0 || raw.length < MIN_KEY_PREFIX ? named : devices2.filter((device) => device.key.startsWith(raw));
5396
+ if (matches.length === 1) return succeed$4(matches[0]);
5397
+ if (matches.length === 0)
5398
+ return fail$1(usageError(`no device is named ${raw} or has a key starting with it. Run hinacode devices.`));
5399
+ return fail$1(
5400
+ usageError(
5401
+ [
5402
+ `${raw} matches more than one device. Pass more of its key:`,
5403
+ ...matches.map((device) => ` ${device.key.slice(0, 12)} ${device.name}`)
5404
+ ].join("\n")
5405
+ )
5406
+ );
5407
+ };
5408
+ const approve = make(
5409
+ "approve",
5410
+ { code: String$2("code").pipe(withDescription$2("The code the waiting device shows, like K7Q-F2M.")) },
5411
+ ({ code }) => emit(
5412
+ withClient(
5413
+ (client) => gen(function* () {
5414
+ const device = yield* client.call("remote.devices.approve", { code });
5415
+ return succeed(yield* encode(RpcMethods["remote.devices.approve"].response, device));
5416
+ })
5417
+ )
5418
+ )
5419
+ ).pipe(withDescription("Trust the waiting device that shows this code."));
5420
+ const remove = make(
5421
+ "remove",
5422
+ {
5423
+ device: String$2("device").pipe(
5424
+ withDescription$2(`A device's name, or ${MIN_KEY_PREFIX}+ characters of its key.`)
5425
+ )
5426
+ },
5427
+ (args) => emit(
5428
+ withClient(
5429
+ (client) => gen(function* () {
5430
+ const { devices: devices2 } = yield* client.call("remote.devices", void 0);
5431
+ const device = yield* fromResult(resolveDevice(args.device, devices2));
5432
+ yield* client.call("remote.devices.remove", { key: device.key });
5433
+ return succeed({ key: device.key, name: device.name });
5434
+ })
5435
+ )
5436
+ )
5437
+ ).pipe(withDescription("Stop trusting a device and end its sessions. It must pair again."));
5438
+ const devices = make(
5439
+ "devices",
5440
+ {},
5441
+ () => emit(
5442
+ withClient(
5443
+ (client) => gen(function* () {
5444
+ const listed = yield* client.call("remote.devices", void 0);
5445
+ return succeed(yield* encode(RpcMethods["remote.devices"].response, listed));
5446
+ })
5447
+ )
5448
+ )
5449
+ ).pipe(
5450
+ withDescription(
5451
+ "List the devices this machine trusts and how many wait for approval. Approve one with the code it shows, or remove one."
5452
+ ),
5453
+ withSubcommands([approve, remove])
5454
+ );
5455
+ const Ask = Union([
5456
+ Struct({ kind: Literal("approval"), threadId: String$6, request: ApprovalRequest }),
5457
+ Struct({ kind: Literal("question"), threadId: String$6, request: QuestionRequest }),
5458
+ Struct({ kind: Literal("secret"), threadId: String$6, request: SecretRequest }),
5459
+ Struct({ kind: Literal("interrupted"), thread: Thread }),
5460
+ Struct({ kind: Literal("limited"), thread: Thread })
5461
+ ]);
5462
+ const pendingAsks = (threadId, pending) => [
5463
+ ...pending.approvals.map((request) => ({ kind: "approval", threadId, request })),
5464
+ ...pending.questions.map((request) => ({ kind: "question", threadId, request })),
5465
+ ...pending.secretRequests.map((request) => ({ kind: "secret", threadId, request }))
5466
+ ];
5467
+ const asksFrom = (threads, transcripts) => threads.flatMap((thread) => {
5468
+ if (thread.status === "interrupted") return [{ kind: "interrupted", thread }];
5469
+ if (thread.status === "limited") return [{ kind: "limited", thread }];
5470
+ const pending = transcripts.get(thread.id);
5471
+ return thread.status === "awaiting_approval" && pending !== void 0 ? pendingAsks(thread.id, pending) : [];
5472
+ });
5407
5473
  const InboxSnapshot = Struct({ asks: ArraySchema(Ask), running: Number$2, idle: Number$2 });
5408
5474
  const countStatus = (threads, status) => threads.filter((thread) => thread.sideOf === null && thread.status === status).length;
5409
5475
  const loadInbox = (client) => gen(function* () {
@@ -5883,9 +5949,11 @@ const serve = make(
5883
5949
  ),
5884
5950
  optional
5885
5951
  ),
5886
- rotateToken: Boolean("rotate-token").pipe(
5952
+ resetPairing: Boolean("reset-pairing").pipe(
5887
5953
  withDefault(false),
5888
- withDescription$1("Replace the token, which unpairs every client, or HINACODE_SERVE_ROTATE_TOKEN=1.")
5954
+ withDescription$1(
5955
+ "Replace the cloud's key and pairing secret and remove every device, so each must pair again, or HINACODE_SERVE_RESET_PAIRING=1."
5956
+ )
5889
5957
  ),
5890
5958
  relay: Boolean("relay").pipe(
5891
5959
  withDescription$1(
@@ -5903,7 +5971,7 @@ const serve = make(
5903
5971
  port: getOrUndefined(flags.port),
5904
5972
  host: getOrUndefined(flags.host),
5905
5973
  relay: getOrUndefined(map$4(flags.relay, (on) => on ? "on" : "off")),
5906
- rotateToken: flags.rotateToken
5974
+ resetPairing: flags.resetPairing
5907
5975
  },
5908
5976
  userData
5909
5977
  )
@@ -6106,7 +6174,7 @@ const hinacode = make("hinacode").pipe(
6106
6174
  withDescription(
6107
6175
  "Drive the agents HinaCode runs on every machine you reach, from scripts and other programs. Every command prints one JSON document on stdout, except watch, which prints one JSON line per event."
6108
6176
  ),
6109
- withSubcommands([run, ...threadCommands, inbox, watch, routines, ...cloudCommands, service]),
6177
+ withSubcommands([run, ...threadCommands, inbox, watch, routines, ...cloudCommands, devices, service]),
6110
6178
  withGlobalFlags([DataDir])
6111
6179
  );
6112
6180
  const exitCode = (exit) => {