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.
@@ -2,12 +2,12 @@ import { createRequire as __createRequire } from "node:module";
2
2
  globalThis.require ??= __createRequire(import.meta.url);
3
3
  import { execFile, spawn } from "node:child_process";
4
4
  import * as NFS from "node:fs";
5
- import NFS__default, { createReadStream, rmSync, existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, mkdtempSync, watch, constants as constants$8, chmodSync, statSync, createWriteStream } from "node:fs";
5
+ import NFS__default, { createReadStream, rmSync, existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, mkdtempSync, closeSync, openSync, chmodSync, watch, constants as constants$8, statSync, createWriteStream } from "node:fs";
6
6
  import { homedir, tmpdir, networkInterfaces, hostname, userInfo, loadavg, cpus, totalmem } from "node:os";
7
7
  import path__default, { join as join$1, sep, resolve as resolve$1, basename, relative, dirname, isAbsolute, extname, parse as parse$4, delimiter } from "node:path";
8
8
  import { isSea } from "node:sea";
9
9
  import NodeUrl__default, { fileURLToPath } from "node:url";
10
- import { d as dual, ai as assignProperty, b8 as isFailure, au as succeed, av as fail$1, K as some, N as none, bn as hash, bo as equals, ad as pipeArguments, bp as NodeInspectSymbol, bq as toJson, g as format$2, Z as isSome, br as withFiber, bs as uninterruptibleMask, bt as get$7, bu as Scope, bv as flow$1, bw as fromInputUnsafe, bx as constant, by as zero, be as as, bz as addFinalizerExit, v as void_, b2 as forEach, bA as exit, bB as tap$1, $ as sync, aw as interrupt, p as fail$2, bC as ExceededCapacityError, bD as makeUnsafe$5, bE as makeUnsafe$6, bF as makeUnsafe$7, H as suspend, bG as runForkWith, bH as runIn, bI as hasInterrupts, bJ as doneUnsafe, bK as getUnsafe$1, bL as addFinalizer, ax as andThen, bM as _await, bN as getCurrent, bO as interrupt$1, bP as close, bQ as isZero, bR as isFinite$1, bS as Clock, bT as toMillis, _ as flatMap, bU as millis, a8 as ensuring, bV as void_$1, bW as getOrThrow, e as hasProperty, bX as BaseProto, aI as TaggedError, bY as Error$1, bZ as toSeconds, b_ as symbol$2, b$ as structure, c0 as symbol$3, c1 as redact$1, c2 as symbolRedactable, O as make$1q, R as Reference, c3 as strictEqual, c4 as map$1, c5 as try_, c6 as flatMap$1, c7 as combine, c8 as string$2, c9 as number$4, ca as optimize, cb as contextWith, w as withFiber$1, b as sync$1, cc as infinity, cd as PipeInspectableProto, ce as updateContext, cf as merge$4, cg as succeed$1, ch as exitHasInterrupts, ci as ClockRef, cj as forkUnsafe, ck as onExitUnsafe, cl as void_$2, cm as fiberInterrupt, cn as fiberJoin, co as filterMap, cp as failVoid, cq as isGreaterThanOrEqualTo$1, cr as LogLevelOrder, aN as acquireRelease, i as isEffect, cs as interruptAs, n as succeed$2, r as runFork, ct as isFailure$1, h as hasInterruptsOnly, cu as into, cv as asVoid, cw as done, cx as filterInterruptors, cy as interruptAllAs, cz as interruptAll, cA as empty$5, cB as forkUnsafe$1, cC as runPromise, cD as runPromiseWith, cE as runPromiseExit, cF as runPromiseExitWith, cG as runSync, cH as runSyncWith, cI as runSyncExit, cJ as runSyncExitWith, cK as runCallback, cL as runCallbackWith, cM as makeMemoMapUnsafe, aB as provideContext, cN as buildWithMemoMap, cO as flatten, cP as await_, cQ as scopeRemoveFinalizerUnsafe, cR as die, cS as isResult, cT as isSuccess$1, m as identity, cU as set$5, cV as make$1r, cW as effect, aj as Service$1, cX as contextWith$1, cY as getOrUndefined, am as gen, cZ as context, c_ as make$1s, V as map$2, c$ as fromQueue, d0 as unwrap, aq as provideService, d1 as onExit, d2 as failCauseUnsafe, aV as offerUnsafe, T as TaggedError$1, U as Union, S as String$1, o as optional$7, D as Defect, P as Prototype, d3 as makeSpanUnsafe, d4 as TracerTimingEnabled, d5 as endSpan, d6 as makeSpanScoped, d7 as useSpan, d8 as constUndefined, d9 as provideService$1, da as ParentSpan, z as scoped, t as tapCause, y as fnUntraced, db as serviceOption, a3 as match, dc as make$1t, dd as provide$1, de as onError, df as catchIf, dg as scope$1, dh as getOption, di as onExitPrimitive, a as isSuccess$2, dj as catchCause, dk as matchCauseEffect, dl as failCause, dm as combine$1, a9 as orDie, dn as add$1, dp as makeUnsafe$8, dq as fromReasons, dr as isFailReason, ds as makeDieReason, dt as reasonAnnotations, du as failCause$1, dv as yieldNow, dw as constTrue, dx as normalizeNonEmpty, dy as unbounded, dz as publishUnsafe, dA as fromPubSub, dB as getDefaultExportFromCjs, a$ as all$1, M as match$1, b7 as promise$1, b6 as ProviderId, dC as now, dD as formatIso, a2 as pipe$2, dE as sort, Y as map$3, dF as flatMapNullishOr, dG as catch_, bh as map$4, dH as fromNullishOr, x as mapError, dI as logDebug, dJ as annotateLogs, dK as withSpan, ay as catchTag, dL as logInfo, dM as catchDefect, dN as filterOrFail, dO as make$1u, dP as Number$1, dQ as encodeEffect, k as decodeUnknownEffect, aZ as succeedNone, a7 as isReadonlyArrayNonEmpty, dR as asSome, dS as mutable, A as ArraySchema, dT as NoSuchElementError, dU as Literals, b1 as Number$2, b3 as NullOr, aD as Struct, dV as FileSystem, dW as orElseSucceed, dX as chatFolder, dY as Boolean$1, dZ as ProjectKind, d_ as ignore$1, d$ as logWarning, aT as callback, e0 as sleep$3, e1 as forkDetach, e2 as signedOutFailure, e3 as succeed$3, e4 as decodeUnknownOption, an as isNone, aL as fromJsonString, L as Literal, e5 as Unknown, e6 as toArray, aJ as seconds, f as optionalKey, e7 as cachedWithTTL, e8 as minutes, aO as unbounded$1, e9 as toAsyncIterable, bg as tryPromise, ea as timeout, eb as addFinalizer$1, ec as callback$1, ed as offer, ee as withPermit, ef as acquireUseRelease, aP as endUnsafe, eg as shutdownUnsafe, eh as make$1v, bd as try_$1, bk as tapError, ei as forkIn, ej as fromAsyncIterable, ek as runForEach, s as squash, el as CLAUDE_EFFORT_LEVELS, em as ensuring$1, en as currentTimeMillis, eo as sum, ep as race, eq as publishedArtifactId, er as PUBLISH_DOCUMENT_TOOL, es as PUBLISH_ARTIFACT_TOOL, et as PUBLISH_WHITEBOARD_TOOL, eu as isDone, ev as empty$6, ew as succeed$4, ex as fromIterable$2, ey as flatMap$2, ez as interruptWhen, eA as concat, eB as fromEffectDrain, eC as fromEffect, eD as fromIterableEffect, eE as suspend$1, eF as unlistedModel, eG as make$1w, eH as tap$2, eI as tick, eJ as map$5, eK as drop, eL as merge$5, eM as onInterrupt, aS as timeoutOrElse, eN as format$3, eO as getOrNull, eP as Record, eQ as make$1x, aa as take, eR as join$2, ab as raceFirst, eS as end, eT as takeUnsafe, eU as forkScoped, eV as isObject$2, J as getOrElse, eW as repeat, ao as succeed$5, eX as subscribe, eY as fromSubscription, eZ as applySettingsPatch, e_ as publish, e$ as defaultSettings, f0 as Settings$2, f1 as vmProviderBeforeTheChoice, f2 as flatMapNullishOr$1, f3 as option, f4 as delay, q as is$2, f5 as isTailscaleHost, f6 as PRIVATE_NETWORKS, f7 as RelayHostList, f8 as RelayMachineList, f9 as encodeSync, fa as mergeAll, bb as PushEvent, fb as makeUnsafe$9, fc as effectDiscard, fd as changes$1, fe as Void, ff as AppConnection, fg as decodeEffect, fh as toCodecJson, fi as RecordFromUrlParams, fj as decodeTo, fk as externalSpan, fl as isOption, fm as isExit, af as fromUndefinedOr, fn as zero$1, fo as fromInput$1, fp as badArgument, fq as isSchemaError, fr as isNoSuchElementError, fs as StackTrace, ft as mapEager, fu as updateContext$1, fv as makeUnsafe$a, fw as tag$2, fx as Error$2, I as Int, fy as fromInputUnsafe$1, fz as Path, fA as run$5, fB as mebibytes, fC as Class, fD as constFalse, fE as withLogSpan, fF as log, ah as getOrUndefined$1, fG as Tracer, fH as nativeTracer, fI as hasInterrupts$1, fJ as succeed$6, fK as setStackTraceLimit, fL as fail$3, fM as getStackTraceLimit, fN as fiberEnterUninterruptibleUnsafe, fO as contA, fP as effectIsExit, fQ as closeUnsafe, fR as contE, fS as reportCauseUnsafe, fT as matchCauseEffectEager, fU as flatMapEager, fV as provideMerge, fW as fromInput$2, fX as fromReadable, fY as toArrayBuffer, G as cached$1, fZ as provide$2, f_ as layer$Y, f$ as pipeThroughDuplex, g0 as toUint8Array, bm as layer$Z, b0 as fromResult, g1 as WebSocketServer, g2 as orDie$1, g3 as runForEachArray, g4 as interruptible, g5 as die$1, g6 as Duration, g7 as DateTimeUtc, g8 as withConstructorDefault, g9 as withDecodingDefault, ga as Redacted, gb as Tuple, gc as isRedacted, gd as MutableJson, ag as isNotUndefined, ge as Never, ak as empty$7, gf as toJsonSchemaDocument, gg as effectContext, gh as annotateCurrentSpan, gi as isUndefined, az as result$1, gj as failCause$2, gk as forkChild, gl as catch_$1, gm as isSchemaError$1, gn as failCause$3, go as mapEffect, gp as onEnd, gq as isSchema, aQ as encodeUnknownEffect, gr as annotate, gs as fail$4, aA as make$1y, gt as make$1z, gu as declare, gv as isStream, gw as Class$1, gx as Exit, gy as getOrUndefinedUnsafe, bl as provide$3, gz as provideContext$1, gA as Opaque, gB as StructWithRest, gC as JsonObject$3, gD as transformOptional, gE as flatMap$3, gF as toType, gG as Any, gH as UndefinedOr, gI as Finite, gJ as passthrough, gK as Uint8ArrayFromBase64, gL as Json, gM as TemplateLiteral, gN as decode$3, gO as withDefault, gP as isBetween, W as taggedEnum, gQ as take$1, gR as isNullish, gS as isString, gT as never$1, gU as bounded, gV as withParentSpan, gW as die$2, gX as offerAll, gY as decodeSync, l as logError, gZ as NonEmptyArray, g_ as interrupt$2, g$ as interruptors, h0 as catchCauseIf, h1 as decode$4, h2 as decodeUnknownResult, h3 as fn, h4 as isTagged, h5 as isReadonlyObject, h6 as IllegalArgumentError, h7 as encode$1, h8 as omit$1, h9 as merge$6, ha as succeedContext, hb as unwrap$1, hc as CurrentMemoMap, hd as fromIterable$3, he as reverse, a0 as empty$8, hf as withFiberSucceed, hg as fiberEnterInterruptibleUnsafe, hh as compose$1, hi as collect, hj as catchDone, hk as takeAll, hl as fromArray, hm as whileLoop, hn as matchEffect, ho as defaultFormatter, hp as logFatal, hq as isDeferred, hr as hasDies, c as constVoid, hs as shutdown, ht as Scheduler$1, ae as catchTags, hu as CurrentLogLevel, hv as UnknownFromJsonString, hw as ignoreCause, hx as forever, hy as Class$2, hz as TaggedStruct, hA as toEncoded, hB as isMaxLength, hC as makeFilter, hD as isPattern, hE as timeoutOption, hF as runLast, hG as fromOption, hH as decodeUnknownSync, hI as spawnsSubagent, hJ as isPublishArtifactTool, hK as outputText, hL as publishedArtifact, hM as toolArgument, hN as isPublishDocumentTool, hO as commonjsGlobal, hP as isRunAgentTool, hQ as presetModels, hR as filter$1, hS as take$2, hT as runDrain, hU as min, hV as ChildProcessSpawner, hW as make$1A, hX as mkString, hY as decodeText$2, hZ as ForkPoint, h_ as TokenUsage, h$ as MessagePart, i0 as Message, i1 as parseGitHubPullRequestUrl, i2 as PullRequestReviewer, i3 as PullRequestLabel, i4 as PullRequestComment, i5 as DiffSide, i6 as subtract, i7 as PULL_REQUEST_REFRESH, i8 as parseGitHubIssueUrl, i9 as parseGitHubRepository, ia as request$2, ib as Class$3, ic as AgentProfile, id as AccountProviderId, ie as ProjectAction, ig as Project, ih as BooleanFromBit, ii as Worktree, bf as isThreadBusy, bc as ThreadStatus, ij as ScheduledMessage, ik as QueuedMessage, il as UsageLimit, aH as Thread, im as getOrThrow$1, io as PullRequestWatch, ip as PullRequestLink, iq as allWatchEventKinds, ir as parsePairingUrl, is as pairingUrl, aM as ServerFrame, it as Environment, iu as relayWebSocketUrl, iv as remoteWebSocketUrl, aW as WebSocket$1, iw as CHALLENGE_WAIT_MS, aU as methodKind, aR as RpcMethods, ix as dialPlan, iy as REMOTE_PROTOCOL_VERSION, iz as spaced, iA as DIRECT_CHECK_INTERVAL_MS, iB as DIRECT_CHECK_TIMEOUT_MS, iC as WAIT_AGENT_TOOL, iD as enabledProviders, iE as transcriptThreadId, iF as resumeGraceMs, iG as fail$5, iH as isDoneUnsafe, iI as filter$2, iJ as startingProvider, iK as kilobytes$1, iL as monotonicTimeNanos, iM as retry$3, iN as die$3, iO as snakeToCamel, iP as camelToSnake, iQ as UpdatableProviderId, iR as fromNullishOr$1, iS as filter$3, iT as AgentAccount, iU as schedule, iV as BrowserFrame, iW as PagePick, iX as defaultClientSettings, iY as ClientSettings$1, ap as value$2, iZ as BoatVmSize, i_ as GitHubRepository, i$ as next, j0 as bytes, j1 as Timestamp, j2 as RoutineSchedule, j3 as RoutineRun, j4 as launch, j5 as uninterruptible, j6 as parseUnsafe, j7 as RoutineWorkspace, j8 as LinearIssue, j9 as when$2, ja as threadDeviceId, jb as shownScreen, jc as requirementPlatform, jd as devicePlatformOf, je as RUN_AGENT_TOOL, jf as ARTIFACT_THEME_GUIDE, jg as DeviceApp, jh as DeviceUrl, ji as INSTALL_CHUNK_BYTES, jj as DeviceButton, jk as WatchEventKind, jl as isMinLength, jm as GuideGroup, jn as PullRequestGuide, jo as flatten$1, jp as diskFullness, jq as pretty, jr as min$1, js as exponential, jt as desktopOnlyPushes, ju as reachesPhone, jv as mutations, jw as desktopOnlyMethods, jx as isAddressNotUpYet, jy as ClientFrame, aY as REMOTE_MAX_FRAME_BYTES, aX as REMOTE_PATH, jz as empty$9, a_ as cliSocketPath, jA as RemoteFeature, jB as BindHost, jC as getAugmentedNamespace, jD as make$1B, jE as NativeSpan, jF as currentTimeNanos, aC as MinimumLogLevel, bj as packageJson, jG as desktopPid, jH as chromiumDir, bi as isAlive$1, jI as isPortInUse } from "./chunks/dataDir-D7GgMeKc.js";
10
+ import { d as dual, ai as assignProperty, b9 as isFailure, au as succeed, av as fail$1, K as some, N as none, bo as hash, bp as equals, ad as pipeArguments, bq as NodeInspectSymbol, br as toJson, g as format$2, Z as isSome, bs as withFiber, bt as uninterruptibleMask, bu as get$7, bv as Scope, bw as flow$1, bx as fromInputUnsafe, by as constant, bz as zero, bf as as, bA as addFinalizerExit, v as void_, b3 as forEach, bB as exit, bC as tap$1, $ as sync, aw as interrupt, p as fail$2, bD as ExceededCapacityError, bE as makeUnsafe$5, bF as makeUnsafe$6, bG as makeUnsafe$7, H as suspend, bH as runForkWith, bI as runIn, bJ as hasInterrupts, bK as doneUnsafe, bL as getUnsafe$1, bM as addFinalizer, ax as andThen, bN as _await, bO as getCurrent, bP as interrupt$1, bQ as close, bR as isZero, bS as isFinite$1, bT as Clock, bU as toMillis, _ as flatMap, bV as millis, a8 as ensuring, bW as void_$1, bX as getOrThrow, e as hasProperty, bY as BaseProto, aD as TaggedError, bZ as Error$1, b_ as toSeconds, b$ as symbol$2, c0 as structure, c1 as symbol$3, c2 as redact$1, c3 as symbolRedactable, O as make$1q, R as Reference, c4 as strictEqual, c5 as map$1, c6 as try_, c7 as flatMap$1, c8 as combine, c9 as string$2, ca as number$4, cb as optimize, cc as contextWith, w as withFiber$1, b as sync$1, cd as infinity, ce as PipeInspectableProto, cf as updateContext, cg as merge$4, ch as succeed$1, ci as exitHasInterrupts, cj as ClockRef, ck as forkUnsafe, cl as onExitUnsafe, cm as void_$2, cn as fiberInterrupt, co as fiberJoin, cp as filterMap, cq as failVoid, cr as isGreaterThanOrEqualTo$1, cs as LogLevelOrder, aJ as acquireRelease, i as isEffect, ct as interruptAs, n as succeed$2, r as runFork, cu as isFailure$1, h as hasInterruptsOnly, cv as into, cw as asVoid, cx as done, cy as filterInterruptors, cz as interruptAllAs, cA as interruptAll, cB as empty$5, cC as forkUnsafe$1, cD as runPromise, cE as runPromiseWith, cF as runPromiseExit, cG as runPromiseExitWith, cH as runSync, cI as runSyncWith, cJ as runSyncExit, cK as runSyncExitWith, cL as runCallback, cM as runCallbackWith, cN as makeMemoMapUnsafe, aB as provideContext, cO as buildWithMemoMap, cP as flatten, cQ as await_, cR as scopeRemoveFinalizerUnsafe, cS as die, cT as isResult, cU as isSuccess$1, m as identity, cV as set$5, cW as make$1r, cX as effect, aj as Service$1, cY as contextWith$1, cZ as getOrUndefined, am as gen, c_ as context, c$ as make$1s, V as map$2, d0 as fromQueue, d1 as unwrap, aq as provideService, d2 as onExit, d3 as failCauseUnsafe, aR as offerUnsafe, T as TaggedError$1, U as Union, S as String$1, o as optional$7, D as Defect, P as Prototype, d4 as makeSpanUnsafe, d5 as TracerTimingEnabled, d6 as endSpan, d7 as makeSpanScoped, d8 as useSpan, d9 as constUndefined, da as provideService$1, db as ParentSpan, z as scoped, t as tapCause, y as fnUntraced, dc as serviceOption, a3 as match, dd as make$1t, de as provide$1, df as onError, dg as catchIf, dh as scope$1, di as getOption, dj as onExitPrimitive, a as isSuccess$2, dk as catchCause, dl as matchCauseEffect, dm as failCause, dn as combine$1, a9 as orDie, dp as add$1, dq as makeUnsafe$8, dr as fromReasons, ds as isFailReason, dt as makeDieReason, du as reasonAnnotations, dv as failCause$1, dw as yieldNow, dx as constTrue, dy as normalizeNonEmpty, dz as unbounded, dA as publishUnsafe, dB as fromPubSub, dC as getDefaultExportFromCjs, aX as all$1, M as match$1, b8 as promise$1, b7 as ProviderId, dD as now, dE as formatIso, a2 as pipe$2, dF as sort, Y as map$3, dG as flatMapNullishOr, dH as catch_, bi as map$4, dI as fromNullishOr, x as mapError, dJ as logDebug, dK as annotateLogs, dL as withSpan, ay as catchTag, dM as logInfo, dN as catchDefect, dO as filterOrFail, dP as make$1u, dQ as Number$1, dR as encodeEffect, k as decodeUnknownEffect, aV as succeedNone, a7 as isReadonlyArrayNonEmpty, dS as asSome, dT as mutable, A as ArraySchema, dU as NoSuchElementError, dV as Literals, b2 as Number$2, b4 as NullOr, aZ as Struct, dW as FileSystem, dX as orElseSucceed, dY as chatFolder, dZ as Boolean$1, d_ as ProjectKind, d$ as ignore$1, e0 as logWarning, aP as callback, e1 as sleep$3, e2 as forkDetach, e3 as signedOutFailure, e4 as succeed$3, e5 as decodeUnknownOption, an as isNone, aG as fromJsonString, L as Literal, e6 as Unknown, e7 as toArray, aE as seconds, f as optionalKey, e8 as cachedWithTTL, e9 as minutes, aK as unbounded$1, ea as toAsyncIterable, bh as tryPromise, eb as timeout, ec as addFinalizer$1, ed as callback$1, ee as offer, ef as withPermit, eg as acquireUseRelease, aL as endUnsafe, eh as shutdownUnsafe, ei as make$1v, be as try_$1, bl as tapError, ej as forkIn, ek as fromAsyncIterable, el as runForEach, s as squash, em as CLAUDE_EFFORT_LEVELS, en as ensuring$1, eo as currentTimeMillis, ep as sum, eq as race, er as publishedArtifactId, es as PUBLISH_DOCUMENT_TOOL, et as PUBLISH_ARTIFACT_TOOL, eu as PUBLISH_WHITEBOARD_TOOL, ev as isDone, ew as empty$6, ex as succeed$4, ey as fromIterable$2, ez as flatMap$2, eA as interruptWhen, eB as concat, eC as fromEffectDrain, eD as fromEffect, eE as fromIterableEffect, eF as suspend$1, eG as unlistedModel, eH as make$1w, eI as tap$2, eJ as tick, eK as map$5, eL as drop, eM as merge$5, eN as onInterrupt, aO as timeoutOrElse, eO as format$3, eP as getOrNull, eQ as Record, eR as make$1x, aa as take, eS as join$2, ab as raceFirst, eT as end, eU as takeUnsafe, eV as forkScoped, eW as isObject$2, J as getOrElse, eX as repeat, ao as succeed$5, ah as getOrUndefined$1, eY as option, eZ as subscribe, e_ as fromSubscription, e$ as applySettingsPatch, f0 as publish, f1 as defaultSettings, f2 as Settings$2, f3 as vmProviderBeforeTheChoice, f4 as flatMapNullishOr$1, f5 as delay, q as is$2, f6 as bytesToHex, f7 as hmac, f8 as utf8ToBytes, f9 as sha256$2, fa as isTailscaleHost, fb as encodeSync, fc as mergeAll, bc as PushEvent, fd as generateKeyPair, fe as keyPairFromSecret, ff as encodeKey, fg as CLOSE_UNAUTHORIZED, fh as normalizeApprovalCode, fi as PRIVATE_NETWORKS, fj as Void, fk as RelayHostList, fl as RelayMachineList, fm as never$1, fn as SelfHostedRelayUrl, fo as AppConnection, fp as makeUnsafe$9, fq as effectDiscard, fr as changes$1, fs as decodeEffect, ft as toCodecJson, fu as RecordFromUrlParams, fv as decodeTo, fw as externalSpan, fx as isOption, fy as isExit, af as fromUndefinedOr, fz as zero$1, fA as fromInput$1, fB as badArgument, fC as isSchemaError, fD as isNoSuchElementError, fE as StackTrace, fF as mapEager, fG as updateContext$1, fH as makeUnsafe$a, fI as tag$2, fJ as Error$2, I as Int, fK as fromInputUnsafe$1, fL as Path, fM as run$5, fN as mebibytes, fO as Class, fP as constFalse, fQ as withLogSpan, fR as log, fS as Tracer, fT as nativeTracer, fU as hasInterrupts$1, fV as succeed$6, fW as setStackTraceLimit, fX as fail$3, fY as getStackTraceLimit, fZ as fiberEnterUninterruptibleUnsafe, f_ as contA, f$ as effectIsExit, g0 as closeUnsafe, g1 as contE, g2 as reportCauseUnsafe, g3 as matchCauseEffectEager, g4 as flatMapEager, g5 as provideMerge, g6 as fromInput$2, g7 as fromReadable, g8 as toArrayBuffer, G as cached$1, g9 as provide$2, ga as layer$Y, gb as pipeThroughDuplex, gc as toUint8Array, bn as layer$Z, aY as fromResult, gd as WebSocketServer, ge as orDie$1, gf as runForEachArray, gg as interruptible, gh as die$1, gi as Duration, gj as DateTimeUtc, gk as withConstructorDefault, gl as withDecodingDefault, gm as Redacted, gn as Tuple, go as isRedacted, gp as MutableJson, ag as isNotUndefined, gq as Never, ak as empty$7, gr as toJsonSchemaDocument, gs as effectContext, gt as annotateCurrentSpan, gu as isUndefined, az as result$1, gv as failCause$2, gw as forkChild, gx as catch_$1, gy as isSchemaError$1, gz as failCause$3, gA as mapEffect, gB as onEnd, gC as isSchema, aM as encodeUnknownEffect, gD as annotate, gE as fail$4, aA as make$1y, gF as make$1z, gG as declare, gH as isStream, gI as Class$1, gJ as Exit, gK as getOrUndefinedUnsafe, bm as provide$3, gL as provideContext$1, gM as Opaque, gN as StructWithRest, gO as JsonObject$3, gP as transformOptional, gQ as flatMap$3, gR as toType, gS as Any, gT as UndefinedOr, gU as Finite, gV as passthrough, gW as Uint8ArrayFromBase64, gX as Json, gY as TemplateLiteral, gZ as decode$3, g_ as withDefault, g$ as isBetween, W as taggedEnum, h0 as take$1, h1 as isNullish, h2 as isString, h3 as bounded, h4 as withParentSpan, h5 as die$2, h6 as offerAll, h7 as decodeSync, l as logError, h8 as NonEmptyArray, h9 as interrupt$2, ha as interruptors, hb as catchCauseIf, hc as decode$4, hd as decodeUnknownResult, he as fn, hf as isTagged, hg as isReadonlyObject, hh as IllegalArgumentError, hi as encode$1, hj as omit$1, hk as merge$6, hl as succeedContext, hm as unwrap$1, hn as CurrentMemoMap, ho as fromIterable$3, hp as reverse, a0 as empty$8, hq as withFiberSucceed, hr as fiberEnterInterruptibleUnsafe, hs as compose$1, ht as collect, hu as catchDone, hv as takeAll, hw as fromArray, hx as whileLoop, hy as matchEffect, hz as defaultFormatter, hA as logFatal, hB as isDeferred, hC as hasDies, c as constVoid, hD as shutdown, hE as Scheduler$1, ae as catchTags, hF as CurrentLogLevel, hG as UnknownFromJsonString, hH as ignoreCause, hI as forever, hJ as Class$2, hK as TaggedStruct, hL as toEncoded, hM as isMaxLength, hN as makeFilter, hO as isPattern, hP as timeoutOption, hQ as runLast, hR as fromOption, hS as decodeUnknownSync, hT as spawnsSubagent, hU as isPublishArtifactTool, hV as outputText, hW as publishedArtifact, hX as toolArgument, hY as isPublishDocumentTool, hZ as commonjsGlobal, h_ as isRunAgentTool, h$ as presetModels, i0 as filter$1, i1 as take$2, i2 as runDrain, i3 as min, i4 as ChildProcessSpawner, i5 as make$1A, i6 as mkString, i7 as decodeText$2, i8 as ForkPoint, i9 as TokenUsage, ia as MessagePart, ib as Message, ic as parseGitHubPullRequestUrl, id as PullRequestReviewer, ie as PullRequestLabel, ig as PullRequestComment, ih as DiffSide, ii as subtract, ij as PULL_REQUEST_REFRESH, ik as parseGitHubIssueUrl, il as parseGitHubRepository, im as request$4, io as Class$3, ip as AgentProfile, iq as AccountProviderId, ir as ProjectAction, is as Project, it as BooleanFromBit, iu as Worktree, bg as isThreadBusy, bd as ThreadStatus, iv as ScheduledMessage, iw as QueuedMessage, ix as UsageLimit, b1 as Thread, iy as getOrThrow$1, iz as PullRequestWatch, iA as PullRequestLink, iB as allWatchEventKinds, aH as ServerFrame, iC as initiate, iD as REMOTE_PROLOGUE, iE as hexToBytes, iF as newNonce$1, iG as equalBytes, iH as commitment, iI as approvalCode, iJ as parsePairingUrl, iK as pairingUrl, iL as Environment, iM as decodeKey, iN as relayWebSocketUrl, iO as remoteWebSocketUrl, aQ as methodKind, aN as RpcMethods, iP as dialPlan, aS as WebSocket$1, iQ as spaced, iR as DIRECT_CHECK_INTERVAL_MS, iS as DIRECT_CHECK_TIMEOUT_MS, iT as CLOSE_PAIRING_RESET, iU as CLOSE_HANDSHAKE_FAILED, iV as REMOTE_PROTOCOL_VERSION, iW as WAIT_AGENT_TOOL, iX as enabledProviders, iY as transcriptThreadId, iZ as resumeGraceMs, i_ as fail$5, i$ as isDoneUnsafe, j0 as filter$2, j1 as startingProvider, j2 as kilobytes$1, j3 as monotonicTimeNanos, j4 as retry$3, j5 as die$3, j6 as snakeToCamel, j7 as camelToSnake, j8 as UpdatableProviderId, j9 as fromNullishOr$1, ja as filter$3, jb as AgentAccount, jc as schedule, jd as BrowserFrame, je as PagePick, jf as defaultClientSettings, jg as ClientSettings$1, ap as value$2, jh as BoatVmSize, ji as GitHubRepository, jj as next, jk as bytes, jl as Timestamp, jm as RoutineSchedule, jn as RoutineRun, jo as launch, jp as uninterruptible, jq as parseUnsafe, jr as RoutineWorkspace, js as LinearIssue, jt as when$2, ju as threadDeviceId, jv as shownScreen, jw as requirementPlatform, jx as devicePlatformOf, jy as RUN_AGENT_TOOL, jz as ARTIFACT_THEME_GUIDE, jA as DeviceApp, jB as DeviceUrl, jC as INSTALL_CHUNK_BYTES, jD as DeviceButton, jE as WatchEventKind, jF as isMinLength, jG as GuideGroup, jH as PullRequestGuide, jI as flatten$1, jJ as diskFullness, jK as pretty, jL as min$1, jM as exponential, jN as desktopOnlyPushes, jO as reachesPhone, jP as mutations, jQ as desktopOnlyMethods, jR as machineOnlyMethods, aT as REMOTE_PATH, jS as isAddressNotUpYet, jT as CLOSE_MALFORMED_FRAME, jU as ClientFrame, jV as CLOSE_LISTENER_STOPPED, jW as empty$9, aW as cliSocketPath, jX as RemoteFeature, aU as REMOTE_MAX_FRAME_BYTES, jY as LegacyAuth, jZ as REMOTE_SEALED_FRAME_BYTES, j_ as REMOTE_PRE_READY_MAX_BYTES, j$ as CLOSE_AUTH_TIMEOUT, k0 as respond, k1 as BindHost, k2 as getAugmentedNamespace, k3 as make$1B, k4 as NativeSpan, k5 as currentTimeNanos, aC as MinimumLogLevel, bk as packageJson, k6 as desktopPid, k7 as chromiumDir, bj as isAlive$1, k8 as isPortInUse } from "./chunks/dataDir-kSsTIMx3.js";
11
11
  import Ee__default from "fs";
