@rivus/gateway 0.23.0 → 0.24.0

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.
@@ -1,19 +1,20 @@
1
- import { i as formatSchemaIssuePath, n as readTenantKey, r as storedFeishuReceiveMessageSchema } from "./feishu-receive-message.js";
1
+ import { a as readLocalJsonFrame } from "./superagent-worker-wire.js";
2
+ import { a as storedFeishuReceiveMessageSchema, i as readTenantKey, l as formatSchemaIssuePath, n as HerdrRequestError } from "./herdr-socket-client.js";
2
3
  import { createRequire } from "node:module";
3
4
  import { Cause, Context, Deferred, Effect, Exit, Option, Result, Schema, SchemaGetter, SchemaIssue, Semaphore } from "effect";
4
- import { access, appendFile, constants, cp, mkdir, open, readFile, readdir, realpath, rename, rm, stat } from "node:fs/promises";
5
+ import { createServer } from "node:net";
6
+ import { access, appendFile, chmod, constants, cp, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
5
7
  import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from "node:path";
6
8
  import { assertPathWithin, isNodeErrorWithCode, isPathWithin } from "@rivus/platform/filesystem";
7
9
  import { RIVUS_RUNTIME_TOOL_IDS, createRecoveryAction, openJsonlToolOperationLedger } from "@rivus/runtime";
8
10
  import { readPersistenceFile, writeAtomicTextFile, writePersistenceFile } from "@rivus/platform/persistence";
9
11
  import { fileURLToPath, pathToFileURL } from "node:url";
10
- import { execFile, spawn } from "node:child_process";
11
- import { promisify } from "node:util";
12
12
  import { coerce, satisfies } from "semver";
13
13
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
14
- import { createHash, randomUUID } from "node:crypto";
14
+ import { createHash, randomInt, randomUUID } from "node:crypto";
15
15
  import { acquireProcessLock } from "@rivus/agent-kit-collab/process-lock";
16
16
  import { constants as constants$1 } from "node:fs";
17
+ import { spawn } from "node:child_process";
17
18
  //#region src/lib/deep-freeze.ts
18
19
  function deepFreeze(value) {
19
20
  if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
@@ -104,6 +105,62 @@ function invokeRuntimeControl(runtime, control) {
104
105
  return runtime.pipe(Effect.flatMap((selected) => selected ? control(selected) ?? Effect.succeed(false) : Effect.succeed(false)));
105
106
  }
106
107
  //#endregion
108
+ //#region src/agent-host/infra/adapters/local-json-socket-server.ts
109
+ /** The caller holds the deployment process lock before creating or recovering a socket. */
110
+ async function openLocalJsonSocket(path, handle, serializeFailure) {
111
+ await mkdir(dirname(path), {
112
+ recursive: true,
113
+ mode: 448
114
+ });
115
+ await chmod(dirname(path), 448);
116
+ try {
117
+ if (!(await lstat(path)).isSocket()) throw new Error("Rivus socket path contains a non-socket file");
118
+ await unlink(path);
119
+ } catch (error) {
120
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
121
+ }
122
+ const clients = /* @__PURE__ */ new Set();
123
+ const requests = /* @__PURE__ */ new Set();
124
+ const server = createServer((socket) => {
125
+ clients.add(socket);
126
+ socket.setTimeout(1e4, () => socket.destroy());
127
+ socket.once("error", () => socket.destroy());
128
+ socket.once("close", () => clients.delete(socket));
129
+ readLocalJsonFrame(socket, (frame) => {
130
+ const response = Promise.resolve().then(() => handle(frame)).then((value) => socket.end(JSON.stringify({
131
+ ok: true,
132
+ value: value ?? null
133
+ }) + "\n")).catch((error) => {
134
+ const failure = serializeFailure?.(error) ?? { error: "Rivus request was rejected" };
135
+ socket.end(JSON.stringify({
136
+ ok: false,
137
+ ...failure
138
+ }) + "\n");
139
+ }).then(() => void 0);
140
+ requests.add(response);
141
+ response.finally(() => requests.delete(response));
142
+ });
143
+ });
144
+ await new Promise((resolve, reject) => {
145
+ server.once("error", reject);
146
+ server.listen(path, resolve);
147
+ });
148
+ const close = async () => {
149
+ for (const client of clients) client.destroy();
150
+ await new Promise((resolve, reject) => {
151
+ server.close((error) => error ? reject(error) : resolve());
152
+ });
153
+ await Promise.allSettled(requests);
154
+ };
155
+ try {
156
+ await chmod(path, 384);
157
+ } catch (error) {
158
+ await close();
159
+ throw error;
160
+ }
161
+ return { close };
162
+ }
163
+ //#endregion
107
164
  //#region src/lib/error-message.ts
108
165
  /** Renders a thrown value as text: an Error's message, anything else through `String`. */
109
166
  function errorMessage(error) {
@@ -111,6 +168,7 @@ function errorMessage(error) {
111
168
  }
112
169
  //#endregion
113
170
  //#region src/background-session/domain/background-session/background-session-authority.ts
171
+ /** @internal */
114
172
  const BACKGROUND_SESSION_START_TOOL_ID = "background.start";
115
173
  const BACKGROUND_SESSION_TOOL_PLUGIN_ID = "rivus-core";
116
174
  const BACKGROUND_SESSION_TOOL_VERSION = "1.0.0";
@@ -302,8 +360,119 @@ function narrowBackgroundSessionDefinition(definition, digest) {
302
360
  });
303
361
  }
304
362
  //#endregion
305
- //#region ../source-github/dist/index.js
306
- const apiOrigin = "https://api.github.com";
363
+ //#region ../scenarios/coding/dist/index.js
364
+ /** The branch a Task's worker pushes its pull requests from. */
365
+ function taskBranch(shortName) {
366
+ return `agent/${shortName}`;
367
+ }
368
+ /** The short name of the Task a branch belongs to; `undefined` for a branch no Task works on. */
369
+ function branchShortName(branch) {
370
+ return branch.startsWith("agent/") ? branch.slice(6) : void 0;
371
+ }
372
+ /** Whether a pull request host serving `served` serves `repository`, ignoring case. */
373
+ function isServed(served, repository) {
374
+ const wanted = repository.toLowerCase();
375
+ return served.some((name) => name.toLowerCase() === wanted);
376
+ }
377
+ /**
378
+ * Whether a Task waits for the pull request host's account before its worker starts. Only a Task whose repository the
379
+ * host serves waits; other Tasks continue without the account's identity.
380
+ */
381
+ function waitsForHost(served, repository) {
382
+ return repository !== void 0 && isServed(served, repository);
383
+ }
384
+ /**
385
+ * Limits the host does not enforce on a worker's code host writes; they reach the worker only as instructions. A
386
+ * resumed worker checks the branch first, since an earlier execution may already have opened its pull request.
387
+ */
388
+ const workerInstructions = "Do not merge pull requests. Act on code hosts only as the agent account, with the credentials Rivus provides. Before opening a pull request, check whether the task branch already has one. Report the URL of every pull request you open in task_report links.";
389
+ /**
390
+ * Coding: a Task's worker works on the branch `agent/<shortName>` and opens pull requests from it as the host's
391
+ * account. The scenario binds the account's own pull requests from that branch as the Task's deliverables, so the
392
+ * Task ends once they have all closed, and follows a pull request the worker reports from anywhere else. It registers
393
+ * with the host for the pull requests the account opens, so their discovery does not wait for a worker's report.
394
+ */
395
+ function createCodingScenario(host, work) {
396
+ /**
397
+ * The account's own pull requests from the Task's branch. Discovery searches the Task's repository, so it runs only
398
+ * for a repository the host serves.
399
+ */
400
+ async function discover(branch, repository) {
401
+ return isServed(host.repositories, repository) ? host.findPullRequests(repository, branch) : [];
402
+ }
403
+ /**
404
+ * Binds what a report names. Every pull request is read before anything is bound, and the deliverables are bound in
405
+ * one call: a Task ends once all its deliverables have closed, so binding a closed one before an open one would end
406
+ * the Task and drop the open one, and a read that fails after an earlier bind would leave the retry facing an ended
407
+ * Task. Followed threads are bound first because binding to an ended Task does nothing.
408
+ */
409
+ async function bindReport(task, report) {
410
+ const branch = taskBranch(task.shortName);
411
+ const deliverables = report.state === "ready" && task.repository !== void 0 ? [...await discover(branch, task.repository)] : [];
412
+ const followed = [];
413
+ for (const link of report.links ?? []) {
414
+ const read = await host.readPullRequest(link, branch);
415
+ if (read === "unverified") work.reportFailure(`pull-request:${task.id}`);
416
+ else if (read !== "unrecognized") (read.own ? deliverables : followed).push(read.thread);
417
+ }
418
+ for (const thread of followed) await work.bindThread(task.id, thread);
419
+ if (deliverables.length > 0) await work.bindDeliverables(task.id, deliverables);
420
+ }
421
+ /**
422
+ * Binds the pull requests of the open Task whose branch the account's new pull request came from, unless the Task
423
+ * already follows that thread.
424
+ */
425
+ async function ownPullRequestSeen(repository, branch, thread) {
426
+ const shortName = branchShortName(branch);
427
+ const taskId = shortName === void 0 ? void 0 : work.openTaskByShortName(shortName);
428
+ if (taskId === void 0 || work.isSubscribed(thread)) return;
429
+ const threads = await discover(branch, repository);
430
+ if (threads.length > 0) await work.bindDeliverables(taskId, threads);
431
+ }
432
+ host.onOwnPullRequestSeen(ownPullRequestSeen);
433
+ const helper = work.gitCredentialHelper;
434
+ return {
435
+ repositories: host.repositories,
436
+ repositoryOf: host.repositoryOf,
437
+ workerInstructions,
438
+ onTaskReported: ({ task, report }) => bindReport(task, report),
439
+ /** `waiting` holds a Task in a served repository until the account is verified. */
440
+ workerEnvironment(task) {
441
+ const identity = host.identity();
442
+ if (identity === void 0 && waitsForHost(host.repositories, task.repository)) return "waiting";
443
+ return {
444
+ variables: identity?.variables ?? {},
445
+ gitConfig: [...helper === void 0 ? [] : [["credential.helper", helper]], ...identity?.gitConfig ?? []]
446
+ };
447
+ },
448
+ credential: (_task, request) => host.credential(request.repository)
449
+ };
450
+ }
451
+ const callable = Schema.Any.check(Schema.makeFilter((value) => typeof value === "function"));
452
+ const hostingKind = Schema.is(Schema.Struct({ codingHost: Schema.Struct({ repositories: callable }) }));
453
+ const hostingSource = Schema.is(Schema.Struct({ codingHost: Schema.Struct({
454
+ onOwnPullRequestSeen: callable,
455
+ identity: callable
456
+ }) }));
457
+ const offersCodingHost = (kind) => hostingKind(kind);
458
+ const isCodingHost = (source) => hostingSource(source);
459
+ /**
460
+ * The coding scenario kind. `codeHost` must name a source whose kind offers the coding host; the scenario acts through
461
+ * that host, so polling, pull request binding, worker credentials and the worker identity act as one account.
462
+ */
463
+ const codingScenarioKind = {
464
+ kind: "coding",
465
+ config: Schema.Struct({}),
466
+ codeHost: ({ kind, settings }) => offersCodingHost(kind) ? { repositories: kind.codingHost.repositories(settings) } : void 0,
467
+ create(context) {
468
+ const { codeHost } = context;
469
+ if (!isCodingHost(codeHost)) throw new Error("The coding scenario's code host source offers no coding host");
470
+ return createCodingScenario(codeHost.codingHost, context);
471
+ }
472
+ };
473
+ //#endregion
474
+ //#region ../triggers/github/dist/index.js
475
+ const apiOrigin$1 = "https://api.github.com";
307
476
  const pageLimit = 20;
308
477
  const nonempty$1 = Schema.NonEmptyString;
309
478
  /**
@@ -355,8 +524,8 @@ function createGitHubTransport(token, request, state) {
355
524
  headers.set("authorization", `Bearer ${token}`);
356
525
  headers.set("content-type", "application/json");
357
526
  headers.set("X-GitHub-Api-Version", "2022-11-28");
358
- const url = new URL(path, apiOrigin);
359
- if (url.origin !== apiOrigin || url.username !== "" || url.password !== "") throw new Error("GitHub pagination link is outside the configured API");
527
+ const url = new URL(path, apiOrigin$1);
528
+ if (url.origin !== apiOrigin$1 || url.username !== "" || url.password !== "") throw new Error("GitHub pagination link is outside the configured API");
360
529
  const timeout = AbortSignal.timeout(2e4);
361
530
  const signal = init?.signal == null ? timeout : AbortSignal.any([init.signal, timeout]);
362
531
  const result = await request(url, {
@@ -394,7 +563,7 @@ function createGitHubTransport(token, request, state) {
394
563
  function conditionalReads(signal) {
395
564
  const pending = /* @__PURE__ */ new Map();
396
565
  async function page(path, schema, options) {
397
- const url = new URL(path, apiOrigin);
566
+ const url = new URL(path, apiOrigin$1);
398
567
  const key = `github-page:${url.pathname}${url.search}`;
399
568
  const entry = cachedPage(schema);
400
569
  const memoryOnly = options?.memoryOnly === true;
@@ -444,7 +613,7 @@ function createGitHubTransport(token, request, state) {
444
613
  values.push(...result.value);
445
614
  inferredNext = result.next === void 0 && result.value.length === 100;
446
615
  if (inferredNext) {
447
- const url = new URL(next, apiOrigin);
616
+ const url = new URL(next, apiOrigin$1);
448
617
  url.searchParams.set("page", String(Number(url.searchParams.get("page") ?? 1) + 1));
449
618
  next = url.href;
450
619
  } else next = result.next;
@@ -532,9 +701,9 @@ async function pollUntilAborted(context, options, poll, signal) {
532
701
  }
533
702
  }
534
703
  /** The GitHub REST shapes the GitHub source kinds read; unknown fields are ignored. */
535
- const nonempty = Schema.NonEmptyString;
704
+ const nonempty$2 = Schema.NonEmptyString;
536
705
  const actor = Schema.Struct({
537
- login: nonempty,
706
+ login: nonempty$2,
538
707
  type: Schema.String
539
708
  });
540
709
  const issue = Schema.Struct({
@@ -542,8 +711,8 @@ const issue = Schema.Struct({
542
711
  state: Schema.String,
543
712
  user: Schema.NullOr(actor),
544
713
  body: Schema.NullOr(Schema.String),
545
- created_at: nonempty,
546
- updated_at: Schema.optionalKey(nonempty),
714
+ created_at: nonempty$2,
715
+ updated_at: Schema.optionalKey(nonempty$2),
547
716
  closed_at: Schema.NullOr(Schema.String),
548
717
  pull_request: Schema.optionalKey(Schema.Unknown)
549
718
  });
@@ -551,9 +720,9 @@ const comment = Schema.Struct({
551
720
  id: Schema.Int,
552
721
  user: Schema.NullOr(actor),
553
722
  body: Schema.NullOr(Schema.String),
554
- created_at: Schema.optionalKey(nonempty),
555
- updated_at: Schema.optionalKey(nonempty),
556
- submitted_at: Schema.optionalKey(Schema.NullOr(nonempty)),
723
+ created_at: Schema.optionalKey(nonempty$2),
724
+ updated_at: Schema.optionalKey(nonempty$2),
725
+ submitted_at: Schema.optionalKey(Schema.NullOr(nonempty$2)),
557
726
  in_reply_to_id: Schema.optionalKey(Schema.Int),
558
727
  /** A review's state, such as `APPROVED` or `CHANGES_REQUESTED`; comments have none. */
559
728
  state: Schema.optionalKey(Schema.String)
@@ -564,47 +733,47 @@ const commentList = Schema.Array(comment);
564
733
  * which thread changed and when, so the page may persist without comment bodies.
565
734
  */
566
735
  const repositoryComments = Schema.Array(Schema.Struct({
567
- updated_at: nonempty,
568
- issue_url: nonempty
736
+ updated_at: nonempty$2,
737
+ issue_url: nonempty$2
569
738
  }));
570
739
  /** A repository's inline review comments, read like `repositoryComments`. */
571
740
  const repositoryReviewComments = Schema.Array(Schema.Struct({
572
- updated_at: nonempty,
573
- pull_request_url: nonempty
741
+ updated_at: nonempty$2,
742
+ pull_request_url: nonempty$2
574
743
  }));
575
744
  /** The open pull requests of a repository, most recently updated first; only metadata, so the page may persist. */
576
745
  const recentPullRequests = Schema.Array(Schema.Struct({
577
746
  number: Schema.Int,
578
- created_at: nonempty,
579
- updated_at: nonempty
747
+ created_at: nonempty$2,
748
+ updated_at: nonempty$2
580
749
  }));
581
750
  const timeline = Schema.Array(Schema.Struct({
582
- event: nonempty,
751
+ event: nonempty$2,
583
752
  id: Schema.optionalKey(Schema.Int),
584
753
  actor: Schema.optionalKey(Schema.NullOr(actor)),
585
754
  assignee: Schema.optionalKey(Schema.NullOr(actor)),
586
755
  requested_reviewer: Schema.optionalKey(Schema.NullOr(actor)),
587
756
  review_requester: Schema.optionalKey(Schema.NullOr(actor)),
588
- created_at: Schema.optionalKey(nonempty)
757
+ created_at: Schema.optionalKey(nonempty$2)
589
758
  }));
590
759
  const revisions = Schema.Array(Schema.Struct({
591
760
  id: Schema.Int,
592
- digest: nonempty
761
+ digest: nonempty$2
593
762
  }));
594
763
  const repository = Schema.Struct({
595
- full_name: nonempty,
764
+ full_name: nonempty$2,
596
765
  private: Schema.Boolean
597
766
  });
598
767
  const pullRequestFields = {
599
768
  head: Schema.Struct({
600
- sha: nonempty,
601
- ref: nonempty,
769
+ sha: nonempty$2,
770
+ ref: nonempty$2,
602
771
  repo: Schema.NullOr(repository)
603
772
  }),
604
773
  user: actor,
605
774
  state: Schema.Literals(["open", "closed"]),
606
- updated_at: nonempty,
607
- closed_at: Schema.NullOr(nonempty)
775
+ updated_at: nonempty$2,
776
+ closed_at: Schema.NullOr(nonempty$2)
608
777
  };
609
778
  const pr = Schema.Struct({
610
779
  ...pullRequestFields,
@@ -612,13 +781,13 @@ const pr = Schema.Struct({
612
781
  });
613
782
  /** The combined commit status; `total_count` tells a commit without statuses from one whose statuses still run. */
614
783
  const status = Schema.Struct({
615
- state: nonempty,
784
+ state: nonempty$2,
616
785
  total_count: Schema.optionalKey(Schema.Int)
617
786
  });
618
787
  const checkRun = Schema.Struct({
619
788
  id: Schema.Int,
620
- name: nonempty,
621
- status: nonempty,
789
+ name: nonempty$2,
790
+ status: nonempty$2,
622
791
  conclusion: Schema.NullOr(Schema.String)
623
792
  });
624
793
  /** A check-runs page read as its runs, so the page cache can replay it like any other listing. */
@@ -635,6 +804,21 @@ function pullRequestThreadUrl(key) {
635
804
  const match = threadPattern.exec(key);
636
805
  return match === null ? void 0 : `https://github.com/${match[1]}/pull/${match[2]}`;
637
806
  }
807
+ /**
808
+ * A pull request's web address, also as a link into one of its tabs and with a trailing slash, query or fragment. A
809
+ * number without a leading zero keeps one thread key per pull request. Path segments after a tab hold only letters,
810
+ * digits, `_` and `-`, and neither repository part is `.` or `..`: a dot segment, plain or percent-encoded, would make
811
+ * the address resolve to another page than the pull request the pattern captures.
812
+ */
813
+ const pullRequestPage = /^https:\/\/github\.com\/((?!\.{1,2}\/)[\w.-]+\/(?!\.{1,2}\/)[\w.-]+)\/pull\/([1-9]\d*)(?:\/(?:files|commits|checks|changes)(?:\/[\w-]+)*\/?|\/)?(?:[?#].*)?$/iu;
814
+ /** The repository, as written, and the number of the pull request a GitHub web link names. */
815
+ function pullRequestOfUrl(link) {
816
+ const match = pullRequestPage.exec(link);
817
+ return match === null ? void 0 : {
818
+ repo: match[1],
819
+ number: match[2]
820
+ };
821
+ }
638
822
  const failing = /* @__PURE__ */ new Set([
639
823
  "failure",
640
824
  "timed_out",
@@ -647,6 +831,7 @@ const failing = /* @__PURE__ */ new Set([
647
831
  * The settled CI verdict of a commit: `failure` once any check or status fails, `success` once every check finished
648
832
  * without failing, and `undefined` while anything runs or nothing reported. GitHub reports a commit without statuses as
649
833
  * `pending` with no statuses, so only a pending status that exists holds the verdict back.
834
+ * @internal
650
835
  */
651
836
  function ciVerdict(combined, checks) {
652
837
  const { state } = combined;
@@ -665,7 +850,7 @@ function createThreadStateSync(context, watched) {
665
850
  if (at === null) return;
666
851
  const sourceEventId = opened ? `${key}:open:${at}` : `${key}:closed:${at}`;
667
852
  const stateKey = `github-thread-state:${key}`;
668
- if (await context.state.get(stateKey, nonempty) === sourceEventId) return;
853
+ if (await context.state.get(stateKey, nonempty$2) === sourceEventId) return;
669
854
  await context.receive({
670
855
  sourceEventId,
671
856
  kind: opened ? "thread_open" : "thread_closed",
@@ -680,7 +865,7 @@ function createThreadStateSync(context, watched) {
680
865
  text: "",
681
866
  ...opened ? {} : { closeOutcome: merged ? "merged" : "closed" }
682
867
  });
683
- await context.state.set(stateKey, nonempty, sourceEventId);
868
+ await context.state.set(stateKey, nonempty$2, sourceEventId);
684
869
  };
685
870
  }
686
871
  /** Whether `text` mentions the account, lowercase, anywhere. */
@@ -695,6 +880,7 @@ function ownMentionPattern(account) {
695
880
  * The stored text of a review: a review without a body says what it is (`APPROVED review`), and an approval or a change
696
881
  * request leads with its state; a plain `COMMENTED` review keeps its body as written, so a stop request still reads
697
882
  * as one.
883
+ * @internal
698
884
  */
699
885
  function reviewText(state, body) {
700
886
  if (state === void 0) return body;
@@ -718,7 +904,7 @@ function createThreadPoll(options) {
718
904
  */
719
905
  async function syncVerdict(receive, state, key, audience, verdict) {
720
906
  const stateKey = `github-ci-verdict:${key}`;
721
- const [previous, count] = (await state.get(stateKey, nonempty) ?? ":0").split(":");
907
+ const [previous, count] = (await state.get(stateKey, nonempty$2) ?? ":0").split(":");
722
908
  if (verdict === void 0 || verdict === previous) return;
723
909
  const revision = Number(count) + 1;
724
910
  if (previous !== "" || verdict === "failure") await receive({
@@ -734,7 +920,7 @@ function createThreadPoll(options) {
734
920
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
735
921
  text: verdict
736
922
  });
737
- await state.set(stateKey, nonempty, `${verdict}:${revision}`);
923
+ await state.set(stateKey, nonempty$2, `${verdict}:${revision}`);
738
924
  }
739
925
  /** Polls a thread; the issue or pull request state it read, or `undefined` for a thread outside the source. */
740
926
  async function pollThread(key, reason, signal, baseline = false, observing = false) {
@@ -906,18 +1092,21 @@ function createThreadPoll(options) {
906
1092
  }
907
1093
  return pollThread;
908
1094
  }
909
- const decodeIdentity$1 = Schema.decodeUnknownSync(Schema.Struct({ login: nonempty }));
1095
+ const decodeIdentity$1 = Schema.decodeUnknownSync(Schema.Struct({ login: nonempty$2 }));
910
1096
  const decodeSearch = Schema.decodeUnknownSync(Schema.Struct({
911
1097
  incomplete_results: Schema.Boolean,
912
1098
  items: Schema.Array(Schema.Struct({
913
1099
  number: Schema.Int,
914
- repository_url: nonempty
1100
+ repository_url: nonempty$2
915
1101
  }))
916
1102
  }));
917
1103
  const repositoryUrl = /^https:\/\/api\.github\.com\/repos\/([\w.-]+)\/([\w.-]+)$/u;
918
1104
  const watchedKey = "contributions-watched";
919
- const watchedSchema = Schema.Array(nonempty);
920
- /** The search for an author's open pull requests outside the excluded owners' repositories. */
1105
+ const watchedSchema = Schema.Array(nonempty$2);
1106
+ /**
1107
+ * The search for an author's open pull requests outside the excluded owners' repositories.
1108
+ * @internal
1109
+ */
921
1110
  function contributionQuery(author, excluded) {
922
1111
  return [
923
1112
  "is:pr",
@@ -1038,6 +1227,8 @@ const githubContributionsSourceKind = {
1038
1227
  pollIntervalMs: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(6e4)))
1039
1228
  }),
1040
1229
  watches: true,
1230
+ routerNotes: "A watch candidate with sourceKind github-contributions comes from a pull request the owner authored in another project. An accepted task for it must name the repository and pull request in its scope, and tell the worker to clone the repository into its empty directory, check out the pull request head, commit the fix locally, and never push, comment, review or open pull requests upstream.",
1231
+ defaultWatchInstructions: ["Accept when a reviewer requests a concrete change, or CI fails with a cause you can identify, and the fix is a small local change.", "Ignore approvals, questions, discussion, merges, and anything that needs the owner's design or product decision."].join(" "),
1041
1232
  normalizeActor: (id) => id.toLowerCase(),
1042
1233
  preflight: (settings, host) => {
1043
1234
  sourceToken(settings.credentialRef, host);
@@ -1050,8 +1241,8 @@ const githubContributionsSourceKind = {
1050
1241
  * again; those of other threads, cut off by the budget or the page end, are still followed.
1051
1242
  */
1052
1243
  const streamCursor = Schema.Struct({
1053
- at: nonempty,
1054
- threads: Schema.Array(nonempty)
1244
+ at: nonempty$2,
1245
+ threads: Schema.Array(nonempty$2)
1055
1246
  });
1056
1247
  /**
1057
1248
  * What observing remembers per repository: the last seen update of each recently updated open pull request, and per
@@ -1060,10 +1251,10 @@ const streamCursor = Schema.Struct({
1060
1251
  * `null` while observing is off.
1061
1252
  */
1062
1253
  const observedRepository = Schema.NullOr(Schema.Struct({
1063
- pulls: Schema.Record(Schema.String, nonempty),
1064
- pullRequests: Schema.NullOr(Schema.Struct({ start: nonempty })),
1254
+ pulls: Schema.Record(Schema.String, nonempty$2),
1255
+ pullRequests: Schema.NullOr(Schema.Struct({ start: nonempty$2 })),
1065
1256
  comments: Schema.NullOr(Schema.Struct({
1066
- start: nonempty,
1257
+ start: nonempty$2,
1067
1258
  conversation: streamCursor,
1068
1259
  inline: streamCursor
1069
1260
  }))
@@ -1227,8 +1418,8 @@ function createRepositoryObserver(options) {
1227
1418
  pollRepository
1228
1419
  };
1229
1420
  }
1230
- const identity = Schema.Struct({
1231
- login: nonempty,
1421
+ const identity$1 = Schema.Struct({
1422
+ login: nonempty$2,
1232
1423
  id: Schema.Int
1233
1424
  });
1234
1425
  const notification = Schema.Struct({
@@ -1238,15 +1429,14 @@ const notification = Schema.Struct({
1238
1429
  const pullRequests = Schema.Array(Schema.Struct({
1239
1430
  number: Schema.Int,
1240
1431
  ...pullRequestFields,
1241
- merged_at: Schema.NullOr(nonempty)
1432
+ merged_at: Schema.NullOr(nonempty$2)
1242
1433
  }));
1243
- const decodeIdentity = Schema.decodeUnknownSync(identity);
1434
+ const decodeIdentity = Schema.decodeUnknownSync(identity$1);
1244
1435
  const decodeComments = Schema.decodeUnknownSync(commentList);
1245
1436
  const decodeRepository = Schema.decodeUnknownSync(repository);
1246
1437
  const decodeNotifications = Schema.decodeUnknownSync(Schema.Array(notification));
1247
1438
  const decodePr = Schema.decodeUnknownSync(pr);
1248
1439
  const decodePullRequests = Schema.decodeUnknownSync(pullRequests);
1249
- const pullRequestUrl = /^https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/([1-9]\d*)$/iu;
1250
1440
  const notificationPattern = /^https:\/\/api\.github\.com\/repos\/([\w.-]+\/[\w.-]+)\/(?:issues|pulls)\/([1-9]\d*)$/u;
1251
1441
  /** GitHub's comment body limit, less room for the outbox marker `send` appends. */
1252
1442
  const commentLimit = 65336;
@@ -1265,9 +1455,9 @@ function createGitHubSource(context, token, request = fetch) {
1265
1455
  if (details.head.repo === null) return;
1266
1456
  await syncThreadState(`${repo.toLowerCase()}#${number}`, details.head.repo.private ? "internal" : "public", details.state, details.updated_at, details.closed_at, merged);
1267
1457
  }
1268
- async function discoverPullRequest(taskId, branch, repository) {
1458
+ async function findPullRequests(repository, branch) {
1269
1459
  const repo = repository.toLowerCase();
1270
- if (verifiedLogin === void 0 || !allowedRepos.has(repo)) return false;
1460
+ if (verifiedLogin === void 0 || !allowedRepos.has(repo)) return [];
1271
1461
  const signal = AbortSignal.timeout(2e4);
1272
1462
  const owner = repo.split("/")[0];
1273
1463
  const query = new URLSearchParams({
@@ -1284,13 +1474,60 @@ function createGitHubSource(context, token, request = fetch) {
1284
1474
  } catch (error) {
1285
1475
  if (!unavailable(error, true)) throw error;
1286
1476
  }
1287
- if (discovered.length === 0) return false;
1288
1477
  for (const pr of discovered) await syncOwnPullRequest(repo, pr.number, pr, pr.merged_at !== null);
1289
- const threads = discovered.map((pr) => `${repo}#${pr.number}`);
1290
- if (context.bindOwnedThreads !== void 0) await context.bindOwnedThreads(taskId, threads);
1291
- else await Promise.all(threads.map((thread) => context.bindThread(taskId, thread, true)));
1292
- return true;
1478
+ return discovered.map((pr) => `${repo}#${pr.number}`);
1479
+ }
1480
+ async function readPullRequest(link, branch) {
1481
+ const pullRequest = pullRequestOfUrl(link);
1482
+ if (pullRequest === void 0) return "unrecognized";
1483
+ const { repo, number } = pullRequest;
1484
+ if (!allowedRepos.has(repo.toLowerCase()) || verifiedLogin === void 0) return "unverified";
1485
+ try {
1486
+ const details = decodePr(await read(`/repos/${repo}/pulls/${number}`, AbortSignal.timeout(1e4)));
1487
+ const own = ownPullRequest(details, repo, branch);
1488
+ if (own) await syncOwnPullRequest(repo, number, details, details.merged);
1489
+ return {
1490
+ thread: `${repo.toLowerCase()}#${number}`,
1491
+ own
1492
+ };
1493
+ } catch (error) {
1494
+ if (unavailable(error, true)) return "unverified";
1495
+ throw error;
1496
+ }
1293
1497
  }
1498
+ let ownPullRequestSeen;
1499
+ const codingHost = {
1500
+ repositories: config.repositories,
1501
+ onOwnPullRequestSeen(handler) {
1502
+ if (ownPullRequestSeen !== void 0) throw new Error("The GitHub coding host already notifies a scenario");
1503
+ ownPullRequestSeen = handler;
1504
+ },
1505
+ repositoryOf: threadRepository,
1506
+ findPullRequests,
1507
+ readPullRequest,
1508
+ credential(repo) {
1509
+ return verifiedLogin === void 0 || repo !== void 0 && !allowedRepos.has(repo.toLowerCase()) ? void 0 : {
1510
+ username: verifiedLogin,
1511
+ token
1512
+ };
1513
+ },
1514
+ identity: () => verifiedLogin === void 0 ? void 0 : {
1515
+ variables: identityEnv,
1516
+ gitConfig: [
1517
+ ["url.https://github.com/.insteadOf", "git@github.com:"],
1518
+ ["url.https://github.com/.insteadOf", "ssh://git@github.com/"],
1519
+ ...[.../* @__PURE__ */ new Set([...config.repositories, ...allowedRepos])].flatMap((repo) => {
1520
+ const destination = `url.https://github.com/${repo}.`;
1521
+ return [
1522
+ [destination + "insteadOf", `https://github.com/${repo}`],
1523
+ [destination + "insteadOf", `git@github.com:${repo}`],
1524
+ [destination + "insteadOf", `ssh://git@github.com/${repo}`],
1525
+ [destination + "pushInsteadOf", `https://github.com/${repo}`]
1526
+ ];
1527
+ })
1528
+ ]
1529
+ }
1530
+ };
1294
1531
  let observer;
1295
1532
  const pollThread = createThreadPoll({
1296
1533
  context,
@@ -1301,10 +1538,7 @@ function createGitHubSource(context, token, request = fetch) {
1301
1538
  predatesObserving: (repo, at) => observer?.predatesObserving(repo, at) === true,
1302
1539
  now,
1303
1540
  onPullRequest: async (details, repo, key) => {
1304
- if (ownPullRequest(details, repo, details.head.ref) && details.head.ref.startsWith("agent/")) {
1305
- const taskId = context.openTaskForBranch?.(details.head.ref);
1306
- if (taskId !== void 0 && !context.isSubscribed(key)) await discoverPullRequest(taskId, details.head.ref, repo);
1307
- }
1541
+ if (ownPullRequest(details, repo, details.head.ref)) await ownPullRequestSeen?.(repo, details.head.ref, key);
1308
1542
  }
1309
1543
  });
1310
1544
  observer = createRepositoryObserver({
@@ -1369,48 +1603,6 @@ function createGitHubSource(context, token, request = fetch) {
1369
1603
  GIT_COMMITTER_EMAIL: email
1370
1604
  };
1371
1605
  }
1372
- const codeHost = {
1373
- repositories: config.repositories,
1374
- repository: threadRepository,
1375
- async claimPullRequest(taskId, branch, url) {
1376
- const match = pullRequestUrl.exec(url);
1377
- if (match === null || !allowedRepos.has(match[1].toLowerCase()) || verifiedLogin === void 0) return false;
1378
- const repo = match[1];
1379
- try {
1380
- const details = decodePr(await read(`/repos/${repo}/pulls/${match[2]}`, AbortSignal.timeout(1e4)));
1381
- const own = ownPullRequest(details, repo, branch);
1382
- if (own) await syncOwnPullRequest(repo, match[2], details, details.merged);
1383
- await context.bindThread(taskId, `${repo.toLowerCase()}#${match[2]}`, own);
1384
- return true;
1385
- } catch (error) {
1386
- if (unavailable(error, true)) return false;
1387
- throw error;
1388
- }
1389
- },
1390
- discoverPullRequest,
1391
- credential(repo) {
1392
- return verifiedLogin === void 0 || repo !== void 0 && !allowedRepos.has(repo.toLowerCase()) ? void 0 : {
1393
- username: verifiedLogin,
1394
- token
1395
- };
1396
- },
1397
- environment: () => verifiedLogin === void 0 ? void 0 : {
1398
- variables: identityEnv,
1399
- gitConfig: [
1400
- ["url.https://github.com/.insteadOf", "git@github.com:"],
1401
- ["url.https://github.com/.insteadOf", "ssh://git@github.com/"],
1402
- ...[.../* @__PURE__ */ new Set([...config.repositories, ...allowedRepos])].flatMap((repo) => {
1403
- const destination = `url.https://github.com/${repo}.`;
1404
- return [
1405
- [destination + "insteadOf", `https://github.com/${repo}`],
1406
- [destination + "insteadOf", `git@github.com:${repo}`],
1407
- [destination + "insteadOf", `ssh://git@github.com/${repo}`],
1408
- [destination + "pushInsteadOf", `https://github.com/${repo}`]
1409
- ];
1410
- })
1411
- ]
1412
- }
1413
- };
1414
1606
  return {
1415
1607
  prepare,
1416
1608
  reply: {
@@ -1419,7 +1611,7 @@ function createGitHubSource(context, token, request = fetch) {
1419
1611
  maxCharacters: commentLimit
1420
1612
  },
1421
1613
  describeThread: (thread) => ({ url: pullRequestThreadUrl(thread) }),
1422
- codeHost,
1614
+ codingHost,
1423
1615
  async start(signal) {
1424
1616
  if (verifiedLogin === void 0) await prepare(signal);
1425
1617
  await pollUntilAborted(context, {
@@ -1490,9 +1682,10 @@ function createGitHubSource(context, token, request = fetch) {
1490
1682
  };
1491
1683
  }
1492
1684
  /**
1493
- * GitHub issues and pull requests as a Superagent source, polled through the account's notifications. It is the
1494
- * Superagent's code host: it owns the pull requests of Tasks in its repositories and the worker Git identity. With
1495
- * `observe`, it also offers new pull requests and comments in its repositories as observed candidates.
1685
+ * GitHub issues and pull requests as a Superagent source, polled through the account's notifications. It offers the
1686
+ * coding host: a coding scenario that names it as `codeHost` binds the pull requests of Tasks in its repositories and
1687
+ * gives workers its account's Git identity. With `observe`, it also offers new pull requests and comments in its
1688
+ * repositories as observed candidates.
1496
1689
  */
1497
1690
  const githubSourceKind = {
1498
1691
  kind: "github",
@@ -1507,7 +1700,9 @@ const githubSourceKind = {
1507
1700
  comments: Schema.optionalKey(Schema.Boolean)
1508
1701
  }))
1509
1702
  }),
1703
+ codingHost: { repositories: (settings) => settings.repositories },
1510
1704
  observes: true,
1705
+ routerNotes: "An observed candidate with sourceKind github is a new pull request or comment in a configured repository the source observes.",
1511
1706
  normalizeActor: (id) => id.toLowerCase(),
1512
1707
  preflight: (settings, host) => {
1513
1708
  sourceToken(settings.credentialRef, host);
@@ -1515,11 +1710,353 @@ const githubSourceKind = {
1515
1710
  create: (context) => createGitHubSource(context, sourceToken(context.config.credentialRef, context.host))
1516
1711
  };
1517
1712
  //#endregion
1713
+ //#region ../triggers/wechat/dist/index.js
1714
+ /** The iLink bot API shapes the WeChat source reads; unknown fields are ignored. */
1715
+ const nonempty = Schema.NonEmptyString;
1716
+ /** A 64-bit ID, kept as its decimal digits: `parseJson` leaves an integer beyond the safe range as a string. */
1717
+ const id$3 = Schema.Union([nonempty, Schema.Int]);
1718
+ const item = Schema.Struct({
1719
+ type: Schema.optionalKey(Schema.Int),
1720
+ msg_id: Schema.optionalKey(id$3),
1721
+ text_item: Schema.optionalKey(Schema.Struct({ text: Schema.optionalKey(Schema.String) })),
1722
+ /** `text` is WeChat's own transcript of the voice message. */
1723
+ voice_item: Schema.optionalKey(Schema.Struct({ text: Schema.optionalKey(Schema.String) })),
1724
+ file_item: Schema.optionalKey(Schema.Struct({ file_name: Schema.optionalKey(Schema.String) }))
1725
+ });
1726
+ /** One message of a `getupdates` page. A page keeps its other messages when one of them does not decode. */
1727
+ const decodeMessage = Schema.decodeUnknownOption(Schema.Struct({
1728
+ message_id: Schema.optionalKey(id$3),
1729
+ from_user_id: nonempty,
1730
+ group_id: Schema.optionalKey(Schema.String),
1731
+ /** 1 is a message from a WeChat user, 2 one from a bot. */
1732
+ message_type: Schema.optionalKey(Schema.Int),
1733
+ create_time_ms: Schema.optionalKey(Schema.Int),
1734
+ context_token: Schema.optionalKey(Schema.String),
1735
+ item_list: Schema.optionalKey(Schema.Array(item))
1736
+ }));
1737
+ const updates = Schema.Struct({
1738
+ ret: Schema.optionalKey(Schema.Int),
1739
+ errcode: Schema.optionalKey(Schema.Int),
1740
+ msgs: Schema.optionalKey(Schema.Array(Schema.Unknown)),
1741
+ get_updates_buf: Schema.optionalKey(Schema.String),
1742
+ longpolling_timeout_ms: Schema.optionalKey(Schema.Int)
1743
+ });
1744
+ const sent = Schema.Struct({
1745
+ ret: Schema.optionalKey(Schema.Int),
1746
+ message_id: Schema.optionalKey(id$3)
1747
+ });
1748
+ Schema.Struct({
1749
+ qrcode: nonempty,
1750
+ qrcode_img_content: nonempty
1751
+ });
1752
+ Schema.Struct({
1753
+ status: Schema.String,
1754
+ bot_token: Schema.optionalKey(Schema.String),
1755
+ ilink_user_id: Schema.optionalKey(Schema.String),
1756
+ baseurl: Schema.optionalKey(Schema.String),
1757
+ redirect_host: Schema.optionalKey(Schema.String)
1758
+ });
1759
+ /**
1760
+ * Why: the server refuses clients whose `channel_version` is below a minimum it configures, and a host that is not
1761
+ * Tencent's plugin sends the plugin protocol version it implements followed by its own name.
1762
+ */
1763
+ const baseInfo = {
1764
+ channel_version: "2.4.10/rivus-1.0",
1765
+ bot_agent: "Rivus"
1766
+ };
1767
+ /** The plugin protocol version above as `major << 16 | minor << 8 | patch`. */
1768
+ const clientVersion = String(132106);
1769
+ const longPollMs = 35e3;
1770
+ /** The origin of an iLink API base URL; throws unless it is a bare `https` origin. */
1771
+ function apiOrigin(baseUrl) {
1772
+ const url = new URL(baseUrl);
1773
+ if (url.protocol !== "https:" || url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") throw new Error("WeChat API base URL must be an https origin");
1774
+ if (url.pathname !== "/") throw new Error("WeChat API base URL must not have a path");
1775
+ return url.origin;
1776
+ }
1777
+ /**
1778
+ * Parses a response body, keeping an integer beyond the safe range as its decimal digits.
1779
+ * Why: message IDs are unsigned 64-bit integers, and as numbers neighbouring IDs would collapse into one.
1780
+ */
1781
+ function parseJson(text) {
1782
+ if (text.trim() === "") return {};
1783
+ return JSON.parse(text, (_key, value, context) => typeof value === "number" && !Number.isSafeInteger(value) && context?.source !== void 0 && /^-?\d+$/u.test(context.source) ? context.source : value);
1784
+ }
1785
+ /** The headers of every iLink request; the login requests carry no bot token yet. */
1786
+ function requestHeaders(token) {
1787
+ const headers = new Headers({
1788
+ "content-type": "application/json",
1789
+ AuthorizationType: "ilink_bot_token",
1790
+ "X-WECHAT-UIN": Buffer.from(String(randomInt(2 ** 32))).toString("base64"),
1791
+ "iLink-App-Id": "bot",
1792
+ "iLink-App-ClientVersion": clientVersion
1793
+ });
1794
+ if (token !== void 0) headers.set("authorization", `Bearer ${token}`);
1795
+ return headers;
1796
+ }
1797
+ /** The API answered with an HTTP failure, so it did not carry the request out. */
1798
+ var WechatHttpError = class extends Error {
1799
+ constructor(status) {
1800
+ super(`WeChat request failed with HTTP ${status}`);
1801
+ }
1802
+ };
1803
+ /** The `cause.code` of a `fetch` failure before any connection existed, so no request left. */
1804
+ const connectFailures = /* @__PURE__ */ new Set([
1805
+ "ENOTFOUND",
1806
+ "EAI_AGAIN",
1807
+ "ECONNREFUSED",
1808
+ "ENETUNREACH",
1809
+ "EHOSTUNREACH",
1810
+ "UND_ERR_CONNECT_TIMEOUT"
1811
+ ]);
1812
+ const decodeCause = Schema.decodeUnknownOption(Schema.Struct({ cause: Schema.Struct({ code: Schema.String }) }));
1813
+ /**
1814
+ * Whether a failed request certainly did not take effect: the API answered with an HTTP failure, or no connection
1815
+ * was made. A timeout, a connection lost midway or an unreadable answer leaves that open.
1816
+ */
1817
+ function notDelivered(error) {
1818
+ if (error instanceof WechatHttpError) return true;
1819
+ const failure = decodeCause(error);
1820
+ return failure._tag === "Some" && connectFailures.has(failure.value.cause.code);
1821
+ }
1822
+ async function readJson(response, schema) {
1823
+ if (!response.ok) throw new WechatHttpError(response.status);
1824
+ return Schema.decodeUnknownSync(schema)(parseJson(await response.text()));
1825
+ }
1826
+ function createWechatTransport(options) {
1827
+ async function post(path, body, schema, timeoutMs, signal) {
1828
+ const timeout = AbortSignal.timeout(timeoutMs);
1829
+ return readJson(await options.request(new URL(path, options.origin), {
1830
+ method: "POST",
1831
+ redirect: "error",
1832
+ headers: requestHeaders(options.token),
1833
+ body: JSON.stringify({
1834
+ ...body,
1835
+ base_info: baseInfo
1836
+ }),
1837
+ signal: signal === void 0 ? timeout : AbortSignal.any([signal, timeout])
1838
+ }), schema);
1839
+ }
1840
+ return {
1841
+ /**
1842
+ * Holds until messages arrive or the long poll ends, which reads as an empty page. `holdMs` is how long the server
1843
+ * said it holds a poll, when it said so.
1844
+ */
1845
+ async getUpdates(cursor, holdMs, signal) {
1846
+ try {
1847
+ return await post("/ilink/bot/getupdates", { get_updates_buf: cursor }, updates, holdMs ?? longPollMs, signal);
1848
+ } catch (error) {
1849
+ signal.throwIfAborted();
1850
+ if (error instanceof Error && error.name === "TimeoutError") return {};
1851
+ throw error;
1852
+ }
1853
+ },
1854
+ sendText(message) {
1855
+ return post("/ilink/bot/sendmessage", { msg: {
1856
+ from_user_id: "",
1857
+ to_user_id: message.to,
1858
+ client_id: message.clientId,
1859
+ message_type: 2,
1860
+ message_state: 2,
1861
+ context_token: message.contextToken,
1862
+ item_list: [{
1863
+ type: 1,
1864
+ text_item: { text: message.text }
1865
+ }]
1866
+ } }, sent, 15e3);
1867
+ },
1868
+ /** Tells the API the channel started or stopped, as Tencent's client does; the source works without it. */
1869
+ async notify(event) {
1870
+ await post(`/ilink/bot/msg/notify${event}`, {}, Schema.Unknown, 1e4).catch(() => {});
1871
+ }
1872
+ };
1873
+ }
1874
+ const retryMs = 2e3;
1875
+ const backoffMs = 3e4;
1876
+ /** Tencent's client waits this long before it polls again with a bot token whose session ended. */
1877
+ const expiredRetryMs = 36e5;
1878
+ const cursorKey = "cursor";
1879
+ const contextTokenKey = (userId) => `context-token:${userId}`;
1880
+ /** The API origin a source's configuration names; throws on a `baseUrl` that is no https origin. */
1881
+ function sourceOrigin(config) {
1882
+ return apiOrigin(config.baseUrl ?? "https://ilinkai.weixin.qq.com");
1883
+ }
1884
+ /** Text items keep their text and voice items WeChat's transcript; other items are named, not downloaded. */
1885
+ function itemText(item) {
1886
+ switch (item.type) {
1887
+ case 1: return item.text_item?.text;
1888
+ case 2: return "[image]";
1889
+ case 3: return item.voice_item?.text || "[voice message]";
1890
+ case 4: return item.file_item?.file_name ? `[file: ${item.file_item.file_name}]` : "[file]";
1891
+ case 5: return "[video]";
1892
+ default: return;
1893
+ }
1894
+ }
1895
+ const digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 32);
1896
+ /**
1897
+ * Direct chats with a personal WeChat bot over the iLink bot API: one long poll receives every message sent to the
1898
+ * bot, and a reply goes to the person through the context token of their latest message.
1899
+ */
1900
+ function createWechatSource(context, token, request = fetch) {
1901
+ const transport = createWechatTransport({
1902
+ token,
1903
+ origin: sourceOrigin(context.config),
1904
+ request
1905
+ });
1906
+ async function receive(raw) {
1907
+ const decoded = decodeMessage(raw);
1908
+ if (Option.isNone(decoded) || decoded.value.message_type === 2 || (decoded.value.group_id ?? "") !== "") return;
1909
+ const message = decoded.value;
1910
+ const items = message.item_list ?? [];
1911
+ const text = items.map(itemText).filter((part) => part !== void 0).join("\n");
1912
+ const userId = message.from_user_id;
1913
+ const contextToken = message.context_token || void 0;
1914
+ if (contextToken !== void 0) await context.state.set(contextTokenKey(userId), Schema.String, contextToken);
1915
+ await context.receive({
1916
+ sourceEventId: String(message.message_id ?? items.find(({ msg_id }) => msg_id !== void 0)?.msg_id ?? digest([
1917
+ userId,
1918
+ message.create_time_ms,
1919
+ text
1920
+ ])),
1921
+ kind: "message",
1922
+ threads: [`direct:${userId}`],
1923
+ actor: {
1924
+ id: userId,
1925
+ kind: "person"
1926
+ },
1927
+ addressed: "direct",
1928
+ audience: "private",
1929
+ occurredAt: new Date(message.create_time_ms ?? Date.now()).toISOString(),
1930
+ text,
1931
+ replyTarget: {
1932
+ userId,
1933
+ ...contextToken === void 0 ? {} : { contextToken }
1934
+ }
1935
+ });
1936
+ }
1937
+ return {
1938
+ reply: {
1939
+ conversational: true,
1940
+ locale: "zh"
1941
+ },
1942
+ directTarget: (actor) => ({
1943
+ thread: `direct:${actor}`,
1944
+ address: { userId: actor }
1945
+ }),
1946
+ describeThread: (thread) => thread.startsWith("direct:") ? { label: "WeChat direct chat" } : {},
1947
+ async start(signal) {
1948
+ let lastReported;
1949
+ function report(state, reason) {
1950
+ const key = `${state}:${reason}`;
1951
+ if (!signal.aborted && key !== lastReported) {
1952
+ lastReported = key;
1953
+ context.report({
1954
+ state,
1955
+ reason
1956
+ });
1957
+ }
1958
+ }
1959
+ const wait = (ms) => setTimeout$1(ms, void 0, { signal }).catch(() => {});
1960
+ transport.notify("start");
1961
+ let cursor = await context.state.get(cursorKey, Schema.String) ?? "";
1962
+ let holdMs;
1963
+ let failures = 0;
1964
+ try {
1965
+ while (!signal.aborted) try {
1966
+ const page = await transport.getUpdates(cursor, holdMs, signal);
1967
+ const code = [page.errcode, page.ret].find((value) => value !== void 0 && value !== 0) ?? 0;
1968
+ if (code === -14) {
1969
+ report("failed", "WeChat session expired; log in again and update the bot token");
1970
+ await wait(expiredRetryMs);
1971
+ continue;
1972
+ }
1973
+ if (code !== 0) throw new Error(`WeChat getupdates failed with code ${code}`);
1974
+ if (page.longpolling_timeout_ms !== void 0) holdMs = page.longpolling_timeout_ms + 5e3;
1975
+ for (const raw of page.msgs ?? []) await receive(raw);
1976
+ if (page.get_updates_buf && page.get_updates_buf !== cursor) {
1977
+ cursor = page.get_updates_buf;
1978
+ await context.state.set(cursorKey, Schema.String, cursor);
1979
+ }
1980
+ failures = 0;
1981
+ report("ready");
1982
+ } catch {
1983
+ failures += 1;
1984
+ report("degraded", "WeChat message polling failed");
1985
+ await wait(failures >= 3 ? backoffMs : retryMs);
1986
+ }
1987
+ } finally {
1988
+ await transport.notify("stop");
1989
+ }
1990
+ },
1991
+ async send(reply) {
1992
+ const { userId } = reply.target;
1993
+ if (userId === void 0) return {
1994
+ status: "gone",
1995
+ reason: "WeChat reply has no user target"
1996
+ };
1997
+ const contextToken = await context.state.get(contextTokenKey(userId), Schema.String) ?? reply.target.contextToken;
1998
+ if (contextToken === void 0) return {
1999
+ status: "gone",
2000
+ reason: "WeChat user has not messaged the bot"
2001
+ };
2002
+ const clientId = `rivus-${digest([reply.id, reply.generation])}`;
2003
+ try {
2004
+ const result = await transport.sendText({
2005
+ to: userId,
2006
+ contextToken,
2007
+ clientId,
2008
+ text: reply.text
2009
+ });
2010
+ return (result.ret ?? 0) === 0 ? {
2011
+ status: "sent",
2012
+ remoteId: String(result.message_id ?? clientId)
2013
+ } : {
2014
+ status: "retry",
2015
+ reason: `WeChat reply failed with code ${result.ret}`
2016
+ };
2017
+ } catch (error) {
2018
+ return notDelivered(error) ? {
2019
+ status: "retry",
2020
+ reason: "WeChat reply failed"
2021
+ } : {
2022
+ status: "unknown",
2023
+ reason: "WeChat reply has no readable answer"
2024
+ };
2025
+ }
2026
+ }
2027
+ };
2028
+ }
2029
+ const config = Schema.Struct({
2030
+ /** The bot token a QR code login issued, as an `env:<NAME>` reference. */
2031
+ credentialRef: Schema.NonEmptyString,
2032
+ /** The API base URL the login returned, when it is not the default one. */
2033
+ baseUrl: Schema.optionalKey(Schema.NonEmptyString)
2034
+ });
2035
+ function botToken(credentialRef, host) {
2036
+ const value = host.secret(credentialRef);
2037
+ if (value === void 0) throw new Error(`Missing WeChat bot token ${credentialRef}`);
2038
+ return value;
2039
+ }
2040
+ /**
2041
+ * Direct chats with a personal WeChat bot as a Superagent source. `allowedActors` lists WeChat user IDs
2042
+ * (`<id>@im.wechat`), such as the one the login reports for the person who scanned the QR code.
2043
+ */
2044
+ const wechatSourceKind = {
2045
+ kind: "wechat",
2046
+ config,
2047
+ preflight: (settings, host) => {
2048
+ botToken(settings.credentialRef, host);
2049
+ sourceOrigin(settings);
2050
+ },
2051
+ create: (context) => createWechatSource(context, botToken(context.config.credentialRef, context.host))
2052
+ };
2053
+ //#endregion
1518
2054
  //#region src/bootstrap/superagent/builtin-source-preset.ts
1519
2055
  const feishuConfig = Schema.Struct({ endpointId: Schema.NonEmptyString });
1520
2056
  const builtinSourcePresetId = "builtin";
1521
2057
  /**
1522
- * The source kinds Gateway ships: Feishu, GitHub and GitHub contributions. The startup check passes no Feishu factory:
2058
+ * The kinds Gateway ships: the Feishu, GitHub, GitHub contributions and WeChat source kinds and the coding scenario
2059
+ * kind, whose code host a GitHub source can be. The startup check passes no Feishu factory:
1523
2060
  * it never creates sources, and leaving it out keeps the Feishu SDK out of the modules that `rivus doctor` evaluates.
1524
2061
  */
1525
2062
  function builtinSourcePreset(createFeishu) {
@@ -1528,6 +2065,7 @@ function builtinSourcePreset(createFeishu) {
1528
2065
  sourceKinds: [
1529
2066
  githubSourceKind,
1530
2067
  githubContributionsSourceKind,
2068
+ wechatSourceKind,
1531
2069
  {
1532
2070
  kind: "feishu",
1533
2071
  config: feishuConfig,
@@ -1536,7 +2074,8 @@ function builtinSourcePreset(createFeishu) {
1536
2074
  return createFeishu(context);
1537
2075
  }
1538
2076
  }
1539
- ]
2077
+ ],
2078
+ scenarioKinds: [codingScenarioKind]
1540
2079
  };
1541
2080
  }
1542
2081
  //#endregion
@@ -1665,10 +2204,10 @@ const gatewayAudioTranscriberAssetDirectory = fileURLToPath(new URL("assets/audi
1665
2204
  //#endregion
1666
2205
  //#region src/home/infra/adapters/project/release-descriptor.ts
1667
2206
  const RIVUS_RELEASE_DESCRIPTOR = Object.freeze({
1668
- version: "0.23.0",
2207
+ version: "0.24.0",
1669
2208
  dependencies: Object.freeze({
1670
2209
  "@earendil-works/pi-coding-agent": "1.5.2",
1671
- "@larksuiteoapi/node-sdk": "1.74.0",
2210
+ "@larksuiteoapi/node-sdk": "1.76.0",
1672
2211
  effect: "4.1.1"
1673
2212
  })
1674
2213
  });
@@ -1961,6 +2500,7 @@ function importNodeRivusModule(request, options = {}) {
1961
2500
  catch: toError
1962
2501
  })));
1963
2502
  }
2503
+ /** @internal */
1964
2504
  function loadNodeRivusPluginModule(request, options = {}) {
1965
2505
  return importNodeRivusModule(request, options);
1966
2506
  }
@@ -1971,17 +2511,27 @@ function createNodeRivusPluginModuleLoader(options = {}) {
1971
2511
  //#region src/bootstrap/superagent/source-presets.ts
1972
2512
  const hasDefaultExport = Schema.is(Schema.Struct({ default: Schema.Unknown }));
1973
2513
  const Function = Schema.Any.check(Schema.makeFilter((value) => typeof value === "function"));
2514
+ const Codec = Schema.Any.check(Schema.makeFilter((value) => Schema.isSchema(value)));
1974
2515
  const isSourcePreset = Schema.is(Schema.Struct({
1975
2516
  id: Schema.NonEmptyString,
1976
2517
  sourceKinds: Schema.Array(Schema.Struct({
1977
2518
  kind: Schema.String,
1978
- config: Schema.Any.check(Schema.makeFilter((value) => Schema.isSchema(value))),
2519
+ config: Codec,
1979
2520
  create: Function,
1980
2521
  normalizeActor: Schema.optional(Function),
1981
2522
  preflight: Schema.optional(Function),
1982
2523
  watches: Schema.optional(Schema.Boolean),
1983
- observes: Schema.optional(Schema.Boolean)
1984
- }))
2524
+ observes: Schema.optional(Schema.Boolean),
2525
+ routerNotes: Schema.optional(Schema.String),
2526
+ defaultWatchInstructions: Schema.optional(Schema.String),
2527
+ defaultObservedInstructions: Schema.optional(Schema.String)
2528
+ })),
2529
+ scenarioKinds: Schema.optional(Schema.Array(Schema.Struct({
2530
+ kind: Schema.String,
2531
+ config: Codec,
2532
+ codeHost: Function,
2533
+ create: Function
2534
+ })))
1985
2535
  }));
1986
2536
  async function importSourcePreset(specifier, location) {
1987
2537
  const module = await Effect.runPromise(importNodeRivusModule({
@@ -1993,13 +2543,24 @@ async function importSourcePreset(specifier, location) {
1993
2543
  if (!isSourcePreset(preset)) throw new Error("its default export is not a source preset or a factory returning one");
1994
2544
  return preset;
1995
2545
  }
2546
+ /** Adds the kinds of the preset `name` to `into`; a kind name may come from only one preset. */
2547
+ function claimKinds(owners, label, name, kinds, into) {
2548
+ for (const kind of kinds) {
2549
+ const owner = owners.get(kind.kind);
2550
+ if (owner !== void 0) throw new Error(`Superagent source preset ${name} declares ${label} ${kind.kind}, already declared by ${owner}`);
2551
+ owners.set(kind.kind, name);
2552
+ into.push(kind);
2553
+ }
2554
+ }
1996
2555
  /**
1997
- * The source kinds of the presets a Superagent names, in order. `builtin` is Gateway's own preset; any other entry is
1998
- * a module specifier. Each failure names the preset, and a kind name may come from only one preset.
2556
+ * The source and scenario kinds of the presets a Superagent names, in order. `builtin` is Gateway's own preset; any
2557
+ * other entry is a module specifier. Each failure names the preset, and a kind name may come from only one preset.
1999
2558
  */
2000
- async function loadSuperagentSourceKinds(specifiers, builtin, location) {
2001
- const owners = /* @__PURE__ */ new Map();
2002
- const kinds = [];
2559
+ async function loadSuperagentKinds(specifiers, builtin, location) {
2560
+ const sourceOwners = /* @__PURE__ */ new Map();
2561
+ const scenarioOwners = /* @__PURE__ */ new Map();
2562
+ const sourceKinds = [];
2563
+ const scenarioKinds = [];
2003
2564
  for (const specifier of specifiers) {
2004
2565
  let preset;
2005
2566
  try {
@@ -2008,49 +2569,54 @@ async function loadSuperagentSourceKinds(specifiers, builtin, location) {
2008
2569
  throw new Error(`Superagent source preset ${specifier} failed to load: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
2009
2570
  }
2010
2571
  const name = preset.id === specifier ? specifier : `${preset.id} (${specifier})`;
2011
- for (const kind of preset.sourceKinds) {
2012
- const owner = owners.get(kind.kind);
2013
- if (owner !== void 0) throw new Error(`Superagent source preset ${name} declares source kind ${kind.kind}, already declared by ${owner}`);
2014
- owners.set(kind.kind, name);
2015
- kinds.push(kind);
2016
- }
2572
+ claimKinds(sourceOwners, "source kind", name, preset.sourceKinds, sourceKinds);
2573
+ claimKinds(scenarioOwners, "scenario kind", name, preset.scenarioKinds ?? [], scenarioKinds);
2017
2574
  }
2018
- return kinds;
2575
+ return {
2576
+ sourceKinds,
2577
+ scenarioKinds
2578
+ };
2019
2579
  }
2020
2580
  //#endregion
2021
2581
  //#region src/bootstrap/deployment/superagent-preflight.ts
2022
- async function checkSuperagentRuntime(version) {
2582
+ /** Reads `git --version` through Superagent's Git client. */
2583
+ async function installedGitVersion() {
2584
+ const { createGitClient } = await import("./dist.js");
2585
+ return createGitClient().version();
2586
+ }
2587
+ /** Checks Node `version` before it reads the Git version, so an older Node never imports the Superagent SDK. */
2588
+ async function checkSuperagentRuntime(version, gitVersion = installedGitVersion) {
2023
2589
  if (!satisfies(version, ">=26.13.1", { includePrerelease: true })) throw new Error("Superagent requires Node 26.13.1 or newer");
2024
- const { stdout } = await promisify(execFile)("git", ["--version"], { timeout: 5e3 });
2025
- const git = coerce(stdout);
2590
+ const git = coerce(await gitVersion());
2026
2591
  if (git === null || !satisfies(git, ">=2.31.0")) throw new Error("Superagent requires Git 2.31 or newer");
2027
2592
  }
2028
2593
  /** The startup check shared by `rivus doctor`/`--check-config` and the daemon: the configuration parses, every
2029
- * Superagent Automation names a configured worker, every source kind's preflight passes, and the Herdr root the
2030
- * workers need is set. */
2594
+ * Superagent Automation names a configured worker, the scenario names a registered kind and a configured source that
2595
+ * can host it and whose repositories are configured, every source kind's preflight passes, and the Herdr root the
2596
+ * workers need is set. It creates no source and makes no network request. */
2031
2597
  function checkSuperagentDefinition(sdk, definition, manifest, env, kinds) {
2032
2598
  let config;
2033
2599
  try {
2034
- config = sdk.parseSuperagentConfig(definition.configuration, kinds);
2600
+ config = sdk.parseSuperagentConfig(definition.configuration, kinds.sourceKinds, kinds.scenarioKinds);
2035
2601
  } catch (error) {
2036
2602
  throw new Error(`Superagent configuration is invalid: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
2037
2603
  }
2038
2604
  for (const automation of manifest.automations ?? []) if (automation.enabled && automation.superagent === true && automation.workerId !== void 0 && !config.workers.some(({ id }) => id === automation.workerId)) throw new Error(`Automation ${automation.id} references unknown worker: ${automation.workerId}`);
2039
2605
  const host = superagentSourceHost(env);
2040
2606
  for (const source of config.sources) try {
2041
- kinds.find(({ kind }) => kind === source.kind)?.preflight?.(source.settings, host);
2607
+ kinds.sourceKinds.find(({ kind }) => kind === source.kind)?.preflight?.(source.settings, host);
2042
2608
  } catch (error) {
2043
2609
  throw new Error(`Superagent source ${source.id} is not ready: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
2044
2610
  }
2045
- if (config.workers.some(({ via }) => via === "herdr") && !env.RIVUS_SUPERAGENT_HERDR_ROOT?.trim()) throw new Error("Herdr workers require RIVUS_SUPERAGENT_HERDR_ROOT");
2611
+ if (config.workers.some((worker) => worker.via === "herdr" && worker.machine === void 0) && !env.RIVUS_SUPERAGENT_HERDR_ROOT?.trim()) throw new Error("Herdr workers require RIVUS_SUPERAGENT_HERDR_ROOT");
2046
2612
  return config;
2047
2613
  }
2048
2614
  /** The `rivus doctor` check: it also imports the configured source preset modules, which run their top-level code. */
2049
- async function checkSuperagentConfigurations(manifest, env, version, location) {
2615
+ async function checkSuperagentConfigurations(manifest, env, version, location, gitVersion) {
2050
2616
  const definition = manifest.superagent;
2051
2617
  if (definition === void 0) return;
2052
- await checkSuperagentRuntime(version);
2053
- const kinds = await loadSuperagentSourceKinds(definition.sourcePresets, builtinSourcePreset(), location);
2618
+ await checkSuperagentRuntime(version, gitVersion);
2619
+ const kinds = await loadSuperagentKinds(definition.sourcePresets, builtinSourcePreset(), location);
2054
2620
  checkSuperagentDefinition(await import("./dist.js"), definition, manifest, env, kinds);
2055
2621
  }
2056
2622
  //#endregion
@@ -2493,6 +3059,7 @@ function parseRivusModelManagementWireRequest(value) {
2493
3059
  //#region src/model-management/infra/adapters/cli/rivus-model-socket.ts
2494
3060
  const RIVUS_MODEL_SOCKET_ENV = "RIVUS_MODEL_SOCKET";
2495
3061
  const RIVUS_MODEL_MANAGEMENT_ENABLED_ENV = "RIVUS_MODEL_MANAGEMENT_ENABLED";
3062
+ /** @internal */
2496
3063
  const RIVUS_MODEL_SOCKET_RELATIVE_PATH = "state/model-management/control.sock";
2497
3064
  function resolveAbsoluteHome(value) {
2498
3065
  if (!isAbsolute(value)) throw new Error("RIVUS_HOME must be an absolute path");
@@ -2520,6 +3087,7 @@ function isRivusModelManagementEnabled(env) {
2520
3087
  const RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID_ENV = "RIVUS_MODEL_MANAGEMENT_OWNER_OPEN_ID";
2521
3088
  const RIVUS_MODEL_MANAGEMENT_TENANT_KEY_ENV = "RIVUS_MODEL_MANAGEMENT_TENANT_KEY";
2522
3089
  const RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL_ENV = "RIVUS_MODEL_MANAGEMENT_REQUIRE_APPROVAL";
3090
+ /** @internal */
2523
3091
  var RivusModelManagementConfigError = class extends Error {
2524
3092
  code;
2525
3093
  name = "RivusModelManagementConfigError";
@@ -2746,7 +3314,7 @@ function sortRecoverySnapshot(snapshot) {
2746
3314
  }
2747
3315
  //#endregion
2748
3316
  //#region src/cli/lib/superagent/superagent-command.ts
2749
- const id = Schema.NonEmptyString;
3317
+ const id$2 = Schema.NonEmptyString;
2750
3318
  const superagentCommand = Schema.Union([
2751
3319
  Schema.Struct({ operation: Schema.Literals([
2752
3320
  "status",
@@ -2760,13 +3328,13 @@ const superagentCommand = Schema.Union([
2760
3328
  "resend",
2761
3329
  "dismiss"
2762
3330
  ]),
2763
- id
3331
+ id: id$2
2764
3332
  }),
2765
3333
  Schema.Struct({
2766
3334
  operation: Schema.Literal("retry"),
2767
- id,
3335
+ id: id$2,
2768
3336
  resend: Schema.Boolean,
2769
- workerId: Schema.optionalKey(id)
3337
+ workerId: Schema.optionalKey(id$2)
2770
3338
  }),
2771
3339
  Schema.Struct({
2772
3340
  operation: Schema.Literal("reset"),
@@ -2774,15 +3342,15 @@ const superagentCommand = Schema.Union([
2774
3342
  Schema.Literals(["public", "internal"]),
2775
3343
  Schema.TemplateLiteral([
2776
3344
  "private:",
2777
- id,
3345
+ id$2,
2778
3346
  ":",
2779
- id
3347
+ id$2
2780
3348
  ]),
2781
3349
  Schema.TemplateLiteral([
2782
3350
  "group:",
2783
- id,
3351
+ id$2,
2784
3352
  ":",
2785
- id
3353
+ id$2
2786
3354
  ])
2787
3355
  ]))
2788
3356
  })
@@ -3621,17 +4189,6 @@ const presentationFields = {
3621
4189
  title: Schema.String,
3622
4190
  trendColors: Schema.optional(Schema.Literals(["red-up", "green-up"]))
3623
4191
  };
3624
- Schema.Struct({
3625
- ...presentationFields,
3626
- meta: Schema.optional(Schema.Array(Schema.String)),
3627
- sections: Schema.Array(Schema.Struct({
3628
- ...sectionFields,
3629
- items: Schema.Array(Schema.Struct({
3630
- ...itemFields,
3631
- sources: Schema.optional(Schema.Array(sourceSchema))
3632
- }))
3633
- }))
3634
- });
3635
4192
  const presentationSchema = Schema.Struct({
3636
4193
  ...presentationFields,
3637
4194
  meta: Schema.Array(Schema.String),
@@ -3697,7 +4254,7 @@ function safeHttpUrl(value, path) {
3697
4254
  }
3698
4255
  function normalizePresentation(input) {
3699
4256
  const title = requiredText(input.title, "title", 120);
3700
- const meta = (input.meta ?? []).map((value, index) => requiredText(value, `meta[${index}]`, 80));
4257
+ const meta = input.meta.map((value, index) => requiredText(value, `meta[${index}]`, 80));
3701
4258
  if (meta.length > 6) throw new InvalidAutomationPresentation("Automation presentation meta exceeds 6 items");
3702
4259
  if (input.sections.length > 12) throw new InvalidAutomationPresentation("Automation presentation sections exceeds 12 sections");
3703
4260
  if (input.summaryStyle === "highlight" && !input.summary?.trim()) throw new InvalidAutomationPresentation("Automation presentation summaryStyle highlight requires summary");
@@ -3723,7 +4280,7 @@ function normalizePresentation(input) {
3723
4280
  ...item.emphasis === void 0 ? {} : { emphasis: item.emphasis },
3724
4281
  headline: requiredText(item.headline, `${itemPath}.headline`, 240),
3725
4282
  ...item.note ? { note: requiredText(item.note, `${itemPath}.note`, 400) } : {},
3726
- sources: Object.freeze((item.sources ?? []).map((source, sourceIndex) => Object.freeze({
4283
+ sources: Object.freeze(item.sources.map((source, sourceIndex) => Object.freeze({
3727
4284
  label: requiredText(source.label, `${itemPath}.sources[${sourceIndex}].label`, 60),
3728
4285
  url: safeHttpUrl(source.url, `${itemPath}.sources[${sourceIndex}].url`)
3729
4286
  })))
@@ -3906,16 +4463,16 @@ function parseInboundDeliveryTimestamp(value, label) {
3906
4463
  value: timestamp
3907
4464
  } : invalidInboundDelivery(`Inbound Delivery ${label} is invalid`);
3908
4465
  }
3909
- function nonEmpty(value) {
4466
+ function nonEmpty$1(value) {
3910
4467
  return value.trim().length > 0;
3911
4468
  }
3912
4469
  function validateInboundDeliveryRecoveryAudit(recovery) {
3913
- if (!nonEmpty(recovery.actorId) || !nonEmpty(recovery.note)) return invalidInboundDelivery("Inbound Delivery recovery audit is incomplete");
4470
+ if (!nonEmpty$1(recovery.actorId) || !nonEmpty$1(recovery.note)) return invalidInboundDelivery("Inbound Delivery recovery audit is incomplete");
3914
4471
  const at = parseInboundDeliveryTimestamp(recovery.at, "recovery audit timestamp");
3915
4472
  return at.ok ? valid$1 : at;
3916
4473
  }
3917
4474
  function requireInboundDeliveryLease(leaseId, leasedAt, leaseExpiresAt) {
3918
- if (!nonEmpty(leaseId)) return invalidInboundDelivery("Inbound Delivery lease id must not be empty");
4475
+ if (!nonEmpty$1(leaseId)) return invalidInboundDelivery("Inbound Delivery lease id must not be empty");
3919
4476
  const leasedAtMilliseconds = parseInboundDeliveryTimestamp(leasedAt, "lease timestamp");
3920
4477
  if (!leasedAtMilliseconds.ok) return leasedAtMilliseconds;
3921
4478
  const expiresAt = parseInboundDeliveryTimestamp(leaseExpiresAt, "lease expiration");
@@ -3936,15 +4493,15 @@ function validateInboundDeliveryState(state) {
3936
4493
  case "dead": {
3937
4494
  const failedAt = parseInboundDeliveryTimestamp(state.failedAt, "failure timestamp");
3938
4495
  if (!failedAt.ok) return failedAt;
3939
- return nonEmpty(state.reason) ? valid$1 : invalidInboundDelivery("Inbound Delivery Dead Letter reason must not be empty");
4496
+ return nonEmpty$1(state.reason) ? valid$1 : invalidInboundDelivery("Inbound Delivery Dead Letter reason must not be empty");
3940
4497
  }
3941
4498
  }
3942
4499
  }
3943
4500
  function validateInboundDeliverySnapshot(delivery) {
3944
4501
  const acceptedAt = parseInboundDeliveryTimestamp(delivery.acceptedAt, "acceptance timestamp");
3945
4502
  if (!acceptedAt.ok) return acceptedAt;
3946
- if (!nonEmpty(delivery.id)) return invalidInboundDelivery("Inbound Delivery id must not be empty");
3947
- if (!nonEmpty(delivery.laneKey)) return invalidInboundDelivery("Inbound Delivery lane must not be empty");
4503
+ if (!nonEmpty$1(delivery.id)) return invalidInboundDelivery("Inbound Delivery id must not be empty");
4504
+ if (!nonEmpty$1(delivery.laneKey)) return invalidInboundDelivery("Inbound Delivery lane must not be empty");
3948
4505
  if (!Number.isSafeInteger(delivery.attempts) || delivery.attempts < 0) return invalidInboundDelivery("Inbound Delivery attempts must be a non-negative integer");
3949
4506
  if (!Number.isSafeInteger(delivery.revision) || delivery.revision < 1) return invalidInboundDelivery("Inbound Delivery revision must be a positive integer");
3950
4507
  if (delivery.recovery !== void 0) {
@@ -4498,6 +5055,7 @@ function createInMemoryDurableQueueStore(options = {}) {
4498
5055
  })),
4499
5056
  deadLetters: () => [...deliveries.values()].filter((delivery) => delivery.state.status === "dead").map((delivery) => accepted(freezeInboundDeliverySnapshot(delivery))),
4500
5057
  fail: (input) => serialized(mutateLeased(deliveries, input.id, input.leaseId, save, (current) => failInboundDelivery(current, input))),
5058
+ snapshotIds: () => new Set(deliveries.keys()),
4501
5059
  pendingCount: () => pendingCount(deliveries),
4502
5060
  renew: (input) => serialized(Effect.gen(function* () {
4503
5061
  const current = requireDelivery(deliveries, input.id);
@@ -4527,6 +5085,7 @@ const feishuInboundDeliveryPayloadCodec = Object.freeze({
4527
5085
  return structuredClone(value);
4528
5086
  }
4529
5087
  });
5088
+ /** @internal */
4530
5089
  function createFeishuInboundDeliveryInput(payload) {
4531
5090
  const message = payload.event.message;
4532
5091
  return {
@@ -4569,6 +5128,7 @@ const decodePersistedDelivery = Schema.decodeUnknownOption(Schema.Struct({
4569
5128
  revision: Schema.Number,
4570
5129
  state: Schema.optionalKey(Schema.Unknown)
4571
5130
  }));
5131
+ /** @internal */
4572
5132
  function encodeInboundDeliverySnapshot(delivery) {
4573
5133
  const validated = validateInboundDeliverySnapshot(delivery);
4574
5134
  if (!validated.ok) throw toInvalidInboundDeliveryError(validated.error);
@@ -4605,6 +5165,7 @@ function decodeDelivery(raw, payloadCodec) {
4605
5165
  if (!delivery.ok) throw toInvalidInboundDeliveryError(delivery.error);
4606
5166
  return delivery.value;
4607
5167
  }
5168
+ /** @internal Persistence tests also read the durable history through this decoder. */
4608
5169
  function decodeInboundDeliverySnapshots(raw, options) {
4609
5170
  if (raw === void 0) return [];
4610
5171
  const latest = /* @__PURE__ */ new Map();
@@ -4672,6 +5233,7 @@ function requireTimestamp(value) {
4672
5233
  function requireToolOperationInstance(instanceId, record) {
4673
5234
  if (record.binding.instanceId !== instanceId) throw new Error(`Tool operation ${record.operationId} is stored under the wrong instance`);
4674
5235
  }
5236
+ /** @internal */
4675
5237
  function createRecoveryControl(owners) {
4676
5238
  const automations = new Map(owners.automations.map(({ automationId, repository }) => [automationId, repository]));
4677
5239
  const inboxes = new Map(owners.inboxes.map(({ endpointId, store }) => [endpointId, store]));
@@ -5286,5 +5848,1393 @@ function runRivusAudioPassthroughProcess(request) {
5286
5848
  });
5287
5849
  }
5288
5850
  //#endregion
5289
- export { validateTrustedModulePath as $, parseSuperagentArguments as A, createRivusModelManagementWireRequest as B, AutomationOccurrenceRepository as C, superagentControlSocketPath as D, resolveRivusDeploymentStateDirectory as E, parseRivusModelManagementHomeConfig as F, renderRivusModelCliArgumentError as G, projectRivusModelCliResponse as H, RIVUS_MODEL_SOCKET_ENV as I, checkSuperagentDefinition as J, renderRivusModelCliHelp as K, isRivusModelManagementEnabled as L, superagentUsage as M, handOffRivusModelManagementEnv as N, superagentDirectory as O, parseRivusModelManagementEnabled as P, resolveNodeRivusPluginModulePath as Q, resolveRivusModelSocketPath as R, AutomationIdentity as S, deploymentStateDirectoryFromEnv as T, toRivusModelManagementSubmission as U, parseRivusModelManagementWireRequest as V, parseRivusModelCliArguments as W, loadSuperagentSourceKinds as X, checkSuperagentRuntime as Y, createNodeRivusPluginModuleLoader as Z, readAutomationPresentation as _, createRuntimeCache as _t, readRivusAudioInstalledRelease as a, gatewayPackageManifestPath as at, AutomationClock as b, deepFreeze as bt, withoutRivusHomeDeployment as c, loadMergedLocalEnvFile as ct, decodeInboundDeliverySnapshots as d, toError as dt, findTrustedPackageRoot as et, openJsonlInboundDeliveryStore as f, superagentSourceHost as ft, openAutomationOccurrenceRepository as g, errorMessage as gt, createInMemoryDurableQueueStore as h, narrowBackgroundSessionDefinition as ht, installRivusAudioTranscriber as i, gatewayPackageDirectory as it, superagentRejectionExitCode as j, decodeSuperagentCommand as k, openJsonlRecoveryControl as l, resolveAcpRuntimeEnvironment as lt, feishuInboundDeliveryPayloadCodec as m, createBackgroundSessionToolContracts as mt, runRivusAudioProcess as n, RIVUS_RELEASE_DESCRIPTOR as nt, readRivusAudioStatus as o, gatewaySkillsDirectory as ot, createFeishuInboundDelivery as p, builtinSourcePreset as pt, checkSuperagentConfigurations as q, RivusAudioInstallStepError as r, gatewayAudioTranscriberAssetDirectory as rt, RIVUS_HOME_DEPLOYMENT_ENV as s, gatewayTemplateDirectory as st, runRivusAudioPassthroughProcess as t, loadRivusDeploymentManifest as tt, runRivusRecoveryCliCommand as u, resolveFeishuEndpointCredentials as ut, AutomationOccurrence as v, disposeRuntimeCacheEntries as vt, AutomationRunner as w, AutomationDeliverySink as x, toAutomationOccurrenceError as y, invokeRuntimeControl as yt, createRivusModelManagementFailure as z };
5851
+ //#region src/herdr/infra/adapters/continue-session.ts
5852
+ /**
5853
+ * The arguments that make each agent kind continue the most recent session of its working directory. Every execution
5854
+ * of a Task runs in the Task's own directory, so that session is the Task's previous execution. Only kinds whose CLI
5855
+ * scopes "most recent" to the current directory are listed: opencode keys sessions by the repository's root commit,
5856
+ * which worktrees of one repository share, and agy does not state a scope, so either could continue another Task's
5857
+ * conversation. A kind missing here cannot continue a session.
5858
+ */
5859
+ const continueArguments = /* @__PURE__ */ new Map([
5860
+ ["claude", ["--continue"]],
5861
+ ["codex", ["resume", "--last"]],
5862
+ ["grok", ["-c"]],
5863
+ ["dsh-tui", ["-c"]]
5864
+ ]);
5865
+ function continuesSession(kind) {
5866
+ return continueArguments.has(kind);
5867
+ }
5868
+ /**
5869
+ * The arguments that start `kind` continuing its latest session, or none for an ordinary start. They come before any
5870
+ * other argument, because Codex takes `resume --last` as a subcommand.
5871
+ */
5872
+ function sessionArguments(kind, continueSession) {
5873
+ return continueSession ? continueArguments.get(kind) ?? [] : [];
5874
+ }
5875
+ //#endregion
5876
+ //#region src/herdr/lib/prompt-kinds.ts
5877
+ const builtInKinds = /* @__PURE__ */ new Set([
5878
+ "pi",
5879
+ "claude",
5880
+ "codex",
5881
+ "gemini",
5882
+ "cursor",
5883
+ "devin",
5884
+ "agy",
5885
+ "cline",
5886
+ "omp",
5887
+ "mastracode",
5888
+ "opencode",
5889
+ "copilot",
5890
+ "kimi",
5891
+ "kiro",
5892
+ "droid",
5893
+ "amp",
5894
+ "grok",
5895
+ "hermes",
5896
+ "kilo",
5897
+ "qodercli",
5898
+ "qwen",
5899
+ "letta",
5900
+ "maki",
5901
+ "muse"
5902
+ ]);
5903
+ function acceptsPrompt(label) {
5904
+ return label != null && builtInKinds.has(label);
5905
+ }
5906
+ //#endregion
5907
+ //#region src/herdr/infra/adapters/claude-worker-launch.ts
5908
+ function shellWords(words) {
5909
+ return words.map((value) => "'" + value.replaceAll("'", "'\"'\"'") + "'").join(" ");
5910
+ }
5911
+ /**
5912
+ * Writes a Claude worker's private launch files into the execution directory and returns the Claude arguments that
5913
+ * load them: the Rivus MCP server, the standing instructions, and settings with the task hooks.
5914
+ */
5915
+ async function claudeArguments(directory, launch, strict, paths) {
5916
+ await mkdir(directory, {
5917
+ recursive: true,
5918
+ mode: 448
5919
+ });
5920
+ await chmod(directory, 448);
5921
+ const mcp = join(directory, "mcp.json");
5922
+ const prompt = join(directory, "prompt.md");
5923
+ const settings = join(directory, "settings.json");
5924
+ const hook = [{
5925
+ type: "command",
5926
+ command: shellWords([join(directory, "task")]) + " hook",
5927
+ timeout: 10
5928
+ }];
5929
+ await Promise.all([
5930
+ writeFile(mcp, JSON.stringify({ mcpServers: { "rivus-worker": {
5931
+ command: process.execPath,
5932
+ args: [paths.mcpPath, "--worker"],
5933
+ env: {
5934
+ RIVUS_WORKER_SOCKET: paths.workerPath,
5935
+ RIVUS_WORKER_KEY: launch.key,
5936
+ RIVUS_WORKER_TOKEN: launch.token
5937
+ }
5938
+ } } }), { mode: 384 }),
5939
+ writeFile(prompt, [
5940
+ "Work within the assigned scope. Report using the Rivus worker tools.",
5941
+ launch.scope,
5942
+ launch.notes
5943
+ ].filter(Boolean).join("\n\n"), { mode: 384 }),
5944
+ writeFile(settings, JSON.stringify({
5945
+ env: launch.environment,
5946
+ permissions: { allow: [
5947
+ "mcp__rivus-worker__task_status",
5948
+ "mcp__rivus-worker__task_show",
5949
+ "mcp__rivus-worker__task_report",
5950
+ "mcp__rivus-worker__task_ask",
5951
+ "mcp__rivus-worker__task_read",
5952
+ "mcp__rivus-worker__task_follow",
5953
+ "mcp__rivus-worker__task_unrelated",
5954
+ "mcp__rivus-worker__task_followup",
5955
+ "mcp__rivus-worker__task_ack",
5956
+ "mcp__rivus-worker__task_handback"
5957
+ ] },
5958
+ hooks: {
5959
+ PreToolUse: [{
5960
+ matcher: "AskUserQuestion",
5961
+ hooks: hook
5962
+ }],
5963
+ ...Object.fromEntries([
5964
+ "UserPromptSubmit",
5965
+ "PostToolUse",
5966
+ "PermissionRequest",
5967
+ "Notification",
5968
+ "Stop",
5969
+ "StopFailure",
5970
+ "SubagentStop"
5971
+ ].map((event) => [event, [{ hooks: hook }]]))
5972
+ }
5973
+ }), { mode: 384 })
5974
+ ]);
5975
+ return [
5976
+ "--mcp-config",
5977
+ mcp,
5978
+ ...strict ? ["--strict-mcp-config"] : [],
5979
+ "--append-system-prompt-file",
5980
+ prompt,
5981
+ "--settings",
5982
+ settings
5983
+ ];
5984
+ }
5985
+ //#endregion
5986
+ //#region src/herdr/infra/adapters/execution-receipts.ts
5987
+ const id$1 = Schema.NonEmptyString;
5988
+ const launchReceipt = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Struct({
5989
+ generation: id$1,
5990
+ paneId: id$1,
5991
+ terminalId: id$1,
5992
+ processGroupId: Schema.optional(Schema.Int)
5993
+ })));
5994
+ const turnReceipt = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Struct({
5995
+ backend: id$1,
5996
+ completionSequence: Schema.NullOr(Schema.Int)
5997
+ })));
5998
+ async function readReceipt(path, decode) {
5999
+ const content = await readFile(path, "utf8").catch((error) => {
6000
+ if (error.code !== "ENOENT") throw error;
6001
+ });
6002
+ return content === void 0 ? void 0 : decode(content);
6003
+ }
6004
+ async function replacePrivateFile(path, content, mode) {
6005
+ const temporary = path + "." + randomUUID();
6006
+ try {
6007
+ await writeFile(temporary, content, {
6008
+ mode,
6009
+ flag: "wx"
6010
+ });
6011
+ await rename(temporary, path);
6012
+ } finally {
6013
+ await rm(temporary, { force: true });
6014
+ }
6015
+ }
6016
+ const readLaunchReceipt = (path) => readReceipt(path, launchReceipt);
6017
+ /** An input's completion sequence before submission, retained across bridge processes for the same pane. */
6018
+ function trackTurn(path) {
6019
+ let live = false;
6020
+ let baseline;
6021
+ let saved;
6022
+ return {
6023
+ get baseline() {
6024
+ return baseline;
6025
+ },
6026
+ async submitting(backend, seq) {
6027
+ await replacePrivateFile(path, JSON.stringify({
6028
+ backend,
6029
+ completionSequence: seq ?? null
6030
+ }), 384);
6031
+ baseline = seq;
6032
+ live = true;
6033
+ },
6034
+ async completed(seq, matches) {
6035
+ let before = baseline;
6036
+ if (!live) {
6037
+ const receipt = await (saved ??= readReceipt(path, turnReceipt).catch(() => void 0));
6038
+ if (receipt && matches(receipt.backend)) before = receipt.completionSequence;
6039
+ }
6040
+ if (before !== void 0 && seq != null) return seq > (before ?? -1);
6041
+ return live ? false : void 0;
6042
+ }
6043
+ };
6044
+ }
6045
+ //#endregion
6046
+ //#region src/herdr/infra/adapters/key-press.ts
6047
+ const defaultPromptSettle = {
6048
+ pollMs: 100,
6049
+ settleMs: 800
6050
+ };
6051
+ /** The pane write that presses one key: a character is typed, any other key is sent by its Herdr name. */
6052
+ function keyWrite(key) {
6053
+ if (key === "space") return {
6054
+ method: "pane.send_text",
6055
+ text: " "
6056
+ };
6057
+ return key.length === 1 ? {
6058
+ method: "pane.send_text",
6059
+ text: key
6060
+ } : {
6061
+ method: "pane.send_keys",
6062
+ keys: [key]
6063
+ };
6064
+ }
6065
+ /**
6066
+ * The screen after a key: the first one that differs from `before` and reads the same again, or the last one read
6067
+ * when `settleMs` passes, since the agent redraws some time after the key. `undefined` once `read` returns no screen.
6068
+ */
6069
+ async function settledScreen(read, before, { pollMs, settleMs }) {
6070
+ const deadline = Date.now() + settleMs;
6071
+ let previous = before;
6072
+ while (true) {
6073
+ await setTimeout$1(pollMs);
6074
+ const screen = await read();
6075
+ if (screen === void 0 || screen !== before && screen === previous || Date.now() >= deadline) return screen;
6076
+ previous = screen;
6077
+ }
6078
+ }
6079
+ //#endregion
6080
+ //#region src/herdr/infra/adapters/numbered-menu.ts
6081
+ const row = /^\s*([>❯›→])?\s*(\d+)[.)]\s+(.+)$/u;
6082
+ const separator = /^\s*[─━═-]{3,}\s*$/u;
6083
+ const navigation = /(?:↑.*↓|↓.*↑|enter to (?:select|confirm)|esc to cancel)/iu;
6084
+ function lastLine(lines, matches) {
6085
+ for (let index = lines.length - 1; index >= 0; index--) if (matches.test(lines[index])) return index;
6086
+ return -1;
6087
+ }
6088
+ function picker(question, options, selected, workspaceTrust) {
6089
+ return {
6090
+ signature: createHash("sha256").update(JSON.stringify(workspaceTrust ? [
6091
+ "agy-workspace-trust",
6092
+ question,
6093
+ options
6094
+ ] : [question, options])).digest("hex"),
6095
+ text: [question, ...options.map((label, index) => `${index + 1}. ${label}`)].join("\n"),
6096
+ options,
6097
+ selected,
6098
+ workspaceTrust
6099
+ };
6100
+ }
6101
+ /** Antigravity's startup picker has no numbers. Only its own launch directory can be confirmed unattended. */
6102
+ async function agyWorkspaceMenu(screen, cwd, unattended) {
6103
+ const lines = screen.trim().split("\n").map((line) => line.trim()).filter(Boolean);
6104
+ const [heading, directory, question, explanation, yes, no, navigation, footer] = lines;
6105
+ if (heading !== "Accessing workspace:" || !directory?.startsWith("/") || question !== "Do you trust the contents of this project?" || explanation !== "Antigravity CLI requires permission to read, edit, and execute files here." || !(yes === "> Yes, I trust this folder" && no === "No, exit" || yes === "Yes, I trust this folder" && no === "> No, exit") || navigation !== "↑/↓ Navigate · enter Confirm" || lines.length > 8 || footer !== void 0 && !/^[\w-]+\s+·\s+[^·]+\s+·\s+[\w-]+$/u.test(footer)) return;
6106
+ const selected = yes.startsWith(">") ? 1 : 2;
6107
+ return picker([
6108
+ heading,
6109
+ directory,
6110
+ question,
6111
+ explanation
6112
+ ].join("\n"), ["Yes, I trust this folder", "No, exit"], selected, unattended && selected === 1 && (directory === cwd || directory === await realpath(cwd).catch(() => void 0)) ? "confirm" : "ask");
6113
+ }
6114
+ /** Reads the numbered picker drawn at the bottom of a blocked agent's visible pane. */
6115
+ function numberedMenu(screen) {
6116
+ const lines = screen.trimEnd().split("\n");
6117
+ const selectedLine = lastLine(lines, /^\s*[>❯›→]\s*\d+[.)]\s+/u);
6118
+ if (selectedLine < 0) return;
6119
+ let start = selectedLine;
6120
+ while (start > 0 && !/^\s*[>❯›→]?\s*1[.)]\s+/u.test(lines[start])) start--;
6121
+ const options = [];
6122
+ let selected = 0;
6123
+ let end = start;
6124
+ for (; end < lines.length; end++) {
6125
+ const line = lines[end];
6126
+ const match = row.exec(line);
6127
+ if (match) {
6128
+ if (Number(match[2]) !== options.length + 1 || match[1] && selected !== 0) return;
6129
+ options.push(match[3].trim());
6130
+ if (match[1]) selected = options.length;
6131
+ } else if (line.trim() && /^\s{3,}\S/u.test(line) && !navigation.test(line) && options.length > 0) options[options.length - 1] += " " + line.trim();
6132
+ else break;
6133
+ }
6134
+ if (!selected || options.length < 2 || lines.slice(end).some((line) => line.trim() && !navigation.test(line) && !separator.test(line))) return;
6135
+ const before = lines.slice(0, start);
6136
+ const divider = lastLine(before, separator);
6137
+ const command = lastLine(before, /^\s*Requesting permission for:\s*$/iu);
6138
+ const question = before.slice(command >= 0 ? command : divider + 1).join("\n").trim();
6139
+ if (!question || /^Run this command\?$/iu.test(question)) return;
6140
+ return picker(question, options, selected);
6141
+ }
6142
+ /** Observe each cursor move before pressing the next key, including Enter on the requested row. */
6143
+ async function chooseNumberedOption(signature, number, read, press) {
6144
+ let menu = await read();
6145
+ if (menu?.signature !== signature) return "changed";
6146
+ if (!Number.isSafeInteger(number) || number < 1 || number > menu.options.length) return "invalid";
6147
+ while (menu.selected !== number) {
6148
+ const step = number > menu.selected ? 1 : -1;
6149
+ const next = menu.selected + step;
6150
+ if (!await press(step === 1 ? "down" : "up", menu.selected)) return "changed";
6151
+ menu = await read();
6152
+ if (menu?.signature !== signature || menu.selected !== next) return "changed";
6153
+ }
6154
+ if (!await press("enter", number)) return "changed";
6155
+ return (await read())?.signature === signature ? "uncertain" : "confirmed";
6156
+ }
6157
+ //#endregion
6158
+ //#region src/herdr/infra/adapters/terminal-input.ts
6159
+ function terminalInput(options) {
6160
+ const { readScreen, readBlocked, writer, settle } = options;
6161
+ async function parseMenu(launch, screen) {
6162
+ const profile = options.profile(launch.workerId);
6163
+ if (profile.kind === "agy") {
6164
+ const trust = await agyWorkspaceMenu(screen, launch.cwd, profile.command?.includes("--dangerously-skip-permissions") === true);
6165
+ if (trust) return trust;
6166
+ }
6167
+ return numberedMenu(screen);
6168
+ }
6169
+ async function readMenu(launch, backend) {
6170
+ const screen = await readBlocked(launch, backend);
6171
+ return screen === void 0 ? void 0 : parseMenu(launch, screen);
6172
+ }
6173
+ return {
6174
+ readScreen,
6175
+ readMenu,
6176
+ async pressKey(launch, backend, key) {
6177
+ const read = () => readScreen(launch, backend);
6178
+ const before = await read();
6179
+ const press = before === void 0 ? void 0 : await writer(launch, backend, false);
6180
+ if (before === void 0 || !press) return {
6181
+ pressed: false,
6182
+ screen: before
6183
+ };
6184
+ await press(key);
6185
+ return {
6186
+ pressed: true,
6187
+ screen: await settledScreen(read, before, settle)
6188
+ };
6189
+ },
6190
+ async chooseMenu(launch, backend, signature, number, claim) {
6191
+ const read = () => readBlocked(launch, backend);
6192
+ const menu = () => readMenu(launch, backend);
6193
+ const result = await chooseNumberedOption(signature, number, menu, async (key, selected) => {
6194
+ if (key === "enter" && !await claim()) return false;
6195
+ const press = await writer(launch, backend, true);
6196
+ if (!press) return false;
6197
+ const before = await read();
6198
+ const current = before === void 0 ? void 0 : await parseMenu(launch, before);
6199
+ if (before === void 0 || current?.signature !== signature || current.selected !== selected) return false;
6200
+ await press(key);
6201
+ await settledScreen(read, before, settle);
6202
+ return true;
6203
+ });
6204
+ if (result === "confirmed" && !await options.leftPrompt(launch, backend)) {
6205
+ const current = await menu();
6206
+ return current !== void 0 && current.signature !== signature ? "confirmed" : "uncertain";
6207
+ }
6208
+ return result;
6209
+ }
6210
+ };
6211
+ }
6212
+ //#endregion
6213
+ //#region src/herdr/infra/adapters/superagent-worker.ts
6214
+ const id = Schema.NonEmptyString;
6215
+ const pane = Schema.Struct({
6216
+ pane_id: id,
6217
+ tab_id: id,
6218
+ terminal_id: id,
6219
+ agent: Schema.optional(Schema.NullOr(Schema.String)),
6220
+ agent_session: Schema.optional(Schema.Json),
6221
+ agent_status: Schema.String,
6222
+ interactive_ready: Schema.optional(Schema.Boolean),
6223
+ completion_seq: Schema.optional(Schema.NullOr(Schema.Int))
6224
+ });
6225
+ const agent = Schema.Struct({
6226
+ ...pane.fields,
6227
+ name: Schema.optional(Schema.NullOr(Schema.String))
6228
+ });
6229
+ const workspace = Schema.Struct({
6230
+ workspace_id: id,
6231
+ label: Schema.String
6232
+ });
6233
+ const workspacePane = Schema.Struct({
6234
+ ...pane.fields,
6235
+ workspace_id: id
6236
+ });
6237
+ const snapshot = Schema.decodeUnknownSync(Schema.Struct({ snapshot: Schema.Struct({
6238
+ protocol: Schema.Literal(22),
6239
+ panes: Schema.Array(workspacePane),
6240
+ agents: Schema.Array(agent),
6241
+ workspaces: Schema.Array(workspace)
6242
+ }) }));
6243
+ const workspaceCreated = Schema.decodeUnknownSync(Schema.Struct({
6244
+ workspace,
6245
+ root_pane: workspacePane
6246
+ }));
6247
+ const agentStarted = Schema.decodeUnknownSync(Schema.Struct({ agent }));
6248
+ const shellProcess = Schema.decodeUnknownSync(Schema.Struct({ process_info: Schema.Struct({
6249
+ shell_pid: Schema.NullOr(Schema.Int),
6250
+ foreground_process_group_id: Schema.NullOr(Schema.Int),
6251
+ foreground_processes: Schema.Array(Schema.Struct({ pid: Schema.Int }))
6252
+ }) }));
6253
+ const sessionRef = Schema.decodeUnknownOption(Schema.Struct({
6254
+ agent: id,
6255
+ kind: id,
6256
+ value: id
6257
+ }));
6258
+ const terminalRead = Schema.decodeUnknownSync(Schema.Struct({ read: Schema.Struct({ text: Schema.String }) }));
6259
+ var HerdrStartPending = class extends Error {};
6260
+ function sessionReference(pane) {
6261
+ const ref = sessionRef(pane.agent_session);
6262
+ return ref._tag === "Some" && ref.value.agent === pane.agent ? ref.value : void 0;
6263
+ }
6264
+ function fingerprint(parts) {
6265
+ return createHash("sha256").update(JSON.stringify(parts)).digest("hex");
6266
+ }
6267
+ function identity(pane, generation, previous) {
6268
+ const base = fingerprint([
6269
+ generation,
6270
+ pane.pane_id,
6271
+ pane.terminal_id,
6272
+ pane.agent
6273
+ ]) + ".";
6274
+ const reference = sessionReference(pane);
6275
+ const active = base + (reference === void 0 ? "" : fingerprint(reference.kind === "id" ? [reference.value] : [reference.kind, reference.value]));
6276
+ return previous === void 0 || previous === active || previous === base ? active : void 0;
6277
+ }
6278
+ function isIdle(pane) {
6279
+ return pane.agent_status === "idle" || pane.agent_status === "done";
6280
+ }
6281
+ /** Idle or waiting at a prompt: the states in which a key cannot interrupt a running turn. */
6282
+ const outsideTurn = (pane) => isIdle(pane) || pane.agent_status === "blocked";
6283
+ function canPrompt(pane) {
6284
+ return Boolean(pane.agent) && isIdle(pane) && pane.interactive_ready !== false;
6285
+ }
6286
+ function workerName(key) {
6287
+ return "rivus-" + createHash("sha256").update(key).digest("hex").slice(0, 24);
6288
+ }
6289
+ function workerTag(key) {
6290
+ return createHash("sha256").update(key).digest("hex").slice(0, 16);
6291
+ }
6292
+ function createHerdrWorkerExecutor(options) {
6293
+ const settle = options.promptSettle ?? defaultPromptSettle;
6294
+ const watches = /* @__PURE__ */ new Map();
6295
+ function unwatch(key) {
6296
+ const previous = watches.get(key);
6297
+ watches.delete(key);
6298
+ previous?.controller.abort();
6299
+ }
6300
+ function watch(key, session, paneId) {
6301
+ const active = watches.get(key);
6302
+ if (active?.paneId === paneId && !active.disconnected) return active;
6303
+ unwatch(key);
6304
+ const previous = active?.paneId === paneId ? active : void 0;
6305
+ const current = {
6306
+ controller: new AbortController(),
6307
+ paneId,
6308
+ disconnected: false,
6309
+ turn: previous?.turn ?? trackTurn(join(options.directory, workerTag(key), "turn.json")),
6310
+ started: previous?.started ?? false,
6311
+ completed: previous?.completed ?? false,
6312
+ lost: previous?.lost ?? false
6313
+ };
6314
+ watches.set(key, current);
6315
+ const subscribe = options.client.subscribeWorker(session, paneId, (status) => {
6316
+ if (status === "working") current.started = true;
6317
+ else if (status === "lost") current.lost = true;
6318
+ else if ((status === "done" || status === "idle") && current.started) current.completed = true;
6319
+ });
6320
+ Effect.runPromiseExit(subscribe, { signal: current.controller.signal }).then(() => {
6321
+ current.disconnected = true;
6322
+ });
6323
+ return current;
6324
+ }
6325
+ async function inspect(launch) {
6326
+ const { herdrSession: session } = options.profile(launch.workerId);
6327
+ const result = await Effect.runPromise(options.client.invoke(session, "session.snapshot", {}));
6328
+ const inventory = snapshot(result.result).snapshot;
6329
+ return {
6330
+ session,
6331
+ generation: result.generation,
6332
+ inventory
6333
+ };
6334
+ }
6335
+ async function workerPane(launch, current, tag) {
6336
+ const marker = ` [rivus:${tag}]`;
6337
+ const { session, generation, inventory } = current;
6338
+ const matches = inventory.workspaces.filter(({ label }) => label.endsWith(marker));
6339
+ if (matches.length === 0) {
6340
+ const directory = join(options.directory, tag);
6341
+ const intent = join(directory, "workspace-requested");
6342
+ await mkdir(directory, {
6343
+ recursive: true,
6344
+ mode: 448
6345
+ });
6346
+ try {
6347
+ await writeFile(intent, "", {
6348
+ flag: "wx",
6349
+ mode: 384
6350
+ });
6351
+ } catch (error) {
6352
+ if (isNodeErrorWithCode(error, "EEXIST")) throw new HerdrStartPending();
6353
+ throw error;
6354
+ }
6355
+ try {
6356
+ const result = await Effect.runPromise(options.client.invoke(session, "workspace.create", {
6357
+ cwd: launch.cwd,
6358
+ label: launch.title.slice(0, 64) + marker,
6359
+ focus: false,
6360
+ env: launch.environment
6361
+ }));
6362
+ const created = workspaceCreated(result.result);
6363
+ if (result.generation !== generation || created.root_pane.workspace_id !== created.workspace.workspace_id) throw new HerdrStartPending();
6364
+ return created.root_pane;
6365
+ } catch (error) {
6366
+ if (error instanceof HerdrRequestError && ["invalid_params", "unknown_method"].includes(error.code)) {
6367
+ await rm(intent, { force: true });
6368
+ throw error;
6369
+ }
6370
+ throw new HerdrStartPending();
6371
+ }
6372
+ }
6373
+ const panes = inventory.panes.filter(({ workspace_id }) => workspace_id === matches[0]?.workspace_id);
6374
+ if (matches.length !== 1 || panes.length !== 1) throw new HerdrStartPending();
6375
+ return panes[0];
6376
+ }
6377
+ async function recordWorkspace(directory, generation, target) {
6378
+ const path = join(directory, "workspace-pane.json");
6379
+ const receipt = await readLaunchReceipt(path);
6380
+ if (receipt === void 0) {
6381
+ await mkdir(directory, {
6382
+ recursive: true,
6383
+ mode: 448
6384
+ });
6385
+ await replacePrivateFile(path, JSON.stringify({
6386
+ generation,
6387
+ paneId: target.pane_id,
6388
+ terminalId: target.terminal_id
6389
+ }), 384);
6390
+ } else if (receipt.generation !== generation || receipt.paneId !== target.pane_id || receipt.terminalId !== target.terminal_id) throw new HerdrStartPending();
6391
+ }
6392
+ async function paneProcess(session, paneId, generation) {
6393
+ const response = await Effect.runPromise(options.client.invoke(session, "pane.process_info", { pane_id: paneId }));
6394
+ if (response.generation !== generation) throw new Error("Herdr server changed while checking the worker process");
6395
+ return shellProcess(response.result).process_info;
6396
+ }
6397
+ async function launchedAgent(launch, current, match) {
6398
+ const receipt = await readLaunchReceipt(join(options.directory, workerTag(launch.key), "launch.json"));
6399
+ if (receipt?.processGroupId === void 0 || receipt.generation !== current.generation) return;
6400
+ const target = current.inventory.agents.find((candidate) => match(candidate) && candidate.pane_id === receipt.paneId && candidate.terminal_id === receipt.terminalId);
6401
+ if (target === void 0) return;
6402
+ return (await paneProcess(current.session, target.pane_id, current.generation)).foreground_process_group_id === receipt.processGroupId ? target : void 0;
6403
+ }
6404
+ async function findAgent(launch, current) {
6405
+ const profile = options.profile(launch.workerId);
6406
+ const named = current.inventory.agents.find(({ name }) => name === workerName(launch.key));
6407
+ if (named !== void 0 || profile.command === void 0) return named;
6408
+ return launchedAgent(launch, current, (candidate) => candidate.name == null && candidate.agent === profile.kind);
6409
+ }
6410
+ async function startAgent(launch, session, paneId, generation, kind, args) {
6411
+ const deadline = Date.now() + 5e3;
6412
+ while (true) try {
6413
+ return await Effect.runPromise(options.client.invoke(session, "agent.start", {
6414
+ kind,
6415
+ name: workerName(launch.key),
6416
+ pane_id: paneId,
6417
+ timeout_ms: 6e4,
6418
+ args
6419
+ }, 65e3));
6420
+ } catch (error) {
6421
+ if (!(error instanceof HerdrRequestError) || error.code !== "agent_pane_busy" || Date.now() >= deadline) throw error;
6422
+ await setTimeout$1(250);
6423
+ const current = await inspect(launch);
6424
+ const pane = current.inventory.panes.find(({ pane_id }) => pane_id === paneId);
6425
+ if (current.generation !== generation || pane === void 0 || pane.agent) throw error;
6426
+ }
6427
+ }
6428
+ async function waitForAgent(launch, target, generation, predicate) {
6429
+ const kind = options.profile(launch.workerId).kind;
6430
+ const deadline = Date.now() + 6e4;
6431
+ while (Date.now() < deadline) {
6432
+ const current = await inspect(launch);
6433
+ if (current.generation !== generation) throw new Error("Herdr server changed while the worker was starting");
6434
+ const pane = current.inventory.agents.find((candidate) => candidate.pane_id === target.pane_id && candidate.terminal_id === target.terminal_id && candidate.agent === kind && predicate(candidate));
6435
+ if (pane && (canPrompt(pane) || pane.agent_status === "blocked")) return pane;
6436
+ await setTimeout$1(250);
6437
+ }
6438
+ throw new Error("Herdr did not recognize the worker before its startup deadline");
6439
+ }
6440
+ async function startCommand(launch, directory, session, target, generation, command) {
6441
+ const path = join(directory, "launch.json");
6442
+ const previous = await readLaunchReceipt(path);
6443
+ const expected = {
6444
+ generation,
6445
+ paneId: target.pane_id,
6446
+ terminalId: target.terminal_id
6447
+ };
6448
+ if (previous === void 0) {
6449
+ if (target.agent) throw new Error("Herdr worker tab already contains an agent");
6450
+ const deadline = Date.now() + 5e3;
6451
+ while (true) {
6452
+ const info = await paneProcess(session, target.pane_id, generation);
6453
+ if (info.foreground_processes.length === 1 && info.foreground_processes[0]?.pid === info.shell_pid) break;
6454
+ if (Date.now() >= deadline) throw new Error("Herdr worker tab does not have an available shell");
6455
+ await setTimeout$1(250);
6456
+ }
6457
+ await mkdir(directory, {
6458
+ recursive: true,
6459
+ mode: 448
6460
+ });
6461
+ await writeFile(path, JSON.stringify(expected), {
6462
+ flag: "wx",
6463
+ mode: 384
6464
+ });
6465
+ await Effect.runPromise(options.client.invoke(session, "pane.send_input", {
6466
+ pane_id: target.pane_id,
6467
+ text: shellWords(command),
6468
+ keys: ["enter"]
6469
+ })).catch(() => {
6470
+ throw new HerdrStartPending();
6471
+ });
6472
+ } else if (expected.generation !== previous.generation || expected.paneId !== previous.paneId || expected.terminalId !== previous.terminalId) throw new HerdrStartPending();
6473
+ const name = workerName(launch.key);
6474
+ const reported = await waitForAgent(launch, target, generation, (candidate) => candidate.name == null || candidate.name === name).catch(() => {
6475
+ throw new HerdrStartPending();
6476
+ });
6477
+ try {
6478
+ const process = await paneProcess(session, reported.pane_id, generation);
6479
+ if (process.foreground_process_group_id !== null && process.foreground_process_group_id !== process.shell_pid) await replacePrivateFile(path, JSON.stringify({
6480
+ ...expected,
6481
+ processGroupId: process.foreground_process_group_id
6482
+ }), 384);
6483
+ await Effect.runPromise(options.client.invoke(session, "agent.rename", {
6484
+ target: reported.pane_id,
6485
+ name
6486
+ }));
6487
+ } catch {
6488
+ throw new HerdrStartPending();
6489
+ }
6490
+ return reported;
6491
+ }
6492
+ async function startNative(launch, directory, current, target, kind, args) {
6493
+ const { session, generation } = current;
6494
+ const path = join(directory, "native-start.json");
6495
+ const previous = await readLaunchReceipt(path);
6496
+ if (previous === void 0) {
6497
+ if (target.agent) throw new Error("Herdr worker workspace does not have an available shell");
6498
+ await mkdir(directory, {
6499
+ recursive: true,
6500
+ mode: 448
6501
+ });
6502
+ await writeFile(path, JSON.stringify({
6503
+ generation,
6504
+ paneId: target.pane_id,
6505
+ terminalId: target.terminal_id
6506
+ }), {
6507
+ mode: 384,
6508
+ flag: "wx"
6509
+ });
6510
+ try {
6511
+ const started = await startAgent(launch, session, target.pane_id, generation, kind, args);
6512
+ const acknowledged = agentStarted(started.result).agent;
6513
+ if (started.generation === generation && acknowledged.pane_id === target.pane_id && acknowledged.terminal_id === target.terminal_id && acknowledged.agent === kind && (canPrompt(acknowledged) || acknowledged.agent_status === "blocked")) return acknowledged;
6514
+ } catch (error) {
6515
+ if (error instanceof HerdrRequestError && [
6516
+ "agent_pane_busy",
6517
+ "invalid_params",
6518
+ "agent_kind_unknown",
6519
+ "agent_binary_not_found"
6520
+ ].includes(error.code)) {
6521
+ await rm(path, { force: true });
6522
+ throw error;
6523
+ }
6524
+ throw new HerdrStartPending();
6525
+ }
6526
+ } else if (previous.generation !== generation || previous.paneId !== target.pane_id || previous.terminalId !== target.terminal_id) throw new HerdrStartPending();
6527
+ return waitForAgent(launch, target, generation, ({ name }) => name === workerName(launch.key)).catch(() => {
6528
+ throw new HerdrStartPending();
6529
+ });
6530
+ }
6531
+ function workerCli() {
6532
+ return shellWords([process.execPath, join(dirname(options.mcpPath), "cli.js")]) + " task";
6533
+ }
6534
+ async function prepareTaskCommand(directory, launch) {
6535
+ await mkdir(directory, {
6536
+ recursive: true,
6537
+ mode: 448
6538
+ });
6539
+ const script = [
6540
+ "#!/bin/sh",
6541
+ "export RIVUS_WORKER_SOCKET=" + shellWords([options.workerPath]),
6542
+ "export RIVUS_WORKER_KEY=" + shellWords([launch.key]),
6543
+ "export RIVUS_WORKER_TOKEN=" + shellWords([launch.token]),
6544
+ `exec ${workerCli()} "$@"`,
6545
+ ""
6546
+ ].join("\n");
6547
+ await replacePrivateFile(join(directory, "task"), script, 448);
6548
+ }
6549
+ function assignment(execution, text) {
6550
+ if (options.profile(execution.workerId).kind === "claude") return text;
6551
+ const command = shellWords([join(options.directory, workerTag(execution.key), "task")]);
6552
+ return [
6553
+ "Use the Rivus worker commands from this task terminal.",
6554
+ command + " show",
6555
+ command + " call <tool-name> '<JSON>'",
6556
+ command + ` report '{"id":"<unique-report-id>","state":"ready","summary":"<what you completed>"}'`,
6557
+ "Submit a structured report when you finish. Use task_report with state waiting if you need a decision.",
6558
+ ...execution.continueSession ? ["This session continues an earlier run of the task: task commands from earlier in this conversation that name another path are closed, so use only the commands above."] : [],
6559
+ text
6560
+ ].join("\n");
6561
+ }
6562
+ async function inspectAgent(execution, backend) {
6563
+ const current = await inspect(execution);
6564
+ const agent = await findAgent(execution, current);
6565
+ return agent === void 0 || identity(agent, current.generation, backend) === void 0 ? void 0 : {
6566
+ agent,
6567
+ session: current.session,
6568
+ inspected: current
6569
+ };
6570
+ }
6571
+ async function waitForDraftActivity(execution, backend, tracking) {
6572
+ const deadline = Date.now() + 8e3;
6573
+ while (Date.now() < deadline && !tracking.lost) {
6574
+ const target = await inspectAgent(execution, backend);
6575
+ if (target === void 0) break;
6576
+ const { agent } = target;
6577
+ if (tracking.started || agent.agent_status === "working" || agent.agent_status === "blocked" || agent.completion_seq != null && agent.completion_seq > (tracking.turn.baseline ?? -1)) {
6578
+ tracking.started ||= agent.agent_status === "working";
6579
+ return true;
6580
+ }
6581
+ await setTimeout$1(250);
6582
+ }
6583
+ return false;
6584
+ }
6585
+ async function holdsForeground(execution, { agent: worker, inspected }) {
6586
+ return worker.name == null || await launchedAgent(execution, inspected, (c) => c === worker) !== void 0;
6587
+ }
6588
+ async function agentHoldsForeground(execution, target) {
6589
+ if (options.profile(execution.workerId).command !== void 0) return holdsForeground(execution, target);
6590
+ const process = await paneProcess(target.session, target.agent.pane_id, target.inspected.generation);
6591
+ return process.foreground_process_group_id !== null && process.foreground_process_group_id !== process.shell_pid;
6592
+ }
6593
+ async function submitDraft(execution, backend, tracking) {
6594
+ const target = await inspectAgent(execution, backend);
6595
+ if (target === void 0 || tracking.lost) return false;
6596
+ if (tracking.started || target.agent.agent_status === "working") return true;
6597
+ if (!canPrompt(target.agent) || !await holdsForeground(execution, target)) return false;
6598
+ await Effect.runPromise(options.client.invoke(target.session, "pane.send_keys", {
6599
+ pane_id: target.agent.pane_id,
6600
+ keys: ["enter"]
6601
+ }));
6602
+ return waitForDraftActivity(execution, backend, tracking);
6603
+ }
6604
+ async function deliverDraft(execution, backend, text, tracking) {
6605
+ const current = await inspectAgent(execution, backend);
6606
+ if (current === void 0) return "lost";
6607
+ if (!await holdsForeground(execution, current)) return "uncertain";
6608
+ if (!canPrompt(current.agent)) return "busy";
6609
+ const marker = options.profile(execution.workerId).kind === "dsh-tui" ? "Rivus-" + randomUUID().slice(0, 8) : void 0;
6610
+ await Effect.runPromise(options.client.invoke(current.session, "pane.send_text", {
6611
+ pane_id: current.agent.pane_id,
6612
+ text: marker === void 0 ? text : text + "\n" + marker
6613
+ }));
6614
+ if (marker === void 0) {
6615
+ await setTimeout$1(250);
6616
+ return await submitDraft(execution, backend, tracking) ? "delivered" : "uncertain";
6617
+ }
6618
+ await Effect.runPromise(options.client.invoke(current.session, "pane.wait_for_output", {
6619
+ pane_id: current.agent.pane_id,
6620
+ source: "visible",
6621
+ match: {
6622
+ type: "substring",
6623
+ value: marker
6624
+ },
6625
+ timeout_ms: 8e3
6626
+ }, 1e4));
6627
+ await setTimeout$1(250);
6628
+ if (await submitDraft(execution, backend, tracking)) return "delivered";
6629
+ const target = await inspectAgent(execution, backend);
6630
+ if (target === void 0 || !canPrompt(target.agent) || tracking.started || tracking.completed) return "uncertain";
6631
+ const visible = await Effect.runPromise(options.client.invoke(target.session, "pane.read", {
6632
+ pane_id: target.agent.pane_id,
6633
+ source: "visible",
6634
+ format: "text",
6635
+ lines: 80
6636
+ }));
6637
+ return terminalRead(visible.result).read.text.split("\n").some((line) => line.includes("│ ❯") && line.includes(marker)) && await submitDraft(execution, backend, tracking) ? "delivered" : "uncertain";
6638
+ }
6639
+ /**
6640
+ * Reads the worker's pane only while `settled` holds for it before and after the read, so a changing screen is never
6641
+ * read, and only from the pane this execution started.
6642
+ */
6643
+ async function readPane(launch, backend, settled, source, limit) {
6644
+ const current = await inspect(launch);
6645
+ const target = await findAgent(launch, current);
6646
+ if (target === void 0 || !settled(target) || identity(target, current.generation, backend) !== backend) return;
6647
+ const result = await Effect.runPromise(options.client.invoke(current.session, "pane.read", {
6648
+ pane_id: target.pane_id,
6649
+ source,
6650
+ format: "text",
6651
+ ...limit === void 0 ? {} : { lines: 80 }
6652
+ }));
6653
+ if (result.generation !== current.generation) return;
6654
+ const latest = await inspect(launch);
6655
+ const confirmed = await findAgent(launch, latest);
6656
+ return confirmed === void 0 || !settled(confirmed) || identity(confirmed, latest.generation, backend) !== backend ? void 0 : terminalRead(result.result).read.text.trim().slice(limit === void 0 ? 0 : -limit);
6657
+ }
6658
+ /** Reads the terminal only while the worker is still in `state`, so a changing screen is never read. */
6659
+ function readTerminal(launch, backend, state) {
6660
+ return readPane(launch, backend, (pane) => state === "idle" ? isIdle(pane) : pane.agent_status === "blocked", "recent_unwrapped", 2048);
6661
+ }
6662
+ function readScreen(launch, backend) {
6663
+ const seen = watches.get(launch.key);
6664
+ const free = (pane) => outsideTurn(pane) && !(seen?.started === true && !seen.completed);
6665
+ return readPane(launch, backend, free, "visible", 16e3);
6666
+ }
6667
+ function readBlockedScreen(launch, backend) {
6668
+ return readPane(launch, backend, (pane) => pane.agent_status === "blocked", "visible");
6669
+ }
6670
+ async function start(launch, backend) {
6671
+ const profile = options.profile(launch.workerId);
6672
+ const tag = workerTag(launch.key);
6673
+ const directory = join(options.directory, tag);
6674
+ await prepareTaskCommand(directory, launch);
6675
+ let inspected;
6676
+ let current;
6677
+ try {
6678
+ inspected = await inspect(launch);
6679
+ current = await findAgent(launch, inspected);
6680
+ } catch (error) {
6681
+ if (backend === void 0 && await readFile(join(directory, "workspace-requested"), "utf8").catch(() => void 0) !== void 0) throw new HerdrStartPending();
6682
+ throw error;
6683
+ }
6684
+ const { session, generation } = inspected;
6685
+ if (current !== void 0) {
6686
+ const active = identity(current, generation, backend);
6687
+ if (active === void 0 || current.agent !== profile.kind) throw new Error("Herdr worker identity changed");
6688
+ watch(launch.key, session, current.pane_id);
6689
+ return active;
6690
+ }
6691
+ if (backend !== void 0) throw new Error("Herdr worker pane is unavailable");
6692
+ const args = [...sessionArguments(profile.kind, launch.continueSession), ...profile.kind === "claude" ? await claudeArguments(join(options.directory, tag), launch, profile.strictMcpConfig, options) : []];
6693
+ const target = await workerPane(launch, inspected, tag);
6694
+ await recordWorkspace(directory, generation, target).catch(() => {
6695
+ throw new HerdrStartPending();
6696
+ });
6697
+ if (profile.command !== void 0) {
6698
+ const launched = await startCommand(launch, directory, session, target, generation, [...profile.command, ...args]);
6699
+ watch(launch.key, session, launched.pane_id);
6700
+ return identity(launched, generation);
6701
+ }
6702
+ const launched = await startNative(launch, directory, inspected, target, profile.kind, args);
6703
+ watch(launch.key, session, launched.pane_id);
6704
+ return identity(launched, generation);
6705
+ }
6706
+ return {
6707
+ async available(workerId, signal) {
6708
+ const { herdrSession } = options.profile(workerId);
6709
+ const current = await Effect.runPromise(options.client.invoke(herdrSession, "session.snapshot", {}), { signal });
6710
+ snapshot(current.result);
6711
+ return true;
6712
+ },
6713
+ async start(launch, backend) {
6714
+ try {
6715
+ return await start(launch, backend);
6716
+ } catch (error) {
6717
+ if (error instanceof HerdrStartPending) return { status: "starting" };
6718
+ throw error;
6719
+ }
6720
+ },
6721
+ async deliver({ execution, backend, text }) {
6722
+ const inspected = await inspect(execution).catch(() => void 0);
6723
+ if (inspected === void 0) return "busy";
6724
+ const { session, generation } = inspected;
6725
+ const current = await findAgent(execution, inspected);
6726
+ if (current === void 0 || identity(current, generation, backend) === void 0) return "lost";
6727
+ if (!canPrompt(current)) return "busy";
6728
+ const tracking = watch(execution.key, session, current.pane_id);
6729
+ try {
6730
+ await tracking.turn.submitting(identity(current, generation), current.completion_seq);
6731
+ } catch {
6732
+ return "busy";
6733
+ }
6734
+ tracking.started = false;
6735
+ tracking.completed = false;
6736
+ const prompt = assignment(execution, text);
6737
+ const command = options.profile(execution.workerId).command !== void 0;
6738
+ if (command && !acceptsPrompt(current.agent)) return deliverDraft(execution, backend, prompt, tracking).catch(() => "uncertain");
6739
+ try {
6740
+ await Effect.runPromise(options.client.invoke(session, "agent.prompt", {
6741
+ target: current.pane_id,
6742
+ text: prompt
6743
+ }, 1e4));
6744
+ return "delivered";
6745
+ } catch (error) {
6746
+ if (command && error instanceof HerdrRequestError && error.code === "agent_not_ready") return deliverDraft(execution, backend, prompt, tracking).catch(() => "uncertain");
6747
+ return "uncertain";
6748
+ }
6749
+ },
6750
+ async observe(launch, backend) {
6751
+ const current = await inspect(launch).catch(() => void 0);
6752
+ if (current === void 0) return;
6753
+ const target = await findAgent(launch, current);
6754
+ const active = target === void 0 ? void 0 : identity(target, current.generation, backend);
6755
+ if (target === void 0 || active === void 0) {
6756
+ unwatch(launch.key);
6757
+ return { state: "lost" };
6758
+ }
6759
+ const tracking = watch(launch.key, current.session, target.pane_id);
6760
+ if (tracking.lost) {
6761
+ unwatch(launch.key);
6762
+ return { state: "lost" };
6763
+ }
6764
+ const updated = active === backend ? {} : { backend: active };
6765
+ switch (target.agent_status) {
6766
+ case "blocked": return {
6767
+ state: "blocked",
6768
+ ...updated
6769
+ };
6770
+ case "working":
6771
+ tracking.started = true;
6772
+ return {
6773
+ state: "working",
6774
+ ...updated
6775
+ };
6776
+ case "idle":
6777
+ case "done": {
6778
+ if (tracking.completed || tracking.started) return {
6779
+ state: "idle",
6780
+ completed: true,
6781
+ ...updated
6782
+ };
6783
+ const completed = await tracking.turn.completed(target.completion_seq, (saved) => identity(target, current.generation, saved) !== void 0);
6784
+ return {
6785
+ state: "idle",
6786
+ ...completed === void 0 ? {} : { completed },
6787
+ ...updated
6788
+ };
6789
+ }
6790
+ default: return;
6791
+ }
6792
+ },
6793
+ continuesSession(workerId) {
6794
+ try {
6795
+ return continuesSession(options.profile(workerId).kind);
6796
+ } catch {
6797
+ return false;
6798
+ }
6799
+ },
6800
+ emitsActivity(workerId) {
6801
+ try {
6802
+ return options.profile(workerId).kind === "claude";
6803
+ } catch {
6804
+ return false;
6805
+ }
6806
+ },
6807
+ readTerminal,
6808
+ ...terminalInput({
6809
+ profile: options.profile,
6810
+ readScreen,
6811
+ readBlocked: readBlockedScreen,
6812
+ settle,
6813
+ async writer(launch, backend, blocked) {
6814
+ const target = await inspectAgent(launch, backend);
6815
+ if (!target || !(blocked ? target.agent.agent_status === "blocked" : outsideTurn(target.agent)) || !await agentHoldsForeground(launch, target)) return;
6816
+ return async (key) => {
6817
+ const { method, ...input } = keyWrite(key);
6818
+ await Effect.runPromise(options.client.invoke(target.session, method, {
6819
+ pane_id: target.agent.pane_id,
6820
+ ...input
6821
+ }));
6822
+ };
6823
+ },
6824
+ async leftPrompt(launch, backend) {
6825
+ const target = await inspectAgent(launch, backend);
6826
+ return target !== void 0 && (isIdle(target.agent) || target.agent.agent_status === "working");
6827
+ }
6828
+ }),
6829
+ async retire(launch, backend) {
6830
+ const current = await inspect(launch);
6831
+ const target = await findAgent(launch, current);
6832
+ if (backend !== void 0) {
6833
+ if (target !== void 0 && identity(target, current.generation, backend) !== void 0) await Effect.runPromise(options.client.invoke(current.session, "pane.close", { pane_id: target.pane_id }));
6834
+ return;
6835
+ }
6836
+ const tag = workerTag(launch.key);
6837
+ const receipt = await readLaunchReceipt(join(options.directory, tag, "workspace-pane.json"));
6838
+ const space = current.inventory.workspaces.find(({ label }) => label.endsWith(` [rivus:${tag}]`));
6839
+ const panes = current.inventory.panes.filter(({ workspace_id }) => workspace_id === space?.workspace_id);
6840
+ const owned = panes.length === 1 ? panes[0] : void 0;
6841
+ if (owned === void 0 || receipt?.generation !== current.generation || receipt.paneId !== owned.pane_id || receipt.terminalId !== owned.terminal_id) return;
6842
+ if (target?.pane_id !== owned.pane_id || target.terminal_id !== owned.terminal_id) {
6843
+ if (owned.agent) return;
6844
+ const process = await paneProcess(current.session, owned.pane_id, current.generation);
6845
+ if (process.shell_pid === null || process.foreground_process_group_id !== process.shell_pid || process.foreground_processes.length !== 1 || process.foreground_processes[0]?.pid !== process.shell_pid) return;
6846
+ }
6847
+ await Effect.runPromise(options.client.invoke(current.session, "pane.close", { pane_id: owned.pane_id }));
6848
+ },
6849
+ async stop(launch) {
6850
+ unwatch(launch.key);
6851
+ },
6852
+ async close() {
6853
+ for (const key of watches.keys()) unwatch(key);
6854
+ }
6855
+ };
6856
+ }
6857
+ /** Raw attachment bytes that fit base64-encoded in one frame. */
6858
+ const FILE_CHUNK_BYTES = 1048576;
6859
+ function decodeStrict(schema) {
6860
+ return Schema.decodeUnknownSync(schema, { onExcessProperty: "error" });
6861
+ }
6862
+ const nonEmpty = Schema.NonEmptyString;
6863
+ const stringRecord = Schema.Record(Schema.String, Schema.String);
6864
+ const remoteHerdrProfileSchema = Schema.Struct({
6865
+ id: nonEmpty,
6866
+ kind: nonEmpty,
6867
+ herdrSession: nonEmpty,
6868
+ command: Schema.optionalKey(Schema.NonEmptyArray(nonEmpty)),
6869
+ strictMcpConfig: Schema.Boolean
6870
+ });
6871
+ const remoteWorkerLaunchSchema = Schema.Struct({
6872
+ key: nonEmpty,
6873
+ workerId: nonEmpty,
6874
+ taskId: nonEmpty,
6875
+ cwd: nonEmpty,
6876
+ branch: nonEmpty,
6877
+ title: Schema.String,
6878
+ scope: Schema.String,
6879
+ repository: Schema.NullOr(nonEmpty),
6880
+ notes: Schema.NullOr(Schema.String),
6881
+ environment: stringRecord,
6882
+ token: nonEmpty,
6883
+ continueSession: Schema.Boolean
6884
+ });
6885
+ const bridgeErrorSchema = Schema.Struct({
6886
+ code: nonEmpty,
6887
+ message: Schema.String,
6888
+ data: Schema.optionalKey(Schema.Json)
6889
+ });
6890
+ const bridgeFrameSchema = Schema.Union([
6891
+ Schema.Struct({
6892
+ type: Schema.Literal("chunk"),
6893
+ id: nonEmpty,
6894
+ data: nonEmpty
6895
+ }),
6896
+ Schema.Struct({
6897
+ type: Schema.Literal("request"),
6898
+ id: nonEmpty,
6899
+ method: nonEmpty,
6900
+ params: Schema.Json
6901
+ }),
6902
+ Schema.Struct({
6903
+ type: Schema.Literal("response"),
6904
+ id: nonEmpty,
6905
+ ok: Schema.Literal(true),
6906
+ result: Schema.Json
6907
+ }),
6908
+ Schema.Struct({
6909
+ type: Schema.Literal("response"),
6910
+ id: nonEmpty,
6911
+ ok: Schema.Literal(false),
6912
+ error: bridgeErrorSchema
6913
+ })
6914
+ ]);
6915
+ const decodeBridgeFrame = decodeStrict(Schema.fromJsonString(bridgeFrameSchema));
6916
+ function encodeBridgeFrame(frame) {
6917
+ return JSON.stringify(frame) + "\n";
6918
+ }
6919
+ const decodeHelloParams = decodeStrict(Schema.Struct({
6920
+ protocol: Schema.Literal(1),
6921
+ machineId: nonEmpty
6922
+ }));
6923
+ const decodeHelloResult = decodeStrict(Schema.Struct({ protocol: Schema.Literal(1) }));
6924
+ const decodeWorkspacePrepareParams = decodeStrict(Schema.Struct({
6925
+ prepare: Schema.NullOr(nonEmpty),
6926
+ shortName: nonEmpty,
6927
+ taskId: nonEmpty,
6928
+ environment: stringRecord,
6929
+ allowCreate: Schema.Boolean
6930
+ }));
6931
+ const decodeWorkspacePrepareResult = decodeStrict(Schema.Struct({
6932
+ cwd: nonEmpty,
6933
+ branch: nonEmpty
6934
+ }));
6935
+ const decodeWorkspaceFailureData = Schema.decodeUnknownOption(Schema.Struct({
6936
+ path: nonEmpty,
6937
+ stage: Schema.Literals(["prepare", "verify"])
6938
+ }));
6939
+ const decodeWorkspaceReadFileParams = decodeStrict(Schema.Struct({
6940
+ shortName: nonEmpty,
6941
+ path: nonEmpty,
6942
+ maxBytes: Schema.Int
6943
+ }));
6944
+ const decodeWorkspaceReadFileResult = decodeStrict(Schema.Struct({
6945
+ name: nonEmpty,
6946
+ contentBase64: Schema.String,
6947
+ size: Schema.optionalKey(Schema.Int)
6948
+ }));
6949
+ const decodeFileChunk = Schema.decodeUnknownSync(Schema.Uint8ArrayFromBase64);
6950
+ const decodeWorkerAvailableParams = decodeStrict(Schema.Struct({ profile: remoteHerdrProfileSchema }));
6951
+ const decodeWorkerAvailableResult = Schema.decodeUnknownSync(Schema.Boolean);
6952
+ const launchFields = {
6953
+ profile: remoteHerdrProfileSchema,
6954
+ launch: remoteWorkerLaunchSchema
6955
+ };
6956
+ const backendFields = {
6957
+ ...launchFields,
6958
+ backend: nonEmpty
6959
+ };
6960
+ const lifecycleParams = Schema.Struct({
6961
+ ...launchFields,
6962
+ backend: Schema.NullOr(nonEmpty)
6963
+ });
6964
+ const decodeWorkerStartParams = decodeStrict(lifecycleParams);
6965
+ const decodeWorkerStartResult = decodeStrict(Schema.Union([nonEmpty, Schema.Struct({ status: Schema.Literal("starting") })]));
6966
+ const decodeWorkerDeliverParams = decodeStrict(Schema.Struct({
6967
+ profile: remoteHerdrProfileSchema,
6968
+ execution: remoteWorkerLaunchSchema,
6969
+ backend: nonEmpty,
6970
+ requestId: nonEmpty,
6971
+ attempt: Schema.Int,
6972
+ text: Schema.String
6973
+ }));
6974
+ const decodeWorkerDeliverResult = Schema.decodeUnknownSync(Schema.Literals([
6975
+ "delivered",
6976
+ "accepted",
6977
+ "busy",
6978
+ "lost",
6979
+ "uncertain"
6980
+ ]));
6981
+ const decodeWorkerBackendParams = decodeStrict(Schema.Struct(backendFields));
6982
+ const decodeWorkerObserveResult = decodeStrict(Schema.NullOr(Schema.Struct({
6983
+ state: Schema.Literals([
6984
+ "idle",
6985
+ "working",
6986
+ "blocked",
6987
+ "lost"
6988
+ ]),
6989
+ backend: Schema.optionalKey(nonEmpty),
6990
+ completed: Schema.optionalKey(Schema.Boolean)
6991
+ })));
6992
+ const decodeWorkerReadTerminalParams = decodeStrict(Schema.Struct({
6993
+ ...backendFields,
6994
+ state: Schema.Literals(["idle", "blocked"])
6995
+ }));
6996
+ const decodeOptionalStringResult = Schema.decodeUnknownSync(Schema.NullOr(Schema.String));
6997
+ const decodeWorkerPressKeyParams = decodeStrict(Schema.Struct({
6998
+ ...backendFields,
6999
+ key: nonEmpty
7000
+ }));
7001
+ const decodeWorkerPressKeyResult = decodeStrict(Schema.Struct({
7002
+ pressed: Schema.Boolean,
7003
+ screen: Schema.NullOr(Schema.String)
7004
+ }));
7005
+ const decodeWorkerReadMenuResult = decodeStrict(Schema.NullOr(Schema.Struct({
7006
+ signature: nonEmpty,
7007
+ text: Schema.String,
7008
+ workspaceTrust: Schema.optionalKey(Schema.Literals(["ask", "confirm"]))
7009
+ })));
7010
+ const decodeWorkerChooseMenuParams = decodeStrict(Schema.Struct({
7011
+ ...backendFields,
7012
+ signature: nonEmpty,
7013
+ number: Schema.Int,
7014
+ claimId: nonEmpty
7015
+ }));
7016
+ const decodeWorkerChooseMenuResult = Schema.decodeUnknownSync(Schema.Literals([
7017
+ "confirmed",
7018
+ "changed",
7019
+ "invalid",
7020
+ "uncertain"
7021
+ ]));
7022
+ const decodeMenuClaimParams = decodeStrict(Schema.Struct({ claimId: nonEmpty }));
7023
+ const decodeMenuClaimResult = Schema.decodeUnknownSync(Schema.Boolean);
7024
+ const decodeWorkerRetireParams = decodeStrict(lifecycleParams);
7025
+ const decodeToolRequestParams = decodeStrict(Schema.Struct({ frame: Schema.String }));
7026
+ //#endregion
7027
+ //#region src/remote-worker/infra/adapters/stdio-rpc-channel.ts
7028
+ var BridgeRpcError = class extends Error {
7029
+ code;
7030
+ data;
7031
+ name = "BridgeRpcError";
7032
+ constructor(code, message, data) {
7033
+ super(message);
7034
+ this.code = code;
7035
+ this.data = data;
7036
+ }
7037
+ };
7038
+ var BridgeTransportError = class extends Error {
7039
+ phase;
7040
+ name = "BridgeTransportError";
7041
+ constructor(phase, message, options) {
7042
+ super(message, options);
7043
+ this.phase = phase;
7044
+ }
7045
+ };
7046
+ /**
7047
+ * Full-duplex newline-delimited JSON RPC multiplexer over a pair of byte streams (`ssh -T` stdin/stdout or in-memory
7048
+ * duplex streams in tests). Concurrent calls in both directions share one stream by request ID.
7049
+ */
7050
+ function createStdioRpcChannel(options) {
7051
+ const maxFrameBytes = options.maxFrameBytes ?? 2097152;
7052
+ const pending = /* @__PURE__ */ new Map();
7053
+ let closed = false;
7054
+ let buffer = "";
7055
+ const isClosed = () => closed;
7056
+ function sendFrame(frame, written) {
7057
+ if (isClosed() || options.output.destroyed || options.output.writableEnded) return false;
7058
+ const encoded = encodeBridgeFrame(frame);
7059
+ if (Buffer.byteLength(encoded, "utf8") > maxFrameBytes) throw new BridgeRpcError("frame_too_large", "Bridge frame exceeds maximum size");
7060
+ options.output.write(encoded, written);
7061
+ return true;
7062
+ }
7063
+ function takePending(id) {
7064
+ const entry = pending.get(id);
7065
+ if (entry !== void 0) {
7066
+ pending.delete(id);
7067
+ clearTimeout(entry.timer);
7068
+ entry.cleanup();
7069
+ }
7070
+ return entry;
7071
+ }
7072
+ function close(reason = "Bridge channel closed") {
7073
+ if (closed) return;
7074
+ closed = true;
7075
+ options.input.off("data", onData);
7076
+ options.input.off("end", onEnd);
7077
+ options.input.off("close", onEnd);
7078
+ options.input.off("error", onStreamError);
7079
+ options.output.off("error", onStreamError);
7080
+ for (const id of pending.keys()) takePending(id)?.reject(new BridgeTransportError("in-flight", reason));
7081
+ options.onClose?.(reason);
7082
+ }
7083
+ function handleRequest(id, method, params) {
7084
+ const writeChunk = (data) => new Promise((resolve, reject) => {
7085
+ if (!sendFrame({
7086
+ type: "chunk",
7087
+ id,
7088
+ data
7089
+ }, (error) => error ? reject(error) : resolve())) reject(new BridgeTransportError("in-flight", "Bridge channel closed while writing a chunk"));
7090
+ });
7091
+ Promise.resolve().then(() => options.onRequest(method, params, writeChunk)).then((result) => {
7092
+ sendFrame({
7093
+ type: "response",
7094
+ id,
7095
+ ok: true,
7096
+ result: result ?? null
7097
+ });
7098
+ }, (error) => {
7099
+ sendFrame({
7100
+ type: "response",
7101
+ id,
7102
+ ok: false,
7103
+ error: error instanceof BridgeRpcError ? {
7104
+ code: error.code,
7105
+ message: error.message,
7106
+ ...error.data === void 0 ? {} : { data: error.data }
7107
+ } : {
7108
+ code: "internal_error",
7109
+ message: error instanceof Error ? error.message : String(error)
7110
+ }
7111
+ });
7112
+ });
7113
+ }
7114
+ function handleFrame(line) {
7115
+ let frame;
7116
+ try {
7117
+ frame = decodeBridgeFrame(line);
7118
+ } catch (error) {
7119
+ close(`Invalid bridge frame: ${error instanceof Error ? error.message : String(error)}`);
7120
+ return;
7121
+ }
7122
+ if (frame.type === "request") {
7123
+ handleRequest(frame.id, frame.method, frame.params);
7124
+ return;
7125
+ }
7126
+ if (frame.type === "chunk") {
7127
+ const entry = pending.get(frame.id);
7128
+ if (entry !== void 0) try {
7129
+ if (entry.onChunk === void 0) throw new BridgeRpcError("unexpected_chunk", "This request does not accept chunks");
7130
+ entry.onChunk(frame.data);
7131
+ entry.timer.refresh();
7132
+ } catch (error) {
7133
+ takePending(frame.id)?.reject(error);
7134
+ }
7135
+ return;
7136
+ }
7137
+ const entry = takePending(frame.id);
7138
+ if (entry === void 0) return;
7139
+ if (frame.ok) entry.resolve(frame.result);
7140
+ else entry.reject(new BridgeRpcError(frame.error.code, frame.error.message, frame.error.data));
7141
+ }
7142
+ const onData = (chunk) => {
7143
+ if (isClosed()) return;
7144
+ buffer += chunk;
7145
+ let newline = buffer.indexOf("\n");
7146
+ while (newline !== -1 && !isClosed()) {
7147
+ const line = buffer.slice(0, newline);
7148
+ buffer = buffer.slice(newline + 1);
7149
+ if (Buffer.byteLength(line, "utf8") > maxFrameBytes) {
7150
+ close("Bridge frame exceeds maximum size");
7151
+ return;
7152
+ }
7153
+ if (line.length > 0) handleFrame(line);
7154
+ newline = buffer.indexOf("\n");
7155
+ }
7156
+ if (!isClosed() && Buffer.byteLength(buffer, "utf8") > maxFrameBytes) close("Bridge frame exceeds maximum size");
7157
+ };
7158
+ const onEnd = () => close("Bridge stream ended");
7159
+ const onStreamError = (error) => close(`Bridge stream error: ${error.message}`);
7160
+ options.input.setEncoding("utf8").on("data", onData);
7161
+ options.input.on("end", onEnd);
7162
+ options.input.on("close", onEnd);
7163
+ options.input.on("error", onStreamError);
7164
+ options.output.on("error", onStreamError);
7165
+ return {
7166
+ isClosed: () => closed,
7167
+ request(method, params, requestOptions = {}) {
7168
+ if (closed || options.output.destroyed || options.output.writableEnded) return Promise.reject(new BridgeTransportError("before-send", "Bridge channel is closed"));
7169
+ if (requestOptions.signal?.aborted) return Promise.reject(new BridgeTransportError("before-send", "Bridge request aborted before send"));
7170
+ const id = randomUUID();
7171
+ const timeoutMs = requestOptions.timeoutMs ?? 15e3;
7172
+ return new Promise((resolve, reject) => {
7173
+ const fail = (error) => takePending(id)?.reject(error);
7174
+ const onAbort = () => fail(new BridgeTransportError("in-flight", "Bridge request aborted"));
7175
+ const timer = setTimeout(() => fail(new BridgeTransportError("in-flight", `Bridge request ${method} timed out`)), timeoutMs);
7176
+ pending.set(id, {
7177
+ onChunk: requestOptions.onChunk,
7178
+ resolve,
7179
+ reject,
7180
+ timer,
7181
+ cleanup: () => requestOptions.signal?.removeEventListener("abort", onAbort)
7182
+ });
7183
+ requestOptions.signal?.addEventListener("abort", onAbort, { once: true });
7184
+ try {
7185
+ if (!sendFrame({
7186
+ type: "request",
7187
+ id,
7188
+ method,
7189
+ params
7190
+ })) fail(new BridgeTransportError("before-send", "Bridge channel is closed"));
7191
+ } catch (error) {
7192
+ fail(error instanceof BridgeRpcError ? error : new BridgeTransportError("before-send", `Failed to write bridge frame: ${error instanceof Error ? error.message : String(error)}`, { cause: error }));
7193
+ }
7194
+ });
7195
+ },
7196
+ close
7197
+ };
7198
+ }
7199
+ //#endregion
7200
+ //#region src/bootstrap/deployment/superagent-worker-programs.ts
7201
+ function quote(value) {
7202
+ return "'" + value.replaceAll("'", "'\"'\"'") + "'";
7203
+ }
7204
+ async function findGh(path) {
7205
+ for (const directory of path.split(delimiter).filter(isAbsolute)) {
7206
+ const candidate = join(directory, "gh");
7207
+ if (await access(candidate, constants$1.X_OK).then(() => true, () => false)) return candidate;
7208
+ }
7209
+ return "";
7210
+ }
7211
+ async function prepareWorkerPrograms(directory, mcpPath, path) {
7212
+ const bin = join(directory, "bin");
7213
+ const ghConfig = join(directory, "gh");
7214
+ await Promise.all([mkdir(bin, {
7215
+ mode: 448,
7216
+ recursive: true
7217
+ }), mkdir(ghConfig, {
7218
+ mode: 448,
7219
+ recursive: true
7220
+ })]);
7221
+ const command = `exec ${quote(process.execPath)} ${quote(mcpPath)}`;
7222
+ const helper = join(bin, "git-credential-rivus");
7223
+ const denySsh = join(bin, "git-ssh-disabled");
7224
+ await Promise.all([
7225
+ writeFile(helper, `#!/bin/sh\n${command} --git-credential "$@"\n`, { mode: 448 }),
7226
+ writeFile(join(bin, "gh"), `#!/bin/sh\n${command} --gh ${quote(await findGh(path))} "$@"\n`, { mode: 448 }),
7227
+ writeFile(denySsh, "#!/bin/sh\nprintf '%s\\n' 'Rivus workers use HTTPS for configured GitHub repositories.' >&2\nexit 1\n", { mode: 448 })
7228
+ ]);
7229
+ return {
7230
+ environment: {
7231
+ PATH: bin + delimiter + path,
7232
+ GH_CONFIG_DIR: ghConfig,
7233
+ RIVUS_WORKER_DENY_SSH: denySsh
7234
+ },
7235
+ helper: `!exec ${quote(helper)}`
7236
+ };
7237
+ }
7238
+ //#endregion
7239
+ export { AutomationClock as $, invokeRuntimeControl as $t, decodeWorkspacePrepareResult as A, createNodeRivusPluginModuleLoader as At, readRivusAudioStatus as B, gatewayTemplateDirectory as Bt, decodeWorkerReadMenuResult as C, parseRivusModelCliArguments as Ct, decodeWorkerStartResult as D, checkSuperagentDefinition as Dt, decodeWorkerStartParams as E, checkSuperagentConfigurations as Et, runRivusAudioPassthroughProcess as F, RIVUS_RELEASE_DESCRIPTOR as Ft, openJsonlInboundDeliveryStore as G, superagentSourceHost as Gt, withoutRivusHomeDeployment as H, resolveAcpRuntimeEnvironment as Ht, runRivusAudioProcess as I, gatewayAudioTranscriberAssetDirectory as It, createInMemoryDurableQueueStore as J, narrowBackgroundSessionDefinition as Jt, createFeishuInboundDelivery as K, builtinSourcePreset as Kt, RivusAudioInstallStepError as L, gatewayPackageDirectory as Lt, decodeWorkspaceReadFileResult as M, validateTrustedModulePath as Mt, createHerdrWorkerExecutor as N, findTrustedPackageRoot as Nt, decodeWorkspaceFailureData as O, checkSuperagentRuntime as Ot, continuesSession as P, loadRivusDeploymentManifest as Pt, toAutomationOccurrenceError as Q, disposeRuntimeCacheEntries as Qt, installRivusAudioTranscriber as R, gatewayPackageManifestPath as Rt, decodeWorkerPressKeyResult as S, toRivusModelManagementSubmission as St, decodeWorkerRetireParams as T, renderRivusModelCliHelp as Tt, openJsonlRecoveryControl as U, resolveFeishuEndpointCredentials as Ut, RIVUS_HOME_DEPLOYMENT_ENV as V, loadMergedLocalEnvFile as Vt, runRivusRecoveryCliCommand as W, toError as Wt, readAutomationPresentation as X, openLocalJsonSocket as Xt, openAutomationOccurrenceRepository as Y, errorMessage as Yt, AutomationOccurrence as Z, createRuntimeCache as Zt, decodeWorkerChooseMenuResult as _, resolveRivusModelSocketPath as _t, FILE_CHUNK_BYTES as a, resolveRivusDeploymentStateDirectory as at, decodeWorkerObserveResult as b, parseRivusModelManagementWireRequest as bt, decodeHelloResult as c, decodeSuperagentCommand as ct, decodeOptionalStringResult as d, superagentUsage as dt, deepFreeze as en, AutomationDeliverySink as et, decodeToolRequestParams as f, handOffRivusModelManagementEnv as ft, decodeWorkerChooseMenuParams as g, isRivusModelManagementEnabled as gt, decodeWorkerBackendParams as h, RIVUS_MODEL_SOCKET_ENV as ht, createStdioRpcChannel as i, deploymentStateDirectoryFromEnv as it, decodeWorkspaceReadFileParams as j, resolveNodeRivusPluginModulePath as jt, decodeWorkspacePrepareParams as k, loadSuperagentKinds as kt, decodeMenuClaimParams as l, parseSuperagentArguments as lt, decodeWorkerAvailableResult as m, parseRivusModelManagementHomeConfig as mt, BridgeRpcError as n, AutomationOccurrenceRepository as nt, decodeFileChunk as o, superagentControlSocketPath as ot, decodeWorkerAvailableParams as p, parseRivusModelManagementEnabled as pt, feishuInboundDeliveryPayloadCodec as q, createBackgroundSessionToolContracts as qt, BridgeTransportError as r, AutomationRunner as rt, decodeHelloParams as s, superagentDirectory as st, prepareWorkerPrograms as t, AutomationIdentity as tt, decodeMenuClaimResult as u, superagentRejectionExitCode as ut, decodeWorkerDeliverParams as v, createRivusModelManagementFailure as vt, decodeWorkerReadTerminalParams as w, renderRivusModelCliArgumentError as wt, decodeWorkerPressKeyParams as x, projectRivusModelCliResponse as xt, decodeWorkerDeliverResult as y, createRivusModelManagementWireRequest as yt, readRivusAudioInstalledRelease as z, gatewaySkillsDirectory as zt };
5290
7240