hinacode 0.3.0-alpha.16 → 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-ETCSyq0-.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,22 +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("limited"), thread: Thread })
5154
- ]);
5155
- const pendingAsks = (threadId, pending) => [
5156
- ...pending.approvals.map((request) => ({ kind: "approval", threadId, request })),
5157
- ...pending.questions.map((request) => ({ kind: "question", threadId, request })),
5158
- ...pending.secretRequests.map((request) => ({ kind: "secret", threadId, request }))
5159
- ];
5160
- const asksFrom = (threads, transcripts) => threads.flatMap((thread) => {
5161
- if (thread.status === "limited") return [{ kind: "limited", thread }];
5162
- const pending = transcripts.get(thread.id);
5163
- return thread.status === "awaiting_approval" && pending !== void 0 ? pendingAsks(thread.id, pending) : [];
5164
- });
5165
5149
  const EXIT = {
5166
5150
  done: 0,
5167
5151
  failed: 1,
@@ -5196,22 +5180,25 @@ class RpcError extends TaggedError$1("RpcError") {
5196
5180
  class NoSocket extends TaggedError$1("NoSocket") {
5197
5181
  }
5198
5182
  const decodeServerFrame = decodeUnknownExit(fromJsonString(ServerFrame));
5183
+ const decodeFirstFrame = decodeUnknownExit(fromJsonString(Union([ServerFrame, LegacyChallenge])));
5199
5184
  const forwardTo = (queue) => (event) => event === null ? endUnsafe(queue) : offerUnsafe(queue, event);
5200
5185
  const disconnected = () => unreachableError("lost the connection to HinaCode");
5201
- const open$1 = (socketPath) => callback((resume) => {
5202
- const socket = new WebSocket(`ws+unix://${socketPath}:${REMOTE_PATH}`, { maxPayload: REMOTE_MAX_FRAME_BYTES });
5203
- socket.once("error", () => resume(fail(new NoSocket({ socketPath }))));
5204
- socket.once("close", () => resume(fail(new NoSocket({ socketPath }))));
5205
- socket.once("message", (raw) => {
5206
- const decoded = decodeServerFrame(String(raw));
5207
- resume(
5208
- decoded._tag === "Success" ? succeed$2({ socket, first: decoded.value }) : fail(
5209
- new CliFailure({ code: EXIT.unreachable, message: `${socketPath} sent a frame the CLI can't read` })
5210
- )
5211
- );
5212
- });
5213
- return sync$1(() => socket.terminate());
5214
- });
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
+ );
5215
5202
  const handshake = (socketPath) => gen(function* () {
5216
5203
  const { socket, first } = yield* open$1(socketPath).pipe(
5217
5204
  timeoutOrElse({ duration: READY_TIMEOUT, orElse: () => fail(new NoSocket({ socketPath })) })
@@ -5402,6 +5389,87 @@ const writeLine = (value2) => sync$1(() => void process.stdout.write(`${JSON.str
5402
5389
  `));
5403
5390
  const emit = (output) => flatMap$1(output, ({ value: value2, code }) => andThen(writeLine(value2), exitWith(code)));
5404
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
+ });
5405
5473
  const InboxSnapshot = Struct({ asks: ArraySchema(Ask), running: Number$2, idle: Number$2 });
5406
5474
  const countStatus = (threads, status) => threads.filter((thread) => thread.sideOf === null && thread.status === status).length;
5407
5475
  const loadInbox = (client) => gen(function* () {
@@ -5433,7 +5501,7 @@ const inbox = make(
5433
5501
  )
5434
5502
  ).pipe(
5435
5503
  withDescription(
5436
- "Print what waits on a human: open approvals, questions and secret requests, limited threads, and how many threads run or idle."
5504
+ "Print what waits on a human: open approvals, questions and secret requests, threads a restart interrupted, limited threads, and how many threads run or idle."
5437
5505
  )
5438
5506
  );
5439
5507
  const ListedRoutine = Struct({ ...Routine.fields, machine: NullOr(String$6) });
@@ -5785,6 +5853,16 @@ const stop = make(
5785
5853
  )
5786
5854
  )
5787
5855
  ).pipe(withDescription("Interrupt a thread's turn."));
5856
+ const continueThread = make(
5857
+ "continue",
5858
+ { thread: threadArgument },
5859
+ (args) => emit(
5860
+ withThread(
5861
+ args.thread,
5862
+ (client, thread) => as(client.call("threads.continue", { threadId: thread.id }), succeed({ threadId: thread.id }))
5863
+ )
5864
+ )
5865
+ ).pipe(withDescription("Continue a turn a restart interrupted."));
5788
5866
  const open = make(
5789
5867
  "open",
5790
5868
  { thread: threadArgument },
@@ -5844,7 +5922,7 @@ const log = make(
5844
5922
  )
5845
5923
  )
5846
5924
  ).pipe(withDescription("Print a thread's transcript."));
5847
- const threadCommands = [ls, send, stop, log, open, machines, rpc];
5925
+ const threadCommands = [ls, send, stop, continueThread, log, open, machines, rpc];
5848
5926
  const cloudData = gen(function* () {
5849
5927
  const flag2 = getOrUndefined(yield* DataDir);
5850
5928
  return flag2 ?? (process.env["HINACODE_USER_DATA"] || join(homedir(), ".hinacode-cloud"));
@@ -5871,9 +5949,11 @@ const serve = make(
5871
5949
  ),
5872
5950
  optional
5873
5951
  ),
5874
- rotateToken: Boolean("rotate-token").pipe(
5952
+ resetPairing: Boolean("reset-pairing").pipe(
5875
5953
  withDefault(false),
5876
- 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
+ )
5877
5957
  ),
5878
5958
  relay: Boolean("relay").pipe(
5879
5959
  withDescription$1(
@@ -5891,7 +5971,7 @@ const serve = make(
5891
5971
  port: getOrUndefined(flags.port),
5892
5972
  host: getOrUndefined(flags.host),
5893
5973
  relay: getOrUndefined(map$4(flags.relay, (on) => on ? "on" : "off")),
5894
- rotateToken: flags.rotateToken
5974
+ resetPairing: flags.resetPairing
5895
5975
  },
5896
5976
  userData
5897
5977
  )
@@ -6094,7 +6174,7 @@ const hinacode = make("hinacode").pipe(
6094
6174
  withDescription(
6095
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."
6096
6176
  ),
6097
- withSubcommands([run, ...threadCommands, inbox, watch, routines, ...cloudCommands, service]),
6177
+ withSubcommands([run, ...threadCommands, inbox, watch, routines, ...cloudCommands, devices, service]),
6098
6178
  withGlobalFlags([DataDir])
6099
6179
  );
6100
6180
  const exitCode = (exit) => {