12
12
  import require$$0 from "util";
13
13
  import require$$1$1 from "stream";
@@ -19,15 +19,15 @@ import Pe__default from "path";
19
19
  import crypto__default, { randomUUID, createHash, randomBytes, timingSafeEqual, createHmac } from "node:crypto";
20
20
  import { createInterface } from "node:readline";
21
21
  import require$$0$5 from "node:assert";
22
- import require$$1$2, { BlockList, isIPv4, connect as connect$3, createConnection, createServer as createServer$1 } from "node:net";
22
+ import require$$1$2, { BlockList, isIPv4, connect as connect$2, createConnection, createServer as createServer$1 } from "node:net";
23
23
  import * as require$$2 from "node:http";
24
- import require$$2__default, { createServer, request as request$3 } from "node:http";
24
+ import require$$2__default, { request as request$3, createServer } from "node:http";
25
25
  import require$$0$6, { Readable, pipeline, Duplex } from "node:stream";
26
26
  import require$$5$1 from "node:querystring";
27
27
  import require$$0$4, { once } from "node:events";
28
28
  import require$$0$7 from "node:diagnostics_channel";
29
29
  import require$$3$2, { stripVTControlCharacters, promisify, isDeepStrictEqual } from "node:util";
30
- import Tls, { connect as connect$2 } from "node:tls";
30
+ import Tls, { connect as connect$3 } from "node:tls";
31
31
  import require$$0$8 from "node:buffer";
32
32
  import * as Zlib from "node:zlib";
33
33
  import Zlib__default from "node:zlib";
@@ -39,6 +39,7 @@ import require$$1$4 from "node:async_hooks";
39
39
  import require$$1$5 from "node:console";
40
40
  import require$$2$2 from "node:timers";
41
41
  import require$$1$6 from "node:dns";
42
+ import { request as request$2 } from "node:https";
42
43
  import * as NodeStreamP from "node:stream/promises";
43
44
  import { pipeline as pipeline$1 } from "node:stream/promises";
44
45
  import require$$0$9 from "constants";
@@ -6925,10 +6926,10 @@ function requirePng() {
6925
6926
  })(png$1);
6926
6927
  return png$1;
6927
6928
  }
6928
- var utf8$1 = {};
6929
+ var utf8$3 = {};
6929
6930
  var hasRequiredUtf8$1;
6930
6931
  function requireUtf8$1() {
6931
- if (hasRequiredUtf8$1) return utf8$1;
6932
+ if (hasRequiredUtf8$1) return utf8$3;
6932
6933
  hasRequiredUtf8$1 = 1;
6933
6934
  (function(exports) {
6934
6935
  const Utils = requireUtils$3();
@@ -6987,8 +6988,8 @@ function requireUtf8$1() {
6987
6988
  const utf82 = exports.render(qrData, options);
6988
6989
  fs2.writeFile(path2, utf82, cb);
6989
6990
  };
6990
- })(utf8$1);
6991
- return utf8$1;
6991
+ })(utf8$3);
6992
+ return utf8$3;
6992
6993
  }
6993
6994
  var terminal$1 = {};
6994
6995
  var terminal = {};
@@ -7730,10 +7731,10 @@ const installedBinary = (provider, name) => gen(function* () {
7730
7731
  const key2 = `${command}\0${process.env["PATH"] ?? ""}`;
7731
7732
  const path2 = found.get(key2) ?? (yield* promise$1(() => findBinary(command)));
7732
7733
  if (path2 === void 0) {
7733
- const { name: label, installUrl, binary } = providerInfo[provider];
7734
+ const { name: label, installUrl, binary: binary2 } = providerInfo[provider];
7734
7735
  return yield* new AgentError({
7735
7736
  provider,
7736
- message: command === binary ? `${label} is not installed. Install it from ${installUrl}, then try again` : name === binary ? `${label} was not found at ${command}. Fix its CLI path in Settings > Providers` : `${label} was not found at ${command}, the account's binary path`
7737
+ message: command === binary2 ? `${label} is not installed. Install it from ${installUrl}, then try again` : name === binary2 ? `${label} was not found at ${command}. Fix its CLI path in Settings > Providers` : `${label} was not found at ${command}, the account's binary path`
7737
7738
  });
7738
7739
  }
7739
7740
  found.set(key2, path2);
@@ -8041,6 +8042,13 @@ class WorktreeBusyError extends TaggedError$1()("WorktreeBusyError", {
8041
8042
  }
8042
8043
  }
8043
8044
  const persistence = (operation) => (cause) => new PersistenceError({ operation, cause });
8045
+ class NoWaitingDeviceError extends TaggedError$1()("NoWaitingDeviceError", {
8046
+ code: String$1
8047
+ }) {
8048
+ get message() {
8049
+ return "No waiting device shows that code";
8050
+ }
8051
+ }
8044
8052
  const workspaceFields = {
8045
8053
  cwd: String$1,
8046
8054
  rootPath: String$1,
@@ -8706,7 +8714,7 @@ function makeApprovals(provider, emit) {
8706
8714
  message: note === void 0 ? "The user denied this tool call" : `The user denied this tool call and said: ${note}`
8707
8715
  };
8708
8716
  };
8709
- const respond = (requestId, decision, note) => suspend(() => {
8717
+ const respond2 = (requestId, decision, note) => suspend(() => {
8710
8718
  const approval = pending.get(requestId);
8711
8719
  if (approval === void 0) return succeed$2(false);
8712
8720
  if (decision === "allow_for_session") approval.session.sessionGrants.add(grantKey$2(approval.scope));
@@ -8715,7 +8723,7 @@ function makeApprovals(provider, emit) {
8715
8723
  as(delivered)
8716
8724
  );
8717
8725
  });
8718
- return { ask, respond };
8726
+ return { ask, respond: respond2 };
8719
8727
  }
8720
8728
  const threadMention = (threadId) => `@thread:${threadId}`;
8721
8729
  const terminalMention = (terminalId) => `@terminal:${terminalId}`;
@@ -44545,11 +44553,11 @@ function makeQuestions(provider, emit) {
44545
44553
  updatedInput: { ...input, answers: Object.fromEntries(answered.map(([id2, values2]) => [id2, values2.join(", ")])) }
44546
44554
  };
44547
44555
  };
44548
- const respond = (requestId, answers) => suspend(() => {
44556
+ const respond2 = (requestId, answers) => suspend(() => {
44549
44557
  const deferred = pending.get(requestId);
44550
44558
  return deferred === void 0 ? void_ : succeed$3(deferred, answers);
44551
44559
  }).pipe(asVoid);
44552
- return { ask, respond };
44560
+ return { ask, respond: respond2 };
44553
44561
  }
44554
44562
  const claudeHome = () => process.env.CLAUDE_CONFIG_DIR ?? join$1(homedir(), ".claude");
44555
44563
  const AssistantLine = fromJsonString(
@@ -45133,6 +45141,8 @@ const sameContext = (a, b) => a.cwd === b.cwd && sameHome(a.home, b.home);
45133
45141
  const homeEnv = (home) => home === null ? { ...process.env } : { ...process.env, CLAUDE_CONFIG_DIR: home.dir };
45134
45142
  const errorMessage$1 = (cause) => cause instanceof Error ? cause.message : String(cause);
45135
45143
  const agentError$1 = (provider, message2) => (cause) => new AgentError({ provider, message: `${message2}: ${errorMessage$1(cause)}` });
45144
+ const absolutePathRule = (path2) => process.platform === "win32" ? `//${path2.replace(/^([A-Za-z]):/, (_, drive) => drive.toLowerCase()).replaceAll("\\", "/")}` : `/${path2}`;
45145
+ const readDenials = (paths) => paths.length === 0 ? {} : { permissions: { deny: paths.map((path2) => `Read(${absolutePathRule(path2)})`) } };
45136
45146
  const writeSettingsFile = (provider, directory, settings) => tryPromise({
45137
45147
  try: async () => {
45138
45148
  const path2 = join$1(directory ?? tmpdir(), `claude-settings-${randomUUID()}.json`);
@@ -45498,7 +45508,8 @@ const makeClaudeHarness = ({ id: id2, listModels, launchEnv }) => gen(function*
45498
45508
  ...Object.keys(launch2).length > 0 && { env: { ...launch2 } },
45499
45509
  fastMode: input.fastMode,
45500
45510
  ...input.autoCompactTokens !== null && { autoCompactWindow: input.autoCompactTokens },
45501
- ...input.effort === ULTRACODE && { ultracode: true }
45511
+ ...input.effort === ULTRACODE && { ultracode: true },
45512
+ ...readDenials(input.unreadablePaths)
45502
45513
  });
45503
45514
  const handle = yield* try_$1({
45504
45515
  try: () => query({
@@ -51643,11 +51654,11 @@ function requireCore$1() {
51643
51654
  Ajv2.ValidationError = validation_error_1.default;
51644
51655
  Ajv2.MissingRefError = ref_error_1.default;
51645
51656
  exports.default = Ajv2;
51646
- function checkOptions(checkOpts2, options, msg, log2 = "error") {
51647
- for (const key2 in checkOpts2) {
51657
+ function checkOptions(checkOpts, options, msg, log2 = "error") {
51658
+ for (const key2 in checkOpts) {
51648
51659
  const opt = key2;
51649
51660
  if (opt in options)
51650
- this.logger[log2](`${msg}: option ${key2}. ${checkOpts2[opt]}`);
51661
+ this.logger[log2](`${msg}: option ${key2}. ${checkOpts[opt]}`);
51651
51662
  }
51652
51663
  }
51653
51664
  function getSchEnv(keyRef) {
@@ -56345,6 +56356,7 @@ HinaCode changed your instructions since you last read them. Each block below re
56345
56356
  ${blocks.join("\n\n")}
56346
56357
  </hinacode-update>`;
56347
56358
  };
56359
+ const PERMISSION_PROFILE = "hinacode";
56348
56360
  const approvalPolicies = {
56349
56361
  supervised: "untrusted",
56350
56362
  auto: "on-request",
@@ -56357,10 +56369,27 @@ const sandboxPolicy = (accessMode) => accessMode === "full" ? { type: "dangerFul
56357
56369
  excludeTmpdirEnvVar: false,
56358
56370
  excludeSlashTmp: false
56359
56371
  };
56360
- const threadAccess = (accessMode) => ({
56372
+ const permissionProfile = (unreadablePaths, userSandbox) => {
56373
+ const userProfile = userSandbox?.default_permissions ?? null;
56374
+ const workspaceWrite = userProfile === null ? userSandbox?.sandbox_workspace_write ?? null : null;
56375
+ return {
56376
+ extends: userProfile ?? ":workspace",
56377
+ ...workspaceWrite !== null && { network: { enabled: workspaceWrite.network_access } },
56378
+ filesystem: Object.fromEntries([
56379
+ ...(workspaceWrite?.writable_roots ?? []).map((root2) => [root2, "write"]),
56380
+ ...workspaceWrite?.exclude_tmpdir_env_var ? [[":tmpdir", "read"]] : [],
56381
+ ...workspaceWrite?.exclude_slash_tmp ? [[":slash_tmp", "read"]] : [],
56382
+ ...unreadablePaths.map((path2) => [path2, "deny"])
56383
+ ])
56384
+ };
56385
+ };
56386
+ const threadAccess = (accessMode, unreadablePaths, userSandbox) => accessMode === "full" ? { approvalPolicy: approvalPolicies.full, sandbox: "danger-full-access" } : {
56361
56387
  approvalPolicy: approvalPolicies[accessMode],
56362
- sandbox: accessMode === "full" ? "danger-full-access" : "workspace-write"
56363
- });
56388
+ config: {
56389
+ default_permissions: PERMISSION_PROFILE,
56390
+ permissions: { [PERMISSION_PROFILE]: permissionProfile(unreadablePaths, userSandbox) }
56391
+ }
56392
+ };
56364
56393
  const turnAccess = (accessMode, current) => {
56365
56394
  const wanted = sandboxPolicy(accessMode);
56366
56395
  return {
@@ -56843,6 +56872,21 @@ const toImportedHistory = ({ thread: thread2 }, turns) => {
56843
56872
  const messages = transcript.finish();
56844
56873
  return { title: title2, model, messages: messages.length === 0 ? null : messages };
56845
56874
  };
56875
+ const ConfigReadResponse = Struct({
56876
+ config: Struct({
56877
+ default_permissions: optional$7(NullOr(String$1)),
56878
+ sandbox_workspace_write: optional$7(
56879
+ NullOr(
56880
+ Struct({
56881
+ writable_roots: ArraySchema(String$1),
56882
+ network_access: Boolean$1,
56883
+ exclude_tmpdir_env_var: optional$7(Boolean$1),
56884
+ exclude_slash_tmp: optional$7(Boolean$1)
56885
+ })
56886
+ )
56887
+ )
56888
+ })
56889
+ });
56846
56890
  const PlanType = Literals([
56847
56891
  "free",
56848
56892
  "go",
@@ -56923,6 +56967,11 @@ const ThreadTurnsListResponse = Struct({
56923
56967
  });
56924
56968
  const CLIENT_VERSION$2 = "0.1.0";
56925
56969
  const FAST_SERVICE_TIER = "priority";
56970
+ const readSandboxConfig = (client2, cwd) => client2.request("config/read", { cwd, includeLayers: false }).pipe(
56971
+ flatMap(decodeUnknownEffect(ConfigReadResponse)),
56972
+ map$2((response2) => response2.config),
56973
+ catch_((error2) => logWarning("could not read the Codex config", error2).pipe(as(null)))
56974
+ );
56926
56975
  const decisionToWire = {
56927
56976
  allow: "accept",
56928
56977
  allow_for_session: "acceptForSession",
@@ -57268,11 +57317,14 @@ const make$1a = gen(function* () {
57268
57317
  sync(() => threadsInTurn.add(input.threadId)),
57269
57318
  () => sync(() => leaveTurn(client2, input.threadId, inbox))
57270
57319
  );
57320
+ const userSandbox = input.accessMode === "full" ? null : yield* readSandboxConfig(client2, input.cwd);
57321
+ const access2 = threadAccess(input.accessMode, input.unreadablePaths, userSandbox);
57271
57322
  const overrides = {
57272
57323
  cwd: input.cwd,
57273
57324
  model: input.model,
57274
- ...threadAccess(input.accessMode),
57325
+ ...access2,
57275
57326
  config: {
57327
+ ...access2.config,
57276
57328
  tools: { update_plan: { enabled: true } },
57277
57329
  ...input.tmpDirectory !== null && { shell_environment_policy: { set: tmpEnv(input.tmpDirectory) } },
57278
57330
  ...input.autoCompactTokens !== null && { model_auto_compact_token_limit: input.autoCompactTokens },
@@ -57288,7 +57340,8 @@ const make$1a = gen(function* () {
57288
57340
  };
57289
57341
  const resumed = input.resumeSessionId;
57290
57342
  const loaded = resumed === null ? void 0 : loadedThreads.get(resumed);
57291
- const reloads = loaded !== void 0 && loaded.autoCompactTokens !== input.autoCompactTokens;
57343
+ const sandboxed = access2.config !== void 0;
57344
+ const reloads = loaded !== void 0 && (loaded.autoCompactTokens !== input.autoCompactTokens || loaded.sandboxed !== sandboxed);
57292
57345
  if (resumed !== null && reloads) {
57293
57346
  yield* client2.request("thread/unsubscribe", { threadId: resumed });
57294
57347
  }
@@ -57309,7 +57362,11 @@ const make$1a = gen(function* () {
57309
57362
  items: [{ type: "message", role: "developer", content: [{ type: "input_text", text: update2 }] }]
57310
57363
  }).pipe(ignore$1);
57311
57364
  }
57312
- loadedThreads.set(thread2.id, { autoCompactTokens: input.autoCompactTokens, instructions: input.instructions });
57365
+ loadedThreads.set(thread2.id, {
57366
+ autoCompactTokens: input.autoCompactTokens,
57367
+ instructions: input.instructions,
57368
+ sandboxed
57369
+ });
57313
57370
  loadedSessions.set(input.threadId, { client: client2, codexThreadId: thread2.id });
57314
57371
  yield* emit({ type: "session_bound", providerSessionId: thread2.id });
57315
57372
  const compacting2 = isCompactCommand(input.prompt);
@@ -59384,7 +59441,7 @@ const make$19 = gen(function* () {
59384
59441
  });
59385
59442
  const openSession = (entry, input) => gen(function* () {
59386
59443
  const { host, sessions } = entry;
59387
- const permissionProfile = permissionProfiles[input.accessMode];
59444
+ const permissionProfile2 = permissionProfiles[input.accessMode];
59388
59445
  const config2 = {
59389
59446
  mcpServers: {
59390
59447
  hinacode: { transport: "streamableHttp", url: input.mcpServer.url, headers: { ...input.mcpServer.headers } }
@@ -59394,12 +59451,12 @@ const make$19 = gen(function* () {
59394
59451
  const { session } = yield* host.command("session/start", {
59395
59452
  workspaceRoot: input.cwd,
59396
59453
  modelId: input.model,
59397
- permissionProfile,
59454
+ permissionProfile: permissionProfile2,
59398
59455
  config: config2
59399
59456
  });
59400
59457
  sessions.set(session.sessionId, {
59401
59458
  model: input.model,
59402
- permissionProfile,
59459
+ permissionProfile: permissionProfile2,
59403
59460
  cwd: input.cwd,
59404
59461
  usedTokens: null,
59405
59462
  compacting: false,
@@ -59414,12 +59471,12 @@ const make$19 = gen(function* () {
59414
59471
  const { session } = yield* host.command("session/resume", {
59415
59472
  sessionId,
59416
59473
  excludeItems: true,
59417
- permissionProfile,
59474
+ permissionProfile: permissionProfile2,
59418
59475
  config: config2
59419
59476
  });
59420
59477
  loaded = {
59421
59478
  model: session.modelId,
59422
- permissionProfile,
59479
+ permissionProfile: permissionProfile2,
59423
59480
  cwd: input.cwd,
59424
59481
  // FIXME: an `excludeItems` resume carries no context usage
59425
59482
  usedTokens: input.autoCompactTokens === null ? null : yield* latestUsedTokens(host, sessionId),
@@ -59433,9 +59490,9 @@ const make$19 = gen(function* () {
59433
59490
  yield* host.command("session/setModel", { sessionId, model: { modelId: input.model } });
59434
59491
  loaded.model = input.model;
59435
59492
  }
59436
- if (loaded.permissionProfile !== permissionProfile) {
59437
- yield* host.command("session/setPermissionProfile", { sessionId, profileId: permissionProfile });
59438
- loaded.permissionProfile = permissionProfile;
59493
+ if (loaded.permissionProfile !== permissionProfile2) {
59494
+ yield* host.command("session/setPermissionProfile", { sessionId, profileId: permissionProfile2 });
59495
+ loaded.permissionProfile = permissionProfile2;
59439
59496
  }
59440
59497
  return sessionId;
59441
59498
  }).pipe(mapError(toAgentError));
@@ -59929,13 +59986,15 @@ class MuseProvider extends Service$1()("hinacode/MuseProvider") {
59929
59986
  static layer = effect(MuseProvider, make$19);
59930
59987
  }
59931
59988
  const StoredSecret = fromJsonString(Struct({ encrypted: Boolean$1, value: String$1 }));
59932
- const rowKey = (name) => `secret.${name}`;
59989
+ const ROW_PREFIX = "secret.";
59990
+ const rowKey = (name) => `${ROW_PREFIX}${name}`;
59991
+ const threadSecretPrefix = (threadId) => `thread.${threadId}.`;
59933
59992
  class Keyring extends Service$1()("hinacode/Keyring") {
59934
59993
  }
59935
59994
  const noKeyring = succeed$5(
59936
59995
  Keyring,
59937
59996
  Keyring.of({
59938
- seal: () => void 0,
59997
+ backend: "none",
59939
59998
  open: () => {
59940
59999
  throw new Error("no keyring");
59941
60000
  }
@@ -59946,52 +60005,85 @@ class Secrets extends Service$1()("hinacode/Secrets") {
59946
60005
  const make$18 = gen(function* () {
59947
60006
  const sql = yield* SqlClient;
59948
60007
  const keyring = yield* Keyring;
59949
- let warnedPlaintext = false;
59950
60008
  const findOne2 = findOneOption({
59951
60009
  Request: String$1,
59952
60010
  Result: Struct({ value: StoredSecret }),
59953
60011
  execute: (key2) => sql`SELECT value FROM setting WHERE key = ${key2}`
59954
60012
  });
60013
+ const keysUnder = (prefix2) => {
60014
+ const full = rowKey(prefix2);
60015
+ return sql`
60016
+ SELECT key, value FROM setting WHERE substr(key, 1, ${full.length}) = ${full}
60017
+ `;
60018
+ };
59955
60019
  const encode2 = encodeEffect(StoredSecret);
59956
- const open2 = (name, stored) => stored.encrypted ? try_$1(() => keyring.open(Buffer.from(stored.value, "base64"))).pipe(
59957
- map$2(some),
59958
- catch_(
59959
- () => as(
59960
- logWarning(`secret ${name} was sealed under another key; treating it as unset`),
59961
- none()
59962
- )
59963
- )
59964
- ) : succeed$2(some(stored.value));
60020
+ const decode2 = decodeUnknownOption(StoredSecret);
60021
+ const openStored = (stored) => stored.encrypted ? try_$1(() => keyring.open(Buffer.from(stored.value, "base64"))).pipe(option) : succeed$2(some(stored.value));
60022
+ const sealed = (value2) => keyring.backend === "none" ? { encrypted: false, value: value2 } : { encrypted: true, value: keyring.seal(value2).toString("base64") };
60023
+ const write = (key2, value2) => gen(function* () {
60024
+ const json2 = yield* encode2(sealed(value2));
60025
+ yield* sql`
60026
+ INSERT INTO setting (key, value) VALUES (${key2}, ${json2})
60027
+ ON CONFLICT (key) DO UPDATE SET value = excluded.value
60028
+ `;
60029
+ });
59965
60030
  const get2 = (name) => findOne2(rowKey(name)).pipe(
59966
60031
  flatMap(
59967
- match({ onNone: () => succeed$2(none()), onSome: ({ value: value2 }) => open2(name, value2) })
60032
+ match({
60033
+ onNone: () => succeed$2(none()),
60034
+ onSome: ({ value: value2 }) => tap$1(
60035
+ openStored(value2),
60036
+ (opened) => isNone(opened) ? logWarning(`secret ${name} was sealed under another key; treating it as unset`) : void_
60037
+ )
60038
+ })
59968
60039
  ),
59969
60040
  mapError(persistence("secrets.get"))
59970
60041
  );
59971
- const seal = (value2) => gen(function* () {
59972
- const sealed = keyring.seal(value2);
59973
- if (sealed !== void 0) return { encrypted: true, value: sealed.toString("base64") };
59974
- if (!warnedPlaintext) {
59975
- warnedPlaintext = true;
59976
- yield* logWarning("no OS keyring; secrets are stored as plaintext");
59977
- }
59978
- return { encrypted: false, value: value2 };
60042
+ const needsRewrite = (stored) => keyring.backend === "none" ? stored.encrypted : !stored.encrypted || !keyring.sealedByThisKey(Buffer.from(stored.value, "base64"));
60043
+ const withSecureDelete = (effect2) => gen(function* () {
60044
+ const [setting] = yield* sql`PRAGMA secure_delete`;
60045
+ const previous = Object.values(setting ?? {})[0] ?? 0;
60046
+ yield* sql`PRAGMA secure_delete = ON`;
60047
+ const result2 = yield* effect2.pipe(
60048
+ ensuring(ignore$1(sql`PRAGMA secure_delete = ${sql.literal(String(previous))}`))
60049
+ );
60050
+ yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
60051
+ return result2;
59979
60052
  });
59980
- const set2 = (name, value2) => gen(function* () {
59981
- const json2 = yield* flatMap(seal(value2), encode2);
59982
- yield* sql`
59983
- INSERT INTO setting (key, value) VALUES (${rowKey(name)}, ${json2})
59984
- ON CONFLICT (key) DO UPDATE SET value = excluded.value
59985
- `;
59986
- }).pipe(mapError(persistence("secrets.set")));
60053
+ const resealAll = gen(function* () {
60054
+ const stale = [];
60055
+ for (const { key: key2, value: value2 } of yield* keysUnder("")) {
60056
+ const stored = getOrUndefined$1(decode2(value2));
60057
+ if (stored === void 0 || !needsRewrite(stored)) continue;
60058
+ const opened = yield* openStored(stored);
60059
+ if (isSome(opened)) stale.push({ key: key2, value: opened.value });
60060
+ }
60061
+ if (stale.length === 0) return;
60062
+ yield* withSecureDelete(forEach(stale, ({ key: key2, value: value2 }) => write(key2, value2), { discard: true }));
60063
+ yield* logInfo(`stored ${stale.length} secrets again under keyring ${keyring.backend}`);
60064
+ }).pipe(catchCause((cause) => logWarning("resealing secrets failed", cause)));
60065
+ yield* resealAll;
60066
+ if (keyring.backend === "none") yield* logWarning("no OS keyring; secrets are stored as plaintext");
59987
60067
  return Secrets.of({
60068
+ backend: keyring.backend,
59988
60069
  get: get2,
59989
60070
  has: (name) => map$2(get2(name), isSome),
59990
- set: set2,
60071
+ set: (name, value2) => write(rowKey(name), value2).pipe(mapError(persistence("secrets.set"))),
59991
60072
  clear: (name) => sql`DELETE FROM setting WHERE key = ${rowKey(name)}`.pipe(
59992
60073
  asVoid,
59993
60074
  mapError(persistence("secrets.clear"))
59994
- )
60075
+ ),
60076
+ namesUnder: (prefix2) => keysUnder(prefix2).pipe(
60077
+ map$2((rows) => rows.map(({ key: key2 }) => key2.slice(rowKey(prefix2).length))),
60078
+ mapError(persistence("secrets.namesUnder"))
60079
+ ),
60080
+ clearUnder: (prefix2) => {
60081
+ const full = rowKey(prefix2);
60082
+ return sql`DELETE FROM setting WHERE substr(key, 1, ${full.length}) = ${full}`.pipe(
60083
+ asVoid,
60084
+ mapError(persistence("secrets.clearUnder"))
60085
+ );
60086
+ }
59995
60087
  });
59996
60088
  });
59997
60089
  const layer$U = effect(Secrets, make$18);
@@ -61706,7 +61798,7 @@ const makeExtensionFile = acquireRelease(
61706
61798
  );
61707
61799
  const makePiProvider = gen(function* () {
61708
61800
  const providerScope = yield* scope$1;
61709
- const { name, binary } = providerInfo.pi;
61801
+ const { name, binary: binary2 } = providerInfo.pi;
61710
61802
  const extension = yield* makeExtensionFile;
61711
61803
  const extensionPath = sync(() => {
61712
61804
  if (existsSync(extension.path)) return extension.path;
@@ -61735,7 +61827,7 @@ const makePiProvider = gen(function* () {
61735
61827
  )
61736
61828
  );
61737
61829
  const startPi = (options) => gen(function* () {
61738
- const binaryPath = yield* installedBinary("pi", binary);
61830
+ const binaryPath = yield* installedBinary("pi", binary2);
61739
61831
  return yield* makePiClient({
61740
61832
  binaryPath,
61741
61833
  args: ["--mode", "rpc", "--approve", ...options.args],
@@ -62020,7 +62112,7 @@ Your next message starts a new ${name} session.`,
62020
62112
  const provider = {
62021
62113
  id: "pi",
62022
62114
  listModels,
62023
- account: (home) => home === null ? installedBinary("pi", binary).pipe(as({ type: "external", service: "pi" })) : fail$2(agentError(`${name} runs on its CLI login only`)),
62115
+ account: (home) => home === null ? installedBinary("pi", binary2).pipe(as({ type: "external", service: "pi" })) : fail$2(agentError(`${name} runs on its CLI login only`)),
62024
62116
  planLimits: () => succeed$2(null),
62025
62117
  usage: () => succeed$2(null),
62026
62118
  listCommands: ({ cwd }) => get$4(probedCommands, cwd),
@@ -62036,479 +62128,6 @@ Your next message starts a new ${name} session.`,
62036
62128
  class PiProvider extends Service$1()("hinacode/PiProvider") {
62037
62129
  static layer = effect(PiProvider, makePiProvider);
62038
62130
  }
62039
- function isBytes(a) {
62040
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
62041
- }
62042
- const atitle = (title2) => title2 ? `"${title2}" ` : "";
62043
- function anumber(n, title2 = "") {
62044
- if (typeof n !== "number")
62045
- throw new TypeError(atitle(title2) + "expected number, got " + typeof n);
62046
- if (!Number.isSafeInteger(n) || n < 0)
62047
- throw new RangeError(atitle(title2) + "expected integer >= 0, got " + n);
62048
- return n;
62049
- }
62050
- function abytes(value2, length, title2 = "") {
62051
- if (isBytes(value2) && length === void 0)
62052
- return value2;
62053
- const bytes2 = isBytes(value2);
62054
- const ofLen = "";
62055
- const got = bytes2 ? `length=${value2.length}` : `type=${typeof value2}`;
62056
- const message2 = atitle(title2) + "expected Uint8Array" + ofLen + ", got " + got;
62057
- if (!bytes2)
62058
- throw new TypeError(message2);
62059
- throw new RangeError(message2);
62060
- }
62061
- function ahash(h) {
62062
- if (typeof h !== "function" || typeof h.create !== "function")
62063
- throw new TypeError("expected hash wrapped by utils.createHasher");
62064
- anumber(h.outputLen);
62065
- anumber(h.blockLen);
62066
- if (h.outputLen < 1 || h.blockLen < 1)
62067
- throw new Error("hash blockLen / outputLen must be >= 1");
62068
- }
62069
- const aobject = (value2, label) => {
62070
- if (value2 === null || typeof value2 !== "object" || Array.isArray(value2))
62071
- throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value2);
62072
- };
62073
- const aopts = (value2, label) => {
62074
- aobject(value2, label);
62075
- const proto = Object.getPrototypeOf(value2);
62076
- if (proto !== Object.prototype && proto !== null)
62077
- throw new TypeError(`"${label}" expected plain object`);
62078
- if (Object.hasOwn(value2, "__proto__"))
62079
- throw new TypeError(`"${label}.__proto__" is not allowed`);
62080
- };
62081
- function aexists(instance, checkFinished = true) {
62082
- if (instance.destroyed)
62083
- throw new Error("hash was destroyed");
62084
- if (checkFinished && instance.finished)
62085
- throw new Error("digest() was already called");
62086
- }
62087
- function aoutput(out, instance) {
62088
- abytes(out, void 0, "output");
62089
- const min2 = instance.outputLen;
62090
- if (!(out.length >= min2)) {
62091
- throw new RangeError('"output" expected length >= ' + min2);
62092
- }
62093
- }
62094
- function clean(...arrays) {
62095
- for (let i = 0; i < arrays.length; i++) {
62096
- arrays[i].fill(0);
62097
- }
62098
- }
62099
- function createView(arr) {
62100
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
62101
- }
62102
- function rotr(word, shift) {
62103
- return word << 32 - shift | word >>> shift;
62104
- }
62105
- const hasHexBuiltin = /* @__PURE__ */ (() => (
62106
- // @ts-ignore
62107
- typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
62108
- ))();
62109
- const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
62110
- function bytesToHex(bytes2) {
62111
- abytes(bytes2);
62112
- if (hasHexBuiltin)
62113
- return bytes2.toHex();
62114
- let hex = "";
62115
- for (let i = 0; i < bytes2.length; i++) {
62116
- hex += hexes[bytes2[i]];
62117
- }
62118
- return hex;
62119
- }
62120
- function utf8ToBytes(str) {
62121
- if (typeof str !== "string")
62122
- throw new TypeError("string expected");
62123
- const encoded = new TextEncoder().encode(str);
62124
- try {
62125
- return new Uint8Array(encoded);
62126
- } finally {
62127
- clean(encoded);
62128
- }
62129
- }
62130
- function checkOpts(defaults2, opts, title2 = "opts") {
62131
- aopts(defaults2, "defaults");
62132
- if (opts !== void 0)
62133
- aopts(opts, title2);
62134
- const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults2, opts);
62135
- return merged;
62136
- }
62137
- function createHasher(hashCons, info = {}) {
62138
- if (typeof hashCons !== "function")
62139
- throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
62140
- info = checkOpts({}, info, "info");
62141
- const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
62142
- const tmp = hashCons(void 0);
62143
- hashC.outputLen = tmp.outputLen;
62144
- hashC.blockLen = tmp.blockLen;
62145
- hashC.canXOF = tmp.canXOF;
62146
- hashC.create = (opts) => hashCons(opts);
62147
- Object.assign(hashC, info);
62148
- return Object.freeze(hashC);
62149
- }
62150
- const oidNist = (suffix) => ({
62151
- // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
62152
- // Larger suffix values would need base-128 OID encoding and a different length byte.
62153
- oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
62154
- });
62155
- class _HMAC {
62156
- oHash;
62157
- iHash;
62158
- blockLen;
62159
- outputLen;
62160
- canXOF = false;
62161
- finished = false;
62162
- destroyed = false;
62163
- constructor(hash2, key2) {
62164
- ahash(hash2);
62165
- abytes(key2, void 0, "key");
62166
- this.iHash = hash2.create();
62167
- if (typeof this.iHash.update !== "function")
62168
- throw new Error("expected Hash instance");
62169
- this.blockLen = this.iHash.blockLen;
62170
- this.outputLen = this.iHash.outputLen;
62171
- const blockLen = this.blockLen;
62172
- const pad = new Uint8Array(blockLen);
62173
- pad.set(key2.length > blockLen ? hash2.create().update(key2).digest() : key2);
62174
- for (let i = 0; i < pad.length; i++)
62175
- pad[i] ^= 54;
62176
- this.iHash.update(pad);
62177
- this.oHash = hash2.create();
62178
- for (let i = 0; i < pad.length; i++)
62179
- pad[i] ^= 54 ^ 92;
62180
- this.oHash.update(pad);
62181
- clean(pad);
62182
- }
62183
- update(buf) {
62184
- aexists(this);
62185
- this.iHash.update(buf);
62186
- return this;
62187
- }
62188
- digestInto(out) {
62189
- aexists(this);
62190
- aoutput(out, this);
62191
- this.finished = true;
62192
- const buf = out.subarray(0, this.outputLen);
62193
- this.iHash.digestInto(buf);
62194
- this.oHash.update(buf);
62195
- this.oHash.digestInto(buf);
62196
- this.destroy();
62197
- }
62198
- digest() {
62199
- const out = new Uint8Array(this.oHash.outputLen);
62200
- this.digestInto(out);
62201
- return out;
62202
- }
62203
- _cloneInto(to) {
62204
- to ||= Object.create(Object.getPrototypeOf(this), {});
62205
- const { oHash, iHash, finished: finished2, destroyed, blockLen, outputLen, canXOF } = this;
62206
- to = to;
62207
- to.finished = finished2;
62208
- to.destroyed = destroyed;
62209
- to.blockLen = blockLen;
62210
- to.outputLen = outputLen;
62211
- to.canXOF = canXOF;
62212
- to.oHash = oHash._cloneInto(to.oHash);
62213
- to.iHash = iHash._cloneInto(to.iHash);
62214
- return to;
62215
- }
62216
- clone() {
62217
- return this._cloneInto();
62218
- }
62219
- destroy() {
62220
- this.destroyed = true;
62221
- this.oHash.destroy();
62222
- this.iHash.destroy();
62223
- }
62224
- }
62225
- const hmac = /* @__PURE__ */ (() => {
62226
- const hmac_ = ((hash2, key2, message2) => new _HMAC(hash2, key2).update(message2).digest());
62227
- hmac_.create = (hash2, key2) => new _HMAC(hash2, key2);
62228
- return hmac_;
62229
- })();
62230
- const fromNumH = (n) => n / 2 ** 32 | 0;
62231
- const fromNumL = (n) => n >>> 0;
62232
- function setU64FromNum(view, byteOffset, n, isLE) {
62233
- const h = fromNumH(n);
62234
- const l = fromNumL(n);
62235
- view.setUint32(byteOffset, isLE ? l : h, isLE);
62236
- view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
62237
- }
62238
- function Chi(a, b, c) {
62239
- return a & b ^ ~a & c;
62240
- }
62241
- function Maj(a, b, c) {
62242
- return a & b ^ a & c ^ b & c;
62243
- }
62244
- class HashMD {
62245
- blockLen;
62246
- outputLen;
62247
- canXOF = false;
62248
- padOffset;
62249
- isLE;
62250
- // For partial updates less than block size
62251
- buffer;
62252
- view;
62253
- finished = false;
62254
- length = 0;
62255
- pos = 0;
62256
- destroyed = false;
62257
- constructor(blockLen, outputLen, padOffset, isLE) {
62258
- this.blockLen = blockLen;
62259
- this.outputLen = outputLen;
62260
- this.padOffset = padOffset;
62261
- this.isLE = isLE;
62262
- this.buffer = new Uint8Array(blockLen);
62263
- this.view = createView(this.buffer);
62264
- }
62265
- update(data) {
62266
- aexists(this);
62267
- abytes(data);
62268
- const { view, buffer: buffer2, blockLen } = this;
62269
- const len = data.length;
62270
- let processed = false;
62271
- for (let pos = 0; pos < len; ) {
62272
- const take2 = Math.min(blockLen - this.pos, len - pos);
62273
- if (take2 === blockLen) {
62274
- const dataView = createView(data);
62275
- for (; blockLen <= len - pos; pos += blockLen)
62276
- this.process(dataView, pos);
62277
- processed = true;
62278
- continue;
62279
- }
62280
- buffer2.set(pos === 0 && take2 === len ? data : data.subarray(pos, pos + take2), this.pos);
62281
- this.pos += take2;
62282
- pos += take2;
62283
- if (this.pos === blockLen) {
62284
- this.process(view, 0);
62285
- this.pos = 0;
62286
- processed = true;
62287
- }
62288
- }
62289
- this.length += data.length;
62290
- if (processed)
62291
- this.roundClean();
62292
- return this;
62293
- }
62294
- digestInto(out) {
62295
- aexists(this);
62296
- aoutput(out, this);
62297
- this.finished = true;
62298
- const { buffer: buffer2, view, blockLen, isLE } = this;
62299
- let { pos } = this;
62300
- buffer2[pos++] = 128;
62301
- buffer2.fill(0, pos);
62302
- if (this.padOffset > blockLen - pos) {
62303
- this.process(view, 0);
62304
- buffer2.fill(0);
62305
- }
62306
- setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
62307
- this.process(view, 0);
62308
- this.roundClean();
62309
- const oview = out === buffer2 ? view : createView(out);
62310
- const len = this.outputLen;
62311
- const outLen = len / 4;
62312
- const state = this.get();
62313
- if (len % 4 || outLen > state.length)
62314
- throw new Error("invalid outputLen");
62315
- for (let i = 0; i < outLen; i++)
62316
- oview.setUint32(4 * i, state[i], isLE);
62317
- }
62318
- digest() {
62319
- const { buffer: buffer2, outputLen } = this;
62320
- this.digestInto(buffer2);
62321
- const res = buffer2.slice(0, outputLen);
62322
- this.destroy();
62323
- return res;
62324
- }
62325
- _cloneIntoMeta(to) {
62326
- const { buffer: buffer2, length, finished: finished2, destroyed, pos } = this;
62327
- to.destroyed = destroyed;
62328
- to.finished = finished2;
62329
- to.length = length;
62330
- to.pos = pos;
62331
- if (pos)
62332
- to.buffer.set(buffer2);
62333
- return to;
62334
- }
62335
- clone() {
62336
- return this._cloneInto();
62337
- }
62338
- }
62339
- const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
62340
- 1779033703,
62341
- 3144134277,
62342
- 1013904242,
62343
- 2773480762,
62344
- 1359893119,
62345
- 2600822924,
62346
- 528734635,
62347
- 1541459225
62348
- ]);
62349
- const SHA256_K = /* @__PURE__ */ Uint32Array.from([
62350
- 1116352408,
62351
- 1899447441,
62352
- 3049323471,
62353
- 3921009573,
62354
- 961987163,
62355
- 1508970993,
62356
- 2453635748,
62357
- 2870763221,
62358
- 3624381080,
62359
- 310598401,
62360
- 607225278,
62361
- 1426881987,
62362
- 1925078388,
62363
- 2162078206,
62364
- 2614888103,
62365
- 3248222580,
62366
- 3835390401,
62367
- 4022224774,
62368
- 264347078,
62369
- 604807628,
62370
- 770255983,
62371
- 1249150122,
62372
- 1555081692,
62373
- 1996064986,
62374
- 2554220882,
62375
- 2821834349,
62376
- 2952996808,
62377
- 3210313671,
62378
- 3336571891,
62379
- 3584528711,
62380
- 113926993,
62381
- 338241895,
62382
- 666307205,
62383
- 773529912,
62384
- 1294757372,
62385
- 1396182291,
62386
- 1695183700,
62387
- 1986661051,
62388
- 2177026350,
62389
- 2456956037,
62390
- 2730485921,
62391
- 2820302411,
62392
- 3259730800,
62393
- 3345764771,
62394
- 3516065817,
62395
- 3600352804,
62396
- 4094571909,
62397
- 275423344,
62398
- 430227734,
62399
- 506948616,
62400
- 659060556,
62401
- 883997877,
62402
- 958139571,
62403
- 1322822218,
62404
- 1537002063,
62405
- 1747873779,
62406
- 1955562222,
62407
- 2024104815,
62408
- 2227730452,
62409
- 2361852424,
62410
- 2428436474,
62411
- 2756734187,
62412
- 3204031479,
62413
- 3329325298
62414
- ]);
62415
- const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
62416
- class SHA2_32B extends HashMD {
62417
- // We cannot use array here since array allows indexing by variable
62418
- // which means optimizer/compiler cannot use registers.
62419
- // Numeric initializers matter: starting the fields as `undefined` changes
62420
- // V8's field representation and makes sha256 3x slower (measured).
62421
- A = 0;
62422
- B = 0;
62423
- C = 0;
62424
- D = 0;
62425
- E = 0;
62426
- F = 0;
62427
- G = 0;
62428
- H = 0;
62429
- constructor(outputLen, IV) {
62430
- super(64, outputLen, 8, false);
62431
- this.A = IV[0] | 0;
62432
- this.B = IV[1] | 0;
62433
- this.C = IV[2] | 0;
62434
- this.D = IV[3] | 0;
62435
- this.E = IV[4] | 0;
62436
- this.F = IV[5] | 0;
62437
- this.G = IV[6] | 0;
62438
- this.H = IV[7] | 0;
62439
- }
62440
- get() {
62441
- const { A, B, C, D, E, F, G, H } = this;
62442
- return [A, B, C, D, E, F, G, H];
62443
- }
62444
- // prettier-ignore
62445
- set(A, B, C, D, E, F, G, H) {
62446
- this.A = A | 0;
62447
- this.B = B | 0;
62448
- this.C = C | 0;
62449
- this.D = D | 0;
62450
- this.E = E | 0;
62451
- this.F = F | 0;
62452
- this.G = G | 0;
62453
- this.H = H | 0;
62454
- }
62455
- _cloneInto(to) {
62456
- (to ||= new this.constructor()).set(...this.get());
62457
- return this._cloneIntoMeta(to);
62458
- }
62459
- process(view, offset) {
62460
- for (let i = 0; i < 16; i++, offset += 4)
62461
- SHA256_W[i] = view.getUint32(offset, false);
62462
- for (let i = 16; i < 64; i++) {
62463
- const W15 = SHA256_W[i - 15];
62464
- const W2 = SHA256_W[i - 2];
62465
- const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
62466
- const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
62467
- SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
62468
- }
62469
- let { A, B, C, D, E, F, G, H } = this;
62470
- for (let i = 0; i < 64; i++) {
62471
- const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
62472
- const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
62473
- const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
62474
- const T2 = sigma0 + Maj(A, B, C) | 0;
62475
- H = G;
62476
- G = F;
62477
- F = E;
62478
- E = D + T1 | 0;
62479
- D = C;
62480
- C = B;
62481
- B = A;
62482
- A = T1 + T2 | 0;
62483
- }
62484
- A = A + this.A | 0;
62485
- B = B + this.B | 0;
62486
- C = C + this.C | 0;
62487
- D = D + this.D | 0;
62488
- E = E + this.E | 0;
62489
- F = F + this.F | 0;
62490
- G = G + this.G | 0;
62491
- H = H + this.H | 0;
62492
- this.set(A, B, C, D, E, F, G, H);
62493
- }
62494
- roundClean() {
62495
- clean(SHA256_W);
62496
- }
62497
- destroy() {
62498
- this.destroyed = true;
62499
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
62500
- clean(this.buffer);
62501
- }
62502
- }
62503
- class _SHA256 extends SHA2_32B {
62504
- constructor() {
62505
- super(32, SHA256_IV);
62506
- }
62507
- }
62508
- const sha256$2 = /* @__PURE__ */ createHasher(
62509
- () => new _SHA256(),
62510
- /* @__PURE__ */ oidNist(1)
62511
- );
62512
62131
  const prove = (token, label, first, second) => bytesToHex(hmac(sha256$2, utf8ToBytes(token), utf8ToBytes(`hinacode ${label}
62513
62132
  ${first}
62514
62133
  ${second}`)));
@@ -62542,11 +62161,54 @@ for (const [network, prefix2] of [
62542
62161
  const isPrivateAddress = (address) => privateRanges.check(address, isIPv4(address) ? "ipv4" : "ipv6");
62543
62162
  const privateAddresses = (interfaces = networkInterfaces()) => networkAddresses(interfaces).map((a) => a.address).filter(isPrivateAddress);
62544
62163
  const tailscaleAddress = (interfaces = networkInterfaces()) => networkAddresses(interfaces).find((a) => isTailscaleHost(a.address))?.address ?? null;
62545
- const REMOTE_TOKEN_SECRET = "remote.token";
62164
+ class Events extends Service$1()(
62165
+ "hinacode/Events"
62166
+ ) {
62167
+ }
62168
+ class PushBroadcast extends Service$1()("hinacode/PushBroadcast") {
62169
+ }
62170
+ class WindowBroadcast extends Service$1()("hinacode/WindowBroadcast") {
62171
+ }
62172
+ class WindowPush extends Service$1()("hinacode/WindowPush") {
62173
+ }
62174
+ const encodePushEvent = encodeSync(PushEvent);
62175
+ const subscribeTo = (sinks) => (sink) => acquireRelease(
62176
+ sync(() => void sinks.add(sink)),
62177
+ () => sync(() => void sinks.delete(sink))
62178
+ );
62179
+ const makeEventsLayer = (toWindows) => {
62180
+ const sinks = /* @__PURE__ */ new Set();
62181
+ const windowSinks = /* @__PURE__ */ new Set();
62182
+ const toEveryWindow = (encoded) => {
62183
+ toWindows(encoded);
62184
+ for (const sink of windowSinks) sink(encoded);
62185
+ };
62186
+ const events2 = succeed$5(
62187
+ Events,
62188
+ Events.of({
62189
+ publish: (event) => sync(() => {
62190
+ const encoded = encodePushEvent(event);
62191
+ toEveryWindow(encoded);
62192
+ for (const sink of sinks) sink(encoded);
62193
+ })
62194
+ })
62195
+ );
62196
+ const windows = succeed$5(
62197
+ WindowPush,
62198
+ WindowPush.of({ send: (event) => sync(() => toEveryWindow(encodePushEvent(event))) })
62199
+ );
62200
+ return mergeAll(
62201
+ events2,
62202
+ windows,
62203
+ succeed$5(PushBroadcast, PushBroadcast.of({ subscribe: subscribeTo(sinks) })),
62204
+ succeed$5(WindowBroadcast, WindowBroadcast.of({ subscribe: subscribeTo(windowSinks) }))
62205
+ );
62206
+ };
62207
+ const HOST_KEY_SECRET = "remote.hostKey";
62208
+ const PAIRING_SECRET = "remote.pairingSecret";
62209
+ const LEGACY_TOKEN_SECRET = "remote.token";
62546
62210
  const ENVIRONMENT_ID_KEY = "environment.id";
62547
- const CLOSE_LISTENER_STOPPED = 4003;
62548
- const CLOSE_AUTH_TIMEOUT = 4004;
62549
- const CLOSE_MALFORMED_FRAME = 4005;
62211
+ const MAX_WAITING = 8;
62550
62212
  const LOOPBACK = "127.0.0.1";
62551
62213
  const advertisedHosts = (bindHost) => {
62552
62214
  if (bindHost !== PRIVATE_NETWORKS) return [bindHost];
@@ -62554,6 +62216,10 @@ const advertisedHosts = (bindHost) => {
62554
62216
  return isReadonlyArrayNonEmpty(hosts) ? hosts : [LOOPBACK];
62555
62217
  };
62556
62218
  const relayHostname = (relay2) => "hostname" in relay2 ? relay2.hostname : null;
62219
+ const appsRelayHostname = (relay2) => {
62220
+ const hostname2 = relayHostname(relay2);
62221
+ return hostname2 === null || hostname2.includes("/") ? null : hostname2;
62222
+ };
62557
62223
  class RemoteAccess extends Service$1()("hinacode/RemoteAccess") {
62558
62224
  }
62559
62225
  const loadIdentity = gen(function* () {
@@ -62567,38 +62233,167 @@ const sameSecret = (expected, candidate) => {
62567
62233
  const b = Buffer.from(candidate);
62568
62234
  return a.length === b.length && timingSafeEqual(a, b);
62569
62235
  };
62236
+ const newSecret = () => randomBytes(32).toString("base64url");
62237
+ const encodeSecretKey = (key2) => Buffer.from(key2.secretKey).toString("base64url");
62238
+ const DeviceRow = Struct({
62239
+ key: String$1,
62240
+ name: String$1,
62241
+ createdAt: Number$2,
62242
+ lastSeenAt: NullOr(Number$2)
62243
+ });
62570
62244
  const make$17 = gen(function* () {
62245
+ const sql = yield* SqlClient;
62571
62246
  const secrets = yield* Secrets;
62572
- const identity2 = yield* loadIdentity;
62573
62247
  const settings = yield* Settings$1;
62574
- const rotated = yield* unbounded();
62575
- let token = getOrNull(yield* secrets.get(REMOTE_TOKEN_SECRET));
62576
- let generation = 0;
62248
+ const events2 = yield* Events;
62249
+ const identity2 = yield* loadIdentity;
62250
+ const resets = yield* unbounded();
62251
+ const storedHostKey = getOrNull(yield* secrets.get(HOST_KEY_SECRET));
62252
+ const storedSecret = getOrNull(yield* secrets.get(PAIRING_SECRET));
62253
+ let hostKey = storedHostKey === null ? generateKeyPair() : keyPairFromSecret(Buffer.from(storedHostKey, "base64url"));
62254
+ let secret = storedHostKey === null || storedSecret === null ? newSecret() : storedSecret;
62255
+ if (storedHostKey === null) yield* secrets.set(HOST_KEY_SECRET, encodeSecretKey(hostKey));
62256
+ if (storedSecret !== secret) yield* secrets.set(PAIRING_SECRET, secret);
62257
+ const legacyToken = getOrNull(yield* secrets.get(LEGACY_TOKEN_SECRET));
62577
62258
  let report = { listening: false, listenError: null, connected: 0, relay: { state: "off" } };
62578
- const pairingFor = (current) => map$2(settings.get, ({ remote }) => ({
62259
+ const live = /* @__PURE__ */ new Map();
62260
+ const pending = [];
62261
+ const findDevice = findOneOption({
62262
+ Request: String$1,
62263
+ Result: DeviceRow,
62264
+ execute: (key2) => sql`SELECT key, name, created_at, last_seen_at FROM remote_device WHERE key = ${key2}`
62265
+ });
62266
+ const findDevices = findAll({
62267
+ Request: Void,
62268
+ Result: DeviceRow,
62269
+ execute: () => sql`SELECT key, name, created_at, last_seen_at FROM remote_device ORDER BY created_at, rowid`
62270
+ });
62271
+ const changed = (reason, name) => events2.publish({ type: "remote.devices.changed", reason, ...name !== void 0 && { name } });
62272
+ const withConnected = (row) => ({ ...row, connected: live.has(row.key) });
62273
+ const trust = (key2, name) => gen(function* () {
62274
+ const now2 = yield* currentTimeMillis;
62275
+ const [row] = yield* sql`
62276
+ INSERT INTO remote_device (key, name, created_at, last_seen_at) VALUES (${key2}, ${name}, ${now2}, ${now2})
62277
+ ON CONFLICT (key) DO UPDATE SET last_seen_at = excluded.last_seen_at
62278
+ RETURNING key, name, created_at, last_seen_at
62279
+ `;
62280
+ return row;
62281
+ }).pipe(mapError(persistence("remote.trust")));
62282
+ const touch = (key2) => flatMap(
62283
+ currentTimeMillis,
62284
+ (now2) => sql`UPDATE remote_device SET last_seen_at = ${now2} WHERE key = ${key2}`
62285
+ ).pipe(mapError(persistence("remote.touch")));
62286
+ const replaceSecret = () => {
62287
+ secret = newSecret();
62288
+ return secrets.set(PAIRING_SECRET, secret);
62289
+ };
62290
+ const pairing = map$2(settings.get, ({ remote }) => ({
62579
62291
  hosts: advertisedHosts(remote.bindHost),
62580
62292
  port: remote.port,
62581
- token: current,
62582
- relay: relayHostname(report.relay)
62293
+ relay: relayHostname(report.relay),
62294
+ key: encodeKey(hostKey.publicKey),
62295
+ secret
62583
62296
  }));
62584
- const rotateToken = gen(function* () {
62585
- const next2 = randomBytes(32).toString("base64url");
62586
- yield* secrets.set(REMOTE_TOKEN_SECRET, next2);
62587
- token = next2;
62588
- generation++;
62589
- yield* publish(rotated, void 0);
62590
- return yield* pairingFor(next2);
62297
+ const leave = (request2) => {
62298
+ const index = pending.indexOf(request2);
62299
+ if (index !== -1) pending.splice(index, 1);
62300
+ };
62301
+ const closeDevice = (key2, reason) => {
62302
+ for (const close2 of live.get(key2) ?? []) close2(CLOSE_UNAUTHORIZED, reason);
62303
+ for (const request2 of pending.filter((candidate) => candidate.key === key2)) {
62304
+ leave(request2);
62305
+ request2.close(CLOSE_UNAUTHORIZED, reason);
62306
+ }
62307
+ };
62308
+ const admit = (hello) => gen(function* () {
62309
+ if (hello.verify === true) return "pending";
62310
+ const trusted = yield* findDevice(hello.key).pipe(mapError(persistence("remote.admit")));
62311
+ if (isSome(trusted)) {
62312
+ yield* touch(hello.key);
62313
+ return "ready";
62314
+ }
62315
+ if (hello.secret === void 0 || !sameSecret(secret, hello.secret)) return "pending";
62316
+ yield* replaceSecret();
62317
+ yield* trust(hello.key, hello.name);
62318
+ yield* changed("enrolled", hello.name);
62319
+ return "ready";
62320
+ });
62321
+ const wait = (request2) => {
62322
+ const entry = { ...request2, code: null };
62323
+ if (pending.length >= MAX_WAITING) {
62324
+ const oldest = pending.shift();
62325
+ oldest.close(CLOSE_UNAUTHORIZED, "too many devices are waiting");
62326
+ }
62327
+ pending.push(entry);
62328
+ return {
62329
+ showsCode: (code2) => suspend(() => {
62330
+ if (!pending.includes(entry)) return void_;
62331
+ entry.code = code2;
62332
+ return changed("waiting");
62333
+ }),
62334
+ leave: () => leave(entry)
62335
+ };
62336
+ };
62337
+ const connect2 = (key2, close2) => {
62338
+ const sessions = live.get(key2) ?? /* @__PURE__ */ new Set();
62339
+ sessions.add(close2);
62340
+ live.set(key2, sessions);
62341
+ return () => {
62342
+ sessions.delete(close2);
62343
+ if (sessions.size === 0 && live.get(key2) === sessions) live.delete(key2);
62344
+ };
62345
+ };
62346
+ const devices = map$2(findDevices(void 0), (rows) => ({
62347
+ devices: rows.map(withConnected),
62348
+ waiting: pending.filter((request2) => request2.code !== null).length
62349
+ })).pipe(mapError(persistence("remote.devices")));
62350
+ const approve = (typed) => gen(function* () {
62351
+ const code2 = normalizeApprovalCode(typed);
62352
+ const request2 = pending.find((candidate) => code2 !== null && candidate.code === code2);
62353
+ if (request2 === void 0) return yield* new NoWaitingDeviceError({ code: typed });
62354
+ leave(request2);
62355
+ const row = yield* trust(request2.key, request2.name);
62356
+ request2.admit();
62357
+ yield* changed("approved", row.name);
62358
+ return withConnected(row);
62359
+ });
62360
+ const remove2 = (key2) => gen(function* () {
62361
+ const [row] = yield* sql`DELETE FROM remote_device WHERE key = ${key2} RETURNING name`.pipe(
62362
+ mapError(persistence("remote.remove"))
62363
+ );
62364
+ closeDevice(key2, "device removed");
62365
+ yield* replaceSecret();
62366
+ yield* changed("removed", row?.name);
62367
+ });
62368
+ const resetPairing = gen(function* () {
62369
+ hostKey = generateKeyPair();
62370
+ yield* secrets.set(HOST_KEY_SECRET, encodeSecretKey(hostKey));
62371
+ yield* replaceSecret();
62372
+ yield* sql`DELETE FROM remote_device`.pipe(mapError(persistence("remote.resetPairing")));
62373
+ pending.length = 0;
62374
+ yield* publish(resets, void 0);
62375
+ yield* changed("reset");
62376
+ return yield* pairing;
62591
62377
  });
62592
62378
  return RemoteAccess.of({
62593
62379
  status: sync(() => report),
62594
- pairing: suspend(() => token === null ? rotateToken : pairingFor(token)),
62595
- rotateToken,
62596
- authenticate: (candidate) => token !== null && sameSecret(token, candidate),
62597
- answerChallenge: (serverNonce, clientNonce, proof) => token !== null && sameSecret(clientProof(token, serverNonce, clientNonce), proof) ? serverProof(token, clientNonce, serverNonce) : null,
62598
- generation: () => generation,
62599
- rotations: fromPubSub(rotated),
62600
62380
  report: (patch) => sync(() => void (report = { ...report, ...patch })),
62601
- identity: identity2
62381
+ identity: identity2,
62382
+ hostKey: () => hostKey,
62383
+ pairing,
62384
+ resetPairing,
62385
+ resets: fromPubSub(resets),
62386
+ answerLegacy: (challenge, auth2) => {
62387
+ if (legacyToken === null) return null;
62388
+ if ("token" in auth2) return sameSecret(legacyToken, auth2.token) ? {} : null;
62389
+ return sameSecret(clientProof(legacyToken, challenge, auth2.nonce), auth2.proof) ? { proof: serverProof(legacyToken, auth2.nonce, challenge) } : null;
62390
+ },
62391
+ admit,
62392
+ wait,
62393
+ connect: connect2,
62394
+ devices,
62395
+ approve,
62396
+ remove: remove2
62602
62397
  });
62603
62398
  });
62604
62399
  const layer$S = effect(RemoteAccess, make$17);
@@ -62814,9 +62609,141 @@ const relayService = (fetch2, serviceUrl) => {
62814
62609
  )
62815
62610
  };
62816
62611
  };
62612
+ const RELAY_UPGRADE_PROTOCOL = "hinacode-relay/1";
62613
+ const SIGNAL_PING = 0;
62614
+ const SIGNAL_OPEN = 1;
62615
+ const ATTACH_TIMEOUT_MS = 1e4;
62616
+ const FIRST_RETRY_MS$1 = 1e3;
62617
+ const LAST_RETRY_MS$1 = 3e4;
62618
+ const relayAddress = ({ url: url2, hostId }) => `${url2.host}/h/${hostId}`;
62619
+ const describeRefusal = (status) => status === 401 ? "The relay refused this machine's token." : `The relay answered ${status ?? "nothing"} instead of switching protocols.`;
62620
+ const splice = (relay2, local) => {
62621
+ relay2.pipe(local);
62622
+ local.pipe(relay2);
62623
+ const destroyBoth = () => {
62624
+ relay2.destroy();
62625
+ local.destroy();
62626
+ };
62627
+ relay2.once("error", destroyBoth);
62628
+ local.once("error", destroyBoth);
62629
+ relay2.once("close", () => local.end());
62630
+ local.once("close", () => relay2.end());
62631
+ };
62632
+ const attachToRelay = (attachment2, onState) => {
62633
+ const request2 = attachment2.url.protocol === "https:" ? request$2 : request$3;
62634
+ const parked = /* @__PURE__ */ new Set();
62635
+ const sessions = /* @__PURE__ */ new Set();
62636
+ const dialing = /* @__PURE__ */ new Set();
62637
+ let closed = false;
62638
+ let retryMs = FIRST_RETRY_MS$1;
62639
+ let retry2 = null;
62640
+ let lastError = null;
62641
+ const report = () => {
62642
+ if (closed) return;
62643
+ onState(parked.size > 0 ? { state: "connected" } : { state: "connecting", error: lastError });
62644
+ };
62645
+ const fail2 = (error2) => {
62646
+ lastError = error2;
62647
+ report();
62648
+ if (closed || retry2 !== null) return;
62649
+ retry2 = setTimeout(() => {
62650
+ retry2 = null;
62651
+ refill();
62652
+ }, retryMs);
62653
+ retryMs = Math.min(retryMs * 2, LAST_RETRY_MS$1);
62654
+ };
62655
+ const open2 = (relay2, rest) => {
62656
+ parked.delete(relay2);
62657
+ relay2.removeAllListeners("data");
62658
+ relay2.write(Buffer.of(SIGNAL_OPEN));
62659
+ refill();
62660
+ report();
62661
+ const local = connect$2({ host: attachment2.origin.host, port: attachment2.origin.port, noDelay: true });
62662
+ sessions.add(relay2);
62663
+ relay2.once("close", () => sessions.delete(relay2));
62664
+ if (rest.length > 0) local.write(rest);
62665
+ splice(relay2, local);
62666
+ };
62667
+ const park = (relay2, head2) => {
62668
+ retryMs = FIRST_RETRY_MS$1;
62669
+ lastError = null;
62670
+ relay2.setNoDelay(true);
62671
+ relay2.setKeepAlive(true, 15e3);
62672
+ parked.add(relay2);
62673
+ const onSignals = (chunk) => {
62674
+ for (let at = 0; at < chunk.length; at += 1) {
62675
+ if (chunk[at] === SIGNAL_PING) {
62676
+ relay2.write(Buffer.of(SIGNAL_PING));
62677
+ continue;
62678
+ }
62679
+ if (chunk[at] === SIGNAL_OPEN) return open2(relay2, chunk.subarray(at + 1));
62680
+ return relay2.destroy();
62681
+ }
62682
+ };
62683
+ relay2.on("data", onSignals);
62684
+ relay2.once("close", () => {
62685
+ if (!parked.delete(relay2)) return;
62686
+ report();
62687
+ refill();
62688
+ });
62689
+ relay2.on("error", () => {
62690
+ });
62691
+ report();
62692
+ if (head2.length > 0) onSignals(head2);
62693
+ };
62694
+ const dial2 = () => {
62695
+ const attach = request2(attachment2.url, {
62696
+ method: "GET",
62697
+ path: `/h/${attachment2.hostId}/attach`,
62698
+ agent: false,
62699
+ timeout: ATTACH_TIMEOUT_MS,
62700
+ headers: {
62701
+ authorization: `Bearer ${attachment2.token}`,
62702
+ connection: "Upgrade",
62703
+ upgrade: RELAY_UPGRADE_PROTOCOL
62704
+ }
62705
+ });
62706
+ dialing.add(attach);
62707
+ const settle2 = () => dialing.delete(attach);
62708
+ attach.once("upgrade", (_response, socket, head2) => {
62709
+ if (!settle2() || closed) return void socket.destroy();
62710
+ socket.setTimeout(0);
62711
+ park(socket, head2);
62712
+ });
62713
+ attach.once("response", (response2) => {
62714
+ response2.resume();
62715
+ if (settle2()) fail2(describeRefusal(response2.statusCode));
62716
+ });
62717
+ attach.once("timeout", () => attach.destroy(new Error("the relay did not answer within 10 seconds")));
62718
+ attach.on("error", (error2) => {
62719
+ if (settle2()) fail2(`Cannot reach the relay: ${error2.message}`);
62720
+ });
62721
+ attach.end();
62722
+ };
62723
+ const refill = () => {
62724
+ if (closed || retry2 !== null) return;
62725
+ while (parked.size + dialing.size < attachment2.idle) dial2();
62726
+ };
62727
+ report();
62728
+ refill();
62729
+ return {
62730
+ close: () => {
62731
+ closed = true;
62732
+ if (retry2 !== null) clearTimeout(retry2);
62733
+ for (const pending of dialing) pending.destroy();
62734
+ for (const socket of [...parked, ...sessions]) socket.destroy();
62735
+ dialing.clear();
62736
+ parked.clear();
62737
+ sessions.clear();
62738
+ }
62739
+ };
62740
+ };
62817
62741
  const TUNNEL_KEY = "relay.tunnel";
62818
62742
  const CREDENTIAL_SECRET = "relay.credential";
62819
62743
  const CONNECTOR_TOKEN_SECRET = "relay.connectorToken";
62744
+ const SELF_HOSTED_TOKEN_SECRET = "relay.selfHosted.token";
62745
+ const SELF_HOSTED_IDLE_CONNECTIONS = 2;
62746
+ const SELF_HOSTED_TOKEN_MIN_LENGTH = 32;
62820
62747
  const DEFAULT_RELAY_SERVICE_URL = "https://relay.hinacode.app";
62821
62748
  const FIRST_RETRY_MS = 1e3;
62822
62749
  const LAST_RETRY_MS = 6e4;
@@ -62839,10 +62766,17 @@ const cloudflaredArgs = (http2) => [
62839
62766
  "127.0.0.1:0",
62840
62767
  "run"
62841
62768
  ];
62769
+ const originHost = (bindHost) => bindHost === PRIVATE_NETWORKS ? LOOPBACK : bindHost;
62842
62770
  const relayOrigin = ({ bindHost, port }) => {
62843
- const host = bindHost === PRIVATE_NETWORKS ? LOOPBACK : bindHost;
62771
+ const host = originHost(bindHost);
62844
62772
  return `http://${host.includes(":") ? `[${host}]` : host}:${port}`;
62845
62773
  };
62774
+ const selfHostedRelayOrigin = (input) => {
62775
+ const url2 = URL.parse(input.trim());
62776
+ const bare = url2 !== null && url2.pathname === "/" && url2.search === "" && url2.hash === "" && url2.username === "";
62777
+ return bare && url2.password === "" ? decodeUnknownOption(SelfHostedRelayUrl)(url2.origin) : none();
62778
+ };
62779
+ const attachmentStatus = (attachment2, hostname2) => attachment2.state === "connected" ? { state: "connected", hostname: hostname2 } : { state: "connecting", hostname: hostname2, error: attachment2.error };
62846
62780
  const METRICS_LINE = /Starting metrics server on (\S+)\/metrics/;
62847
62781
  const PROTOCOL = /\bprotocol=(\w+)/;
62848
62782
  const QUIC_FAILURE = /failed to dial to edge with quic|timeout: no recent network activity/;
@@ -62892,7 +62826,8 @@ const make$16 = ({
62892
62826
  const linking = yield* make$1l();
62893
62827
  const status = yield* make$1d({ state: "off" });
62894
62828
  let tunnel = yield* storedTunnel;
62895
- let remote = (yield* settings.get).remote;
62829
+ let { remote, selfHostedRelay } = yield* settings.get;
62830
+ const runFork2 = runForkWith(yield* context());
62896
62831
  const publish2 = (next2) => gen(function* () {
62897
62832
  if (equals(yield* get$1(status), next2)) return;
62898
62833
  yield* access2.report({ relay: next2 });
@@ -62929,8 +62864,8 @@ const make$16 = ({
62929
62864
  });
62930
62865
  const publishPairing = gen(function* () {
62931
62866
  if (tunnel === null) return;
62932
- const { hosts, port, token } = yield* access2.pairing;
62933
- const pairing = { hosts, port, token };
62867
+ const { hosts, port, key: key2 } = yield* access2.pairing;
62868
+ const pairing = { hosts, port, key: key2 };
62934
62869
  const published = createHash("sha256").update(JSON.stringify(pairing)).digest("hex");
62935
62870
  if (published === tunnel.published) return;
62936
62871
  const credential = yield* requireSecret(
@@ -62970,13 +62905,13 @@ const make$16 = ({
62970
62905
  if (code2 === 200 || code2 === 503) yield* offer(events2, { type: "ready", ready: code2 === 200 });
62971
62906
  }
62972
62907
  });
62973
- const runOnce = (binary, hostname2, token) => gen(function* () {
62908
+ const runOnce = (binary2, hostname2, token) => gen(function* () {
62974
62909
  const events2 = yield* unbounded$1();
62975
62910
  const http2 = yield* startsOnHttp2;
62976
62911
  const tryingQuic = !http2 && !transportChosenByUser;
62977
62912
  yield* acquireRelease(
62978
62913
  sync(() => {
62979
- const child = spawn(binary, cloudflaredArgs(http2), {
62914
+ const child = spawn(binary2, cloudflaredArgs(http2), {
62980
62915
  env: { ...process.env, TUNNEL_TOKEN: token },
62981
62916
  stdio: ["ignore", "ignore", "pipe"]
62982
62917
  });
@@ -63031,7 +62966,7 @@ const make$16 = ({
63031
62966
  }).pipe(scoped);
63032
62967
  const keepConnected = (stored) => gen(function* () {
63033
62968
  const { hostname: hostname2 } = stored;
63034
- let binary = cloudflared;
62969
+ let binary2 = cloudflared;
63035
62970
  let retryMs = FIRST_RETRY_MS;
63036
62971
  for (; ; ) {
63037
62972
  const outcome = yield* gen(function* () {
@@ -63040,18 +62975,18 @@ const make$16 = ({
63040
62975
  CONNECTOR_TOKEN_SECRET,
63041
62976
  "The tunnel's connector token is gone. Link this machine again."
63042
62977
  );
63043
- const first = yield* runOnce(binary, hostname2, token);
63044
- if (first.type !== "missing" || binary !== cloudflared || cloudflaredDir === void 0) return first;
63045
- binary = yield* installCloudflared(cloudflaredDir, cloudflaredAsset, (url2) => fetch2(url2, {})).pipe(
62978
+ const first = yield* runOnce(binary2, hostname2, token);
62979
+ if (first.type !== "missing" || binary2 !== cloudflared || cloudflaredDir === void 0) return first;
62980
+ binary2 = yield* installCloudflared(cloudflaredDir, cloudflaredAsset, (url2) => fetch2(url2, {})).pipe(
63046
62981
  mapError(
63047
62982
  (failure2) => new RelayError({ message: `Cannot install cloudflared: ${failure2.message}.` })
63048
62983
  )
63049
62984
  );
63050
- return yield* runOnce(binary, hostname2, token);
62985
+ return yield* runOnce(binary2, hostname2, token);
63051
62986
  }).pipe(
63052
62987
  catch_((failure2) => succeed$2({ type: "exited", error: failure2.message, upMs: 0 }))
63053
62988
  );
63054
- const error2 = outcome.type === "missing" ? `cloudflared is not installed at ${binary}.` : outcome.error;
62989
+ const error2 = outcome.type === "missing" ? `cloudflared is not installed at ${binary2}.` : outcome.error;
63055
62990
  yield* logWarning("cloudflared stopped", error2);
63056
62991
  yield* publish2({ state: "connecting", hostname: hostname2, error: error2 });
63057
62992
  if (outcome.type === "exited" && outcome.upMs >= HEALTHY_MS) retryMs = FIRST_RETRY_MS;
@@ -63059,8 +62994,39 @@ const make$16 = ({
63059
62994
  retryMs = Math.min(retryMs * 2, LAST_RETRY_MS);
63060
62995
  }
63061
62996
  });
62997
+ const attachSelfHosted = (url2, hostname2) => gen(function* () {
62998
+ const token = yield* requireSecret(
62999
+ SELF_HOSTED_TOKEN_SECRET,
63000
+ "The token for your own relay is gone. Enter it again in Settings."
63001
+ );
63002
+ yield* acquireRelease(
63003
+ sync(
63004
+ () => attachToRelay(
63005
+ {
63006
+ url: new URL(url2),
63007
+ hostId: access2.identity.id,
63008
+ token,
63009
+ origin: { host: originHost(remote.bindHost), port: remote.port },
63010
+ idle: SELF_HOSTED_IDLE_CONNECTIONS
63011
+ },
63012
+ (attachment2) => void runFork2(publish2(attachmentStatus(attachment2, hostname2)))
63013
+ )
63014
+ ),
63015
+ (attachment2) => sync(attachment2.close)
63016
+ );
63017
+ return yield* never$1;
63018
+ }).pipe(
63019
+ scoped,
63020
+ catch_((failure2) => publish2({ state: "connecting", hostname: hostname2, error: failure2.message }))
63021
+ );
63062
63022
  const apply2 = gen(function* () {
63063
63023
  yield* clear$1(connector);
63024
+ if (selfHostedRelay !== null) {
63025
+ const hostname2 = relayAddress({ url: new URL(selfHostedRelay), hostId: access2.identity.id });
63026
+ if (!remote.enabled) return yield* publish2({ state: "paused", hostname: hostname2 });
63027
+ yield* publish2({ state: "connecting", hostname: hostname2, error: null });
63028
+ return yield* run$4(connector, attachSelfHosted(selfHostedRelay, hostname2));
63029
+ }
63064
63030
  if (tunnel === null) return yield* publish2({ state: "off" });
63065
63031
  yield* republish;
63066
63032
  if (!remote.enabled) return yield* publish2({ state: "paused", hostname: tunnel.hostname });
@@ -63114,19 +63080,47 @@ const make$16 = ({
63114
63080
  yield* (yield* settings.changes).pipe(
63115
63081
  runForEach((next2) => {
63116
63082
  const { enabled, bindHost, port } = next2.remote;
63117
- if (enabled === remote.enabled && bindHost === remote.bindHost && port === remote.port) return void_;
63083
+ const sameRemote = enabled === remote.enabled && bindHost === remote.bindHost && port === remote.port;
63084
+ if (sameRemote && next2.selfHostedRelay === selfHostedRelay) return void_;
63118
63085
  remote = next2.remote;
63086
+ selfHostedRelay = next2.selfHostedRelay;
63119
63087
  return lock.withPermit(apply2);
63120
63088
  }),
63121
63089
  forkScoped
63122
63090
  );
63123
- yield* merge$5(access2.rotations, drop(tick(PUBLISH_EVERY), 1)).pipe(
63091
+ yield* merge$5(access2.resets, drop(tick(PUBLISH_EVERY), 1)).pipe(
63124
63092
  runForEach(() => lock.withPermit(republish)),
63125
63093
  forkScoped
63126
63094
  );
63095
+ const switchSelfHosted = (url2) => lock.withPermit(
63096
+ gen(function* () {
63097
+ selfHostedRelay = url2;
63098
+ yield* settings.set({ selfHostedRelay: url2 });
63099
+ yield* apply2;
63100
+ })
63101
+ );
63102
+ const useSelfHosted = ({ url: url2, token }) => gen(function* () {
63103
+ const origin = selfHostedRelayOrigin(url2);
63104
+ if (isNone(origin)) {
63105
+ return yield* new RelayError({ message: "Enter the relay as https://host or https://host:port." });
63106
+ }
63107
+ if (token.trim().length < SELF_HOSTED_TOKEN_MIN_LENGTH) {
63108
+ return yield* new RelayError({
63109
+ message: `The relay token has at least ${SELF_HOSTED_TOKEN_MIN_LENGTH} characters.`
63110
+ });
63111
+ }
63112
+ yield* secrets.set(SELF_HOSTED_TOKEN_SECRET, token.trim());
63113
+ yield* switchSelfHosted(origin.value);
63114
+ });
63115
+ const stopSelfHosted = gen(function* () {
63116
+ yield* switchSelfHosted(null);
63117
+ yield* secrets.clear(SELF_HOSTED_TOKEN_SECRET);
63118
+ });
63127
63119
  return Relay.of({
63128
63120
  setup: setup2,
63129
63121
  remove: remove2,
63122
+ useSelfHosted,
63123
+ stopSelfHosted,
63130
63124
  status: get$1(status),
63131
63125
  changes: changes(status),
63132
63126
  serviceUrl,
@@ -63141,48 +63135,6 @@ const make$16 = ({
63141
63135
  });
63142
63136
  });
63143
63137
  const layer$R = (options = {}) => effect(Relay, make$16(options));
63144
- class Events extends Service$1()(
63145
- "hinacode/Events"
63146
- ) {
63147
- }
63148
- class PushBroadcast extends Service$1()("hinacode/PushBroadcast") {
63149
- }
63150
- class WindowBroadcast extends Service$1()("hinacode/WindowBroadcast") {
63151
- }
63152
- class WindowPush extends Service$1()("hinacode/WindowPush") {
63153
- }
63154
- const encodePushEvent = encodeSync(PushEvent);
63155
- const subscribeTo = (sinks) => (sink) => acquireRelease(
63156
- sync(() => void sinks.add(sink)),
63157
- () => sync(() => void sinks.delete(sink))
63158
- );
63159
- const makeEventsLayer = (toWindows) => {
63160
- const sinks = /* @__PURE__ */ new Set();
63161
- const windowSinks = /* @__PURE__ */ new Set();
63162
- const toEveryWindow = (encoded) => {
63163
- for (const sink of windowSinks) sink(encoded);
63164
- };
63165
- const events2 = succeed$5(
63166
- Events,
63167
- Events.of({
63168
- publish: (event) => sync(() => {
63169
- const encoded = encodePushEvent(event);
63170
- toEveryWindow(encoded);
63171
- for (const sink of sinks) sink(encoded);
63172
- })
63173
- })
63174
- );
63175
- const windows = succeed$5(
63176
- WindowPush,
63177
- WindowPush.of({ send: (event) => sync(() => toEveryWindow(encodePushEvent(event))) })
63178
- );
63179
- return mergeAll(
63180
- events2,
63181
- windows,
63182
- succeed$5(PushBroadcast, PushBroadcast.of({ subscribe: subscribeTo(sinks) })),
63183
- succeed$5(WindowBroadcast, WindowBroadcast.of({ subscribe: subscribeTo(windowSinks) }))
63184
- );
63185
- };
63186
63138
  const WAITING_LIFE = minutes(10);
63187
63139
  const AUTHORIZATION_CODE_LIFE = seconds(60);
63188
63140
  const MAX_REQUESTS = 5;
@@ -63222,7 +63174,7 @@ const make$15 = gen(function* () {
63222
63174
  });
63223
63175
  const issuer = map$2(
63224
63176
  access2.status,
63225
- ({ relay: relay2 }) => map$4(fromNullishOr(relayHostname(relay2)), (hostname2) => `https://${hostname2}`)
63177
+ ({ relay: relay2 }) => map$4(fromNullishOr(appsRelayHostname(relay2)), (hostname2) => `https://${hostname2}`)
63226
63178
  );
63227
63179
  const status = gen(function* () {
63228
63180
  yield* forgetExpired2;
@@ -63344,7 +63296,7 @@ const followRelayLayer = effectDiscard(
63344
63296
  const relay2 = yield* Relay;
63345
63297
  const connections = yield* AppConnections;
63346
63298
  yield* relay2.changes.pipe(
63347
- map$5(relayHostname),
63299
+ map$5(appsRelayHostname),
63348
63300
  changes$1,
63349
63301
  drop(1),
63350
63302
  runForEach(() => connections.announce),
@@ -73202,17 +73154,17 @@ class RouterImpl {
73202
73154
  if (currentNode === void 0) return void 0;
73203
73155
  let querystring = "";
73204
73156
  let shouldDecodeParam = false;
73205
- let clean2 = path2.charCodeAt(0) === 47 && (path2.length === 1 || path2.charCodeAt(path2.length - 1) !== 47);
73206
- if (clean2) {
73157
+ let clean = path2.charCodeAt(0) === 47 && (path2.length === 1 || path2.charCodeAt(path2.length - 1) !== 47);
73158
+ if (clean) {
73207
73159
  for (let i = 1; i < path2.length; i++) {
73208
73160
  const code2 = path2.charCodeAt(i);
73209
73161
  if (code2 === 37 || code2 === 63 || code2 === 59 || code2 === 35 || code2 >= 65 && code2 <= 90 || code2 === 47 && path2.charCodeAt(i - 1) === 47) {
73210
- clean2 = false;
73162
+ clean = false;
73211
73163
  break;
73212
73164
  }
73213
73165
  }
73214
73166
  }
73215
- if (!clean2) {
73167
+ if (!clean) {
73216
73168
  if (path2.charCodeAt(0) !== 47) {
73217
73169
  path2 = path2.replace(FULL_PATH_REGEXP, "/");
73218
73170
  }
@@ -73233,7 +73185,7 @@ class RouterImpl {
73233
73185
  }
73234
73186
  }
73235
73187
  const originPath = path2;
73236
- if (!clean2 && this.options.caseSensitive === false) {
73188
+ if (!clean && this.options.caseSensitive === false) {
73237
73189
  path2 = path2.toLowerCase();
73238
73190
  }
73239
73191
  const maxParamLength = this.options.maxParamLength;
@@ -74651,13 +74603,13 @@ class McpServer extends (/* @__PURE__ */ Service$1()("effect/ai/McpServer")) {
74651
74603
  enqueued = true;
74652
74604
  offerUnsafe(notificationsQueue, queued);
74653
74605
  }
74654
- const acknowledge = suspend(() => notifications.write({
74606
+ const acknowledge2 = suspend(() => notifications.write({
74655
74607
  clientId: 0,
74656
74608
  requestId: message2.id,
74657
74609
  _tag: "Exit",
74658
74610
  exit: void_$1
74659
74611
  }));
74660
- return enqueued && queued.requestContext !== void 0 && notificationDelivery.consumers > 0 ? andThen(_await(delivered), acknowledge) : acknowledge;
74612
+ return enqueued && queued.requestContext !== void 0 && notificationDelivery.consumers > 0 ? andThen(_await(delivered), acknowledge2) : acknowledge2;
74661
74613
  })))
74662
74614
  });
74663
74615
  const service2 = McpServer.of({
@@ -77199,14 +77151,14 @@ function requireGracefulFs() {
77199
77151
  return close2;
77200
77152
  })(fs2.close);
77201
77153
  fs2.closeSync = (function(fs$closeSync) {
77202
- function closeSync(fd) {
77154
+ function closeSync2(fd) {
77203
77155
  fs$closeSync.apply(fs2, arguments);
77204
77156
  resetQueue();
77205
77157
  }
77206
- Object.defineProperty(closeSync, previousSymbol, {
77158
+ Object.defineProperty(closeSync2, previousSymbol, {
77207
77159
  value: fs$closeSync
77208
77160
  });
77209
- return closeSync;
77161
+ return closeSync2;
77210
77162
  })(fs2.closeSync);
77211
77163
  if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
77212
77164
  process.on("exit", function() {
@@ -80415,6 +80367,17 @@ const editPullRequestArgs = (url2, { field: field2, add: add2, remove: remove2 }
80415
80367
  ...add2.map((value2) => `${EDIT_FLAGS[field2].add}=${csvField(value2)}`),
80416
80368
  ...remove2.map((value2) => `${EDIT_FLAGS[field2].remove}=${csvField(value2)}`)
80417
80369
  ];
80370
+ const REVIEW_FLAG = {
80371
+ approve: "--approve",
80372
+ requestChanges: "--request-changes"
80373
+ };
80374
+ const reviewArgs = (url2, { verdict, body: body2 }) => [
80375
+ "pr",
80376
+ "review",
80377
+ url2,
80378
+ REVIEW_FLAG[verdict],
80379
+ ...body2.trim() === "" ? [] : ["--body", body2]
80380
+ ];
80418
80381
  const reviewCommentArgs = (url2, comment) => {
80419
80382
  const { pathname } = new URL(url2);
80420
80383
  const [, owner2, repo, , number2] = pathname.split("/");
@@ -80943,6 +80906,7 @@ const FINISHED_PULL_REQUEST_TTL = "1 hour";
80943
80906
  const FRESH_READ_WINDOW = "10 seconds";
80944
80907
  const MERGEABLE_RECHECK = "2 seconds";
80945
80908
  const MERGEABLE_RECHECKS = 5;
80909
+ const ASSET_TIMEOUT_MS = 15e3;
80946
80910
  const make$A = gen(function* () {
80947
80911
  const exec2 = makeExec(yield* ChildProcessSpawner);
80948
80912
  const events2 = yield* Events;
@@ -81148,7 +81112,7 @@ const make$A = gen(function* () {
81148
81112
  );
81149
81113
  };
81150
81114
  const reads = yield* makeWith$1(
81151
- (url2) => request$2(new PullRequestRead({ url: url2 }), pullRequestReads).pipe(
81115
+ (url2) => request$4(new PullRequestRead({ url: url2 }), pullRequestReads).pipe(
81152
81116
  tap$1((json2) => andThen(announceChange(url2, json2), recheckMergeable(url2, json2))),
81153
81117
  catchTag("GitHubRateLimitedError", (error2) => {
81154
81118
  const last = lastRead.get(url2);
@@ -81220,12 +81184,31 @@ const make$A = gen(function* () {
81220
81184
  map$2(parseGitHubRepository),
81221
81185
  orElseSucceed(() => null)
81222
81186
  );
81187
+ const token = ghUnpaused(homedir(), ["auth", "token", "--hostname", "github.com"]).pipe(
81188
+ map$2((stdout) => stdout.trim())
81189
+ );
81190
+ const assetUrl = (id2) => gen(function* () {
81191
+ const authorization = `Bearer ${yield* token}`;
81192
+ const response2 = yield* tryPromise({
81193
+ try: (signal2) => fetch(`https://github.com/user-attachments/assets/${id2}`, {
81194
+ headers: { authorization },
81195
+ redirect: "manual",
81196
+ signal: AbortSignal.any([signal2, AbortSignal.timeout(ASSET_TIMEOUT_MS)])
81197
+ }),
81198
+ catch: () => new GitHubApiError({ detail: "Cannot reach GitHub for this image" })
81199
+ });
81200
+ yield* promise$1(() => response2.body?.cancel() ?? Promise.resolve());
81201
+ if (response2.status === 404) return null;
81202
+ const signed = URL.parse(response2.headers.get("location") ?? "");
81203
+ if (signed?.protocol !== "https:")
81204
+ return yield* new GitHubApiError({ detail: `GitHub answered HTTP ${response2.status} for this image` });
81205
+ return signed.href;
81206
+ });
81223
81207
  return GitHub.of({
81224
81208
  installed: promise$1(() => findBinary("gh")).pipe(map$2((path2) => path2 !== void 0)),
81225
81209
  auth: auth2,
81226
- token: ghUnpaused(homedir(), ["auth", "token", "--hostname", "github.com"]).pipe(
81227
- map$2((stdout) => stdout.trim())
81228
- ),
81210
+ token,
81211
+ assetUrl,
81229
81212
  run: gh,
81230
81213
  pullRequest: (raw2) => map$2(read2(raw2), toPullRequest$1),
81231
81214
  issue: (raw2) => {
@@ -81267,6 +81250,7 @@ const make$A = gen(function* () {
81267
81250
  }),
81268
81251
  editPullRequest: (raw2, edit) => ghWrite(raw2, (url2) => editPullRequestArgs(url2, edit)),
81269
81252
  reviewComment: (raw2, comment) => ghWrite(raw2, (url2) => reviewCommentArgs(url2, comment)),
81253
+ review: (raw2, review) => ghWrite(raw2, (url2) => reviewArgs(url2, review)),
81270
81254
  branchPullRequest,
81271
81255
  pullRequestHead: (cwd, selector) => gh(cwd, ["pr", "view", selector, "--json", "url,number,headRefName,baseRefName,isCrossRepository"]).pipe(
81272
81256
  flatMap(decodePullRequestHead)
@@ -81765,8 +81749,8 @@ const make$x = gen(function* () {
81765
81749
  });
81766
81750
  const home = (id2) => gen(function* () {
81767
81751
  if (id2 === null) return null;
81768
- const { configDir, binary } = yield* get2(id2);
81769
- return { dir: configDir, binary };
81752
+ const { configDir, binary: binary2 } = yield* get2(id2);
81753
+ return { dir: configDir, binary: binary2 };
81770
81754
  });
81771
81755
  return AgentAccounts.of({
81772
81756
  list: findAll$1(void 0).pipe(mapError(persistence("accounts.list"))),
@@ -81778,6 +81762,20 @@ const make$x = gen(function* () {
81778
81762
  });
81779
81763
  });
81780
81764
  const layer$E = effect(AgentAccounts, make$x);
81765
+ const SKIPPED_FOLDERS = /* @__PURE__ */ new Set([".git", "node_modules"]);
81766
+ const folderFiles = async (root2, limit2) => {
81767
+ const files = [];
81768
+ const folders = [""];
81769
+ for (let folder = folders.shift(); folder !== void 0 && files.length < limit2; folder = folders.shift()) {
81770
+ const entries = await readdir(join$1(root2, folder), { withFileTypes: true }).catch(() => []);
81771
+ for (const entry of entries) {
81772
+ const path2 = folder === "" ? entry.name : `${folder}/${entry.name}`;
81773
+ if (entry.isFile()) files.push(path2);
81774
+ else if (entry.isDirectory() && !SKIPPED_FOLDERS.has(entry.name)) folders.push(path2);
81775
+ }
81776
+ }
81777
+ return files.slice(0, limit2);
81778
+ };
81781
81779
  const slugifyBranch = (text2) => text2.toLowerCase().replace(/[^a-z0-9._/-]+/g, "-").replace(/\.{2,}/g, ".").replace(/\/{2,}/g, "/").split("/").map((segment) => segment.replace(/^[-.]+|[-.]+$/g, "").replace(/\.lock$/, "")).filter((segment) => segment !== "").join("/").slice(0, 80);
81782
81780
  class Projects extends Service$1()("hinacode/Projects") {
81783
81781
  }
@@ -82009,6 +82007,8 @@ const make$w = gen(function* () {
82009
82007
  });
82010
82008
  const layer$D = effect(Projects, make$w);
82011
82009
  const MAX_SLUG_LENGTH = 40;
82010
+ const SECRETS_FOLDER = "secrets";
82011
+ const THREAD_ID_SUFFIX = /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
82012
82012
  const REMOVING_SUFFIX = ".removing";
82013
82013
  const TMP_ROOT_HASH_LENGTH = 6;
82014
82014
  const TMP_ID_LENGTH = 8;
@@ -82020,11 +82020,13 @@ class Scratch extends Service$1()("hinacode/Scratch") {
82020
82020
  }
82021
82021
  const layer$C = (root2, {
82022
82022
  tmpRoot = join$1(tmpdir(), `hc-${createHash("sha256").update(root2).digest("hex").slice(0, TMP_ROOT_HASH_LENGTH)}`),
82023
- deleteFolder = deleteTree
82023
+ deleteFolder = deleteTree,
82024
+ privatePaths = []
82024
82025
  } = {}) => effect(
82025
82026
  Scratch,
82026
82027
  gen(function* () {
82027
82028
  const fs2 = yield* FileSystem;
82029
+ const secrets = yield* Secrets;
82028
82030
  const namesIn2 = (folder) => fs2.exists(folder).pipe(flatMap((exists2) => exists2 ? fs2.readDirectory(folder) : succeed$2([])));
82029
82031
  const names2 = namesIn2(root2);
82030
82032
  const find = (threadId) => names2.pipe(map$2((all2) => all2.find((name) => name.endsWith(`-${threadId}`))));
@@ -82056,8 +82058,27 @@ const layer$C = (root2, {
82056
82058
  ),
82057
82059
  ignore$1
82058
82060
  );
82061
+ const threadFolders = names2.pipe(map$2((all2) => all2.filter((name) => !name.endsWith(REMOVING_SUFFIX))));
82062
+ const adoptSecretsIn = (folder) => gen(function* () {
82063
+ const threadId = THREAD_ID_SUFFIX.exec(folder)?.[1];
82064
+ const secretsFolder = join$1(root2, folder, SECRETS_FOLDER);
82065
+ if (threadId === void 0 || !(yield* fs2.exists(secretsFolder))) return;
82066
+ for (const name of yield* fs2.readDirectory(secretsFolder)) {
82067
+ const key2 = `${threadSecretPrefix(threadId)}${name}`;
82068
+ if (yield* secrets.has(key2)) continue;
82069
+ yield* secrets.set(key2, yield* fs2.readFileString(join$1(secretsFolder, name)));
82070
+ }
82071
+ });
82072
+ const deleteSecretsIn = (folder) => adoptSecretsIn(folder).pipe(
82073
+ andThen(fs2.remove(join$1(root2, folder, SECRETS_FOLDER), { recursive: true, force: true })),
82074
+ catchCause((cause) => logWarning("thread secrets removal failed", folder, cause))
82075
+ );
82059
82076
  yield* deleteLeftovers(root2);
82060
82077
  if (yield* ownsTmpRoot) yield* deleteLeftovers(tmpRoot);
82078
+ yield* threadFolders.pipe(
82079
+ flatMap((all2) => forEach(all2, deleteSecretsIn, { discard: true, concurrency: 16 })),
82080
+ ignore$1
82081
+ );
82061
82082
  const ensure = (thread2) => gen(function* () {
82062
82083
  const existing2 = yield* find(thread2.id);
82063
82084
  if (existing2 !== void 0) return join$1(root2, existing2);
@@ -82082,7 +82103,7 @@ const layer$C = (root2, {
82082
82103
  )
82083
82104
  );
82084
82105
  const writeSecret = (thread2, name, value2) => gen(function* () {
82085
- const folder = join$1(yield* ensure(thread2), "secrets");
82106
+ const folder = join$1(yield* ensure(thread2), SECRETS_FOLDER);
82086
82107
  yield* fs2.makeDirectory(folder, { recursive: true, mode: 448 });
82087
82108
  const path2 = join$1(folder, name);
82088
82109
  yield* fs2.writeFileString(path2, value2, { mode: 384 });
@@ -82096,7 +82117,20 @@ const layer$C = (root2, {
82096
82117
  if (name !== void 0) yield* moveAsideAndDelete(join$1(root2, name));
82097
82118
  yield* removeTmp(threadId);
82098
82119
  }).pipe(mapError(persistence("scratch.remove")));
82099
- return Scratch.of({ ensure, ensureTmp, writeSecret, remove: remove2, removeTmp });
82120
+ const removeSecrets = (threadId) => try_$1(() => {
82121
+ if (!fsWithoutAsar.existsSync(root2)) return;
82122
+ const name = fsWithoutAsar.readdirSync(root2).find((entry) => entry.endsWith(`-${threadId}`));
82123
+ if (name !== void 0)
82124
+ fsWithoutAsar.rmSync(join$1(root2, name, SECRETS_FOLDER), { recursive: true, force: true });
82125
+ }).pipe(catchCause((cause) => logWarning("thread secrets removal failed", threadId, cause)));
82126
+ const unreadableBy = (threadId) => threadFolders.pipe(
82127
+ map$2((all2) => [
82128
+ ...privatePaths,
82129
+ ...all2.filter((name) => !name.endsWith(`-${threadId}`)).map((name) => join$1(root2, name, "**"))
82130
+ ]),
82131
+ orElseSucceed(() => privatePaths)
82132
+ );
82133
+ return Scratch.of({ ensure, ensureTmp, writeSecret, removeSecrets, unreadableBy, remove: remove2, removeTmp });
82100
82134
  })
82101
82135
  );
82102
82136
  const indexPaths = /* @__PURE__ */ new Map();
@@ -82324,8 +82358,8 @@ class TerminalError extends TaggedError$1()("TerminalError", {
82324
82358
  message: String$1
82325
82359
  }) {
82326
82360
  }
82327
- const FLUSH_INTERVAL_MS$1 = 16;
82328
- const FLUSH_SIZE$1 = 256 * 1024;
82361
+ const FLUSH_INTERVAL_MS = 16;
82362
+ const FLUSH_SIZE = 256 * 1024;
82329
82363
  const SCROLLBACK_BYTES = 256 * 1024;
82330
82364
  const terminalShell = (platform, env, accountShell) => platform === "win32" ? { file: "powershell.exe", args: ["-NoLogo"] } : { file: env["SHELL"] || accountShell || "/bin/sh", args: ["-l"] };
82331
82365
  const loginShell = () => {
@@ -82365,8 +82399,8 @@ const make$v = gen(function* () {
82365
82399
  live.scrollback.append(data);
82366
82400
  live.pending.push(data);
82367
82401
  live.pendingSize += data.length;
82368
- if (live.pendingSize >= FLUSH_SIZE$1) flush(live);
82369
- else live.timer ??= setTimeout(() => flush(live), FLUSH_INTERVAL_MS$1);
82402
+ if (live.pendingSize >= FLUSH_SIZE) flush(live);
82403
+ else live.timer ??= setTimeout(() => flush(live), FLUSH_INTERVAL_MS);
82370
82404
  };
82371
82405
  const end2 = (live) => {
82372
82406
  live.closing = true;
@@ -82955,6 +82989,7 @@ const make$t = gen(function* () {
82955
82989
  const accounts = yield* AgentAccounts;
82956
82990
  const terminals = yield* Terminals;
82957
82991
  const scratch = yield* Scratch;
82992
+ const secrets = yield* Secrets;
82958
82993
  const events2 = yield* Events;
82959
82994
  const activeWorkspace = yield* makeActiveWorkspace;
82960
82995
  const gitContext = yield* context();
@@ -83335,8 +83370,12 @@ const make$t = gen(function* () {
83335
83370
  });
83336
83371
  const listFiles = (id2) => gen(function* () {
83337
83372
  const { cwd } = yield* activeWorkspace(id2);
83338
- const output = yield* git2.run(cwd, ["ls-files", "--cached", "--others", "--exclude-standard", "-z"]);
83339
- return output.split("\0").filter((path2) => path2 !== "").slice(0, MAX_LISTED_FILES);
83373
+ return yield* git2.run(cwd, ["ls-files", "--cached", "--others", "--exclude-standard", "-z"]).pipe(
83374
+ map$2(
83375
+ (output) => output.split("\0").filter((path2) => path2 !== "").slice(0, MAX_LISTED_FILES)
83376
+ ),
83377
+ catch_(() => promise$1(() => folderFiles(cwd, MAX_LISTED_FILES)))
83378
+ );
83340
83379
  });
83341
83380
  const changes2 = (id2, scope2) => gen(function* () {
83342
83381
  if (scope2 === "worktree") {
@@ -83431,6 +83470,7 @@ const make$t = gen(function* () {
83431
83470
  yield* detachChildren(id2);
83432
83471
  yield* syncChatFolder(thread2, false);
83433
83472
  yield* scratch.remove(id2);
83473
+ yield* secrets.clearUnder(threadSecretPrefix(id2));
83434
83474
  return some(yield* get2(id2));
83435
83475
  })
83436
83476
  );
@@ -83491,6 +83531,7 @@ const make$t = gen(function* () {
83491
83531
  yield* sql`DELETE FROM thread WHERE id = ${id2}`.pipe(mapError(persistence("threads.delete")));
83492
83532
  yield* syncChatFolder(thread2, false);
83493
83533
  yield* scratch.remove(id2);
83534
+ yield* secrets.clearUnder(threadSecretPrefix(id2));
83494
83535
  });
83495
83536
  return Threads.of({
83496
83537
  list: findAll$1(void 0).pipe(mapError(persistence("threads.list"))),
@@ -83852,9 +83893,72 @@ const layer$x = (root2, { artifactsRoot } = {}) => effect(
83852
83893
  return Attachments.of({ stage: stage(root2), read: read(root2), copyInto, prune });
83853
83894
  })
83854
83895
  );
83896
+ const decodeFrame = decodeUnknownOption(fromJsonString(ServerFrame));
83897
+ const utf8$2 = new TextDecoder("utf-8", { fatal: true });
83898
+ const bytesOf = (data) => {
83899
+ if (data instanceof Uint8Array) return data;
83900
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
83901
+ return null;
83902
+ };
83903
+ const openFrame$1 = (channel2, ciphertext) => {
83904
+ try {
83905
+ return getOrNull(decodeFrame(utf8$2.decode(channel2.decrypt(ciphertext))));
83906
+ } catch {
83907
+ return null;
83908
+ }
83909
+ };
83910
+ const clientSession = (input) => {
83911
+ const initiator = initiate({
83912
+ prologue: REMOTE_PROLOGUE,
83913
+ local: input.device,
83914
+ remoteStatic: input.hostKey,
83915
+ payload: new Uint8Array(0)
83916
+ });
83917
+ let channel2 = null;
83918
+ let approval = null;
83919
+ let revealed = false;
83920
+ const send2 = (frame2) => {
83921
+ if (channel2 === null) throw new Error("No frame can be sent before the handshake");
83922
+ input.send(channel2.encrypt(utf8ToBytes(JSON.stringify(frame2))));
83923
+ };
83924
+ const finish = (reply2) => {
83925
+ try {
83926
+ channel2 = initiator.finish(reply2).channel;
83927
+ } catch {
83928
+ return { type: "refused" };
83929
+ }
83930
+ send2({ type: "hello", ...input.hello });
83931
+ return { type: "handshaken" };
83932
+ };
83933
+ const reveal = (secured, serverNonce) => {
83934
+ if (approval === null || revealed) return { type: "broken" };
83935
+ revealed = true;
83936
+ if (!equalBytes(commitment(serverNonce), approval.committed)) return { type: "refused" };
83937
+ return { type: "code", code: approvalCode(secured.handshakeHash, approval.clientNonce, serverNonce) };
83938
+ };
83939
+ const receive = (data) => {
83940
+ const bytes2 = bytesOf(data);
83941
+ if (bytes2 === null) return channel2 === null ? { type: "ignored" } : { type: "broken" };
83942
+ if (channel2 === null) return finish(bytes2);
83943
+ const frame2 = openFrame$1(channel2, bytes2);
83944
+ if (frame2 === null) return { type: "broken" };
83945
+ if (frame2.type === "approval") return reveal(channel2, hexToBytes(frame2.nonce));
83946
+ if (frame2.type !== "pending") return { type: "frame", frame: frame2 };
83947
+ if (approval !== null) return { type: "broken" };
83948
+ approval = { committed: hexToBytes(frame2.commitment), clientNonce: newNonce$1() };
83949
+ send2({ type: "approval", nonce: bytesToHex(approval.clientNonce) });
83950
+ return { type: "pending" };
83951
+ };
83952
+ return {
83953
+ start: () => input.send(initiator.message),
83954
+ receive,
83955
+ send: send2,
83956
+ handshaken: () => channel2 !== null
83957
+ };
83958
+ };
83855
83959
  const planRelaySync = (entries, machines, selfId) => {
83856
83960
  const upsert = machines.filter(
83857
- (machine) => machine.environmentId !== selfId && parsePairingUrl(pairingUrl(machine.pairing)) !== null
83961
+ (machine) => machine.environmentId !== selfId && parsePairingUrl(pairingUrl({ ...machine.pairing, secret: null })) !== null
83858
83962
  );
83859
83963
  const listed = new Set(upsert.map((machine) => machine.environmentId));
83860
83964
  const drop2 = entries.filter(
@@ -83991,10 +84095,7 @@ const unreachableMessage = (target, code2, reason) => {
83991
84095
  return `Could not reach ${host}:${port}: ${reason}`;
83992
84096
  }
83993
84097
  };
83994
- const CLOSE_UNAUTHORIZED = 4001;
83995
- const CLOSE_TOKEN_ROTATED = 4002;
83996
84098
  const OFFLINE_LIMIT_MS = 6e4;
83997
- decodeUnknownOption(ServerFrame);
83998
84099
  class InvalidPairingUrl extends TaggedError$1()("InvalidPairingUrl", {
83999
84100
  message: String$1
84000
84101
  }) {
@@ -84009,7 +84110,9 @@ class EnvironmentUnauthorized extends TaggedError$1()("EnvironmentUnauthorized",
84009
84110
  }
84010
84111
  class Environments extends Service$1()("hinacode/Environments") {
84011
84112
  }
84012
- const tokenSecret = (id2) => `environment.${id2}.token`;
84113
+ const pairingSecret = (id2) => `environment.${id2}.token`;
84114
+ const DEVICE_KEY_SECRET = "remote.deviceKey";
84115
+ const DEVICE_NAME_MAX = 64;
84013
84116
  const GATHER_TIMEOUT = "3 seconds";
84014
84117
  const READY_TIMEOUT_MS = 1e4;
84015
84118
  const PING_INTERVAL = "10 seconds";
@@ -84017,11 +84120,24 @@ const SILENCE_LIMIT_MS = 25e3;
84017
84120
  const STABLE_MS = 6e4;
84018
84121
  const PREFER_EARLIER_HOST_MS = 1e3;
84019
84122
  const reconnectDelay = (attempt2) => Math.min(500 * 2 ** attempt2, 6e4) * (0.7 + Math.random() * 0.6);
84123
+ const deviceName = () => hostname().slice(0, DEVICE_NAME_MAX) || "HinaCode";
84020
84124
  const offline = (name) => ({
84021
84125
  error: { tag: "EnvironmentOffline", message: `${name} is offline` }
84022
84126
  });
84023
- const unauthorized = (name) => ({
84024
- error: { tag: "EnvironmentUnauthorized", message: `${name} refused this desktop's token. Pair it again.` }
84127
+ const refusalMessage = (name, refusal) => {
84128
+ switch (refusal) {
84129
+ case "refused":
84130
+ return `${name} did not accept this device. If you reset its pairing, pair again from its QR code.`;
84131
+ case "removed":
84132
+ return `${name} no longer accepts this device. Pair it again.`;
84133
+ case "reset":
84134
+ return `${name} reset its pairing. Pair it again.`;
84135
+ case "predates":
84136
+ return `Pair ${name} again: this pairing predates encryption.`;
84137
+ }
84138
+ };
84139
+ const unauthorized = (name, refusal) => ({
84140
+ error: { tag: "EnvironmentUnauthorized", message: refusalMessage(name, refusal) }
84025
84141
  });
84026
84142
  const incompatible = (name) => ({
84027
84143
  error: { tag: "EnvironmentIncompatible", message: `${name} runs a hinacode this desktop cannot talk to` }
@@ -84036,64 +84152,47 @@ const unknownEnvironment = (id2) => ({
84036
84152
  const notAnswering = {
84037
84153
  error: { tag: "NotReady", message: "The desktop is still starting." }
84038
84154
  };
84039
- const decodeServerFrame = decodeUnknownOption(ServerFrame);
84040
- const parseFrame$1 = (raw2, isBinary) => {
84041
- if (isBinary) return void 0;
84042
- try {
84043
- return getOrUndefined$1(decodeServerFrame(JSON.parse(String(raw2))));
84044
- } catch {
84045
- return void 0;
84046
- }
84047
- };
84048
- const dial = (url2, token, plainToken, handlers2) => map$2(context(), (services) => {
84155
+ const binary = (raw2) => Array.isArray(raw2) ? Buffer.concat(raw2) : raw2;
84156
+ const dial = (url2, credentials, handlers2) => {
84049
84157
  const socket = new WebSocket$1(url2);
84050
- let expected;
84051
- let authenticated = false;
84052
84158
  let refused = false;
84053
- let waiting;
84054
- const authenticate = (frame2) => socket.send(JSON.stringify(frame2));
84055
- const refuse2 = () => {
84056
- refused = true;
84057
- socket.terminate();
84058
- };
84059
- socket.on("open", () => {
84060
- waiting = runForkWith(services)(
84061
- sleep$3(CHALLENGE_WAIT_MS).pipe(
84062
- andThen(
84063
- sync(() => {
84064
- if (expected !== void 0) return;
84065
- if (!plainToken) return refuse2();
84066
- expected = null;
84067
- authenticate({ type: "auth", token });
84068
- })
84069
- )
84070
- )
84071
- );
84159
+ const session = clientSession({
84160
+ ...credentials,
84161
+ send: (data) => {
84162
+ if (socket.readyState === WebSocket$1.OPEN) socket.send(data);
84163
+ }
84072
84164
  });
84165
+ socket.on("open", () => session.start());
84073
84166
  socket.on("message", (raw2, isBinary) => {
84074
- const frame2 = parseFrame$1(raw2, isBinary);
84075
- if (frame2 === void 0) return handlers2.onUndecodable?.();
84076
- if (authenticated) return handlers2.onFrame(frame2);
84077
- if (frame2.type === "challenge") {
84078
- if (expected !== void 0) return;
84079
- waiting?.interruptUnsafe();
84080
- const nonce = newNonce();
84081
- expected = serverProof(token, nonce, frame2.nonce);
84082
- return authenticate({ type: "auth", nonce, proof: clientProof(token, frame2.nonce, nonce) });
84083
- }
84084
- if (frame2.type !== "ready") return;
84085
- if (expected === void 0 || expected !== null && frame2.proof !== expected) return refuse2();
84086
- authenticated = true;
84087
- handlers2.onFrame(frame2);
84167
+ const received = session.receive(isBinary ? binary(raw2) : String(raw2));
84168
+ switch (received.type) {
84169
+ case "pending":
84170
+ return handlers2.onPending?.();
84171
+ case "code":
84172
+ return handlers2.onCode?.(received.code);
84173
+ case "frame":
84174
+ return handlers2.onFrame(received.frame);
84175
+ case "refused":
84176
+ refused = true;
84177
+ return socket.terminate();
84178
+ case "broken":
84179
+ handlers2.onBroken?.();
84180
+ return socket.terminate();
84181
+ }
84088
84182
  });
84089
84183
  socket.on("pong", () => handlers2.onPong?.());
84090
84184
  socket.on("error", (error2) => handlers2.onError?.(error2));
84091
- socket.on("close", (code2) => {
84092
- waiting?.interruptUnsafe();
84093
- handlers2.onClose(refused ? CLOSE_UNAUTHORIZED : code2);
84094
- });
84095
- return socket;
84096
- });
84185
+ socket.on(
84186
+ "close",
84187
+ (code2) => handlers2.onClose({ code: code2, handshaken: session.handshaken(), refused: refused || code2 === CLOSE_HANDSHAKE_FAILED })
84188
+ );
84189
+ return {
84190
+ socket,
84191
+ send: (frame2) => {
84192
+ if (socket.readyState === WebSocket$1.OPEN && session.handshaken()) session.send(frame2);
84193
+ }
84194
+ };
84195
+ };
84097
84196
  const opens = (url2) => callback((resume) => {
84098
84197
  const socket = new WebSocket$1(url2);
84099
84198
  socket.on("open", () => {
@@ -84126,46 +84225,53 @@ const firstToOpen = (dials, timeoutMs) => gen(function* () {
84126
84225
  timeoutOrElse({ duration: timeoutMs, orElse: () => succeed$2(null) })
84127
84226
  );
84128
84227
  }).pipe(scoped);
84129
- const directAnswers = (direct) => sleep$3(DIRECT_CHECK_INTERVAL_MS).pipe(
84130
- andThen(firstToOpen(direct, DIRECT_CHECK_TIMEOUT_MS)),
84131
- flatMap((opened) => opened === null ? directAnswers(direct) : void_)
84228
+ const directAnswers = (direct, waitingForApproval) => sleep$3(DIRECT_CHECK_INTERVAL_MS).pipe(
84229
+ andThen(
84230
+ suspend(
84231
+ () => waitingForApproval() ? succeed$2(null) : firstToOpen(direct, DIRECT_CHECK_TIMEOUT_MS)
84232
+ )
84233
+ ),
84234
+ flatMap((opened) => opened === null ? directAnswers(direct, waitingForApproval) : void_)
84132
84235
  );
84133
- const probe = (target, token, plainToken) => {
84236
+ const probe = (target, credentials) => {
84134
84237
  const where = "relay" in target ? target.relay : `${target.host}:${target.port}`;
84135
84238
  const url2 = "relay" in target ? relayWebSocketUrl(target.relay) : remoteWebSocketUrl(target);
84136
84239
  return gen(function* () {
84137
84240
  const answered = yield* make$1v();
84138
84241
  let reason = "the connection closed";
84139
84242
  let errorCode2;
84140
- const socket = yield* acquireRelease(
84141
- dial(url2, token, plainToken, {
84142
- onFrame: (frame2) => {
84143
- if (frame2.type !== "ready") return;
84144
- doneUnsafe(answered, succeed$2(frame2));
84145
- socket.close();
84146
- },
84147
- onError: (error2) => {
84148
- reason = error2.message || reason;
84149
- errorCode2 = "code" in error2 && typeof error2.code === "string" ? error2.code : void 0;
84150
- },
84151
- onClose: (code2) => {
84152
- if (code2 === CLOSE_UNAUTHORIZED || code2 === CLOSE_TOKEN_ROTATED) {
84153
- return doneUnsafe(
84243
+ const link = yield* acquireRelease(
84244
+ sync(
84245
+ () => dial(url2, credentials, {
84246
+ onPending: () => {
84247
+ doneUnsafe(answered, succeed$2({ pending: true }));
84248
+ link.socket.close();
84249
+ },
84250
+ onFrame: (frame2) => {
84251
+ if (frame2.type !== "ready") return;
84252
+ doneUnsafe(answered, succeed$2({ ready: frame2 }));
84253
+ link.socket.close();
84254
+ },
84255
+ onError: (error2) => {
84256
+ reason = error2.message || reason;
84257
+ errorCode2 = "code" in error2 && typeof error2.code === "string" ? error2.code : void 0;
84258
+ },
84259
+ onClose: (end2) => {
84260
+ const refusal = refusalOf(end2, false);
84261
+ if (refusal !== null) {
84262
+ return doneUnsafe(
84263
+ answered,
84264
+ fail$2(new EnvironmentUnauthorized({ message: refusalMessage(where, refusal) }))
84265
+ );
84266
+ }
84267
+ doneUnsafe(
84154
84268
  answered,
84155
- fail$2(
84156
- new EnvironmentUnauthorized({
84157
- message: `${where} refused the token. Copy a new pairing URL from hinacode serve.`
84158
- })
84159
- )
84269
+ fail$2(new EnvironmentUnreachable({ message: unreachableMessage(target, errorCode2, reason) }))
84160
84270
  );
84161
84271
  }
84162
- doneUnsafe(
84163
- answered,
84164
- fail$2(new EnvironmentUnreachable({ message: unreachableMessage(target, errorCode2, reason) }))
84165
- );
84166
- }
84167
- }),
84168
- (opened) => sync(() => opened.terminate())
84272
+ })
84273
+ ),
84274
+ (opened) => sync(() => opened.socket.terminate())
84169
84275
  );
84170
84276
  return yield* _await(answered);
84171
84277
  }).pipe(
@@ -84180,7 +84286,13 @@ const probe = (target, token, plainToken) => {
84180
84286
  })
84181
84287
  );
84182
84288
  };
84183
- const probeHosts = (pairing) => gen(function* () {
84289
+ const refusalOf = (end2, ready) => {
84290
+ if (end2.refused) return "refused";
84291
+ if (end2.code === CLOSE_PAIRING_RESET) return "reset";
84292
+ if (end2.code === CLOSE_UNAUTHORIZED) return ready ? "removed" : "refused";
84293
+ return null;
84294
+ };
84295
+ const probeHosts = (pairing, credentials) => gen(function* () {
84184
84296
  const answers = [];
84185
84297
  const graceOver = yield* make$1v();
84186
84298
  let graceStarted = false;
@@ -84191,11 +84303,11 @@ const probeHosts = (pairing) => gen(function* () {
84191
84303
  sleep$3(PREFER_EARLIER_HOST_MS).pipe(andThen(succeed$3(graceOver, void 0)))
84192
84304
  );
84193
84305
  });
84194
- let relayReady;
84306
+ let relayAnswer;
84195
84307
  const relayProbe = pairing.relay === null ? null : yield* forkScoped(
84196
- probe({ relay: pairing.relay }, pairing.token, true).pipe(
84197
- tap$1((ready) => {
84198
- relayReady = ready;
84308
+ probe({ relay: pairing.relay }, credentials).pipe(
84309
+ tap$1((answer) => {
84310
+ relayAnswer = answer;
84199
84311
  return startGrace;
84200
84312
  }),
84201
84313
  result$1
@@ -84204,9 +84316,9 @@ const probeHosts = (pairing) => gen(function* () {
84204
84316
  const probes = yield* forEach(
84205
84317
  pairing.hosts,
84206
84318
  (host, index) => forkScoped(
84207
- probe({ host, port: pairing.port }, pairing.token, pairing.relay === null).pipe(
84208
- tap$1((ready) => {
84209
- answers[index] = ready;
84319
+ probe({ host, port: pairing.port }, credentials).pipe(
84320
+ tap$1((answer) => {
84321
+ answers[index] = answer;
84210
84322
  return startGrace;
84211
84323
  }),
84212
84324
  result$1
@@ -84219,26 +84331,41 @@ const probeHosts = (pairing) => gen(function* () {
84219
84331
  if (outcome === null || outcome._tag === "Success") break;
84220
84332
  failures.push(outcome.failure);
84221
84333
  }
84222
- const won = answers.findIndex((ready) => ready !== void 0);
84223
- if (won !== -1) return { host: pairing.hosts[won], ready: answers[won] };
84224
- if (relayProbe !== null && relayReady === void 0) {
84334
+ const all2 = [...answers, relayAnswer];
84335
+ const usedSecret = all2.some((answer) => answer !== void 0 && "ready" in answer);
84336
+ const won = answers.findIndex((answer) => answer !== void 0);
84337
+ if (won !== -1) return { host: pairing.hosts[won], answer: answers[won], usedSecret };
84338
+ if (relayProbe !== null && relayAnswer === void 0) {
84225
84339
  const outcome = yield* join$2(relayProbe);
84226
84340
  if (outcome._tag === "Failure") failures.push(outcome.failure);
84227
84341
  }
84228
- if (relayReady !== void 0) return { host: pairing.hosts[0], ready: relayReady };
84342
+ if (relayAnswer !== void 0) {
84343
+ return { host: pairing.hosts[0], answer: relayAnswer, usedSecret: usedSecret || "ready" in relayAnswer };
84344
+ }
84229
84345
  return yield* fail$2(failures.find((error2) => error2._tag === "EnvironmentUnauthorized") ?? failures[0]);
84230
84346
  }).pipe(scoped);
84231
- const sendFrame = (socket, frame2) => {
84232
- if (socket.readyState === WebSocket$1.OPEN) socket.send(JSON.stringify(frame2));
84233
- };
84234
- const send$1 = (live, call2) => {
84347
+ const StoredEnvironment = Struct({
84348
+ ...Environment.fields,
84349
+ hostKey: NullOr(String$1),
84350
+ verified: BooleanFromBit
84351
+ });
84352
+ const environmentOf = ({ hostKey: _hostKey, verified: _verified, ...environment2 }) => environment2;
84353
+ const send = (live, call2) => {
84235
84354
  const key2 = live.dedupesCalls ? call2.key : void 0;
84236
84355
  call2.sent = true;
84237
84356
  call2.sentWithoutDedupe = call2.key !== void 0 && key2 === void 0;
84238
84357
  const frame2 = { type: "call", id: call2.id, method: call2.method, payload: call2.payload };
84239
- live.socket.send(JSON.stringify(key2 === void 0 ? frame2 : { ...frame2, key: key2 }));
84358
+ live.link.send(key2 === void 0 ? frame2 : { ...frame2, key: key2 });
84240
84359
  };
84241
84360
  const environmentDialPlan = ({ host, port, relay: relay2 }) => dialPlan({ hosts: [host], port, relay: relay2 });
84361
+ const loadDeviceKey = gen(function* () {
84362
+ const secrets = yield* Secrets;
84363
+ const stored = getOrNull(yield* secrets.get(DEVICE_KEY_SECRET));
84364
+ if (stored !== null) return keyPairFromSecret(Buffer.from(stored, "base64url"));
84365
+ const device = generateKeyPair();
84366
+ yield* secrets.set(DEVICE_KEY_SECRET, Buffer.from(device.secretKey).toString("base64url"));
84367
+ return device;
84368
+ });
84242
84369
  const make$r = gen(function* () {
84243
84370
  const sql = yield* SqlClient;
84244
84371
  const secrets = yield* Secrets;
@@ -84246,9 +84373,11 @@ const make$r = gen(function* () {
84246
84373
  const windows = yield* WindowPush;
84247
84374
  const self2 = (yield* RemoteAccess).identity;
84248
84375
  const clock = yield* Clock;
84376
+ const device = yield* loadDeviceKey;
84249
84377
  const runFork2 = runForkWith(yield* context());
84250
84378
  const owners = makeOwners();
84251
84379
  const clouds = /* @__PURE__ */ new Map();
84380
+ const relayMachines = /* @__PURE__ */ new Map();
84252
84381
  let nextCallId2 = 1;
84253
84382
  let answer = () => succeed$2(notAnswering);
84254
84383
  let hooks = { pushed: () => void_, answered: () => void_, offlineMutation: () => void_ };
@@ -84256,17 +84385,22 @@ const make$r = gen(function* () {
84256
84385
  const nowIso2 = () => new Date(now2()).toISOString();
84257
84386
  const findAll$1 = findAll({
84258
84387
  Request: Void,
84259
- Result: Environment,
84260
- execute: () => sql`SELECT id, name, host, port, relay, source, created_at FROM environment ORDER BY created_at`
84388
+ Result: StoredEnvironment,
84389
+ execute: () => sql`SELECT id, name, host, port, relay, source, created_at, host_key, verified FROM environment ORDER BY created_at`
84261
84390
  });
84262
84391
  const findOne2 = findOneOption({
84263
84392
  Request: String$1,
84264
- Result: Environment,
84265
- execute: (id2) => sql`SELECT id, name, host, port, relay, source, created_at FROM environment WHERE id = ${id2}`
84393
+ Result: StoredEnvironment,
84394
+ execute: (id2) => sql`SELECT id, name, host, port, relay, source, created_at, host_key, verified FROM environment WHERE id = ${id2}`
84266
84395
  });
84267
- const setStatus2 = (cloud, status) => suspend(() => {
84268
- if (cloud.status === status) return void_;
84396
+ const setStatus2 = (cloud, status, detail = {}) => suspend(() => {
84397
+ const approval = detail.approval ?? null;
84398
+ const refusal = detail.refusal ?? null;
84399
+ const same = cloud.status === status && cloud.refusal === refusal && cloud.approval?.code === approval?.code && cloud.approval?.accepted === approval?.accepted;
84269
84400
  cloud.status = status;
84401
+ cloud.approval = approval;
84402
+ cloud.refusal = refusal;
84403
+ if (same) return void_;
84270
84404
  return events2.publish({ type: "environment.status", id: cloud.environment.id, status });
84271
84405
  });
84272
84406
  const pauseOfflineTimer = (call2) => {
@@ -84303,7 +84437,7 @@ const make$r = gen(function* () {
84303
84437
  for (const call2 of cloud.outbox.values()) settle2(cloud, call2, envelope2);
84304
84438
  };
84305
84439
  const disconnect = (cloud, socket) => {
84306
- if (cloud.live?.socket !== socket) return;
84440
+ if (cloud.live?.link.socket !== socket) return;
84307
84441
  cloud.live = null;
84308
84442
  const { name } = cloud.environment;
84309
84443
  for (const call2 of cloud.outbox.values()) {
@@ -84324,113 +84458,178 @@ const make$r = gen(function* () {
84324
84458
  )
84325
84459
  );
84326
84460
  };
84327
- const session = (cloud, token, url2, plainToken, viaRelay) => gen(function* () {
84461
+ const markVerified = (cloud) => sql`UPDATE environment SET verified = 1 WHERE id = ${cloud.environment.id}`.pipe(
84462
+ mapError(persistence("environments.confirmHost")),
84463
+ andThen(
84464
+ sync(() => {
84465
+ cloud.verified = true;
84466
+ })
84467
+ )
84468
+ );
84469
+ const session = (cloud, credentials, url2, viaRelay) => gen(function* () {
84328
84470
  const { id: id2, name } = cloud.environment;
84329
84471
  const closed = yield* make$1v();
84330
84472
  let connectedAt = null;
84331
84473
  let otherProtocol = null;
84474
+ let awaitingApproval = false;
84475
+ let code2 = null;
84476
+ let declined = false;
84477
+ let stalled = false;
84332
84478
  let heardAt = now2();
84333
84479
  const heard = () => {
84334
84480
  heardAt = now2();
84335
84481
  cloud.lastSeenAt = new Date(heardAt).toISOString();
84336
84482
  };
84337
- const socket = yield* acquireRelease(
84338
- dial(url2, token, plainToken, {
84339
- onFrame: (frame2) => {
84340
- heard();
84341
- switch (frame2.type) {
84342
- case "ready": {
84343
- if (frame2.version !== REMOTE_PROTOCOL_VERSION) {
84344
- otherProtocol = frame2.version;
84345
- return socket.close();
84346
- }
84347
- connectedAt = now2();
84348
- cloud.protocol = null;
84349
- learnRelay(cloud, frame2.relay ?? (viaRelay ? cloud.environment.relay : null));
84350
- const live = { socket, dedupesCalls: frame2.features?.includes("call-keys") ?? false };
84351
- cloud.live = live;
84352
- if (frame2.features?.includes("asks")) sendFrame(socket, { type: "hub" });
84353
- for (const call2 of cloud.outbox.values()) {
84354
- pauseOfflineTimer(call2);
84355
- if (call2.priorOfflineMs >= OFFLINE_LIMIT_MS) expire(cloud, call2);
84356
- else send$1(live, call2);
84483
+ const goLive = (frame2) => {
84484
+ if (link.socket.readyState !== WebSocket$1.OPEN) return;
84485
+ connectedAt = now2();
84486
+ cloud.protocol = null;
84487
+ learnRelay(cloud, frame2.relay ?? (viaRelay ? cloud.environment.relay : null));
84488
+ const live = { link, dedupesCalls: frame2.features?.includes("call-keys") ?? false };
84489
+ cloud.live = live;
84490
+ if (frame2.features?.includes("asks")) link.send({ type: "hub" });
84491
+ for (const call2 of cloud.outbox.values()) {
84492
+ pauseOfflineTimer(call2);
84493
+ if (call2.priorOfflineMs >= OFFLINE_LIMIT_MS) expire(cloud, call2);
84494
+ else send(live, call2);
84495
+ }
84496
+ runFork2(setStatus2(cloud, "connected"));
84497
+ };
84498
+ const ready = (frame2) => {
84499
+ if (frame2.version !== REMOTE_PROTOCOL_VERSION) {
84500
+ otherProtocol = frame2.version;
84501
+ return link.socket.close();
84502
+ }
84503
+ if (credentials.hello.secret !== void 0) {
84504
+ runFork2(
84505
+ secrets.clear(pairingSecret(id2)).pipe(catchCause((cause) => logWarning("could not drop a used pairing secret", cause)))
84506
+ );
84507
+ }
84508
+ if (cloud.verified) return goLive(frame2);
84509
+ if (code2 === null) {
84510
+ declined = true;
84511
+ return link.socket.close();
84512
+ }
84513
+ cloud.answerHost = (accepted) => suspend(() => {
84514
+ cloud.answerHost = null;
84515
+ if (!accepted) {
84516
+ declined = true;
84517
+ return sync(() => link.socket.close());
84518
+ }
84519
+ return markVerified(cloud).pipe(andThen(sync(() => goLive(frame2))));
84520
+ });
84521
+ runFork2(setStatus2(cloud, "approval", { approval: { code: code2, accepted: true } }));
84522
+ };
84523
+ const link = yield* acquireRelease(
84524
+ sync(
84525
+ () => dial(url2, credentials, {
84526
+ onPending: () => {
84527
+ heard();
84528
+ awaitingApproval = true;
84529
+ },
84530
+ onCode: (shown2) => {
84531
+ heard();
84532
+ code2 = shown2;
84533
+ runFork2(setStatus2(cloud, "approval", { approval: { code: shown2, accepted: false } }));
84534
+ },
84535
+ onFrame: (frame2) => {
84536
+ heard();
84537
+ if (frame2.type !== "ready" && cloud.live?.link !== link) return;
84538
+ switch (frame2.type) {
84539
+ case "ready":
84540
+ return ready(frame2);
84541
+ case "result": {
84542
+ const call2 = cloud.outbox.get(frame2.id);
84543
+ if (call2 === void 0) return;
84544
+ return settle2(
84545
+ cloud,
84546
+ call2,
84547
+ "error" in frame2.envelope ? frame2.envelope : { result: frame2.envelope.result }
84548
+ );
84357
84549
  }
84358
- return runFork2(setStatus2(cloud, "connected"));
84359
- }
84360
- case "result": {
84361
- const call2 = cloud.outbox.get(frame2.id);
84362
- if (call2 === void 0) return;
84363
- return settle2(
84364
- cloud,
84365
- call2,
84366
- "error" in frame2.envelope ? frame2.envelope : { result: frame2.envelope.result }
84367
- );
84550
+ case "event":
84551
+ learnFromPush(owners, id2, frame2.event);
84552
+ runFork2(hooks.pushed(id2, frame2.event));
84553
+ return runFork2(windows.send(stampPush(frame2.event, id2)));
84554
+ case "ask":
84555
+ return runFork2(
84556
+ answer({ method: frame2.method, payload: frame2.payload }).pipe(
84557
+ map$2((envelope2) => link.send({ type: "answer", id: frame2.id, envelope: envelope2 }))
84558
+ )
84559
+ );
84560
+ default:
84561
+ return;
84368
84562
  }
84369
- case "event":
84370
- learnFromPush(owners, id2, frame2.event);
84371
- runFork2(hooks.pushed(id2, frame2.event));
84372
- return runFork2(windows.send(stampPush(frame2.event, id2)));
84373
- case "pong":
84374
- return;
84375
- case "ask":
84376
- return runFork2(
84377
- answer({ method: frame2.method, payload: frame2.payload }).pipe(
84378
- map$2((envelope2) => sendFrame(socket, { type: "answer", id: frame2.id, envelope: envelope2 }))
84379
- )
84380
- );
84563
+ },
84564
+ onBroken: () => runFork2(logWarning("closed a link whose frame did not decrypt", name)),
84565
+ onPong: heard,
84566
+ onClose: (end22) => {
84567
+ cloud.answerHost = null;
84568
+ disconnect(cloud, link.socket);
84569
+ doneUnsafe(closed, succeed$2(end22));
84381
84570
  }
84382
- },
84383
- onUndecodable: () => runFork2(logWarning("dropped an undecodable frame", name)),
84384
- onPong: heard,
84385
- onClose: (code22) => {
84386
- disconnect(cloud, socket);
84387
- doneUnsafe(closed, succeed$2(code22));
84388
- }
84389
- }),
84571
+ })
84572
+ ),
84390
84573
  (opened) => sync(() => {
84391
- disconnect(cloud, opened);
84392
- opened.terminate();
84574
+ cloud.answerHost = null;
84575
+ disconnect(cloud, opened.socket);
84576
+ opened.socket.terminate();
84393
84577
  })
84394
84578
  );
84395
84579
  yield* forkScoped(
84396
84580
  sleep$3(READY_TIMEOUT_MS).pipe(
84397
84581
  andThen(
84398
84582
  sync(() => {
84399
- if (connectedAt === null) socket.terminate();
84583
+ if (connectedAt !== null || awaitingApproval) return;
84584
+ stalled = true;
84585
+ link.socket.terminate();
84400
84586
  })
84401
84587
  )
84402
84588
  )
84403
84589
  );
84404
84590
  yield* forkScoped(
84405
84591
  sync(() => {
84406
- if (connectedAt !== null && socket.readyState === WebSocket$1.OPEN) socket.ping();
84592
+ if (link.socket.readyState === WebSocket$1.OPEN) link.socket.ping();
84407
84593
  }).pipe(repeat(spaced(PING_INTERVAL)))
84408
84594
  );
84409
84595
  const dropWhenSilent = suspend(() => {
84410
84596
  const left = heardAt + SILENCE_LIMIT_MS - now2();
84411
- if (left <= 0) return sync(() => socket.terminate());
84597
+ if (left <= 0) return sync(() => link.socket.terminate());
84412
84598
  return sleep$3(left).pipe(andThen(dropWhenSilent));
84413
84599
  });
84414
84600
  yield* forkScoped(dropWhenSilent);
84415
- const code2 = yield* _await(closed);
84601
+ const end2 = yield* _await(closed);
84416
84602
  return {
84417
- code: code2,
84603
+ link: end2,
84418
84604
  ready: connectedAt !== null,
84605
+ stalled,
84606
+ declined,
84419
84607
  otherProtocol,
84420
84608
  connectedMs: connectedAt === null ? 0 : now2() - connectedAt
84421
84609
  };
84422
84610
  }).pipe(scoped);
84611
+ const refuse2 = (cloud, refusal) => {
84612
+ failAll(cloud, unauthorized(cloud.environment.name, refusal));
84613
+ return setStatus2(cloud, "unauthorized", { refusal });
84614
+ };
84423
84615
  const maintain = (cloud) => gen(function* () {
84424
- const { name } = cloud.environment;
84425
- const token = getOrNull(yield* secrets.get(tokenSecret(cloud.environment.id)));
84426
- if (token === null) {
84427
- failAll(cloud, unauthorized(name));
84428
- return yield* setStatus2(cloud, "unauthorized");
84429
- }
84616
+ const { id: id2 } = cloud.environment;
84617
+ const hostKey = cloud.hostKey === null ? null : decodeKey(cloud.hostKey);
84618
+ if (hostKey === null) return yield* refuse2(cloud, "predates");
84430
84619
  yield* setStatus2(cloud, "connecting");
84431
84620
  let attempt2 = 0;
84432
84621
  let round = "both";
84433
84622
  for (; ; ) {
84623
+ const secret = getOrNull(yield* secrets.get(pairingSecret(id2)));
84624
+ const credentials = {
84625
+ hostKey,
84626
+ device,
84627
+ hello: {
84628
+ name: deviceName(),
84629
+ ...secret !== null && { secret },
84630
+ ...!cloud.verified && { verify: true }
84631
+ }
84632
+ };
84434
84633
  const plan = environmentDialPlan(cloud.environment);
84435
84634
  const dials = round === "both" ? plan : plan.filter((planned) => planned.route === round);
84436
84635
  const won = yield* firstToOpen(dials, READY_TIMEOUT_MS);
@@ -84443,25 +84642,26 @@ const make$r = gen(function* () {
84443
84642
  } else {
84444
84643
  const direct = plan.filter((planned) => planned.route === "direct");
84445
84644
  const hasRelay = plan.some((planned) => planned.route === "relay");
84446
- const opened = session(cloud, token, won.url, won.route === "relay" || !hasRelay, won.route === "relay");
84447
- const end2 = won.route === "relay" && round === "both" && direct.length > 0 ? yield* raceFirst(opened, directAnswers(direct).pipe(as(null))) : yield* opened;
84645
+ const opened = session(cloud, credentials, won.url, won.route === "relay");
84646
+ const end2 = won.route === "relay" && round === "both" && direct.length > 0 ? yield* raceFirst(
84647
+ opened,
84648
+ directAnswers(direct, () => cloud.status === "approval").pipe(as(null))
84649
+ ) : yield* opened;
84448
84650
  if (end2 === null) {
84449
84651
  round = "direct";
84450
84652
  continue;
84451
84653
  }
84452
- if (!end2.ready && won.route === "direct" && hasRelay) {
84654
+ if ((!end2.link.handshaken || end2.stalled) && won.route === "direct" && hasRelay) {
84453
84655
  round = "relay";
84454
84656
  continue;
84455
84657
  }
84456
- if (end2.code === CLOSE_UNAUTHORIZED || end2.code === CLOSE_TOKEN_ROTATED) {
84457
- failAll(cloud, unauthorized(name));
84458
- return yield* setStatus2(cloud, "unauthorized");
84459
- }
84658
+ const refusal = end2.declined ? "refused" : refusalOf(end2.link, end2.ready);
84659
+ if (refusal !== null) return yield* refuse2(cloud, refusal);
84460
84660
  if (end2.otherProtocol === null) {
84461
84661
  yield* setStatus2(cloud, "offline");
84462
84662
  } else {
84463
84663
  cloud.protocol = end2.otherProtocol;
84464
- failAll(cloud, incompatible(name));
84664
+ failAll(cloud, incompatible(cloud.environment.name));
84465
84665
  yield* setStatus2(cloud, "incompatible");
84466
84666
  }
84467
84667
  if (end2.connectedMs >= STABLE_MS) attempt2 = 0;
@@ -84487,19 +84687,27 @@ const make$r = gen(function* () {
84487
84687
  )
84488
84688
  )
84489
84689
  );
84490
- const start = (environment2) => suspend(() => {
84690
+ const start = (stored) => suspend(() => {
84691
+ const environment2 = environmentOf(stored);
84491
84692
  const existing2 = clouds.get(environment2.id);
84492
84693
  const cloud = existing2 ?? {
84493
84694
  environment: environment2,
84695
+ hostKey: stored.hostKey,
84696
+ verified: stored.verified,
84494
84697
  status: "connecting",
84698
+ approval: null,
84699
+ refusal: null,
84495
84700
  lastSeenAt: null,
84496
84701
  protocol: null,
84497
84702
  live: null,
84498
84703
  wake: null,
84704
+ answerHost: null,
84499
84705
  outbox: /* @__PURE__ */ new Map(),
84500
84706
  remembered: /* @__PURE__ */ new Map()
84501
84707
  };
84502
84708
  cloud.environment = environment2;
84709
+ cloud.hostKey = stored.hostKey;
84710
+ cloud.verified = stored.verified;
84503
84711
  clouds.set(environment2.id, cloud);
84504
84712
  return run$3(connections, environment2.id, maintain(cloud));
84505
84713
  });
@@ -84508,50 +84716,66 @@ const make$r = gen(function* () {
84508
84716
  return {
84509
84717
  clouds: rows.map((row) => {
84510
84718
  const cloud = clouds.get(row.id);
84511
- const entry = { ...row, status: cloud?.status ?? "offline", lastSeenAt: cloud?.lastSeenAt ?? null };
84512
- return cloud?.status === "incompatible" && cloud.protocol !== null ? { ...entry, protocol: cloud.protocol } : entry;
84719
+ return {
84720
+ ...environmentOf(row),
84721
+ status: cloud?.status ?? "offline",
84722
+ lastSeenAt: cloud?.lastSeenAt ?? null,
84723
+ ...cloud?.status === "incompatible" && cloud.protocol !== null && { protocol: cloud.protocol },
84724
+ ...cloud?.approval != null && { approval: cloud.approval },
84725
+ ...cloud?.refusal != null && { refusal: cloud.refusal }
84726
+ };
84513
84727
  })
84514
84728
  };
84515
84729
  });
84516
84730
  const add2 = (input) => gen(function* () {
84517
84731
  const pairing = parsePairingUrl(input.pairingUrl);
84518
- if (pairing === null) {
84732
+ const hostKey = pairing === null ? null : decodeKey(pairing.key);
84733
+ if (pairing === null || hostKey === null) {
84519
84734
  return yield* new InvalidPairingUrl({
84520
84735
  message: "Paste the hinacode://connect URL that hinacode serve printed."
84521
84736
  });
84522
84737
  }
84523
- const { host, ready } = yield* probeHosts(pairing);
84524
- const { port, token, relay: relay2 } = pairing;
84525
- if (ready.environment?.id === self2.id) {
84738
+ const { port, key: key2, relay: relay2, secret } = pairing;
84739
+ const credentials = {
84740
+ hostKey,
84741
+ device,
84742
+ hello: { name: deviceName(), ...secret !== null && { secret } }
84743
+ };
84744
+ const { host, answer: probed, usedSecret } = yield* probeHosts(pairing, credentials);
84745
+ const ready = "ready" in probed ? probed.ready : null;
84746
+ if (ready?.environment?.id === self2.id) {
84526
84747
  return yield* new InvalidPairingUrl({ message: "That pairing URL is for this desktop." });
84527
84748
  }
84528
84749
  const typed = input.name.trim();
84529
- const id2 = ready.environment?.id ?? randomUUID();
84750
+ const id2 = ready?.environment?.id ?? randomUUID();
84530
84751
  const existing2 = getOrNull(yield* findOne2(id2).pipe(mapError(persistence("environments.add"))));
84531
- const environment2 = existing2 ? { ...existing2, name: typed || existing2.name, host, port, relay: relay2 } : {
84752
+ const stored = existing2 ? { ...existing2, name: typed || existing2.name, host, port, relay: relay2, hostKey: key2, verified: true } : {
84532
84753
  id: id2,
84533
- name: typed || ready.environment?.name || host,
84754
+ name: typed || ready?.environment?.name || host,
84534
84755
  host,
84535
84756
  port,
84536
84757
  relay: relay2,
84537
84758
  source: "pairing",
84538
- createdAt: nowIso2()
84759
+ createdAt: nowIso2(),
84760
+ hostKey: key2,
84761
+ verified: true
84539
84762
  };
84540
- const write = existing2 ? sql`UPDATE environment SET name = ${environment2.name}, host = ${host}, port = ${port}, relay = ${relay2} WHERE id = ${id2}` : sql`INSERT INTO environment ${sql.insert(environment2)}`;
84763
+ const write = existing2 ? sql`UPDATE environment SET name = ${stored.name}, host = ${host}, port = ${port}, relay = ${relay2}, host_key = ${key2}, verified = 1 WHERE id = ${id2}` : sql`INSERT INTO environment ${sql.insert({ ...environmentOf(stored), hostKey: key2, verified: 1 })}`;
84764
+ const keepSecret = secret !== null && !usedSecret;
84541
84765
  yield* write.pipe(
84542
- andThen(secrets.set(tokenSecret(id2), token)),
84766
+ andThen(keepSecret ? secrets.set(pairingSecret(id2), secret) : secrets.clear(pairingSecret(id2))),
84543
84767
  sql.withTransaction,
84544
84768
  catchTag("SqlError", (error2) => fail$2(persistence("environments.add")(error2)))
84545
84769
  );
84546
- yield* start(environment2);
84547
- return environment2;
84770
+ yield* start(stored);
84771
+ return environmentOf(stored);
84548
84772
  });
84549
84773
  const remove2 = (id2) => gen(function* () {
84550
84774
  yield* remove$1(connections, id2);
84551
84775
  const cloud = clouds.get(id2);
84552
84776
  if (cloud !== void 0) failAll(cloud, unknownEnvironment(id2));
84553
84777
  yield* sql`DELETE FROM environment WHERE id = ${id2}`.pipe(mapError(persistence("environments.remove")));
84554
- yield* secrets.clear(tokenSecret(id2));
84778
+ yield* secrets.clear(pairingSecret(id2));
84555
84779
  clouds.delete(id2);
84556
84780
  owners.forget(id2);
84557
84781
  });
@@ -84571,46 +84795,56 @@ const make$r = gen(function* () {
84571
84795
  machines,
84572
84796
  self2.id
84573
84797
  );
84798
+ relayMachines.clear();
84799
+ for (const machine of upsert) relayMachines.set(machine.environmentId, machine);
84574
84800
  const rowById = new Map(rows.map((row) => [row.id, row]));
84575
84801
  let changed = drop2.length > 0;
84576
84802
  for (const { environmentId: id2, name, pairing } of upsert) {
84577
- const { port, token, relay: relay2 } = pairing;
84803
+ const { port, key: key2, relay: relay2 } = pairing;
84578
84804
  const host = pairing.hosts[0];
84579
84805
  const existing2 = rowById.get(id2);
84580
84806
  if (existing2 === void 0) {
84581
- const environment22 = {
84807
+ const stored = {
84582
84808
  id: id2,
84583
84809
  name,
84584
84810
  host,
84585
84811
  port,
84586
84812
  relay: relay2,
84587
84813
  source: "relay",
84588
- createdAt: nowIso2()
84814
+ createdAt: nowIso2(),
84815
+ hostKey: key2,
84816
+ verified: false
84589
84817
  };
84590
- yield* sql`INSERT INTO environment ${sql.insert(environment22)}`.pipe(
84591
- andThen(secrets.set(tokenSecret(id2), token)),
84592
- sql.withTransaction,
84593
- catchTag("SqlError", (error2) => fail$2(failed2(error2)))
84818
+ yield* sql`INSERT INTO environment ${sql.insert({ ...environmentOf(stored), hostKey: key2, verified: 0 })}`.pipe(
84819
+ mapError(failed2)
84594
84820
  );
84595
- yield* start(environment22);
84821
+ yield* start(stored);
84596
84822
  changed = true;
84597
84823
  continue;
84598
84824
  }
84599
- const environment2 = { ...existing2, host, port, relay: relay2 };
84600
- const redial = host !== existing2.host || port !== existing2.port || relay2 !== existing2.relay || token !== getOrNull(yield* secrets.get(tokenSecret(id2)));
84601
- if (!redial) continue;
84825
+ if (host === existing2.host && port === existing2.port && relay2 === existing2.relay) continue;
84602
84826
  yield* sql`UPDATE environment SET host = ${host}, port = ${port}, relay = ${relay2} WHERE id = ${id2}`.pipe(
84603
- andThen(secrets.set(tokenSecret(id2), token)),
84604
- sql.withTransaction,
84605
- catchTag("SqlError", (error2) => fail$2(failed2(error2)))
84827
+ mapError(failed2)
84606
84828
  );
84607
84829
  changed = true;
84608
- yield* start(environment2);
84830
+ yield* start({ ...existing2, host, port, relay: relay2 });
84609
84831
  }
84610
84832
  yield* forEach(drop2, (row) => remove2(row.id), { discard: true });
84611
84833
  if (changed) yield* events2.publish({ type: "environments.changed" });
84612
84834
  return upsert.length;
84613
84835
  });
84836
+ const repair = (id2) => gen(function* () {
84837
+ const listed = relayMachines.get(id2);
84838
+ const existing2 = getOrNull(yield* findOne2(id2).pipe(mapError(persistence("environments.repair"))));
84839
+ if (listed === void 0 || existing2 === null) return;
84840
+ const { key: key2 } = listed.pairing;
84841
+ yield* sql`UPDATE environment SET host_key = ${key2}, verified = 0 WHERE id = ${id2}`.pipe(
84842
+ mapError(persistence("environments.repair"))
84843
+ );
84844
+ yield* secrets.clear(pairingSecret(id2));
84845
+ yield* start({ ...existing2, hostKey: key2, verified: false });
84846
+ });
84847
+ const confirmHost = (id2, accepted) => suspend(() => clouds.get(id2)?.answerHost?.(accepted) ?? void_);
84614
84848
  const reconnect = (id2) => suspend(() => {
84615
84849
  const cloud = clouds.get(id2);
84616
84850
  const wake2 = cloud?.wake;
@@ -84623,7 +84857,7 @@ const make$r = gen(function* () {
84623
84857
  const cloud = clouds.get(environmentId);
84624
84858
  if (cloud === void 0) return succeed$2(unknownEnvironment(environmentId));
84625
84859
  const { name } = cloud.environment;
84626
- if (cloud.status === "unauthorized") return succeed$2(unauthorized(name));
84860
+ if (cloud.status === "unauthorized") return succeed$2(unauthorized(name, cloud.refusal ?? "refused"));
84627
84861
  if (cloud.status === "incompatible") return succeed$2(incompatible(name));
84628
84862
  return callback((resume) => {
84629
84863
  const call2 = {
@@ -84639,7 +84873,7 @@ const make$r = gen(function* () {
84639
84873
  timer: null
84640
84874
  };
84641
84875
  cloud.outbox.set(call2.id, call2);
84642
- if (cloud.live !== null) send$1(cloud.live, call2);
84876
+ if (cloud.live !== null) send(cloud.live, call2);
84643
84877
  else {
84644
84878
  startOfflineTimer(cloud, call2);
84645
84879
  if (call2.key !== void 0) runFork2(hooks.offlineMutation(environmentId));
@@ -84684,6 +84918,8 @@ const make$r = gen(function* () {
84684
84918
  remove: remove2,
84685
84919
  rename: rename2,
84686
84920
  syncRelay,
84921
+ repair,
84922
+ confirmHost,
84687
84923
  reconnect,
84688
84924
  reconnectAll,
84689
84925
  forward: forward2,
@@ -84916,6 +85152,7 @@ const make$p = gen(function* () {
84916
85152
  const threads = yield* Threads;
84917
85153
  const worktrees = yield* Worktrees;
84918
85154
  const scratch = yield* Scratch;
85155
+ const secrets = yield* Secrets;
84919
85156
  const attachments = yield* Attachments;
84920
85157
  const git2 = yield* Git;
84921
85158
  const pullRequests = yield* PullRequests;
@@ -85084,16 +85321,24 @@ const make$p = gen(function* () {
85084
85321
  map$2((out) => out.trim()),
85085
85322
  option
85086
85323
  );
85324
+ const writeThreadSecrets = (thread2) => gen(function* () {
85325
+ const prefix2 = threadSecretPrefix(thread2.id);
85326
+ for (const name of yield* secrets.namesUnder(prefix2)) {
85327
+ const value2 = yield* secrets.get(`${prefix2}${name}`);
85328
+ if (isSome(value2)) yield* scratch.writeSecret(thread2, name, value2.value);
85329
+ }
85330
+ }).pipe(catch_((error2) => logWarning("thread secrets could not be written", thread2.id, error2)));
85087
85331
  const readEnvironment = (thread2, { cwd, rootPath }) => all$1(
85088
85332
  [
85089
85333
  gitOutput(cwd, ["branch", "--show-current"]),
85090
85334
  gitOutput(cwd, ["remote", "get-url", "origin"]),
85091
85335
  scratch.ensure(thread2),
85092
- scratch.ensureTmp(thread2.id)
85336
+ scratch.ensureTmp(thread2.id),
85337
+ scratch.unreadableBy(thread2.id)
85093
85338
  ],
85094
85339
  { concurrency: "unbounded" }
85095
85340
  ).pipe(
85096
- map$2(([branch, remote, scratchDirectory, tmpDirectory]) => ({
85341
+ map$2(([branch, remote, scratchDirectory, tmpDirectory, unreadablePaths]) => ({
85097
85342
  gitRepository: isSome(branch),
85098
85343
  branch: getOrNull(branch) || null,
85099
85344
  cwd,
@@ -85101,7 +85346,8 @@ const make$p = gen(function* () {
85101
85346
  remote: getOrNull(remote) || null,
85102
85347
  platform: process.platform,
85103
85348
  scratchDirectory,
85104
- tmpDirectory
85349
+ tmpDirectory,
85350
+ unreadablePaths
85105
85351
  }))
85106
85352
  );
85107
85353
  const sessionInput = (thread2, provider, cwd, home, environment2) => gen(function* () {
@@ -85122,7 +85368,8 @@ const make$p = gen(function* () {
85122
85368
  forkAt: thread2.providerSessionId === null ? thread2.forkedFrom?.checkpoint ?? null : null,
85123
85369
  home,
85124
85370
  mcpServer,
85125
- instructions: yield* subagentInstructions(experimental2, environment2)
85371
+ instructions: yield* subagentInstructions(experimental2, environment2),
85372
+ unreadablePaths: environment2.unreadablePaths
85126
85373
  };
85127
85374
  return input;
85128
85375
  });
@@ -85298,6 +85545,7 @@ const make$p = gen(function* () {
85298
85545
  const withdraw = (event) => publishTranscript({ type: "thread.event", threadId: thread2.id, event });
85299
85546
  const finish = gen(function* () {
85300
85547
  finishing = true;
85548
+ yield* scratch.removeSecrets(thread2.id);
85301
85549
  yield* deltas.flush;
85302
85550
  for (const [id2, request2] of approvals2) {
85303
85551
  if (request2.threadId !== thread2.id) continue;
@@ -85348,7 +85596,8 @@ const make$p = gen(function* () {
85348
85596
  suspend(() => next2 === void 0 ? void_ : forkDetach(startQueued(thread2.id, next2)))
85349
85597
  )
85350
85598
  );
85351
- const follow = (events2) => runForEach(events2, handle).pipe(
85599
+ const follow = (events2) => writeThreadSecrets(thread2).pipe(
85600
+ andThen(runForEach(events2, handle)),
85352
85601
  catchTag(
85353
85602
  "AgentError",
85354
85603
  ({ message: message2, loginCommand }) => handle({
@@ -85520,7 +85769,8 @@ const make$p = gen(function* () {
85520
85769
  forkAt: null,
85521
85770
  home,
85522
85771
  mcpServer,
85523
- instructions
85772
+ instructions,
85773
+ unreadablePaths: environment2.unreadablePaths
85524
85774
  }).pipe(
85525
85775
  runForEach(forward2),
85526
85776
  catchTag("AgentError", (error2) => sync(() => failure2 = error2.message)),
@@ -86170,7 +86420,12 @@ const make$p = gen(function* () {
86170
86420
  const pending = secretRequests.get(requestId);
86171
86421
  if (pending === void 0) return;
86172
86422
  const { threadId, name } = pending.request;
86423
+ const turn = activeTurns.get(threadId);
86424
+ if (value2 !== null) yield* secrets.set(`${threadSecretPrefix(threadId)}${name}`, value2);
86173
86425
  const path2 = value2 === null ? none() : some(yield* scratch.writeSecret(yield* threads.get(threadId), name, value2));
86426
+ const current = activeTurns.get(threadId);
86427
+ const turnEndedWhileWriting = current === void 0 || current === turn && current.isFinishing();
86428
+ if (isSome(path2) && turnEndedWhileWriting) yield* scratch.removeSecrets(threadId);
86174
86429
  yield* resolveSecret(requestId);
86175
86430
  yield* succeed$3(pending.answer, path2);
86176
86431
  });
@@ -86734,7 +86989,7 @@ const routes$1 = effectDiscard(
86734
86989
  const router = yield* HttpRouter;
86735
86990
  const connections = yield* AppConnections;
86736
86991
  const key2 = yield* clientKey;
86737
- const withIssuer = (respond) => flatMap(connections.issuer, match({ onNone: () => succeed$2(notFound), onSome: respond }));
86992
+ const withIssuer = (respond2) => flatMap(connections.issuer, match({ onNone: () => succeed$2(notFound), onSome: respond2 }));
86738
86993
  const resourceMetadata = withIssuer(
86739
86994
  (issuer) => succeed$2(jsonUnsafe(protectedResourceMetadata(issuer)))
86740
86995
  );
@@ -87820,6 +88075,22 @@ const threadInterrupted = gen(function* () {
87820
88075
  yield* sql`ALTER TABLE thread DROP COLUMN status`;
87821
88076
  yield* sql`ALTER TABLE thread RENAME COLUMN next_status TO status`;
87822
88077
  });
88078
+ const remoteDevice = gen(function* () {
88079
+ const sql = yield* SqlClient;
88080
+ yield* sql`
88081
+ CREATE TABLE remote_device (
88082
+ key TEXT PRIMARY KEY,
88083
+ name TEXT NOT NULL,
88084
+ created_at INTEGER NOT NULL,
88085
+ last_seen_at INTEGER
88086
+ )
88087
+ `;
88088
+ });
88089
+ const environmentHostKey = gen(function* () {
88090
+ const sql = yield* SqlClient;
88091
+ yield* sql`ALTER TABLE environment ADD COLUMN host_key TEXT`;
88092
+ yield* sql`ALTER TABLE environment ADD COLUMN verified INTEGER NOT NULL DEFAULT 0 CHECK (verified IN (0, 1))`;
88093
+ });
87823
88094
  const run$2 = make$1c({});
87824
88095
  const runMigrations = run$2({
87825
88096
  loader: fromRecord({
@@ -87874,7 +88145,9 @@ const runMigrations = run$2({
87874
88145
  "50_thread_device_client": threadDeviceClient,
87875
88146
  "51_turn_end_tree": turnEndTree,
87876
88147
  "52_pi_provider": piProvider,
87877
- "53_thread_interrupted": threadInterrupted
88148
+ "53_thread_interrupted": threadInterrupted,
88149
+ "54_remote_device": remoteDevice,
88150
+ "55_environment_host_key": environmentHostKey
87878
88151
  })
87879
88152
  }).pipe(
87880
88153
  tap$1(
@@ -87889,13 +88162,23 @@ const setup = effectDiscard(
87889
88162
  yield* runMigrations;
87890
88163
  })
87891
88164
  );
88165
+ const PRIVATE_FILE_MODE = 384;
88166
+ const keepFilesPrivate = (filename) => effectDiscard(
88167
+ sync(() => {
88168
+ if (filename === ":memory:" || process.platform === "win32") return;
88169
+ closeSync(openSync(filename, "a", PRIVATE_FILE_MODE));
88170
+ for (const path2 of [filename, `${filename}-wal`, `${filename}-shm`]) {
88171
+ if (existsSync(path2)) chmodSync(path2, PRIVATE_FILE_MODE);
88172
+ }
88173
+ })
88174
+ );
87892
88175
  const layer$p = (filename) => setup.pipe(
87893
88176
  provideMerge(
87894
88177
  layer$q({
87895
88178
  filename,
87896
88179
  transformQueryNames: camelToSnake,
87897
88180
  transformResultNames: snakeToCamel
87898
- })
88181
+ }).pipe(provide$2(keepFilesPrivate(filename)))
87899
88182
  )
87900
88183
  );
87901
88184
  const client$1 = { to: "client" };
@@ -87976,6 +88259,8 @@ const routes = {
87976
88259
  "environments.remove": client$1,
87977
88260
  "environments.rename": client$1,
87978
88261
  "environments.reconnect": client$1,
88262
+ "environments.confirmHost": client$1,
88263
+ "environments.repair": client$1,
87979
88264
  "boatMachines.options": client$1,
87980
88265
  "boatMachines.connect": client$1,
87981
88266
  "boatMachines.forThread": client$1,
@@ -87986,6 +88271,8 @@ const routes = {
87986
88271
  "relayAccount.machines": client$1,
87987
88272
  "relayAccount.setShown": client$1,
87988
88273
  "relayAccount.removeMachine": client$1,
88274
+ "relay.useSelfHosted": client$1,
88275
+ "relay.stopSelfHosted": client$1,
87989
88276
  "appConnections.status": client$1,
87990
88277
  "appConnections.start": client$1,
87991
88278
  "appConnections.answer": client$1,
@@ -88017,6 +88304,7 @@ const routes = {
88017
88304
  "magpie.saveKey": named,
88018
88305
  "models.list": named,
88019
88306
  "secrets.has": named,
88307
+ "secrets.storage": named,
88020
88308
  "secrets.set": named,
88021
88309
  "secrets.clear": named,
88022
88310
  "github.auth": named,
@@ -88031,14 +88319,19 @@ const routes = {
88031
88319
  "github.comment": named,
88032
88320
  "github.pullRequestCandidates": named,
88033
88321
  "github.editPullRequest": named,
88322
+ "github.assetUrl": named,
88034
88323
  "github.fileContent": named,
88035
88324
  "github.reviewComment": named,
88325
+ "github.review": named,
88036
88326
  "vm.host": named,
88037
88327
  "network.addresses": named,
88038
88328
  "system.resources": named,
88039
88329
  "remote.status": named,
88040
88330
  "remote.pairing": named,
88041
- "remote.rotateToken": named,
88331
+ "remote.resetPairing": named,
88332
+ "remote.devices": client$1,
88333
+ "remote.devices.approve": client$1,
88334
+ "remote.devices.remove": client$1,
88042
88335
  "projects.create": named,
88043
88336
  "projects.clone": named,
88044
88337
  "projects.cancelClone": named,
@@ -88148,6 +88441,7 @@ const routes = {
88148
88441
  "fs.watch": root$1,
88149
88442
  "fs.completeDirectory": named,
88150
88443
  "artifacts.file": owner("artifact", "id"),
88444
+ "vm.screen.read": owner("stream", "streamId"),
88151
88445
  "vm.screen.send": owner("stream", "streamId"),
88152
88446
  "vm.screen.close": owner("stream", "streamId")
88153
88447
  };
@@ -88185,16 +88479,16 @@ const linkChain = (path2) => promise$1(async () => {
88185
88479
  return hops;
88186
88480
  });
88187
88481
  const isUnder = (path2, dir) => path2.startsWith(`${dir.replace(/\/+$/, "")}/`);
88188
- const miseOwnership = (binary, tool2) => gen(function* () {
88482
+ const miseOwnership = (binary2, tool2) => gen(function* () {
88189
88483
  const none2 = { kind: "none" };
88190
88484
  const manual = { kind: "manual" };
88191
88485
  const mise = yield* promise$1(() => findBinary("mise"));
88192
88486
  if (mise === void 0) return none2;
88193
- const real = yield* resolved(binary);
88487
+ const real = yield* resolved(binary2);
88194
88488
  const launcher = yield* miseLauncher(real, tool2);
88195
88489
  if (launcher === "pinned") return manual;
88196
88490
  const dispatchesThroughMise = launcher === "dispatch";
88197
- if (dispatchesThroughMise && basename(binary).replace(/\.exe$/, "") !== tool2) return manual;
88491
+ if (dispatchesThroughMise && basename(binary2).replace(/\.exe$/, "") !== tool2) return manual;
88198
88492
  const notOwned = dispatchesThroughMise || /\/mise\/installs\/(?!node\/)/.test(real) ? manual : none2;
88199
88493
  const which2 = yield* runMise(mise, ["which", tool2]).pipe(option);
88200
88494
  const miseRuns = isSome(which2) && which2.value !== "" ? yield* resolved(which2.value) : void 0;
@@ -88214,7 +88508,7 @@ const miseOwnership = (binary, tool2) => gen(function* () {
88214
88508
  if (!dispatchesThroughMise) {
88215
88509
  const toolDir = dirname(install2.install_path);
88216
88510
  const latestLinks = [toolDir, yield* resolved(toolDir)].map((dir) => join$1(dir, "latest"));
88217
- const hops = yield* linkChain(binary);
88511
+ const hops = yield* linkChain(binary2);
88218
88512
  if (!hops.some((hop) => latestLinks.some((link) => isUnder(hop, link)))) return manual;
88219
88513
  }
88220
88514
  return { kind: "upgradable", mise };
@@ -88261,13 +88555,13 @@ const npmLatestVersion = (provider) => tryPromise({
88261
88555
  catch: (cause) => new AgentError({ provider, message: `Could not check the latest release: ${String(cause)}` })
88262
88556
  });
88263
88557
  const updaterFor = (provider) => gen(function* () {
88264
- const binary = yield* installedBinary(provider, provider);
88265
- const mise = yield* miseOwnership(binary, provider);
88558
+ const binary2 = yield* installedBinary(provider, provider);
88559
+ const mise = yield* miseOwnership(binary2, provider);
88266
88560
  switch (mise.kind) {
88267
88561
  case "none":
88268
88562
  return some({
88269
88563
  label: `${provider} update`,
88270
- file: binary,
88564
+ file: binary2,
88271
88565
  args: ["update"],
88272
88566
  latestVersion: npmLatestVersion(provider)
88273
88567
  });
@@ -90317,7 +90611,7 @@ Upgrade: tcp\r
90317
90611
  \r
90318
90612
  `
90319
90613
  );
90320
- const socket = secure ? connect$2({ host: url2.hostname, port: hostPort, servername: url2.hostname }, onConnect) : connect$3({ host: url2.hostname, port: hostPort }, onConnect);
90614
+ const socket = secure ? connect$3({ host: url2.hostname, port: hostPort, servername: url2.hostname }, onConnect) : connect$2({ host: url2.hostname, port: hostPort }, onConnect);
90321
90615
  socket.setNoDelay(true);
90322
90616
  let received = Buffer.alloc(0);
90323
90617
  const timer = setTimeout(
@@ -91019,7 +91313,7 @@ for attempt in $(seq 1 60); do
91019
91313
  sleep 1
91020
91314
  done
91021
91315
  echo "hinacode serve did not start" >&2
91022
- sudo journalctl -u hinacode -n 20 --no-pager | sed -E 's/token=[^&[:space:]]+/token=REDACTED/g' >&2
91316
+ sudo journalctl -u hinacode -n 20 --no-pager | sed -E 's/(token|secret)=[^&[:space:]]+/\\1=REDACTED/g' >&2
91023
91317
  exit 1
91024
91318
  `;
91025
91319
  class BoatMachineError extends TaggedError$1()("BoatMachineError", {
@@ -91059,7 +91353,7 @@ const uploadDevPackage = (client2, id2, path2) => tryPromise({
91059
91353
  try: () => readFile(path2),
91060
91354
  catch: () => new BoatMachineError({ message: `Could not read HINACODE_BOAT_PACKAGE at ${path2}.` })
91061
91355
  }).pipe(flatMap((bytes2) => client2.writeFileBytes(id2, DEV_PACKAGE_PATH, bytes2)));
91062
- const withoutTokens = (output) => output.replace(/token=[^&\s]+/g, "token=REDACTED");
91356
+ const withoutSecrets = (output) => output.replace(/(token|secret)=[^&\s]+/g, "$1=REDACTED");
91063
91357
  const install = (client2, id2, devPackage) => gen(function* () {
91064
91358
  if (devPackage !== void 0) yield* uploadDevPackage(client2, id2, devPackage);
91065
91359
  const result2 = yield* client2.exec(id2, {
@@ -91068,7 +91362,7 @@ const install = (client2, id2, devPackage) => gen(function* () {
91068
91362
  });
91069
91363
  const pairing = parsePairingUrl(text.decode(result2.stdout));
91070
91364
  if (result2.exitCode === 0 && pairing !== null) return pairing;
91071
- const output = withoutTokens(text.decode(result2.stderr)).trim().slice(-600);
91365
+ const output = withoutSecrets(text.decode(result2.stderr)).trim().slice(-600);
91072
91366
  return yield* new BoatMachineError({
91073
91367
  message: `HinaCode did not start on the boat sandbox (exit ${result2.exitCode}).${output === "" ? "" : `
91074
91368
  ${output}`}`
@@ -91109,7 +91403,7 @@ const make$g = (env) => gen(function* () {
91109
91403
  };
91110
91404
  });
91111
91405
  const pair2 = (client2, id2) => gen(function* () {
91112
- const { port, token } = yield* install(client2, id2, devPackage);
91406
+ const { port, key: key2, secret } = yield* install(client2, id2, devPackage);
91113
91407
  const hosted = yield* client2.hostPort(id2, port, { public: true, localhost: true });
91114
91408
  const relay2 = URL.parse(hosted)?.hostname;
91115
91409
  if (relay2 === void 0)
@@ -91117,7 +91411,7 @@ const make$g = (env) => gen(function* () {
91117
91411
  const sandbox = yield* client2.getSandbox(id2);
91118
91412
  return yield* environments2.add({
91119
91413
  name: sandbox.name,
91120
- pairingUrl: pairingUrl({ hosts: [relay2], port: 443, token, relay: relay2 })
91414
+ pairingUrl: pairingUrl({ hosts: [relay2], port: 443, relay: relay2, key: key2, secret })
91121
91415
  });
91122
91416
  });
91123
91417
  const pairedOnce = (client2, id2) => removedOnFailure(pair2(client2, id2), (environment2) => environments2.remove(environment2.id));
@@ -93369,10 +93663,44 @@ const BOAT_PREPARE_SCRIPT = [
93369
93663
  const BOAT_PREPARE_TIMEOUT_SECONDS = 600;
93370
93664
  const BoatSandboxMap = fromJsonString(Record(String$1, String$1));
93371
93665
  const isBoatSize = is$2(BoatVmSize);
93372
- const FLUSH_INTERVAL_MS = 16;
93373
- const FLUSH_SIZE = 256 * 1024;
93666
+ const SCREEN_BATCH_MS = 16;
93667
+ const SCREEN_READ_MAX = 1024 * 1024;
93668
+ const SCREEN_UNREAD_MAX = 2 * 1024 * 1024;
93669
+ const SCREEN_READ_WAIT = "1 second";
93670
+ const SCREEN_LEASE = "10 seconds";
93374
93671
  const HAND_BACK_GRACE = "2 seconds";
93375
93672
  const NONE = { status: "none" };
93673
+ const SCREEN_CLOSED = { status: "closed" };
93674
+ const takeUnread = (screen) => {
93675
+ const parts = [];
93676
+ let size2 = 0;
93677
+ for (const chunk of screen.unread) {
93678
+ const room = SCREEN_READ_MAX - size2;
93679
+ if (room <= 0) break;
93680
+ const part = chunk.length > room ? chunk.subarray(0, room) : chunk;
93681
+ parts.push(part);
93682
+ size2 += part.length;
93683
+ }
93684
+ return Buffer.concat(parts, size2);
93685
+ };
93686
+ const acknowledge = (screen, offset) => {
93687
+ let drop2 = offset - screen.readFrom;
93688
+ if (drop2 < 0 || drop2 > screen.unreadSize) return false;
93689
+ screen.readFrom = offset;
93690
+ screen.unreadSize -= drop2;
93691
+ while (drop2 > 0) {
93692
+ const first = screen.unread[0];
93693
+ if (first.length <= drop2) {
93694
+ screen.unread.shift();
93695
+ drop2 -= first.length;
93696
+ } else {
93697
+ screen.unread[0] = first.subarray(drop2);
93698
+ drop2 = 0;
93699
+ }
93700
+ }
93701
+ if (screen.socket.isPaused() && screen.unreadSize < SCREEN_UNREAD_MAX / 2) screen.socket.resume();
93702
+ return true;
93703
+ };
93376
93704
  const toVmError = (error2) => new VmError({ message: error2.message });
93377
93705
  const releasedThreadOf = (event) => {
93378
93706
  if (event.type === "thread.removed") return event.id;
@@ -93414,7 +93742,6 @@ const make$a = (source, dataDir, desktopRedirect = true) => gen(function* () {
93414
93742
  const handBacks = /* @__PURE__ */ new Map();
93415
93743
  const screens = /* @__PURE__ */ new Map();
93416
93744
  const openingScreens = /* @__PURE__ */ new Set();
93417
- const ownedScreens = /* @__PURE__ */ new WeakMap();
93418
93745
  const experimental2 = yield* settings.get.pipe(
93419
93746
  map$2((value2) => value2.experimental),
93420
93747
  orElseSucceed(() => defaultSettings.experimental)
@@ -93431,7 +93758,6 @@ const make$a = (source, dataDir, desktopRedirect = true) => gen(function* () {
93431
93758
  const boatMapLock = yield* make$1x(1);
93432
93759
  const current = (threadId) => vms.get(threadId) ?? NONE;
93433
93760
  const runFork2 = runForkWith(yield* context());
93434
- const publishUnsafe2 = (event) => runFork2(events2.publish(event));
93435
93761
  const setVm = (threadId, vm) => suspend(() => {
93436
93762
  if (vm.status === "none") vms.delete(threadId);
93437
93763
  else vms.set(threadId, vm);
@@ -94082,32 +94408,33 @@ ${output}` : ""}`
94082
94408
  )
94083
94409
  });
94084
94410
  const host = suspend(() => provider === "boat" ? boatHost : sbxHost);
94085
- const flush = (streamId, screen) => {
94086
- clearTimeout(screen.timer);
94087
- screen.timer = void 0;
94088
- if (screen.pendingSize === 0) return;
94089
- const data = Buffer.concat(screen.pending);
94090
- screen.pending = [];
94091
- screen.pendingSize = 0;
94092
- publishUnsafe2({ type: "vm.screen.data", streamId, data });
94093
- };
94094
- const buffer2 = (streamId, screen, data) => {
94411
+ const wakeReader = (screen) => {
94412
+ clearTimeout(screen.batch);
94413
+ screen.batch = void 0;
94414
+ const wake2 = screen.wake;
94415
+ screen.wake = void 0;
94416
+ wake2?.();
94417
+ };
94418
+ const received = (screen, data) => {
94095
94419
  if (data.length === 0) return;
94096
- screen.pending.push(data);
94097
- screen.pendingSize += data.length;
94098
- if (screen.pendingSize >= FLUSH_SIZE) flush(streamId, screen);
94099
- else screen.timer ??= setTimeout(() => flush(streamId, screen), FLUSH_INTERVAL_MS);
94420
+ screen.unread.push(data);
94421
+ screen.unreadSize += data.length;
94422
+ if (screen.unreadSize >= SCREEN_UNREAD_MAX) screen.socket.pause();
94423
+ if (screen.unreadSize >= SCREEN_READ_MAX) wakeReader(screen);
94424
+ else if (screen.wake !== void 0) screen.batch ??= setTimeout(() => wakeReader(screen), SCREEN_BATCH_MS);
94100
94425
  };
94101
94426
  const unwatchedByUser = (threadId) => {
94102
94427
  const vm = current(threadId);
94103
- const watched = [...screens.values()].some((other) => other.threadId === threadId);
94428
+ const watched = [...screens.values()].some((other) => other.threadId === threadId && !other.ended);
94104
94429
  return !watched && vm.status === "running" && vm.control === "user" && vm.request === void 0;
94105
94430
  };
94106
- const screenClosed = (streamId, screen, owner2) => {
94107
- flush(streamId, screen);
94431
+ const finishScreen = (streamId) => {
94432
+ const screen = screens.get(streamId);
94433
+ if (screen === void 0) return;
94108
94434
  screens.delete(streamId);
94109
- ownedScreens.get(owner2)?.delete(streamId);
94110
- publishUnsafe2({ type: "vm.screen.closed", streamId });
94435
+ screen.socket.destroy();
94436
+ wakeReader(screen);
94437
+ if (screen.lease !== void 0) runFork2(interrupt$1(screen.lease));
94111
94438
  if (!unwatchedByUser(screen.threadId)) return;
94112
94439
  runFork2(
94113
94440
  sleep$3(HAND_BACK_GRACE).pipe(
@@ -94119,16 +94446,20 @@ ${output}` : ""}`
94119
94446
  )
94120
94447
  );
94121
94448
  };
94122
- const own2 = (owner2, streamId) => {
94123
- let owned = ownedScreens.get(owner2);
94124
- if (owned === void 0) {
94125
- const streams = /* @__PURE__ */ new Set();
94126
- ownedScreens.set(owner2, owned = streams);
94127
- owner2.once("destroyed", () => streams.forEach((id2) => screens.get(id2)?.socket.destroy()));
94128
- }
94129
- owned.add(streamId);
94449
+ const renewLease = (streamId, screen) => {
94450
+ if (screen.lease !== void 0) runFork2(interrupt$1(screen.lease));
94451
+ screen.lease = runFork2(
94452
+ sleep$3(SCREEN_LEASE).pipe(
94453
+ andThen(
94454
+ sync(() => {
94455
+ screen.lease = void 0;
94456
+ finishScreen(streamId);
94457
+ })
94458
+ )
94459
+ )
94460
+ );
94130
94461
  };
94131
- const openScreen = (threadId, streamId, owner2) => gen(function* () {
94462
+ const openScreen = (threadId, streamId) => gen(function* () {
94132
94463
  if (screens.has(streamId) || openingScreens.has(streamId)) {
94133
94464
  return yield* new VmError({ message: `Screen stream ${streamId} is already open.` });
94134
94465
  }
@@ -94145,18 +94476,65 @@ ${output}` : ""}`
94145
94476
  ),
94146
94477
  mapError(toVmError)
94147
94478
  );
94148
- const screen = { threadId, socket, pending: [], pendingSize: 0, timer: void 0 };
94479
+ const screen = {
94480
+ threadId,
94481
+ socket,
94482
+ unread: [],
94483
+ readFrom: 0,
94484
+ unreadSize: 0,
94485
+ ended: false,
94486
+ readers: 0,
94487
+ wake: void 0,
94488
+ batch: void 0,
94489
+ lease: void 0
94490
+ };
94149
94491
  screens.set(streamId, screen);
94150
- own2(owner2, streamId);
94151
- buffer2(streamId, screen, head2);
94152
- socket.on("data", (data) => buffer2(streamId, screen, data));
94153
- socket.once("close", () => screenClosed(streamId, screen, owner2));
94492
+ renewLease(streamId, screen);
94493
+ received(screen, head2);
94494
+ socket.on("data", (data) => received(screen, data));
94495
+ socket.once("close", () => {
94496
+ screen.ended = true;
94497
+ wakeReader(screen);
94498
+ });
94154
94499
  }).pipe(ensuring(sync(() => openingScreens.delete(streamId))));
94500
+ const waitForBytes = (screen) => screen.unreadSize > 0 || screen.ended ? void_ : callback((resume) => {
94501
+ wakeReader(screen);
94502
+ const wake2 = () => resume(void_);
94503
+ screen.wake = wake2;
94504
+ return sync(() => {
94505
+ if (screen.wake === wake2) screen.wake = void 0;
94506
+ });
94507
+ }).pipe(timeoutOption(SCREEN_READ_WAIT), asVoid);
94508
+ const readScreen = (streamId, offset) => suspend(() => {
94509
+ const screen = screens.get(streamId);
94510
+ if (screen === void 0) return succeed$2(SCREEN_CLOSED);
94511
+ if (!acknowledge(screen, offset)) {
94512
+ return fail$2(new VmError({ message: `Screen stream ${streamId} has no bytes at ${offset}.` }));
94513
+ }
94514
+ return acquireUseRelease(
94515
+ sync(() => {
94516
+ screen.readers++;
94517
+ if (screen.lease !== void 0) runFork2(interrupt$1(screen.lease));
94518
+ screen.lease = void 0;
94519
+ }),
94520
+ () => map$2(waitForBytes(screen), () => {
94521
+ if (screens.get(streamId) !== screen) return SCREEN_CLOSED;
94522
+ if (screen.unreadSize > 0) return { status: "open", data: takeUnread(screen) };
94523
+ if (!screen.ended) return { status: "open", data: new Uint8Array() };
94524
+ finishScreen(streamId);
94525
+ return SCREEN_CLOSED;
94526
+ }),
94527
+ () => sync(() => {
94528
+ screen.readers--;
94529
+ if (screen.readers === 0 && screens.get(streamId) === screen) renewLease(streamId, screen);
94530
+ })
94531
+ );
94532
+ });
94155
94533
  const sendScreen = (streamId, data) => sync(() => {
94156
94534
  const socket = screens.get(streamId)?.socket;
94157
94535
  if (socket?.writable) socket.write(data);
94158
94536
  });
94159
- const closeScreen = (streamId) => sync(() => screens.get(streamId)?.socket.destroy());
94537
+ const closeScreen = (streamId) => sync(() => finishScreen(streamId));
94160
94538
  const release2 = (threadId) => tryPromise(() => rm(join$1(dataDir, PULLED_DIR, threadId), { recursive: true, force: true })).pipe(
94161
94539
  catch_((error2) => logWarning("tiny vm: cannot delete pulled files", String(error2))),
94162
94540
  andThen(stop(threadId))
@@ -94220,6 +94598,7 @@ ${output}` : ""}`
94220
94598
  pullFiles,
94221
94599
  saveProfile,
94222
94600
  openScreen,
94601
+ readScreen,
94223
94602
  sendScreen,
94224
94603
  closeScreen
94225
94604
  });
@@ -99622,6 +100001,8 @@ const handlers = {
99622
100001
  "environments.remove": ({ id: id2 }) => Environments.use((environments2) => environments2.remove(id2)),
99623
100002
  "environments.rename": ({ id: id2, name }) => Environments.use((environments2) => environments2.rename(id2, name)),
99624
100003
  "environments.reconnect": ({ id: id2 }) => Environments.use((environments2) => environments2.reconnect(id2)),
100004
+ "environments.confirmHost": ({ id: id2, accepted }) => Environments.use((environments2) => environments2.confirmHost(id2, accepted)),
100005
+ "environments.repair": ({ id: id2 }) => Environments.use((environments2) => environments2.repair(id2)),
99625
100006
  "boatMachines.options": () => BoatMachines.use((machines) => machines.options),
99626
100007
  "boatMachines.connect": (input) => BoatMachines.use((machines) => machines.connect(input)),
99627
100008
  "boatMachines.forThread": (input) => BoatMachines.use((machines) => machines.forThread(input)),
@@ -99643,6 +100024,8 @@ const handlers = {
99643
100024
  "relayAccount.machines": () => RelayAccount.use((account2) => account2.machines),
99644
100025
  "relayAccount.setShown": (input) => RelayAccount.use((account2) => account2.setShown(input)),
99645
100026
  "relayAccount.removeMachine": (input) => RelayAccount.use((account2) => account2.removeMachine(input)),
100027
+ "relay.useSelfHosted": (input) => Relay.use((relay2) => relay2.useSelfHosted(input)),
100028
+ "relay.stopSelfHosted": () => Relay.use((relay2) => relay2.stopSelfHosted),
99646
100029
  "appConnections.status": () => AppConnections.use((connections) => connections.status),
99647
100030
  "appConnections.start": () => AppConnections.use((connections) => connections.start),
99648
100031
  "appConnections.answer": (input) => AppConnections.use((connections) => connections.answer(input)),
@@ -99719,6 +100102,7 @@ const handlers = {
99719
100102
  "questions.respond": ({ requestId, answers }) => AgentRunner.use((runner) => runner.respondQuestion(requestId, answers)),
99720
100103
  "secrets.respond": ({ requestId, value: value2 }) => AgentRunner.use((runner) => runner.respondSecret(requestId, value2)),
99721
100104
  "secrets.has": ({ name }) => Secrets.use((secrets) => secrets.has(name)),
100105
+ "secrets.storage": () => Secrets.use((secrets) => succeed$2(secrets.backend)),
99722
100106
  "secrets.set": ({ name, value: value2 }) => Secrets.use((secrets) => secrets.set(name, value2)),
99723
100107
  "secrets.clear": ({ name }) => Secrets.use((secrets) => secrets.clear(name)),
99724
100108
  "subagents.list": ({ threadId }) => AgentRunner.use((runner) => runner.subagents(threadId)),
@@ -99751,8 +100135,10 @@ const handlers = {
99751
100135
  "github.comment": ({ url: url2, body: body2 }) => SourceControl.use((sourceControl) => sourceControl.comment(url2, body2)),
99752
100136
  "github.pullRequestCandidates": ({ url: url2 }) => GitHub.use((github) => github.pullRequestCandidates(url2)),
99753
100137
  "github.editPullRequest": ({ url: url2, edit }) => GitHub.use((github) => github.editPullRequest(url2, edit)),
100138
+ "github.assetUrl": ({ id: id2 }) => GitHub.use((github) => github.assetUrl(id2)),
99754
100139
  "github.fileContent": ({ url: url2, ref: ref2, path: path2 }) => GitHub.use((github) => github.fileContent(url2, ref2, path2)),
99755
100140
  "github.reviewComment": ({ url: url2, comment }) => GitHub.use((github) => github.reviewComment(url2, comment)),
100141
+ "github.review": ({ url: url2, review }) => GitHub.use((github) => github.review(url2, review)),
99756
100142
  "linear.issues": () => Linear.use((linear) => linear.assignedIssues),
99757
100143
  "github.repository": ({ projectId }) => Projects.use((projects) => projects.get(projectId)).pipe(
99758
100144
  flatMap(({ rootPath }) => GitHub.use((github) => github.repository(rootPath)))
@@ -99807,10 +100193,8 @@ const handlers = {
99807
100193
  "vm.control": ({ threadId, control }) => TinyVm.use((vm) => vm.setControl(threadId, control)),
99808
100194
  "vm.host": () => TinyVm.use((vm) => vm.host),
99809
100195
  "vm.desktop.url": ({ threadId }) => TinyVm.use((vm) => vm.desktopUrl(threadId)).pipe(map$2((url2) => ({ url: url2 }))),
99810
- "vm.screen.open": ({ threadId, streamId }, desktop) => {
99811
- const owner2 = desktop?.screenOwner;
99812
- return owner2 ? TinyVm.use((vm) => vm.openScreen(threadId, streamId, owner2)) : new VmError({ message: "The VM screen is only available in the desktop window." });
99813
- },
100196
+ "vm.screen.open": ({ threadId, streamId }) => TinyVm.use((vm) => vm.openScreen(threadId, streamId)),
100197
+ "vm.screen.read": ({ streamId, offset }) => TinyVm.use((vm) => vm.readScreen(streamId, offset)),
99814
100198
  "vm.screen.send": ({ streamId, data }) => TinyVm.use((vm) => vm.sendScreen(streamId, data)),
99815
100199
  "vm.screen.close": ({ streamId }) => TinyVm.use((vm) => vm.closeScreen(streamId)),
99816
100200
  "vm.files.drop": ({ threadId, paths }) => TinyVm.use((vm) => vm.dropFiles(threadId, paths)),
@@ -99866,7 +100250,10 @@ const handlers = {
99866
100250
  }),
99867
100251
  "remote.status": () => RemoteAccess.use((remote) => remote.status),
99868
100252
  "remote.pairing": () => RemoteAccess.use((remote) => remote.pairing),
99869
- "remote.rotateToken": () => RemoteAccess.use((remote) => remote.rotateToken)
100253
+ "remote.resetPairing": () => RemoteAccess.use((remote) => remote.resetPairing),
100254
+ "remote.devices": () => RemoteAccess.use((remote) => remote.devices),
100255
+ "remote.devices.approve": ({ code: code2 }) => RemoteAccess.use((remote) => remote.approve(code2)),
100256
+ "remote.devices.remove": ({ key: key2 }) => RemoteAccess.use((remote) => remote.remove(key2))
99870
100257
  };
99871
100258
  const RpcCall = Struct({
99872
100259
  method: Literals(Object.keys(RpcMethods)),
@@ -100170,45 +100557,53 @@ const ADDRESS_RETRY = min$1([exponential("500 millis"), spaced("30 seconds")]);
100170
100557
  const CALL_KEY_TTL_MS = toMillis(minutes(5));
100171
100558
  const MAX_CALL_KEYS = 2e3;
100172
100559
  const decodeClientFrame = decodeUnknownOption(ClientFrame);
100173
- const parseFrame = (raw2) => {
100560
+ const parseClientFrame = (text2) => {
100174
100561
  try {
100175
- return getOrUndefined$1(decodeClientFrame(JSON.parse(String(raw2))));
100562
+ return getOrUndefined$1(decodeClientFrame(JSON.parse(text2)));
100176
100563
  } catch {
100177
100564
  return void 0;
100178
100565
  }
100179
100566
  };
100180
100567
  const readFrame = (socket, raw2, isBinary) => {
100181
100568
  if (socket.readyState !== WebSocket$1.OPEN) return void 0;
100182
- const frame2 = isBinary ? void 0 : parseFrame(raw2);
100569
+ const frame2 = isBinary ? void 0 : parseClientFrame(String(raw2));
100183
100570
  if (frame2 === void 0) socket.close(CLOSE_MALFORMED_FRAME, "malformed frame");
100184
100571
  return frame2;
100185
100572
  };
100186
- const send = (socket, frame2) => {
100187
- if (socket.readyState !== WebSocket$1.OPEN) return;
100188
- socket.send(JSON.stringify(frame2));
100189
- };
100573
+ const socketChannel = (socket, seal = (json2) => json2) => ({
100574
+ send: (frame2) => {
100575
+ if (socket.readyState === WebSocket$1.OPEN) socket.send(seal(JSON.stringify(frame2)));
100576
+ },
100577
+ close: (code2, reason) => socket.close(code2, reason),
100578
+ ping: () => socket.ping(),
100579
+ terminate: () => socket.terminate(),
100580
+ onPong: (listener) => void socket.on("pong", listener),
100581
+ onClose: (listener) => void socket.on("close", listener)
100582
+ });
100190
100583
  const desktopOnly = (method2) => ({
100191
100584
  error: { tag: "DesktopOnly", message: `${method2} is only available in the desktop window` }
100192
100585
  });
100586
+ const machineOnly = (method2) => ({
100587
+ error: { tag: "MachineOnly", message: `${method2} is only available on the machine itself` }
100588
+ });
100193
100589
  const busy = {
100194
100590
  error: { tag: "RemoteBusy", message: "Too many actions are still running. Try again when one finishes." }
100195
100591
  };
100196
100592
  const describeError = (error2) => error2 instanceof Error ? error2.message : String(error2);
100197
- const makeSessions = ({ call: call2, subscribe: subscribe2, environment: environment2, features }) => gen(function* () {
100593
+ const makeSessions = ({ call: call2, subscribe: subscribe2, environment: environment2, features, remote }) => gen(function* () {
100198
100594
  const services = yield* context();
100199
100595
  const runFork2 = runForkWith(services);
100200
100596
  const runPromise2 = runPromiseWith(services);
100201
100597
  const now2 = () => runSyncWith(services)(currentTimeMillis);
100202
100598
  const peers = /* @__PURE__ */ new Map();
100203
- const attach = (socket, {
100599
+ const attach = (channel2, {
100204
100600
  compactEvents,
100205
100601
  relay: relay2,
100206
- proof,
100207
100602
  hosts
100208
100603
  }) => {
100209
100604
  const peer = { awaitingPong: false, watching: null };
100210
- peers.set(socket, peer);
100211
- socket.on("pong", () => {
100605
+ peers.set(channel2, peer);
100606
+ channel2.onPong(() => {
100212
100607
  peer.awaitingPong = false;
100213
100608
  });
100214
100609
  const compactPush = compactPushes();
@@ -100217,25 +100612,24 @@ const makeSessions = ({ call: call2, subscribe: subscribe2, environment: environ
100217
100612
  subscribe2((event) => {
100218
100613
  if (desktopOnlyPushes.has(event.type) || !reachesPhone(event, peer.watching)) return;
100219
100614
  const outgoing = compactEvents ? compactPush(event) : event;
100220
- if (outgoing !== null) send(socket, { type: "event", event: outgoing });
100615
+ if (outgoing !== null) channel2.send({ type: "event", event: outgoing });
100221
100616
  }).pipe(andThen(never$1))
100222
100617
  )
100223
100618
  );
100224
- socket.on("close", () => {
100225
- peers.delete(socket);
100619
+ channel2.onClose(() => {
100620
+ peers.delete(channel2);
100226
100621
  runFork2(interrupt$1(subscription));
100227
100622
  });
100228
- send(socket, {
100623
+ channel2.send({
100229
100624
  type: "ready",
100230
100625
  version: REMOTE_PROTOCOL_VERSION,
100231
100626
  environment: environment2,
100232
100627
  features,
100233
100628
  ...hosts !== void 0 && { hosts },
100234
- ...relay2 !== void 0 && { relay: relay2 },
100235
- ...proof !== void 0 && { proof }
100629
+ ...relay2 !== void 0 && { relay: relay2 }
100236
100630
  });
100237
100631
  };
100238
- const run2 = (method2, payload) => desktopOnlyMethods.has(method2) ? Promise.resolve(desktopOnly(method2)) : runPromise2(call2({ method: method2, payload })).catch((error2) => ({
100632
+ const run2 = (method2, payload) => desktopOnlyMethods.has(method2) ? Promise.resolve(desktopOnly(method2)) : remote && machineOnlyMethods.has(method2) ? Promise.resolve(machineOnly(method2)) : runPromise2(call2({ method: method2, payload })).catch((error2) => ({
100239
100633
  error: { tag: "Defect", message: describeError(error2) }
100240
100634
  }));
100241
100635
  const keyed = /* @__PURE__ */ new Map();
@@ -100266,42 +100660,39 @@ const makeSessions = ({ call: call2, subscribe: subscribe2, environment: environ
100266
100660
  void result2.then(() => markSettled(key2, result2));
100267
100661
  return result2;
100268
100662
  };
100269
- const receive = (socket, frame2) => {
100270
- if (frame2.type === "ping") return send(socket, { type: "pong", at: frame2.at });
100663
+ const receive = (channel2, frame2) => {
100664
+ if (frame2.type === "ping") return channel2.send({ type: "pong", at: frame2.at });
100271
100665
  if (frame2.type === "watch") {
100272
- const peer = peers.get(socket);
100666
+ const peer = peers.get(channel2);
100273
100667
  if (peer !== void 0) peer.watching = new Set(frame2.threadIds);
100274
100668
  return;
100275
100669
  }
100276
100670
  const { id: id2, method: method2, payload, key: key2 } = frame2;
100277
100671
  const result2 = key2 !== void 0 && mutations.has(method2) ? runOnce(key2, method2, payload) : run2(method2, payload);
100278
- void result2.then((envelope2) => send(socket, { type: "result", id: id2, envelope: envelope2 }));
100672
+ void result2.then((envelope2) => channel2.send({ type: "result", id: id2, envelope: envelope2 }));
100279
100673
  };
100280
100674
  const heartbeat = sync(() => {
100281
- for (const [socket, peer] of peers) {
100675
+ for (const [channel2, peer] of peers) {
100282
100676
  if (peer.awaitingPong) {
100283
- socket.terminate();
100677
+ channel2.terminate();
100284
100678
  continue;
100285
100679
  }
100286
100680
  peer.awaitingPong = true;
100287
- socket.ping();
100681
+ channel2.ping();
100288
100682
  }
100289
100683
  });
100290
100684
  yield* heartbeat.pipe(repeat(spaced(HEARTBEAT_INTERVAL)), forkScoped);
100291
100685
  return {
100292
100686
  attach,
100293
100687
  receive,
100294
- count: () => peers.size,
100295
- closeAll: (code2, reason) => {
100296
- for (const socket of peers.keys()) socket.close(code2, reason);
100297
- }
100688
+ count: () => peers.size
100298
100689
  };
100299
100690
  });
100300
100691
  const answerNotFound = (_, response2) => response2.writeHead(404).end();
100301
100692
  const listenWebSockets = ({
100302
100693
  listen,
100303
100694
  accept,
100304
- perMessageDeflate,
100695
+ maxPayload,
100305
100696
  request: request2 = answerNotFound
100306
100697
  }) => acquireRelease(
100307
100698
  callback((resume) => {
@@ -100309,8 +100700,8 @@ const listenWebSockets = ({
100309
100700
  const wss = new WebSocketServer({
100310
100701
  server: server2,
100311
100702
  path: REMOTE_PATH,
100312
- maxPayload: REMOTE_MAX_FRAME_BYTES,
100313
- perMessageDeflate
100703
+ maxPayload,
100704
+ perMessageDeflate: false
100314
100705
  });
100315
100706
  wss.on("connection", accept);
100316
100707
  wss.on("error", (error2) => resume(fail$2(error2)));
@@ -100350,19 +100741,21 @@ const make$3 = (dataDir) => gen(function* () {
100350
100741
  call: (raw2) => route(raw2, null),
100351
100742
  subscribe: windows.subscribe,
100352
100743
  environment: access2.identity,
100353
- features: RemoteFeature.filter((feature) => feature !== "asks")
100744
+ features: RemoteFeature.filter((feature) => feature !== "asks"),
100745
+ remote: false
100354
100746
  });
100355
100747
  const accept = (socket) => {
100748
+ const channel2 = socketChannel(socket);
100356
100749
  socket.on("error", () => {
100357
100750
  });
100358
100751
  socket.on("message", (raw2, isBinary) => {
100359
100752
  const frame2 = readFrame(socket, raw2, isBinary);
100360
100753
  if (frame2 === void 0) return;
100361
- if (frame2.type === "auth" || frame2.type === "hub" || frame2.type === "answer")
100362
- return socket.close(CLOSE_MALFORMED_FRAME, "malformed frame");
100363
- sessions.receive(socket, frame2);
100754
+ if (frame2.type === "call" || frame2.type === "ping" || frame2.type === "watch")
100755
+ return sessions.receive(channel2, frame2);
100756
+ socket.close(CLOSE_MALFORMED_FRAME, "malformed frame");
100364
100757
  });
100365
- sessions.attach(socket, { compactEvents: true });
100758
+ sessions.attach(channel2, { compactEvents: true });
100366
100759
  };
100367
100760
  yield* gen(function* () {
100368
100761
  if (!makePrivate(dirname(socketPath)))
@@ -100373,7 +100766,7 @@ const make$3 = (dataDir) => gen(function* () {
100373
100766
  yield* listenWebSockets({
100374
100767
  listen: (server2, listening2) => server2.listen(socketPath, listening2),
100375
100768
  accept,
100376
- perMessageDeflate: false
100769
+ maxPayload: REMOTE_MAX_FRAME_BYTES
100377
100770
  });
100378
100771
  chmodSync(socketPath, 384);
100379
100772
  yield* logInfo("cli socket listening", socketPath);
@@ -100381,6 +100774,18 @@ const make$3 = (dataDir) => gen(function* () {
100381
100774
  });
100382
100775
  const layer$3 = (dataDir) => process.platform === "win32" ? empty$9 : effectDiscard(make$3(dataDir));
100383
100776
  const AUTH_TIMEOUT = seconds(5);
100777
+ const APPROVAL_TIMEOUT = minutes(5);
100778
+ const CLOSE_INTERNAL_ERROR = 1011;
100779
+ const decodeLegacyAuth = decodeUnknownOption(fromJsonString(LegacyAuth));
100780
+ const utf8$1 = new TextDecoder("utf-8", { fatal: true });
100781
+ const openFrame = (cipher, raw2) => {
100782
+ try {
100783
+ return parseClientFrame(utf8$1.decode(cipher.decrypt(raw2)));
100784
+ } catch {
100785
+ return void 0;
100786
+ }
100787
+ };
100788
+ const sendPlain = (socket, frame2) => socket.send(JSON.stringify(frame2));
100384
100789
  const describeCause = (cause) => describeError(squash(cause));
100385
100790
  const staysOnPrivateNetworks = (socket) => [socket.localAddress, socket.remoteAddress].every((address) => address !== void 0 && isPrivateAddress(address));
100386
100791
  const hostnameOf = (host) => host !== void 0 && URL.canParse(`http://${host}`) ? new URL(`http://${host}`).hostname : null;
@@ -100420,15 +100825,11 @@ const make$2 = gen(function* () {
100420
100825
  call: (raw2) => dispatchHere(raw2, null),
100421
100826
  subscribe: broadcast.subscribe,
100422
100827
  environment: access2.identity,
100423
- features: RemoteFeature
100828
+ features: RemoteFeature,
100829
+ remote: true
100424
100830
  });
100831
+ const sockets = /* @__PURE__ */ new Set();
100425
100832
  const countConnected = () => runFork2(access2.report({ connected: sessions.count() }));
100426
- const attach = (socket, { proof, compactEvents }) => {
100427
- const relay2 = relayHostname(runSync(access2.status).relay) ?? void 0;
100428
- sessions.attach(socket, { compactEvents, relay: relay2, proof, hosts: advertisedHosts(current.bindHost) });
100429
- countConnected();
100430
- socket.on("close", countConnected);
100431
- };
100432
100833
  const forwardToApps = (request2, response2) => {
100433
100834
  const relay2 = relayHostname(runSync(access2.status).relay);
100434
100835
  const port = apps.port();
@@ -100439,40 +100840,129 @@ const make$2 = gen(function* () {
100439
100840
  };
100440
100841
  const accept = (socket) => {
100441
100842
  const challenge = newNonce();
100442
- let generation = null;
100443
- let hub = null;
100444
- const deadline2 = runFork2(
100445
- sleep$3(AUTH_TIMEOUT).pipe(
100446
- andThen(sync(() => socket.close(CLOSE_AUTH_TIMEOUT, "auth timeout")))
100447
- )
100843
+ let phase = { step: "opened" };
100844
+ let approvalDeadline = null;
100845
+ sockets.add(socket);
100846
+ const close2 = (code2, reason) => socket.close(code2, reason);
100847
+ const isOpen2 = () => socket.readyState === socket.OPEN;
100848
+ const malformed = () => close2(CLOSE_MALFORMED_FRAME, "malformed frame");
100849
+ const helloDeadline = runFork2(
100850
+ sleep$3(AUTH_TIMEOUT).pipe(andThen(sync(() => close2(CLOSE_AUTH_TIMEOUT, "auth timeout"))))
100448
100851
  );
100852
+ const answerLegacy = (raw2) => {
100853
+ const auth2 = getOrUndefined$1(decodeLegacyAuth(raw2.toString("utf8")));
100854
+ if (auth2 === void 0) return malformed();
100855
+ const answer = access2.answerLegacy(challenge, auth2);
100856
+ if (answer === null) return close2(CLOSE_UNAUTHORIZED, "unauthorized");
100857
+ sendPlain(socket, { type: "ready", version: REMOTE_PROTOCOL_VERSION, ...answer });
100858
+ close2(1e3, "this app predates end-to-end encryption");
100859
+ };
100860
+ const handshake2 = (raw2) => {
100861
+ try {
100862
+ const responder = respond({ prologue: REMOTE_PROLOGUE, local: access2.hostKey(), message: raw2 });
100863
+ const { message: message2, channel: cipher } = responder.reply(new Uint8Array(0));
100864
+ socket.send(message2);
100865
+ const channel2 = socketChannel(socket, (json2) => cipher.encrypt(utf8ToBytes(json2)));
100866
+ phase = { step: "handshaken", cipher, channel: channel2, key: encodeKey(responder.remoteStatic) };
100867
+ } catch {
100868
+ close2(CLOSE_HANDSHAKE_FAILED, "handshake failed");
100869
+ }
100870
+ };
100871
+ const ready = ({ cipher, channel: channel2, key: key2 }, compactEvents) => {
100872
+ if (!isOpen2()) return;
100873
+ if (approvalDeadline !== null) runFork2(interrupt$1(approvalDeadline));
100874
+ const relay2 = relayHostname(runSync(access2.status).relay) ?? void 0;
100875
+ sessions.attach(channel2, { compactEvents, relay: relay2, hosts: advertisedHosts(current.bindHost) });
100876
+ const disconnect = access2.connect(key2, close2);
100877
+ phase = { step: "ready", cipher, channel: channel2, key: key2, hub: null, disconnect };
100878
+ countConnected();
100879
+ channel2.onClose(countConnected);
100880
+ };
100881
+ const waitForApproval = (introduced) => {
100882
+ const serverNonce = newNonce$1();
100883
+ const waiting = access2.wait({
100884
+ key: introduced.key,
100885
+ name: introduced.hello.name,
100886
+ admit: () => {
100887
+ if (phase.step === "approving") ready(phase, phase.compactEvents);
100888
+ },
100889
+ close: close2
100890
+ });
100891
+ phase = { ...introduced, step: "pending", serverNonce, waiting };
100892
+ approvalDeadline = runFork2(
100893
+ sleep$3(APPROVAL_TIMEOUT).pipe(
100894
+ andThen(sync(() => close2(CLOSE_UNAUTHORIZED, "approval timed out")))
100895
+ )
100896
+ );
100897
+ introduced.channel.send({ type: "pending", commitment: bytesToHex(commitment(serverNonce)) });
100898
+ };
100899
+ const hello = (secured, frame2) => {
100900
+ runFork2(interrupt$1(helloDeadline));
100901
+ const introduced = {
100902
+ ...secured,
100903
+ hello: { key: secured.key, name: frame2.name, secret: frame2.secret, verify: frame2.verify },
100904
+ compactEvents: frame2.compactEvents ?? false
100905
+ };
100906
+ phase = { ...introduced, step: "deciding" };
100907
+ runFork2(
100908
+ access2.admit(introduced.hello).pipe(
100909
+ match$1({
100910
+ onFailure: () => close2(CLOSE_INTERNAL_ERROR, "could not check this device"),
100911
+ onSuccess: (decision) => {
100912
+ if (phase.step !== "deciding" || !isOpen2()) return;
100913
+ if (decision === "ready") ready(introduced, introduced.compactEvents);
100914
+ else waitForApproval(introduced);
100915
+ }
100916
+ })
100917
+ )
100918
+ );
100919
+ };
100920
+ const approval = (pending, frame2) => {
100921
+ pending.channel.send({ type: "approval", nonce: bytesToHex(pending.serverNonce) });
100922
+ const code2 = approvalCode(pending.cipher.handshakeHash, hexToBytes(frame2.nonce), pending.serverNonce);
100923
+ phase = { ...pending, step: "approving" };
100924
+ runFork2(pending.waiting.showsCode(code2));
100925
+ };
100926
+ const receiveBeforeReady = (waiting, raw2) => {
100927
+ const frame2 = openFrame(waiting.cipher, raw2);
100928
+ if (frame2 === void 0) return malformed();
100929
+ if (waiting.step === "handshaken") return frame2.type === "hello" ? hello(waiting, frame2) : malformed();
100930
+ if (frame2.type === "ping") return waiting.channel.send({ type: "pong", at: frame2.at });
100931
+ if (waiting.step === "pending" && frame2.type === "approval") return approval(waiting, frame2);
100932
+ malformed();
100933
+ };
100934
+ const receiveSession = (session, raw2, isBinary) => {
100935
+ const frame2 = isBinary ? openFrame(session.cipher, raw2) : void 0;
100936
+ if (frame2 === void 0 || frame2.type === "hello" || frame2.type === "approval") return malformed();
100937
+ if (frame2.type === "hub") return void (session.hub ??= peers.join((ask) => session.channel.send(ask)));
100938
+ if (frame2.type === "answer") {
100939
+ const { envelope: envelope2 } = frame2;
100940
+ return session.hub?.answer(frame2.id, "error" in envelope2 ? envelope2 : { result: envelope2.result });
100941
+ }
100942
+ sessions.receive(session.channel, frame2);
100943
+ };
100449
100944
  socket.on("close", () => {
100450
- runFork2(interrupt$1(deadline2));
100451
- hub?.leave();
100945
+ sockets.delete(socket);
100946
+ runFork2(interrupt$1(helloDeadline));
100947
+ if (approvalDeadline !== null) runFork2(interrupt$1(approvalDeadline));
100948
+ if (phase.step === "pending" || phase.step === "approving") phase.waiting.leave();
100949
+ if (phase.step === "ready") {
100950
+ phase.hub?.leave();
100951
+ phase.disconnect();
100952
+ }
100953
+ phase = { step: "closed" };
100452
100954
  });
100453
100955
  socket.on("error", () => {
100454
100956
  });
100455
100957
  socket.on("message", (raw2, isBinary) => {
100456
- const frame2 = readFrame(socket, raw2, isBinary);
100457
- if (frame2 === void 0) return;
100458
- if (generation === null) {
100459
- if (frame2.type !== "auth") return socket.close(CLOSE_MALFORMED_FRAME, "expected auth");
100460
- const proof = "proof" in frame2 ? access2.answerChallenge(challenge, frame2.nonce, frame2.proof) : access2.authenticate(frame2.token) ? void 0 : null;
100461
- if (proof === null) return socket.close(CLOSE_UNAUTHORIZED, "unauthorized");
100462
- generation = access2.generation();
100463
- runFork2(interrupt$1(deadline2));
100464
- return attach(socket, { proof, compactEvents: frame2.compactEvents ?? false });
100465
- }
100466
- if (access2.generation() !== generation) return socket.close(CLOSE_TOKEN_ROTATED, "token rotated");
100467
- if (frame2.type === "auth") return;
100468
- if (frame2.type === "hub") return void (hub ??= peers.join((ask) => send(socket, ask)));
100469
- if (frame2.type === "answer") {
100470
- const { envelope: envelope2 } = frame2;
100471
- return hub?.answer(frame2.id, "error" in envelope2 ? envelope2 : { result: envelope2.result });
100472
- }
100473
- sessions.receive(socket, frame2);
100958
+ if (!isOpen2() || phase.step === "closed") return;
100959
+ if (phase.step === "ready") return receiveSession(phase, raw2, isBinary);
100960
+ if (raw2.length > REMOTE_PRE_READY_MAX_BYTES) return malformed();
100961
+ if (phase.step === "opened") return isBinary ? handshake2(raw2) : answerLegacy(raw2);
100962
+ if (!isBinary) return malformed();
100963
+ receiveBeforeReady(phase, raw2);
100474
100964
  });
100475
- send(socket, { type: "challenge", nonce: challenge });
100965
+ sendPlain(socket, { type: "challenge", nonce: challenge });
100476
100966
  };
100477
100967
  const listen = (address) => listenWebSockets({
100478
100968
  listen: (server2, listening2) => {
@@ -100484,7 +100974,7 @@ const make$2 = gen(function* () {
100484
100974
  server2.listen(address.port, everyInterface ? "0.0.0.0" : address.bindHost, listening2);
100485
100975
  },
100486
100976
  accept,
100487
- perMessageDeflate: true,
100977
+ maxPayload: REMOTE_SEALED_FRAME_BYTES,
100488
100978
  request: forwardToApps
100489
100979
  }).pipe(
100490
100980
  tapError(
@@ -100522,8 +101012,12 @@ const make$2 = gen(function* () {
100522
101012
  }),
100523
101013
  forkScoped
100524
101014
  );
100525
- yield* access2.rotations.pipe(
100526
- runForEach(() => sync(() => sessions.closeAll(CLOSE_TOKEN_ROTATED, "token rotated"))),
101015
+ yield* access2.resets.pipe(
101016
+ runForEach(
101017
+ () => sync(() => {
101018
+ for (const socket of sockets) socket.close(CLOSE_PAIRING_RESET, "pairing reset");
101019
+ })
101020
+ ),
100527
101021
  forkScoped
100528
101022
  );
100529
101023
  });
@@ -100542,10 +101036,10 @@ const portOf = (raw2, source) => {
100542
101036
  return port;
100543
101037
  };
100544
101038
  const restartCommand = (process2) => {
100545
- const { HINACODE_SERVE_ROTATE_TOKEN: _rotated, ...env } = process2.env;
101039
+ const { HINACODE_SERVE_RESET_PAIRING: _reset, ...env } = process2.env;
100546
101040
  return {
100547
101041
  file: process2.execPath,
100548
- args: [process2.execPath, ...process2.execArgv, ...process2.argv.slice(1).filter((arg) => arg !== "--rotate-token")],
101042
+ args: [process2.execPath, ...process2.execArgv, ...process2.argv.slice(1).filter((arg) => arg !== "--reset-pairing")],
100549
101043
  env
100550
101044
  };
100551
101045
  };
@@ -100561,6 +101055,15 @@ const boundServeLog = async (path2, maxBytes = SERVE_LOG_MAX_BYTES) => {
100561
101055
  await truncate$2(path2, 0);
100562
101056
  };
100563
101057
  const autoUpdate = (env) => env["HINACODE_SERVE_AUTO_UPDATE"] === void 0 || envFlag(env, "HINACODE_SERVE_AUTO_UPDATE");
101058
+ const selfHostedRelayFromEnv = (env) => {
101059
+ const url2 = env["HINACODE_SERVE_SELF_HOSTED_RELAY"];
101060
+ const token = env["HINACODE_SERVE_SELF_HOSTED_RELAY_TOKEN"];
101061
+ if (url2 === void 0 && token === void 0) return void 0;
101062
+ if (url2 === void 0 || token === void 0) {
101063
+ throw new Error("HINACODE_SERVE_SELF_HOSTED_RELAY and HINACODE_SERVE_SELF_HOSTED_RELAY_TOKEN go together");
101064
+ }
101065
+ return { url: url2, token };
101066
+ };
100564
101067
  const relayFromEnv = (env) => {
100565
101068
  const relay2 = env["HINACODE_SERVE_RELAY"];
100566
101069
  if (relay2 === void 0 || relay2 === "on" || relay2 === "off") return relay2;
@@ -100577,11 +101080,13 @@ const serveConfig = (flags, env) => {
100577
101080
  );
100578
101081
  }
100579
101082
  const relay2 = flags.relay ?? relayFromEnv(env);
101083
+ const selfHostedRelay = selfHostedRelayFromEnv(env);
100580
101084
  return {
100581
101085
  ...bindHost !== void 0 && { bindHost },
100582
101086
  ...port !== void 0 && { port },
100583
101087
  ...relay2 !== void 0 && { relay: relay2 },
100584
- rotateToken: flags.rotateToken || envFlag(env, "HINACODE_SERVE_ROTATE_TOKEN")
101088
+ ...selfHostedRelay !== void 0 && { selfHostedRelay },
101089
+ resetPairing: flags.resetPairing || envFlag(env, "HINACODE_SERVE_RESET_PAIRING")
100585
101090
  };
100586
101091
  };
100587
101092
  const applyServeConfig = (config2) => gen(function* () {
@@ -100592,7 +101097,7 @@ const applyServeConfig = (config2) => gen(function* () {
100592
101097
  if (next2.enabled !== current.enabled || next2.bindHost !== current.bindHost || next2.port !== current.port) {
100593
101098
  yield* settings.set({ remote: next2 });
100594
101099
  }
100595
- if (config2.rotateToken) yield* RemoteAccess.use((remote) => remote.rotateToken);
101100
+ if (config2.resetPairing) yield* RemoteAccess.use((remote) => remote.resetPairing);
100596
101101
  });
100597
101102
  const applyServeRelay = (relay2, onLink) => gen(function* () {
100598
101103
  if (relay2 === void 0) return;
@@ -100601,6 +101106,7 @@ const applyServeRelay = (relay2, onLink) => gen(function* () {
100601
101106
  if ("hostname" in (yield* service2.status)) return;
100602
101107
  yield* service2.setup({ onLink }).pipe(retry$3({ while: (error2) => error2.message === EXPIRED }));
100603
101108
  });
101109
+ const applyServeSelfHostedRelay = (selfHostedRelay) => selfHostedRelay === void 0 ? void_ : Relay.use((relay2) => relay2.useSelfHosted(selfHostedRelay));
100604
101110
  const browserCommand = (url2, platform, env) => {
100605
101111
  const parsed = URL.parse(url2);
100606
101112
  if (parsed === null || parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
@@ -121248,7 +121754,7 @@ function requireServer() {
121248
121754
  server.Server = Server;
121249
121755
  async function handleUnary(call2, handler) {
121250
121756
  let stream2;
121251
- function respond(err, value2, trailer, flags) {
121757
+ function respond2(err, value2, trailer, flags) {
121252
121758
  if (err) {
121253
121759
  call2.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer));
121254
121760
  return;
@@ -121291,7 +121797,7 @@ function requireServer() {
121291
121797
  }
121292
121798
  stream2 = new server_call_1.ServerWritableStreamImpl(handler.path, call2, requestMetadata, requestMessage);
121293
121799
  try {
121294
- handler.func(stream2, respond);
121800
+ handler.func(stream2, respond2);
121295
121801
  } catch (err) {
121296
121802
  let details;
121297
121803
  if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) {
@@ -121316,7 +121822,7 @@ function requireServer() {
121316
121822
  }
121317
121823
  function handleClientStreaming(call2, handler) {
121318
121824
  let stream2;
121319
- function respond(err, value2, trailer, flags) {
121825
+ function respond2(err, value2, trailer, flags) {
121320
121826
  if (err) {
121321
121827
  call2.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer));
121322
121828
  return;
@@ -121333,7 +121839,7 @@ function requireServer() {
121333
121839
  onReceiveMetadata(metadata2) {
121334
121840
  stream2 = new server_call_1.ServerDuplexStreamImpl(handler.path, call2, metadata2);
121335
121841
  try {
121336
- handler.func(stream2, respond);
121842
+ handler.func(stream2, respond2);
121337
121843
  } catch (err) {
121338
121844
  let details;
121339
121845
  if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) {
@@ -124740,8 +125246,8 @@ const makeIosDriver = (options) => {
124740
125246
  );
124741
125247
  const compileHelper = async () => {
124742
125248
  const dir = join$1(options.cacheDir, `simhelper-${sourceHash(options.sources)}`);
124743
- const binary = join$1(dir, "simhelper");
124744
- if (await isExecutable(binary)) return binary;
125249
+ const binary2 = join$1(dir, "simhelper");
125250
+ if (await isExecutable(binary2)) return binary2;
124745
125251
  await mkdir(dir, { recursive: true });
124746
125252
  await Promise.all(Object.entries(options.sources).map(([name, text2]) => writeFile(join$1(dir, name), text2)));
124747
125253
  const output = join$1(dir, `simhelper-${randomUUID()}`);
@@ -124750,8 +125256,8 @@ const makeIosDriver = (options) => {
124750
125256
  ["swiftc", "-O", "-swift-version", "5", join$1(dir, "main.swift"), join$1(dir, "hid.swift"), "-o", output],
124751
125257
  3e5
124752
125258
  );
124753
- await rename(output, binary);
124754
- return binary;
125259
+ await rename(output, binary2);
125260
+ return binary2;
124755
125261
  };
124756
125262
  const helperBinary = () => {
124757
125263
  helper ??= compileHelper().catch((error2) => {
@@ -124762,8 +125268,8 @@ const makeIosDriver = (options) => {
124762
125268
  };
124763
125269
  const connect2 = async (id2, onFrame) => {
124764
125270
  const udid = udidOf(id2);
124765
- const binary = await helperBinary();
124766
- const child = spawn(binary, [udid, await xcodeDeveloperDir(), String(FRAME_QUALITY), String(FRAME_MAX_WIDTH)], {
125271
+ const binary2 = await helperBinary();
125272
+ const child = spawn(binary2, [udid, await xcodeDeveloperDir(), String(FRAME_QUALITY), String(FRAME_MAX_WIDTH)], {
124767
125273
  stdio: ["pipe", "pipe", "pipe"]
124768
125274
  });
124769
125275
  child.stdin.on("error", () => {
@@ -125252,7 +125758,16 @@ const makeAppLayer = ({
125252
125758
  const domain = mergeAll(
125253
125759
  layer$z.pipe(
125254
125760
  provideMerge(chats),
125255
- provideMerge(layer$C(join$1(userData, "scratch"))),
125761
+ provideMerge(
125762
+ layer$C(join$1(userData, "scratch"), {
125763
+ privatePaths: [
125764
+ join$1(userData, "hinacode.sqlite*"),
125765
+ join$1(userData, "chromium", "**"),
125766
+ join$1(userData, "tiny-vm", "chromium-profile*")
125767
+ ]
125768
+ })
125769
+ ),
125770
+ provideMerge(layer$U),
125256
125771
  provideMerge(layer$B),
125257
125772
  provideMerge(layer$A),
125258
125773
  provideMerge(layer$D),
@@ -125331,7 +125846,7 @@ const makeAppLayer = ({
125331
125846
  provideMerge(binaries),
125332
125847
  provideMerge(layer$F),
125333
125848
  provideMerge(mergeAll(layer$J, layer$H, layer$g)),
125334
- provideMerge(makeEventsLayer()),
125849
+ provideMerge(makeEventsLayer(toWindows)),
125335
125850
  provide$2(mergeAll(layer$p(join$1(userData, "hinacode.sqlite")), keyring)),
125336
125851
  provide$2(layer$Z),
125337
125852
  provideMerge(watchdogLayer(spans)),
@@ -125463,6 +125978,7 @@ const hydratePath = (env, cacheFile) => {
125463
125978
  const QUIT_TIMEOUT_MS = 5e3;
125464
125979
  const SERVE_LOG_CHECK_MS = 10 * 6e4;
125465
125980
  const LISTEN_TIMEOUT_MS = 5e3;
125981
+ const WAITING_DEVICE = "A device is waiting for approval. Run hinacode devices approve <code> with the code it shows.\n";
125466
125982
  const { version } = packageJson;
125467
125983
  const packageRoot = isSea() ? void 0 : fileURLToPath(new URL("../..", import.meta.url));
125468
125984
  const appData = () => process.platform === "darwin" ? join$1(homedir(), "Library", "Application Support") : process.platform === "win32" ? process.env["APPDATA"] ?? join$1(homedir(), "AppData", "Roaming") : process.env["XDG_CONFIG_HOME"] ?? join$1(homedir(), ".config");
@@ -125497,7 +126013,8 @@ const pairingText = async (userData, pairing) => {
125497
126013
  ...pairing.relay === null ? [] : [`Reachable from any network through ${pairing.relay}.`, ""],
125498
126014
  "Pair a desktop: Settings > Connections > Add environment, with one of:",
125499
126015
  ...pairing.hosts.map((host) => ` ${pairingUrl({ ...pairing, hosts: [host] })}`),
125500
- "Keep the token in these URLs private. Run `hinacode pair` to print them again.",
126016
+ "The secret in these URLs pairs one device, then the cloud replaces it. Run `hinacode pair` to print a fresh one.",
126017
+ "Run `hinacode devices` to see the paired devices, and `hinacode devices remove` to unpair one.",
125501
126018
  ""
125502
126019
  ].join("\n");
125503
126020
  };
@@ -125535,10 +126052,17 @@ const keepServeLogBounded = (path2) => {
125535
126052
  void check2();
125536
126053
  setInterval(check2, SERVE_LOG_CHECK_MS).unref();
125537
126054
  };
126055
+ const plaintextSecretsWarning = (database) => [
126056
+ `Warning: secrets are stored as plaintext in ${database}.`,
126057
+ "hinacode serve has no OS keyring. Anyone who can read this user's files can read them, including the agents it runs.",
126058
+ "",
126059
+ ""
126060
+ ].join("\n");
125538
126061
  const serve = async (flags, userData) => {
125539
126062
  const config2 = serveConfig(flags, process.env);
125540
126063
  mkdirSync(userData, { recursive: true, mode: 448 });
125541
126064
  lockDataDir(userData);
126065
+ process.stdout.write(plaintextSecretsWarning(join$1(userData, "hinacode.sqlite")));
125542
126066
  const serveLog = process.env["HINACODE_SERVE_LOG"];
125543
126067
  if (serveLog) keepServeLogBounded(serveLog);
125544
126068
  await hydratePath(process.env).ready;
@@ -125557,7 +126081,8 @@ const serve = async (flags, userData) => {
125557
126081
  process.execve(file, args, env);
125558
126082
  })
125559
126083
  }),
125560
- toWindows: () => {
126084
+ toWindows: (event) => {
126085
+ if (event.type === "remote.devices.changed" && event.reason === "waiting") process.stdout.write(WAITING_DEVICE);
125561
126086
  },
125562
126087
  serve: config2
125563
126088
  })
@@ -125588,6 +126113,7 @@ const serve = async (flags, userData) => {
125588
126113
  )
125589
126114
  );
125590
126115
  if (linking) process.stdout.write("Linked.\n");
126116
+ await runtime.runPromise(applyServeSelfHostedRelay(config2.selfHostedRelay));
125591
126117
  } catch (error2) {
125592
126118
  await runtime.dispose();
125593
126119
  throw error2;
@@ -125606,7 +126132,14 @@ const pair = async (userData) => {
125606
126132
  const runtime = make$1j(
125607
126133
  layer$S.pipe(
125608
126134
  provideMerge(mergeAll(layer$T(userData), layer$U)),
125609
- provideMerge(mergeAll(layer$p(database), noKeyring)),
126135
+ provideMerge(
126136
+ mergeAll(
126137
+ layer$p(database),
126138
+ noKeyring,
126139
+ makeEventsLayer(() => {
126140
+ })
126141
+ )
126142
+ ),
125610
126143
  provide$2(succeed$5(MinimumLogLevel, "Warn"))
125611
126144
  )
125612
126145
  );