@chipschat/acp 1.0.15 → 1.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -8,8 +8,8 @@ var __export = (target, all) => {
8
8
  };
9
9
 
10
10
  // src/main.ts
11
- import { existsSync as existsSync10, mkdirSync as mkdirSync5, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "node:fs";
12
- import { basename as basename6, dirname as dirname6, join as join11 } from "node:path";
11
+ import { existsSync as existsSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "node:fs";
12
+ import { basename as basename6, dirname as dirname7, join as join12 } from "node:path";
13
13
 
14
14
  // node_modules/zod/v4/classic/external.js
15
15
  var external_exports = {};
@@ -2021,8 +2021,8 @@ function emoji() {
2021
2021
  }
2022
2022
  var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
2023
2023
  var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
2024
- var mac = (delimiter3) => {
2025
- const escapedDelim = escapeRegex(delimiter3 ?? ":");
2024
+ var mac = (delimiter4) => {
2025
+ const escapedDelim = escapeRegex(delimiter4 ?? ":");
2026
2026
  return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
2027
2027
  };
2028
2028
  var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
@@ -20270,6 +20270,25 @@ var modelChangeFrame = external_exports.object({
20270
20270
  asked_at: isoTimestamp
20271
20271
  }).describe("A person changed an agent's model or effort (ADR 0140). Sent to a harness's socket that said `models` in its `hello`, now or never: it is not in the log. The harness answers with the agent's copy, `answers` or `refuses` naming `change_id`.");
20272
20272
 
20273
+ // node_modules/@chipschat/protocol/dist/src/banners.js
20274
+ var CLOSED_BANNERS_MAX = 1e3;
20275
+ var who = external_exports.string().min(1).max(120);
20276
+ var bannerChoices = external_exports.record(who, external_exports.boolean()).describe("Whether this person wants the banner, by agent or harness. An agent with no choice of its own follows its harness, and a harness with none shows it.");
20277
+ var closedBanner = external_exports.object({
20278
+ space_id: id("space"),
20279
+ asker: who.describe("Whose banner: the agent, or a harness without agents."),
20280
+ since: isoTimestamp.describe("When the yes this banner stood for was given. A later yes is a new one, and shows its banner.")
20281
+ });
20282
+ var closedBanners = external_exports.array(closedBanner).max(CLOSED_BANNERS_MAX).describe("The banners this person closed for now.");
20283
+ var bannersView = external_exports.object({ choices: bannerChoices, closed: closedBanners });
20284
+ var bannerChoiceBody = external_exports.object({ shown: external_exports.boolean() });
20285
+ var closedBannerBody = external_exports.object({ since: isoTimestamp });
20286
+ var bannersFrame = external_exports.object({
20287
+ frame: external_exports.literal("banners"),
20288
+ choices: bannerChoices,
20289
+ closed: closedBanners
20290
+ }).describe("A person changed what they want of the banner, on one of their devices (ADR 0286). The whole of it, sent to that person's sockets that said `banners` in their `hello`.");
20291
+
20273
20292
  // node_modules/@chipschat/protocol/dist/src/capabilities.js
20274
20293
  var HARNESS_CAPABILITIES = {
20275
20294
  /**
@@ -20363,6 +20382,11 @@ var HARNESS_CAPABILITIES = {
20363
20382
  jobs: "jobs"
20364
20383
  };
20365
20384
 
20385
+ // node_modules/@chipschat/protocol/dist/src/commands.js
20386
+ var ENDS = String.raw`(?=$|[\s;&|])`;
20387
+ var DROPPED_AFTER_DESCRIPTOR = new RegExp(String.raw`^(?:>>?[ \t]*\/dev\/null|>&[12])${ENDS}`);
20388
+ var DROPPED_ANY = new RegExp(String.raw`^(?:&?>>?[ \t]*\/dev\/null|>&[12])${ENDS}`);
20389
+
20366
20390
  // node_modules/@chipschat/protocol/dist/src/connectors.js
20367
20391
  var words = (most) => external_exports.string().trim().min(1).max(most);
20368
20392
  var connectorKind = external_exports.enum(["one-line", "sdk", "http", "guide"]).describe("`one-line`: a command to run where the harness runs; `sdk`: code on @chipschat/harness; `http`: a key and curl lines; `guide`: a page to follow.");
@@ -20371,11 +20395,14 @@ var connector = external_exports.object({
20371
20395
  name: words(60).describe("What a person calls it."),
20372
20396
  line: words(120).describe("One line under the name: where it runs, what it needs."),
20373
20397
  needs: words(120).optional().describe('What has to be on the computer first, said after "You need": its harness installed and running as its bridge needs. Chips for Mac says it under Connect.'),
20398
+ program: external_exports.string().regex(/^[a-z0-9][a-z0-9._-]{0,40}$/).optional().describe("The agent's own command, as a person runs it: Chips for Mac looks for it, to say the agent is on this Mac (ADR 0288)."),
20399
+ whose: words(200).optional().describe("Who makes the agent and where what a person sends it goes, in whole sentences, said beside its way in (ADR 0288)."),
20400
+ terms: external_exports.url({ protocol: /^https?$/ }).optional().describe("Its maker's own terms or licence."),
20374
20401
  kind: connectorKind,
20375
20402
  command: words(400).optional().describe("What to run where the harness runs, with `{link}` where the link goes."),
20376
20403
  sentence: words(600).optional().describe("What to say to the agent so it connects itself, with `{link}` in it."),
20377
20404
  package: external_exports.string().regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*@\d{1,4}$/).optional().describe("The npm package its bridge is published as and the major that speaks this server's protocol, `@chipschat/hermes@1`: `chips connect <id>` fetches the newest release of that major (ADR 0218)."),
20378
- args: external_exports.array(external_exports.string().regex(/^[^-\s][^\s]{0,199}$/)).max(4).optional().describe("What `chips connect <id>` passes its bridge before the link is used, a config's path for one: `~/.chips-acp/codex.json`."),
20405
+ args: external_exports.array(external_exports.string().regex(/^[^-\s][^\s]{0,199}$/)).max(4).optional().describe("What `chips connect <id>` passes its bridge before the link is used, a config's path for one: `~/Chips/.bridges/acp/codex.json` (ADR 0283)."),
20379
20406
  capabilities: external_exports.array(external_exports.string().regex(/^[a-z][a-z_]{0,39}$/)).max(16).optional().describe("What its connector needs to do its job (ADR 0046): a link made from the card starts with these on."),
20380
20407
  docs: external_exports.url({ protocol: /^https?$/ }).optional().describe("Its page in the docs."),
20381
20408
  published: external_exports.boolean().optional().describe("False while its command can't be run by somebody outside yet.")
@@ -20428,6 +20455,159 @@ function renderRoomFiles(files) {
20428
20455
  return [ROOM_FILES_HEADING, ...lines2].join("\n");
20429
20456
  }
20430
20457
 
20458
+ // node_modules/@chipschat/protocol/dist/src/project.js
20459
+ var PROJECT_BRANCH = "main";
20460
+ function projectPath(spaceId) {
20461
+ return `/v1/spaces/${spaceId}/project.git`;
20462
+ }
20463
+ var PROJECT_ACTOR_HEADER = "chips-actor";
20464
+ var PROJECT_GIT_VERSION = "2.31.0";
20465
+ var PROJECT_TOKEN_PREFIX = "chips_pt_";
20466
+ var projectToken = external_exports.object({
20467
+ token: external_exports.string().startsWith(PROJECT_TOKEN_PREFIX).describe("Good for this room's project only, until `expires_at`: as a bearer token, or as the password of git's credential helper."),
20468
+ expires_at: isoTimestamp,
20469
+ path: external_exports.string().describe("The project's path on this server, which the device puts its own address in front of.")
20470
+ });
20471
+ var projectFolderOpenAnswer = external_exports.object({
20472
+ macs: external_exports.int().nonnegative().describe("How many of the person's Macs were asked."),
20473
+ opened_app: external_exports.literal(true).optional().describe("No Chips for Mac of theirs was open, so the server opened the one on its own machine and waited for it (ADR 0227).")
20474
+ });
20475
+ var COMMAND_MOST = 1100;
20476
+ var projectRun = external_exports.object({
20477
+ state: external_exports.enum(["never", "starting", "running", "ended", "failed", "stopped", "opened"]).describe("Never run on that Mac; starting (setup, or waiting for it to answer); running; ended by itself; failed; stopped by the person; or opened, for pages that need no starting."),
20478
+ command: external_exports.string().max(COMMAND_MOST).optional().describe("What ran: `setup`, `run` and `open` with what it opens, a line each; the bar compares it with the recipe's."),
20479
+ commit: external_exports.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/).optional().describe("The room's `main` the folder had when it started, so the bar can name who changed the files since (SEC-40)."),
20480
+ since: isoTimestamp.optional(),
20481
+ ended: isoTimestamp.optional(),
20482
+ code: external_exports.int().optional().describe("How it ended, as its shell said."),
20483
+ opened: external_exports.string().max(600).optional().describe("What it opened, once it answered."),
20484
+ lines: external_exports.array(external_exports.string().max(400)).max(20).optional().describe("Its last lines, when it ended, or while it runs and something went wrong."),
20485
+ why: external_exports.string().max(400).optional().describe("Why the Mac didn't run it when it was last asked, in its words: no run file, or a different one."),
20486
+ trouble: external_exports.string().max(400).optional().describe("What went wrong with the run itself, in plain words (ADR 0230): a port in use, a program the Mac doesn't have, nothing answering, the browser refusing its address.")
20487
+ });
20488
+ var heldRun = projectRun.extend({
20489
+ mac: external_exports.string().min(1).max(120).describe("The name of the Mac it runs on."),
20490
+ said_at: isoTimestamp
20491
+ });
20492
+ var projectRunAnswer = external_exports.object({
20493
+ run: heldRun.optional(),
20494
+ macs: external_exports.int().nonnegative()
20495
+ });
20496
+ var commitId = external_exports.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/).describe("A commit, by its full git object id.");
20497
+ var PROJECT_CHANGED_FILES = 200;
20498
+ var projectChangedFile = external_exports.object({
20499
+ path: external_exports.string().min(1).max(1024).describe("Its path in the project, with `/` between folders."),
20500
+ added: external_exports.int().nonnegative().nullable().describe("Lines added; `null` for a binary file."),
20501
+ removed: external_exports.int().nonnegative().nullable().describe("Lines removed; `null` for a binary file.")
20502
+ });
20503
+ var projectChangedPayload = external_exports.object({
20504
+ by: external_exports.string().min(1).max(120).describe("Who pushed: the agent a harness named, or the person. Recorded by Chips."),
20505
+ before: commitId.nullable().describe("Where `main` was, or `null` for the project's first push."),
20506
+ after: commitId.describe("Where `main` is now."),
20507
+ commits: external_exports.int().positive().describe("How many commits the push added to `main`."),
20508
+ message: external_exports.string().max(300).describe("The first line of the newest commit's message."),
20509
+ files: external_exports.array(projectChangedFile).max(PROJECT_CHANGED_FILES).describe("What changed between `before` and `after`, in path order."),
20510
+ more_files: external_exports.int().positive().optional().describe("How many more files changed than are named."),
20511
+ file_count: external_exports.int().nonnegative().optional().describe("How many files `main` has now, for the room sheet's Project tile (ADR 0222)."),
20512
+ undoes: commitId.optional().describe("The change this one takes back, when it is a person's Undo, or Put it back's Undo of an Undo (ADR 0222).")
20513
+ });
20514
+ var SECRETS_FILE = {
20515
+ source: "^\\.env(?:\\..+)?$",
20516
+ unless: "^\\.env\\.(?:example|sample|template)$"
20517
+ };
20518
+ var SECRETS_NAME = new RegExp(SECRETS_FILE.source);
20519
+ var EXAMPLE_NAME = new RegExp(SECRETS_FILE.unless);
20520
+ function isSecretsFile(path) {
20521
+ const name = path.split("/").pop() ?? path;
20522
+ return SECRETS_NAME.test(name) && !EXAMPLE_NAME.test(name);
20523
+ }
20524
+ var SECRET_SHAPES = [
20525
+ { what: "a Chips token", source: "chips_(?:at|inv|j|pt)_[A-Za-z0-9_-]{20,}" },
20526
+ // `sk-` begins a word, so a link's words ("…/elon-musk-terafab-project-…") are never a key.
20527
+ { what: "an Anthropic key", source: "\\bsk-ant-[A-Za-z0-9_-]{20,}" },
20528
+ { what: "an OpenAI key", source: "\\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{40,}" },
20529
+ { what: "an AWS access key", source: "\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b" },
20530
+ {
20531
+ what: "a GitHub token",
20532
+ source: "\\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})"
20533
+ },
20534
+ { what: "a private key", source: "-----BEGIN (?:[A-Z]+ )*PRIVATE KEY-----" }
20535
+ ];
20536
+ var SHAPES = SECRET_SHAPES.map((shape) => ({
20537
+ what: shape.what,
20538
+ pattern: new RegExp(shape.source)
20539
+ }));
20540
+ function secretIn(text) {
20541
+ return SHAPES.find((shape) => shape.pattern.test(text))?.what;
20542
+ }
20543
+ var PROJECT_LEAVE_OUT = [
20544
+ "node_modules/",
20545
+ ".venv/",
20546
+ "__pycache__/",
20547
+ "dist/",
20548
+ "build/",
20549
+ ".DS_Store",
20550
+ ".env",
20551
+ ".env.*",
20552
+ "!.env.example",
20553
+ "!.env.sample",
20554
+ "!.env.template"
20555
+ ];
20556
+ function namesInWords(names) {
20557
+ if (names.length <= 1)
20558
+ return names[0] ?? "";
20559
+ if (names.length > 6)
20560
+ return `${names.slice(0, 6).join(", ")} and ${names.length - 6} more`;
20561
+ return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
20562
+ }
20563
+ function renderProjectNote(facts, options) {
20564
+ return `${renderProjectFacts(facts)}
20565
+ ${renderProjectAsks(facts, options)}`;
20566
+ }
20567
+ function renderProjectFacts(facts) {
20568
+ const files = `${facts.files} file${facts.files === 1 ? "" : "s"}`;
20569
+ const lines2 = [
20570
+ `The space's project is a git repository. Your copy is ${facts.folder} (${files}), ${facts.trouble === void 0 ? "brought up to date just now" : "not brought up to date"}.`
20571
+ ];
20572
+ if (facts.changed.length > 0) {
20573
+ const by = facts.by.length > 0 ? `, by ${namesInWords(facts.by)}` : "";
20574
+ lines2.push(`Changed since your last turn: ${namesInWords(facts.changed)}${by}.`);
20575
+ }
20576
+ if (facts.trouble !== void 0)
20577
+ lines2.push(`It couldn't be: ${facts.trouble}`);
20578
+ if (facts.clashes.length > 0) {
20579
+ const whose = facts.clashedWith.length > 0 ? `${namesInWords(facts.clashedWith)}'s` : "another change";
20580
+ lines2.push(`Your last change to ${namesInWords(facts.clashes)} clashed with ${whose}, which reached the space first. Both sides are in those files now: yours between "<<<<<<< yours" and "=======", theirs from there to the ">>>>>>>" line that names them. Settle each, keeping what both meant, and take the marks out. Nothing of yours is sent until they're gone.`);
20581
+ }
20582
+ for (const key of facts.keys) {
20583
+ lines2.push(`${key.path} holds what looks like ${key.what}, so your last change wasn't sent: take it out and read it from outside the project.`);
20584
+ }
20585
+ return lines2.join("\n");
20586
+ }
20587
+ function renderProjectAsks(facts, options) {
20588
+ const lines2 = [
20589
+ "Work on the project in that folder and leave git to Chips: when your turn ends, what you changed is committed under your name and sent to everyone here. Keep scratch work outside it.",
20590
+ // Sent with the answer too, a project's file became a room file of its own, with versions of
20591
+ // its own, and the agents of a room argued over which copy was current (Phase 8, Run D).
20592
+ "Everyone here sees the project's files, so don't send them with your answer as well."
20593
+ ];
20594
+ if (options.othersInRoom) {
20595
+ lines2.push(
20596
+ "Split the work by file where you can. Changes to different parts of a file are merged, and a clash goes back to whoever sent second.",
20597
+ // Agents whose files must agree each renamed theirs to match the other's at once, so the
20598
+ // names crossed back and forth (Phase 8, AP-7): the project's history says who keeps theirs.
20599
+ "When your file and another's use different names for the same thing, the one that reached the project first keeps its names, and the other changes its names to match."
20600
+ );
20601
+ }
20602
+ lines2.push("When what you make is to be read (pages, PDFs, pictures), keep a start page at .chips/index.html that links to the documents worth seeing (its links start ../), with the documents themselves at the top or in folders of their own, and bring it up to date whenever you add, rename or replace one. Chips opens it in the app, where links to the project's files open too and web links open in the browser. One document needs no start page.", `When what you make has to run on the person's Mac (a server, a script, an app), keep .chips/run.json so Run in Chips can start it from the project's folder: {"run": "the one shell command that starts it", "opens": "http://localhost:<port>, to open once it answers", "setup": "a command run first when it changes, like npm install"}. Have it print the address it listens on, like http://localhost:4173, which is what Run opens; "opens" is for a program that prints none. Everything it runs belongs in the project: Run refuses a command that goes anywhere outside the project's folder (a cd elsewhere, a path in a home folder). Start an app by its own program rather than with open, so Stop can close it, and leave starting it to Run rather than starting it yourself. Leave out what it doesn't need, and check it works in your copy before you say it does.`);
20603
+ if (facts.markdown)
20604
+ lines2.push("In Markdown, put each sentence on a line of its own.");
20605
+ if (facts.pages === true) {
20606
+ lines2.push("A page opens in Chips as one document: name every file it needs in its tags and imports (<link>, <script src>, <img src>, import), since it can't fetch files while it runs.");
20607
+ }
20608
+ return lines2.join("\n");
20609
+ }
20610
+
20431
20611
  // node_modules/@chipschat/protocol/dist/src/spend.js
20432
20612
  var SPEND_CEILING_MIN = 0.25;
20433
20613
  var SPEND_CEILING_MAX = 100;
@@ -20842,7 +21022,8 @@ var hello = defineEvent({
20842
21022
  }).describe("The negotiated range. A client picks a version inside it or is refused."),
20843
21023
  server: external_exports.object({
20844
21024
  name: external_exports.string().min(1).max(120).describe("Usually `chipsd`."),
20845
- version: external_exports.string().min(1).max(60).describe("The server's own version.")
21025
+ version: external_exports.string().min(1).max(60).describe("The server's own version."),
21026
+ takes: external_exports.array(external_exports.string().min(1).max(40)).max(32).optional().describe("What this server keeps of what a person's client may send beyond the base set, by the names in `SERVER_TAKES`. `held_yes` is `for_minutes` and `until_stopped` on `approval.resolved`. A server older than the field says nothing, and drops those fields, so a client offers neither to it (ADR 0281).")
20846
21027
  }).describe("Who the client is talking to."),
20847
21028
  harnesses: external_exports.array(harnessManifest).min(1).max(64).describe("The harness the token belongs to, and only that one. One connection speaks for all of the harness's agents (ADR 0087), which `agents` lists. A harness running inside another is a lane, not a duplicate."),
20848
21029
  harness: harnessManifest.optional().describe("The harness this connection is: `harnesses[0]`, said once. Read this rather than the list."),
@@ -20931,6 +21112,8 @@ var approvalResolved = defineEvent({
20931
21112
  decision: external_exports.enum(["approved", "edited", "denied", "expired"]).describe("`expired` means nobody answered and the fallback applied."),
20932
21113
  scope: external_exports.enum(["once", "session", "always"]).default("once").describe("How far the answer reaches. `always` becomes a policy rule."),
20933
21114
  everywhere: external_exports.boolean().optional().describe("With `always`: the rule is the harness's in every space, not only this one (ADR 0239). An owner or an admin only."),
21115
+ for_minutes: external_exports.number().int().min(5).max(240).optional().describe("With `once` and a yes: for this many minutes, everything the asking agent asks in this space goes ahead without a card (ADR 0239, addendum of 6 November 2026; ADR 0281), commands Chips can't read too. An ask that matters still waits for a person. Chips keeps the rule, so the harness is answered once."),
21116
+ until_stopped: external_exports.literal(true).optional().describe("With `once` and a yes, instead of `for_minutes`: everything the asking agent asks in this space goes ahead without a card until a person stops it (`approval.held_stopped`, ADR 0281). An ask that matters still waits for a person. Chips keeps the rule, so the harness is answered once."),
20934
21117
  updated_input: external_exports.unknown().optional().describe("The edited action input, when the decision is `edited`."),
20935
21118
  reason: external_exports.string().max(4e3).optional().describe("Why. The harness gets to read this."),
20936
21119
  resolved_by: external_exports.string().min(1).max(120).describe("The participant who answered, or `system` on expiry \u2014 a harness when it settles its own ask, answered in its own tools. Filled in by Chips from the credential that sent it; a value the sender writes is replaced."),
@@ -21089,224 +21272,71 @@ var CHIPS_TO_HARNESS = [
21089
21272
  receipt
21090
21273
  ];
21091
21274
 
21092
- // node_modules/@chipschat/protocol/dist/src/project.js
21093
- var PROJECT_BRANCH = "main";
21094
- function projectPath(spaceId) {
21095
- return `/v1/spaces/${spaceId}/project.git`;
21096
- }
21097
- var PROJECT_ACTOR_HEADER = "chips-actor";
21098
- var PROJECT_GIT_VERSION = "2.31.0";
21099
- var PROJECT_TOKEN_PREFIX = "chips_pt_";
21100
- var projectToken = external_exports.object({
21101
- token: external_exports.string().startsWith(PROJECT_TOKEN_PREFIX).describe("Good for this room's project only, until `expires_at`: as a bearer token, or as the password of git's credential helper."),
21102
- expires_at: isoTimestamp,
21103
- path: external_exports.string().describe("The project's path on this server, which the device puts its own address in front of.")
21104
- });
21105
- var projectFolderOpenAnswer = external_exports.object({
21106
- macs: external_exports.int().nonnegative().describe("How many of the person's Macs were asked."),
21107
- opened_app: external_exports.literal(true).optional().describe("No Chips for Mac of theirs was open, so the server opened the one on its own machine and waited for it (ADR 0227).")
21275
+ // node_modules/@chipschat/protocol/dist/src/events/harness-to-chips.js
21276
+ var plannedStep = external_exports.object({
21277
+ step_id: external_exports.string().min(1).max(120).describe("Stable for the life of the run, so updates land on the right row."),
21278
+ title: external_exports.string().min(1).max(300).describe("What this step will do.")
21279
+ }).describe("One step of a plan, shown as a hollow dot until it completes.");
21280
+ var sessionStarted = defineEvent({
21281
+ type: "session.started",
21282
+ direction: "harness_to_chips",
21283
+ sender: "harness",
21284
+ summary: "A visit to a space began: a terminal opened, a process attached. The space outlives it.",
21285
+ requiresRun: false,
21286
+ payload: external_exports.object({
21287
+ session_ref: sessionRef,
21288
+ started_reason: external_exports.string().max(60).optional().describe("Why the visit began, in the harness's own word: `startup`, `resume`, `fork`."),
21289
+ where: external_exports.string().max(300).optional().describe('Where it is running, for a person to read: "mbp \xB7 ~/Work/Chips".'),
21290
+ transcript_ref: external_exports.string().max(1e3).optional().describe("The harness's own transcript of this visit, so a person can jump to it.")
21291
+ })
21108
21292
  });
21109
- var COMMAND_MOST = 1100;
21110
- var projectRun = external_exports.object({
21111
- state: external_exports.enum(["never", "starting", "running", "ended", "failed", "stopped", "opened"]).describe("Never run on that Mac; starting (setup, or waiting for it to answer); running; ended by itself; failed; stopped by the person; or opened, for pages that need no starting."),
21112
- command: external_exports.string().max(COMMAND_MOST).optional().describe("What ran: `setup`, `run` and `open` with what it opens, a line each; the bar compares it with the recipe's."),
21113
- commit: external_exports.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/).optional().describe("The room's `main` the folder had when it started, so the bar can name who changed the files since (SEC-40)."),
21114
- since: isoTimestamp.optional(),
21115
- ended: isoTimestamp.optional(),
21116
- code: external_exports.int().optional().describe("How it ended, as its shell said."),
21117
- opened: external_exports.string().max(600).optional().describe("What it opened, once it answered."),
21118
- lines: external_exports.array(external_exports.string().max(400)).max(20).optional().describe("Its last lines, when it ended, or while it runs and something went wrong."),
21119
- why: external_exports.string().max(400).optional().describe("Why the Mac didn't run it when it was last asked, in its words: no run file, or a different one."),
21120
- trouble: external_exports.string().max(400).optional().describe("What went wrong with the run itself, in plain words (ADR 0230): a port in use, a program the Mac doesn't have, nothing answering, the browser refusing its address.")
21293
+ var sessionEnded = defineEvent({
21294
+ type: "session.ended",
21295
+ direction: "harness_to_chips",
21296
+ sender: "harness",
21297
+ summary: "The visit is over. The space, its history and anything still waiting all stay.",
21298
+ requiresRun: false,
21299
+ payload: external_exports.object({
21300
+ session_ref: sessionRef,
21301
+ ended_reason: external_exports.string().max(60).optional().describe("Why it ended, in the harness's own word: `clear`, `logout`, `other`.")
21302
+ })
21121
21303
  });
21122
- var heldRun = projectRun.extend({
21123
- mac: external_exports.string().min(1).max(120).describe("The name of the Mac it runs on."),
21124
- said_at: isoTimestamp
21304
+ var sessionRenamed = defineEvent({
21305
+ type: "session.renamed",
21306
+ direction: "harness_to_chips",
21307
+ sender: "harness",
21308
+ summary: "What a visit is called, in the harness's own words (ADR 0040).",
21309
+ requiresRun: false,
21310
+ payload: external_exports.object({
21311
+ session_ref: sessionRef,
21312
+ title: external_exports.string().min(1).max(200).describe("What to call this visit on screen. A harness that names its sessions sends this when the name changes and not otherwise; a visit with no name is shown by where it is running instead.")
21313
+ })
21125
21314
  });
21126
- var projectRunAnswer = external_exports.object({
21127
- run: heldRun.optional(),
21128
- macs: external_exports.int().nonnegative()
21315
+ var runStarted = defineEvent({
21316
+ type: "run.started",
21317
+ direction: "harness_to_chips",
21318
+ sender: "harness",
21319
+ summary: "A harness has begun a unit of work, optionally with the plan it intends to follow.",
21320
+ requiresRun: true,
21321
+ payload: external_exports.object({
21322
+ goal: external_exports.string().min(1).max(4e3).describe("What the run is for, in the person's words where possible."),
21323
+ plan: external_exports.array(plannedStep).max(64).optional().describe("The steps the harness expects to take. The run panel draws one hollow dot each."),
21324
+ session_ref: sessionRef.optional().describe("The visit this run belongs to, so two terminals in one space are told apart."),
21325
+ goal_from: external_exports.enum(["harness", "chips"]).optional().describe("Where the goal came from. `harness`: a person asked for it at the harness's own surface \u2014 a terminal, a chat the harness already had \u2014 so Chips shows it as their message, because otherwise the room holds only the answers. `chips`: it arrived as a message here and is already on screen. Either way the room's header and the run panel leave the goal out, because the room shows it. Omit when the goal was not a person's words at all; the header and the run panel then say it.")
21326
+ })
21129
21327
  });
21130
- var commitId = external_exports.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/).describe("A commit, by its full git object id.");
21131
- var PROJECT_CHANGED_FILES = 200;
21132
- var projectChangedFile = external_exports.object({
21133
- path: external_exports.string().min(1).max(1024).describe("Its path in the project, with `/` between folders."),
21134
- added: external_exports.int().nonnegative().nullable().describe("Lines added; `null` for a binary file."),
21135
- removed: external_exports.int().nonnegative().nullable().describe("Lines removed; `null` for a binary file.")
21136
- });
21137
- var projectChangedPayload = external_exports.object({
21138
- by: external_exports.string().min(1).max(120).describe("Who pushed: the agent a harness named, or the person. Recorded by Chips."),
21139
- before: commitId.nullable().describe("Where `main` was, or `null` for the project's first push."),
21140
- after: commitId.describe("Where `main` is now."),
21141
- commits: external_exports.int().positive().describe("How many commits the push added to `main`."),
21142
- message: external_exports.string().max(300).describe("The first line of the newest commit's message."),
21143
- files: external_exports.array(projectChangedFile).max(PROJECT_CHANGED_FILES).describe("What changed between `before` and `after`, in path order."),
21144
- more_files: external_exports.int().positive().optional().describe("How many more files changed than are named."),
21145
- file_count: external_exports.int().nonnegative().optional().describe("How many files `main` has now, for the room sheet's Project tile (ADR 0222)."),
21146
- undoes: commitId.optional().describe("The change this one takes back, when it is a person's Undo, or Put it back's Undo of an Undo (ADR 0222).")
21147
- });
21148
- var SECRETS_FILE = {
21149
- source: "^\\.env(?:\\..+)?$",
21150
- unless: "^\\.env\\.(?:example|sample|template)$"
21151
- };
21152
- var SECRETS_NAME = new RegExp(SECRETS_FILE.source);
21153
- var EXAMPLE_NAME = new RegExp(SECRETS_FILE.unless);
21154
- function isSecretsFile(path) {
21155
- const name = path.split("/").pop() ?? path;
21156
- return SECRETS_NAME.test(name) && !EXAMPLE_NAME.test(name);
21157
- }
21158
- var SECRET_SHAPES = [
21159
- { what: "a Chips token", source: "chips_(?:at|inv|j|pt)_[A-Za-z0-9_-]{20,}" },
21160
- // `sk-` begins a word, so a link's words ("…/elon-musk-terafab-project-…") are never a key.
21161
- { what: "an Anthropic key", source: "\\bsk-ant-[A-Za-z0-9_-]{20,}" },
21162
- { what: "an OpenAI key", source: "\\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{40,}" },
21163
- { what: "an AWS access key", source: "\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b" },
21164
- {
21165
- what: "a GitHub token",
21166
- source: "\\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})"
21167
- },
21168
- { what: "a private key", source: "-----BEGIN (?:[A-Z]+ )*PRIVATE KEY-----" }
21169
- ];
21170
- var SHAPES = SECRET_SHAPES.map((shape) => ({
21171
- what: shape.what,
21172
- pattern: new RegExp(shape.source)
21173
- }));
21174
- function secretIn(text) {
21175
- return SHAPES.find((shape) => shape.pattern.test(text))?.what;
21176
- }
21177
- var PROJECT_LEAVE_OUT = [
21178
- "node_modules/",
21179
- ".venv/",
21180
- "__pycache__/",
21181
- "dist/",
21182
- "build/",
21183
- ".DS_Store",
21184
- ".env",
21185
- ".env.*",
21186
- "!.env.example",
21187
- "!.env.sample",
21188
- "!.env.template"
21189
- ];
21190
- function namesInWords(names) {
21191
- if (names.length <= 1)
21192
- return names[0] ?? "";
21193
- if (names.length > 6)
21194
- return `${names.slice(0, 6).join(", ")} and ${names.length - 6} more`;
21195
- return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
21196
- }
21197
- function renderProjectNote(facts, options) {
21198
- return `${renderProjectFacts(facts)}
21199
- ${renderProjectAsks(facts, options)}`;
21200
- }
21201
- function renderProjectFacts(facts) {
21202
- const files = `${facts.files} file${facts.files === 1 ? "" : "s"}`;
21203
- const lines2 = [
21204
- `The space's project is a git repository. Your copy is ${facts.folder} (${files}), ${facts.trouble === void 0 ? "brought up to date just now" : "not brought up to date"}.`
21205
- ];
21206
- if (facts.changed.length > 0) {
21207
- const by = facts.by.length > 0 ? `, by ${namesInWords(facts.by)}` : "";
21208
- lines2.push(`Changed since your last turn: ${namesInWords(facts.changed)}${by}.`);
21209
- }
21210
- if (facts.trouble !== void 0)
21211
- lines2.push(`It couldn't be: ${facts.trouble}`);
21212
- if (facts.clashes.length > 0) {
21213
- const whose = facts.clashedWith.length > 0 ? `${namesInWords(facts.clashedWith)}'s` : "another change";
21214
- lines2.push(`Your last change to ${namesInWords(facts.clashes)} clashed with ${whose}, which reached the space first. Both sides are in those files now: yours between "<<<<<<< yours" and "=======", theirs from there to the ">>>>>>>" line that names them. Settle each, keeping what both meant, and take the marks out. Nothing of yours is sent until they're gone.`);
21215
- }
21216
- for (const key of facts.keys) {
21217
- lines2.push(`${key.path} holds what looks like ${key.what}, so your last change wasn't sent: take it out and read it from outside the project.`);
21218
- }
21219
- return lines2.join("\n");
21220
- }
21221
- function renderProjectAsks(facts, options) {
21222
- const lines2 = [
21223
- "Work on the project in that folder and leave git to Chips: when your turn ends, what you changed is committed under your name and sent to everyone here. Keep scratch work outside it.",
21224
- // Sent with the answer too, a project's file became a room file of its own, with versions of
21225
- // its own, and the agents of a room argued over which copy was current (Phase 8, Run D).
21226
- "Everyone here sees the project's files, so don't send them with your answer as well."
21227
- ];
21228
- if (options.othersInRoom) {
21229
- lines2.push(
21230
- "Split the work by file where you can. Changes to different parts of a file are merged, and a clash goes back to whoever sent second.",
21231
- // Agents whose files must agree each renamed theirs to match the other's at once, so the
21232
- // names crossed back and forth (Phase 8, AP-7): the project's history says who keeps theirs.
21233
- "When your file and another's use different names for the same thing, the one that reached the project first keeps its names, and the other changes its names to match."
21234
- );
21235
- }
21236
- lines2.push("When what you make is to be read (pages, PDFs, pictures), keep a start page at .chips/index.html that links to the documents worth seeing (its links start ../), with the documents themselves at the top or in folders of their own, and bring it up to date whenever you add, rename or replace one. Chips opens it in the app, and its links open there too. One document needs no start page.", `When what you make has to run on the person's Mac (a server, a script, an app), keep .chips/run.json so Run in Chips can start it from the project's folder: {"run": "the one shell command that starts it", "opens": "http://localhost:<port>, to open once it answers", "setup": "a command run first when it changes, like npm install"}. Have it print the address it listens on, like http://localhost:4173, which is what Run opens; "opens" is for a program that prints none. Everything it runs belongs in the project: Run refuses a command that goes anywhere outside the project's folder (a cd elsewhere, a path in a home folder). Start an app by its own program rather than with open, so Stop can close it, and leave starting it to Run rather than starting it yourself. Leave out what it doesn't need, and check it works in your copy before you say it does.`);
21237
- if (facts.markdown)
21238
- lines2.push("In Markdown, put each sentence on a line of its own.");
21239
- if (facts.pages === true) {
21240
- lines2.push("A page opens in Chips as one document: name every file it needs in its tags and imports (<link>, <script src>, <img src>, import), since it can't fetch files while it runs.");
21241
- }
21242
- return lines2.join("\n");
21243
- }
21244
-
21245
- // node_modules/@chipschat/protocol/dist/src/events/harness-to-chips.js
21246
- var plannedStep = external_exports.object({
21247
- step_id: external_exports.string().min(1).max(120).describe("Stable for the life of the run, so updates land on the right row."),
21248
- title: external_exports.string().min(1).max(300).describe("What this step will do.")
21249
- }).describe("One step of a plan, shown as a hollow dot until it completes.");
21250
- var sessionStarted = defineEvent({
21251
- type: "session.started",
21252
- direction: "harness_to_chips",
21253
- sender: "harness",
21254
- summary: "A visit to a space began: a terminal opened, a process attached. The space outlives it.",
21255
- requiresRun: false,
21256
- payload: external_exports.object({
21257
- session_ref: sessionRef,
21258
- started_reason: external_exports.string().max(60).optional().describe("Why the visit began, in the harness's own word: `startup`, `resume`, `fork`."),
21259
- where: external_exports.string().max(300).optional().describe('Where it is running, for a person to read: "mbp \xB7 ~/Work/Chips".'),
21260
- transcript_ref: external_exports.string().max(1e3).optional().describe("The harness's own transcript of this visit, so a person can jump to it.")
21261
- })
21262
- });
21263
- var sessionEnded = defineEvent({
21264
- type: "session.ended",
21265
- direction: "harness_to_chips",
21266
- sender: "harness",
21267
- summary: "The visit is over. The space, its history and anything still waiting all stay.",
21268
- requiresRun: false,
21269
- payload: external_exports.object({
21270
- session_ref: sessionRef,
21271
- ended_reason: external_exports.string().max(60).optional().describe("Why it ended, in the harness's own word: `clear`, `logout`, `other`.")
21272
- })
21273
- });
21274
- var sessionRenamed = defineEvent({
21275
- type: "session.renamed",
21276
- direction: "harness_to_chips",
21277
- sender: "harness",
21278
- summary: "What a visit is called, in the harness's own words (ADR 0040).",
21279
- requiresRun: false,
21280
- payload: external_exports.object({
21281
- session_ref: sessionRef,
21282
- title: external_exports.string().min(1).max(200).describe("What to call this visit on screen. A harness that names its sessions sends this when the name changes and not otherwise; a visit with no name is shown by where it is running instead.")
21283
- })
21284
- });
21285
- var runStarted = defineEvent({
21286
- type: "run.started",
21287
- direction: "harness_to_chips",
21288
- sender: "harness",
21289
- summary: "A harness has begun a unit of work, optionally with the plan it intends to follow.",
21290
- requiresRun: true,
21291
- payload: external_exports.object({
21292
- goal: external_exports.string().min(1).max(4e3).describe("What the run is for, in the person's words where possible."),
21293
- plan: external_exports.array(plannedStep).max(64).optional().describe("The steps the harness expects to take. The run panel draws one hollow dot each."),
21294
- session_ref: sessionRef.optional().describe("The visit this run belongs to, so two terminals in one space are told apart."),
21295
- goal_from: external_exports.enum(["harness", "chips"]).optional().describe("Where the goal came from. `harness`: a person asked for it at the harness's own surface \u2014 a terminal, a chat the harness already had \u2014 so Chips shows it as their message, because otherwise the room holds only the answers. `chips`: it arrived as a message here and is already on screen. Either way the room's header and the run panel leave the goal out, because the room shows it. Omit when the goal was not a person's words at all; the header and the run panel then say it.")
21296
- })
21297
- });
21298
- var runStatus = defineEvent({
21299
- type: "run.status",
21300
- direction: "harness_to_chips",
21301
- sender: "harness",
21302
- summary: "What the harness is doing right now. This is the harness's typing indicator.",
21303
- requiresRun: true,
21304
- payload: external_exports.object({
21305
- phase: external_exports.string().min(1).max(120).describe("A short machine-ish label, for example `reading`."),
21306
- verb_phrase: external_exports.string().min(1).max(200).describe(`What to show under the harness's name, for example "Reading PO #4471\u2026".`),
21307
- progress: external_exports.number().min(0).max(1).optional().describe("Fraction complete, when the harness knows."),
21308
- estimate_seconds: external_exports.int().nonnegative().optional().describe("Seconds remaining, when the harness knows.")
21309
- })
21328
+ var runStatus = defineEvent({
21329
+ type: "run.status",
21330
+ direction: "harness_to_chips",
21331
+ sender: "harness",
21332
+ summary: "What the harness is doing right now. This is the harness's typing indicator.",
21333
+ requiresRun: true,
21334
+ payload: external_exports.object({
21335
+ phase: external_exports.string().min(1).max(120).describe("A short machine-ish label, for example `reading`."),
21336
+ verb_phrase: external_exports.string().min(1).max(200).describe(`What to show under the harness's name, for example "Reading PO #4471\u2026".`),
21337
+ progress: external_exports.number().min(0).max(1).optional().describe("Fraction complete, when the harness knows."),
21338
+ estimate_seconds: external_exports.int().nonnegative().optional().describe("Seconds remaining, when the harness knows.")
21339
+ })
21310
21340
  });
21311
21341
  var runPlan = defineEvent({
21312
21342
  type: "run.plan",
@@ -22323,6 +22353,28 @@ var approvalRouted = defineEvent({
22323
22353
  routed_at: external_exports.string().datetime().optional().describe("When. Filled in by Chips from its clock.")
22324
22354
  })
22325
22355
  });
22356
+ var approvalHeldStopped = defineEvent({
22357
+ type: "approval.held_stopped",
22358
+ direction: "workspace",
22359
+ sender: "person",
22360
+ summary: "A person stopped the yes that let an agent work without asking in a space, for an hour or until stopped. Its next ask comes to a person.",
22361
+ requiresRun: false,
22362
+ payload: external_exports.object({
22363
+ asker: external_exports.string().min(1).max(120).describe("Whose yes stops: the agent, or a harness without agents, as the run that asked is worked by."),
22364
+ stopped_by: external_exports.string().min(1).max(120).optional().describe("Who stopped it. Filled in by Chips from the credential.")
22365
+ })
22366
+ });
22367
+ var approvalHeldStarted = defineEvent({
22368
+ type: "approval.held_started",
22369
+ direction: "workspace",
22370
+ sender: "person",
22371
+ summary: "A person let an agent work without asking in a space until it is stopped, from the agent's page rather than an ask's card.",
22372
+ requiresRun: false,
22373
+ payload: external_exports.object({
22374
+ asker: external_exports.string().min(1).max(120).describe("Whose asks go ahead: the agent, or a harness without agents, in the space."),
22375
+ started_by: external_exports.string().min(1).max(120).optional().describe("Who gave it. Filled in by Chips from the credential.")
22376
+ })
22377
+ });
22326
22378
  var cap = external_exports.number().int().min(1).nullable();
22327
22379
  var attachmentLimitsSet = defineEvent({
22328
22380
  type: "attachment.limits_set",
@@ -22411,6 +22463,8 @@ var WORKSPACE_EVENTS = [
22411
22463
  messagePinned,
22412
22464
  messageUnpinned,
22413
22465
  approvalRouted,
22466
+ approvalHeldStopped,
22467
+ approvalHeldStarted,
22414
22468
  attachmentLimitsSet,
22415
22469
  exchangeLimitsSet,
22416
22470
  workspaceRenamed,
@@ -22803,6 +22857,7 @@ var serverFrame = external_exports.discriminatedUnion("frame", [
22803
22857
  folderRunFrame,
22804
22858
  folderRunStateFrame,
22805
22859
  readFrame,
22860
+ bannersFrame,
22806
22861
  contextEditFrame,
22807
22862
  modelChangeFrame,
22808
22863
  heartbeatChangeFrame,
@@ -25063,7 +25118,7 @@ function connect(options) {
25063
25118
  // node_modules/@chipschat/harness/dist/join.js
25064
25119
  import { createHash } from "node:crypto";
25065
25120
  import { readFileSync as readFileSync2 } from "node:fs";
25066
- import { hostname as hostname3 } from "node:os";
25121
+ import { hostname as hostname3, networkInterfaces } from "node:os";
25067
25122
  import { join as joinPath } from "node:path";
25068
25123
 
25069
25124
  // node_modules/@chipschat/harness/dist/keep.js
@@ -25226,13 +25281,53 @@ function serverJsonUrl(env2) {
25226
25281
  return void 0;
25227
25282
  }
25228
25283
  }
25284
+ function serverHere(env2) {
25285
+ const url2 = serverJsonUrl(env2);
25286
+ if (url2 === void 0)
25287
+ return void 0;
25288
+ let port;
25289
+ try {
25290
+ const parsed = new URL(url2);
25291
+ if (parsed.protocol !== "http:")
25292
+ return void 0;
25293
+ port = parsed.port;
25294
+ } catch {
25295
+ return void 0;
25296
+ }
25297
+ const hosts = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", hostname3().toLowerCase()]);
25298
+ for (const each of Object.values(networkInterfaces()).flat()) {
25299
+ if (each === void 0)
25300
+ continue;
25301
+ hosts.add(each.family === "IPv6" ? `[${each.address}]` : each.address);
25302
+ }
25303
+ return { url: url2.replace(/\/$/, ""), port, hosts };
25304
+ }
25305
+ function hereInstead(url2, env2) {
25306
+ const here2 = serverHere(env2);
25307
+ if (here2 === void 0)
25308
+ return void 0;
25309
+ try {
25310
+ const parsed = new URL(url2);
25311
+ const same = parsed.protocol === "http:" && parsed.port === here2.port && here2.hosts.has(parsed.hostname.toLowerCase());
25312
+ return same ? here2.url : void 0;
25313
+ } catch {
25314
+ return void 0;
25315
+ }
25316
+ }
25317
+ function accountsHere(url2, name, env2) {
25318
+ const here2 = serverHere(env2);
25319
+ if (here2 === void 0 || here2.url !== url2.replace(/\/$/, ""))
25320
+ return [];
25321
+ return [...here2.hosts].filter((host) => /^\d+\.\d+\.\d+\.\d+$/.test(host) && host !== "127.0.0.1").map((host) => accountOf(`http://${host}${here2.port === "" ? "" : `:${here2.port}`}`, name));
25322
+ }
25229
25323
  function findServer(options, env2) {
25230
25324
  if (options.link !== void 0) {
25231
25325
  const parsed = parseJoinLink(options.link);
25232
25326
  if (parsed === void 0) {
25233
25327
  throw new JoinError("invalid", "That is not a join link: it looks like <address>/j/<secret>.");
25234
25328
  }
25235
- return parsed;
25329
+ const here2 = hereInstead(parsed.url, env2);
25330
+ return here2 === void 0 ? parsed : { url: here2, secret: parsed.secret };
25236
25331
  }
25237
25332
  const url2 = options.url ?? env2["CHIPS_URL"] ?? serverJsonUrl(env2);
25238
25333
  if (url2 === void 0 || url2 === "") {
@@ -25255,6 +25350,27 @@ function joinedOf(answer) {
25255
25350
  function linkHash(secret) {
25256
25351
  return createHash("sha256").update(secret).digest("base64url");
25257
25352
  }
25353
+ function keptAtAny(store, accounts) {
25354
+ for (const account of accounts) {
25355
+ const kept2 = keptAt(store, account);
25356
+ if (kept2 !== void 0)
25357
+ return { account, kept: kept2 };
25358
+ }
25359
+ return void 0;
25360
+ }
25361
+ function rehomed(store, account, joined2, env2) {
25362
+ const here2 = hereInstead(joined2.url, env2);
25363
+ if (here2 === void 0 || here2 === joined2.url)
25364
+ return joined2;
25365
+ if (store !== false) {
25366
+ try {
25367
+ const record2 = JSON.parse(store.get(account) ?? "{}");
25368
+ store.set(account, JSON.stringify({ ...record2, url: here2 }));
25369
+ } catch {
25370
+ }
25371
+ }
25372
+ return { ...joined2, url: here2 };
25373
+ }
25258
25374
  function keptAt(store, account) {
25259
25375
  if (store === false)
25260
25376
  return void 0;
@@ -25357,19 +25473,20 @@ async function join3(options) {
25357
25473
  const server = findServer(options, env2);
25358
25474
  const store = options.keep ?? openKeyStore(env2);
25359
25475
  const account = accountOf(server.url, options.name);
25360
- const kept2 = keptAt(store, account);
25476
+ const found = keptAtAny(store, [account, ...accountsHere(server.url, options.name, env2)]);
25361
25477
  const from = server.secret === void 0 ? void 0 : linkHash(server.secret);
25362
- if (kept2 !== void 0 && (from === void 0 || kept2.from === from))
25363
- return kept2.joined;
25478
+ if (found !== void 0 && (from === void 0 || found.kept.from === from))
25479
+ return rehomed(store, found.account, found.kept.joined, env2);
25364
25480
  let answer;
25365
25481
  try {
25366
25482
  answer = await askOrRedeem(server, options);
25367
25483
  } catch (error62) {
25368
- if (kept2 !== void 0 && usedUp(error62))
25369
- return kept2.joined;
25484
+ if (found !== void 0 && usedUp(error62))
25485
+ return rehomed(store, found.account, found.kept.joined, env2);
25370
25486
  throw error62;
25371
25487
  }
25372
- const joined2 = joinedOf(answer);
25488
+ const answered = joinedOf(answer);
25489
+ const joined2 = { ...answered, url: hereInstead(answered.url, env2) ?? answered.url };
25373
25490
  if (store !== false)
25374
25491
  store.set(account, JSON.stringify({ ...joined2, from, hello: "due" }));
25375
25492
  return joined2;
@@ -25527,9 +25644,9 @@ function promptFor(message, options = {}) {
25527
25644
  const held = options.rulesHeld === true;
25528
25645
  const notes = message.room?.notes ?? {};
25529
25646
  const note = taker === void 0 ? void 0 : held ? noteWithoutRules(message.room, taker) : notes[taker];
25530
- const who = options.sayWho === false ? "" : `${withRole(message.from.display_name, message.from)}: `;
25647
+ const who2 = options.sayWho === false ? "" : `${withRole(message.from.display_name, message.from)}: `;
25531
25648
  const files = (message.attachments ?? []).map(renderAttachment);
25532
- const words4 = [`${who}${message.text}`, ...files].join("\n");
25649
+ const words4 = [`${who2}${message.text}`, ...files].join("\n");
25533
25650
  const sending = options.sendsFiles === true && !held ? sendingFiles({ project: options.project !== void 0 }) : void 0;
25534
25651
  const replying = renderReplyingTo(message.replying_to, {
25535
25652
  sender: {
@@ -26048,52 +26165,429 @@ var AcpClient = class {
26048
26165
  const result = await this.handlers.request(request);
26049
26166
  this.wire.write(JSON.stringify({ jsonrpc: "2.0", id: id2, result: result ?? null }));
26050
26167
  } catch (error62) {
26051
- const code = error62 instanceof AcpError ? error62.code : -32603;
26052
- const message = error62 instanceof Error ? error62.message : String(error62);
26053
- this.wire.write(JSON.stringify({ jsonrpc: "2.0", id: id2, error: { code, message } }));
26168
+ const code = error62 instanceof AcpError ? error62.code : -32603;
26169
+ const message = error62 instanceof Error ? error62.message : String(error62);
26170
+ this.wire.write(JSON.stringify({ jsonrpc: "2.0", id: id2, error: { code, message } }));
26171
+ }
26172
+ }
26173
+ };
26174
+ function configOptionsOf(answer) {
26175
+ const raw = answer["configOptions"];
26176
+ if (!Array.isArray(raw)) return [];
26177
+ return raw.flatMap((each) => {
26178
+ const option = each;
26179
+ if (typeof option["id"] !== "string" || !Array.isArray(option["options"])) return [];
26180
+ return [
26181
+ {
26182
+ id: option["id"],
26183
+ name: typeof option["name"] === "string" ? option["name"] : option["id"],
26184
+ ...typeof option["category"] === "string" ? { category: option["category"] } : {},
26185
+ currentValue: String(option["currentValue"] ?? ""),
26186
+ // A select's values, or its groups' (`{ group, name, options }`), in order.
26187
+ options: option["options"].flatMap((value) => Array.isArray(value["options"]) ? value["options"] : [value]).filter((value) => typeof value["value"] === "string").map((value) => ({ value: String(value["value"]), name: String(value["name"] ?? value["value"]) }))
26188
+ }
26189
+ ];
26190
+ });
26191
+ }
26192
+ function metaOf(meta3) {
26193
+ return meta3 === void 0 ? {} : { _meta: meta3 };
26194
+ }
26195
+ function notOffered(method) {
26196
+ return new AcpError(`${method} is not offered by this client`, -32601);
26197
+ }
26198
+
26199
+ // src/adapter.ts
26200
+ import { spawn as spawn2 } from "node:child_process";
26201
+ import { mkdirSync as mkdirSync4, rmSync as rmSync3 } from "node:fs";
26202
+ import { homedir as homedir5 } from "node:os";
26203
+ import { delimiter as delimiter3, dirname as dirname4, join as join7 } from "node:path";
26204
+
26205
+ // src/kinds.ts
26206
+ var SIGN_IN_DOING = "Run this in Terminal, then try again. Your browser opens to sign in.";
26207
+ var KNOWN2 = [
26208
+ {
26209
+ id: "claude-code",
26210
+ name: "Claude Code",
26211
+ program: "claude-agent-acp",
26212
+ adapter: "@agentclientprotocol/claude-agent-acp",
26213
+ adapterMajor: 0,
26214
+ fetches: false,
26215
+ agent: "claude",
26216
+ installLine: "curl -fsSL https://claude.ai/install.sh | bash",
26217
+ mode: "default",
26218
+ signIn: "run `claude auth login`",
26219
+ signInLine: "claude auth login",
26220
+ signInDoing: SIGN_IN_DOING
26221
+ },
26222
+ {
26223
+ id: "codex",
26224
+ name: "Codex",
26225
+ program: "codex-acp",
26226
+ adapter: "@agentclientprotocol/codex-acp",
26227
+ adapterMajor: 2,
26228
+ fetches: true,
26229
+ agent: "codex",
26230
+ installLine: "curl -fsSL https://chatgpt.com/codex/install.sh | sh",
26231
+ mode: "workspace-write",
26232
+ signIn: "run `codex login`",
26233
+ signInLine: "codex login",
26234
+ signInDoing: SIGN_IN_DOING
26235
+ }
26236
+ ];
26237
+ function knownConfig(id2) {
26238
+ const known = KNOWN2.find((each) => each.id === id2);
26239
+ return known === void 0 ? void 0 : { name: known.name, command: [known.program], mode: known.mode };
26240
+ }
26241
+ var knownBy = (kind2) => {
26242
+ const program = kind2.command[0]?.split("/").pop();
26243
+ return KNOWN2.find((each) => each.program === program);
26244
+ };
26245
+ var knownOf = (kind2) => knownBy(kind2);
26246
+ function knownIdOf(kind2) {
26247
+ return knownBy(kind2)?.id;
26248
+ }
26249
+ var CODEX_DOC_BYTES = 65536;
26250
+ function codexConfigOf(env2) {
26251
+ const raw = env2["CODEX_CONFIG"];
26252
+ if (raw === void 0 || raw.trim() === "") return void 0;
26253
+ try {
26254
+ const parsed = JSON.parse(raw);
26255
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : void 0;
26256
+ } catch {
26257
+ return void 0;
26258
+ }
26259
+ }
26260
+ function adapterEnv(kind2, env2) {
26261
+ if (knownIdOf(kind2) !== "codex") return env2;
26262
+ const raw = env2["CODEX_CONFIG"];
26263
+ const config2 = codexConfigOf(env2);
26264
+ if (raw !== void 0 && raw.trim() !== "" && config2 === void 0) return env2;
26265
+ if (config2?.["project_doc_max_bytes"] !== void 0) return env2;
26266
+ return { ...env2, CODEX_CONFIG: JSON.stringify({ ...config2, project_doc_max_bytes: CODEX_DOC_BYTES }) };
26267
+ }
26268
+ function codexDocBytes(env2) {
26269
+ const said = codexConfigOf(env2)?.["project_doc_max_bytes"];
26270
+ return typeof said === "number" && Number.isFinite(said) && said > 0 ? said : 32768;
26271
+ }
26272
+ function installWords(kind2) {
26273
+ const known = knownBy(kind2);
26274
+ return known === void 0 ? "install the agent's ACP adapter its own way, or name it by its path in the config" : `install it with \`npm install -g ${known.adapter}\``;
26275
+ }
26276
+ function signedOutWords(kind2, info) {
26277
+ const known = knownBy(kind2);
26278
+ if (known !== void 0) return `${kind2.name} isn't signed in on this machine: ${known.signIn} in a terminal.`;
26279
+ const ways = (info?.authMethods ?? []).map((method) => method.name);
26280
+ return `${kind2.name} isn't signed in on this machine: sign it in its own way${ways.length > 0 ? ` (${ways.join(", ")})` : ""}.`;
26281
+ }
26282
+ function notInstalledStop(kind2, program) {
26283
+ const known = knownBy(kind2);
26284
+ if (known === void 0) {
26285
+ return {
26286
+ detail: `${program} isn't on this Mac`,
26287
+ says: `${kind2.name}'s ACP adapter isn't installed.`,
26288
+ doing: "Install the agent's ACP adapter its own way, then try again."
26289
+ };
26290
+ }
26291
+ return {
26292
+ detail: `${kind2.name} can't join Chips yet`,
26293
+ says: `${kind2.name} needs one more piece to join Chips.`,
26294
+ doing: "Run this in Terminal, then try again. It needs npm, which comes with Node.js (nodejs.org).",
26295
+ copy: `npm install -g ${known.adapter}`
26296
+ };
26297
+ }
26298
+ function agentMissingStop(known) {
26299
+ return {
26300
+ detail: `${known.name} isn't on this Mac`,
26301
+ says: `${known.name} isn't installed on this Mac.`,
26302
+ doing: "Run this in Terminal, then try again.",
26303
+ copy: known.installLine
26304
+ };
26305
+ }
26306
+ function adapterFailedStop(name) {
26307
+ return {
26308
+ detail: "The download didn't finish",
26309
+ says: `Chips couldn't get what ${name} needs.`,
26310
+ doing: "Check your connection, then try again."
26311
+ };
26312
+ }
26313
+ function signedOutStop(kind2) {
26314
+ const known = knownBy(kind2);
26315
+ return {
26316
+ detail: "Not signed in",
26317
+ says: `${kind2.name} isn't signed in.`,
26318
+ ...known === void 0 ? { doing: "Sign it in its own way, then try again." } : { doing: known.signInDoing, copy: known.signInLine }
26319
+ };
26320
+ }
26321
+
26322
+ // src/places.ts
26323
+ import { existsSync as existsSync5 } from "node:fs";
26324
+ import { homedir as homedir4 } from "node:os";
26325
+ import { isAbsolute as isAbsolute2, join as join5, relative, resolve as resolve2, sep as sep2 } from "node:path";
26326
+ function placesOf(home = homedir4()) {
26327
+ return {
26328
+ settings: join5(home, "Chips", ".bridges", "acp"),
26329
+ agents: join5(home, "Chips", "Agents"),
26330
+ oldSettings: join5(home, ".chips-acp"),
26331
+ oldAgents: join5(home, "chips-acp")
26332
+ };
26333
+ }
26334
+ var fromHome = (path, home = homedir4()) => path === "~" ? home : path.startsWith("~/") ? join5(home, path.slice(2)) : path;
26335
+ function inside2(root, path) {
26336
+ const under = relative(root, path);
26337
+ return under === "" || under === ".." || under.startsWith(`..${sep2}`) || isAbsolute2(under) ? void 0 : under;
26338
+ }
26339
+ function nowAt(path, before, after) {
26340
+ const under = inside2(before, path);
26341
+ if (under === void 0) return path;
26342
+ const moved = join5(after, under);
26343
+ return existsSync5(path) && !existsSync5(moved) ? path : moved;
26344
+ }
26345
+ function configTargetOf(word, home = homedir4()) {
26346
+ const places = placesOf(home);
26347
+ const path = resolve2(fromHome(word ?? join5(places.settings, "config.json"), home));
26348
+ const under = inside2(places.oldSettings, path);
26349
+ return under === void 0 ? path : join5(places.settings, under);
26350
+ }
26351
+ function configPathOf(word, home = homedir4()) {
26352
+ const places = placesOf(home);
26353
+ const target = configTargetOf(word, home);
26354
+ const under = inside2(places.settings, target);
26355
+ if (under === void 0) return target;
26356
+ const old = join5(places.oldSettings, under);
26357
+ const kept2 = (path) => existsSync5(path) || existsSync5(path.replace(/\.json$/, ""));
26358
+ return kept2(old) && !kept2(target) ? old : target;
26359
+ }
26360
+ function foldersPathOf(path, home = homedir4()) {
26361
+ const places = placesOf(home);
26362
+ const whole2 = resolve2(fromHome(path, home));
26363
+ const under = inside2(places.agents, whole2);
26364
+ const old = under === void 0 ? void 0 : join5(places.oldAgents, under);
26365
+ if (old !== void 0 && existsSync5(old) && !existsSync5(whole2)) return old;
26366
+ return nowAt(whole2, places.oldAgents, places.agents);
26367
+ }
26368
+
26369
+ // src/setup.ts
26370
+ import { accessSync as accessSync2, constants as constants2, existsSync as existsSync6, readFileSync as readFileSync6 } from "node:fs";
26371
+ import { basename as basename3, delimiter as delimiter2, isAbsolute as isAbsolute3, join as join6, resolve as resolve3 } from "node:path";
26372
+
26373
+ // src/version.ts
26374
+ import { readFileSync as readFileSync5 } from "node:fs";
26375
+ var VERSION = JSON.parse(readFileSync5(new URL("../package.json", import.meta.url), "utf8")).version;
26376
+
26377
+ // src/setup.ts
26378
+ var SetupError = class extends Error {
26379
+ constructor(message, words4 = {}) {
26380
+ super(message);
26381
+ this.words = words4;
26382
+ }
26383
+ words;
26384
+ name = "SetupError";
26385
+ };
26386
+ var STILL_GOOD = "The link is still good: run the same command again once that's done.";
26387
+ var EXAMPLE = '{ "name": "Claude Code", "command": ["claude-agent-acp"], "folders": "~/Chips/Agents/claude-code" }';
26388
+ function readConfig(path) {
26389
+ const known = knownConfig(basename3(path, ".json"));
26390
+ if (!existsSync6(path) && known === void 0) {
26391
+ throw new SetupError(
26392
+ `There is no config at ${path}. Write ${EXAMPLE} there, or name claude-code.json or codex.json, which need none. ${STILL_GOOD}`
26393
+ );
26394
+ }
26395
+ const raw = existsSync6(path) ? JSON.parse(readFileSync6(path, "utf8")) : known;
26396
+ const name = raw["name"];
26397
+ const command = raw["command"];
26398
+ if (typeof name !== "string" || name.trim() === "" || !Array.isArray(command) || command.length === 0) {
26399
+ throw new SetupError(`${path} names a kind of agent and how to run it: ${EXAMPLE}. ${STILL_GOOD}`);
26400
+ }
26401
+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
26402
+ return {
26403
+ name,
26404
+ command: command.map(String),
26405
+ folders: foldersPathOf(typeof raw["folders"] === "string" ? raw["folders"] : `~/Chips/Agents/${slug}`),
26406
+ ...typeof raw["folder"] === "string" ? { folder: foldersPathOf(raw["folder"]) } : {},
26407
+ ...typeof raw["mode"] === "string" ? { mode: raw["mode"] } : {},
26408
+ ...typeof raw["env"] === "object" && raw["env"] !== null ? { env: raw["env"] } : {}
26409
+ };
26410
+ }
26411
+ var runnable = (path) => {
26412
+ try {
26413
+ accessSync2(path, constants2.X_OK);
26414
+ return true;
26415
+ } catch {
26416
+ return false;
26417
+ }
26418
+ };
26419
+ var onPath = (program, path) => path.split(delimiter2).some((dir) => dir !== "" && runnable(join6(dir, program)));
26420
+ function checkCommand(kind2, env2 = process.env) {
26421
+ const [program] = kind2.command;
26422
+ if (program === void 0) throw new SetupError(`${kind2.name} has no command to run. ${STILL_GOOD}`);
26423
+ const path = { ...env2, ...kind2.env }["PATH"] ?? "";
26424
+ const found = program.includes("/") ? runnable(isAbsolute3(program) ? program : resolve3(fromHome(program))) : onPath(program, path);
26425
+ if (!found) {
26426
+ throw new SetupError(
26427
+ `${kind2.name}'s command, ${program}, isn't on this machine's PATH: ${installWords(kind2)}. ${STILL_GOOD}`,
26428
+ notInstalledStop(kind2, program)
26429
+ );
26430
+ }
26431
+ }
26432
+ var MINUTE = 6e4;
26433
+ function within(promise2, ms, what) {
26434
+ let timer;
26435
+ const late = new Promise((_, reject) => {
26436
+ timer = setTimeout(() => reject(new Error(what)), ms);
26437
+ });
26438
+ return Promise.race([promise2, late]).finally(() => clearTimeout(timer));
26439
+ }
26440
+ var wordsOf2 = (error62) => error62 instanceof Error ? error62.message : String(error62);
26441
+ async function checkSignIn(kind2, wire, cwd, options = {}) {
26442
+ let status;
26443
+ let heard = () => {
26444
+ };
26445
+ const said = new Promise((resolve5) => {
26446
+ heard = resolve5;
26447
+ });
26448
+ const client = new AcpClient(wire, {
26449
+ update: () => void 0,
26450
+ request: async (request) => {
26451
+ throw notOffered(request.method);
26452
+ },
26453
+ exit: () => heard(),
26454
+ auth: (now) => {
26455
+ status = now;
26456
+ heard();
26457
+ }
26458
+ });
26459
+ try {
26460
+ let info;
26461
+ try {
26462
+ info = await within(client.initialize({ name: "chips-acp", version: VERSION }), MINUTE, "it didn't answer within a minute");
26463
+ } catch (error62) {
26464
+ const last = options.stderr?.().slice(-3).join(" ") ?? "";
26465
+ throw new SetupError(`${kind2.name} didn't start: ${wordsOf2(error62)}.${last === "" ? "" : ` It said: ${last}`} ${STILL_GOOD}`, {
26466
+ detail: "It didn't start",
26467
+ says: `${kind2.name} didn't start: ${wordsOf2(error62)}.`,
26468
+ ...last === "" ? {} : { doing: `It said: ${last}` }
26469
+ });
26470
+ }
26471
+ try {
26472
+ const { sessionId } = await within(client.newSession(cwd), MINUTE, "it didn't answer within a minute");
26473
+ if (info.closeSession) await client.closeSession(sessionId).catch(() => void 0);
26474
+ } catch (error62) {
26475
+ if (isAuthRequired(error62)) throw new SetupError(`${signedOutWords(kind2, info)} ${STILL_GOOD}`, signedOutStop(kind2));
26476
+ throw new SetupError(`${kind2.name} couldn't open a session: ${wordsOf2(error62)}. ${STILL_GOOD}`, {
26477
+ detail: "It couldn't open a session",
26478
+ says: `${kind2.name} couldn't open a session: ${wordsOf2(error62)}.`
26479
+ });
26054
26480
  }
26481
+ if (info.reportsAuth && status === void 0) await within(said, options.waitMs ?? 6e3, "").catch(() => void 0);
26482
+ if (status?.kind === "none") throw new SetupError(`${signedOutWords(kind2, info)} ${STILL_GOOD}`, signedOutStop(kind2));
26483
+ } finally {
26484
+ client.close();
26055
26485
  }
26056
- };
26057
- function configOptionsOf(answer) {
26058
- const raw = answer["configOptions"];
26059
- if (!Array.isArray(raw)) return [];
26060
- return raw.flatMap((each) => {
26061
- const option = each;
26062
- if (typeof option["id"] !== "string" || !Array.isArray(option["options"])) return [];
26063
- return [
26064
- {
26065
- id: option["id"],
26066
- name: typeof option["name"] === "string" ? option["name"] : option["id"],
26067
- ...typeof option["category"] === "string" ? { category: option["category"] } : {},
26068
- currentValue: String(option["currentValue"] ?? ""),
26069
- // A select's values, or its groups' (`{ group, name, options }`), in order.
26070
- options: option["options"].flatMap((value) => Array.isArray(value["options"]) ? value["options"] : [value]).filter((value) => typeof value["value"] === "string").map((value) => ({ value: String(value["value"]), name: String(value["name"] ?? value["value"]) }))
26071
- }
26072
- ];
26486
+ }
26487
+
26488
+ // src/adapter.ts
26489
+ var PATIENCE_MS = 20 * 6e4;
26490
+ var adapterFolder = (id2, home = homedir5()) => join7(placesOf(home).settings, "adapters", id2);
26491
+ var fetchedAt = (id2, program, home) => join7(adapterFolder(id2, home), "node_modules", ".bin", program);
26492
+ var pathOf2 = (kind2, env2) => ({ ...env2, ...kind2.env })["PATH"] ?? "";
26493
+ function withFetchedAdapter(kind2, env2 = process.env, home = homedir5()) {
26494
+ const known = knownOf(kind2);
26495
+ if (known === void 0 || kind2.command[0] !== known.program || onPath(known.program, pathOf2(kind2, env2))) return kind2;
26496
+ const fetched = fetchedAt(known.id, known.program, home);
26497
+ return runnable(fetched) ? { ...kind2, command: [fetched, ...kind2.command.slice(1)] } : kind2;
26498
+ }
26499
+ function npmInstall(job) {
26500
+ return new Promise((resolve5, reject) => {
26501
+ const registry2 = job.env["CHIPS_NPM_REGISTRY"];
26502
+ const child = spawn2(
26503
+ job.node,
26504
+ [
26505
+ job.npm,
26506
+ "install",
26507
+ job.spec,
26508
+ "--prefix",
26509
+ job.folder,
26510
+ "--omit=dev",
26511
+ "--ignore-scripts",
26512
+ "--no-audit",
26513
+ "--no-fund",
26514
+ "--loglevel=error",
26515
+ ...registry2 === void 0 || registry2 === "" ? [] : ["--registry", registry2]
26516
+ ],
26517
+ { env: job.env, stdio: ["ignore", "ignore", "pipe"] }
26518
+ );
26519
+ let said = "";
26520
+ child.stderr.on("data", (chunk) => {
26521
+ said = `${said}${chunk.toString("utf8")}`.slice(-2e3);
26522
+ });
26523
+ const late = setTimeout(() => child.kill("SIGTERM"), PATIENCE_MS);
26524
+ child.on("error", (error62) => {
26525
+ clearTimeout(late);
26526
+ reject(error62);
26527
+ });
26528
+ child.on("exit", (code) => {
26529
+ clearTimeout(late);
26530
+ if (code === 0) resolve5();
26531
+ else reject(new Error(said.trim() || `npm stopped with ${code ?? "a signal"}`));
26532
+ });
26073
26533
  });
26074
26534
  }
26075
- function metaOf(meta3) {
26076
- return meta3 === void 0 ? {} : { _meta: meta3 };
26535
+ async function readyAdapter(kind2, options = {}) {
26536
+ const env2 = options.env ?? process.env;
26537
+ const home = options.home ?? homedir5();
26538
+ const known = knownOf(kind2);
26539
+ if (known === void 0 || kind2.command[0] !== known.program) return kind2;
26540
+ const path = pathOf2(kind2, env2);
26541
+ if (onPath(known.program, path)) return kind2;
26542
+ if (!onPath(known.agent, path)) {
26543
+ throw new SetupError(`${kind2.name} isn't installed on this machine: run \`${known.installLine}\`. ${STILL_GOOD}`, agentMissingStop(known));
26544
+ }
26545
+ const npm = env2["CHIPS_NPM"];
26546
+ if (!known.fetches || npm === void 0 || npm === "") return kind2;
26547
+ const folder2 = adapterFolder(known.id, home);
26548
+ const { CHIPS_JOIN_LINK: _link, ...rest } = env2;
26549
+ const node2 = process.execPath;
26550
+ options.say?.(`Getting what ${kind2.name} needs from npm, a large download`);
26551
+ try {
26552
+ mkdirSync4(folder2, { recursive: true });
26553
+ await (options.install ?? npmInstall)({
26554
+ node: node2,
26555
+ npm,
26556
+ folder: folder2,
26557
+ spec: `${known.adapter}@${known.adapterMajor}`,
26558
+ env: { ...rest, PATH: `${dirname4(node2)}${delimiter3}${rest["PATH"] ?? ""}` }
26559
+ });
26560
+ } catch (error62) {
26561
+ rmSync3(folder2, { recursive: true, force: true });
26562
+ const why = error62 instanceof Error ? error62.message : String(error62);
26563
+ throw new SetupError(`${kind2.name}'s adapter couldn't be downloaded: ${why}. ${STILL_GOOD}`, adapterFailedStop(kind2.name));
26564
+ }
26565
+ const ready = withFetchedAdapter(kind2, env2, home);
26566
+ if (ready.command[0] === known.program) {
26567
+ rmSync3(folder2, { recursive: true, force: true });
26568
+ throw new SetupError(`${known.adapter} installed, but it has no ${known.program}. ${STILL_GOOD}`, adapterFailedStop(kind2.name));
26569
+ }
26570
+ return ready;
26077
26571
  }
26078
- function notOffered(method) {
26079
- return new AcpError(`${method} is not offered by this client`, -32601);
26572
+ function forgetAdapter(id2, home = homedir5()) {
26573
+ if (knownConfig(id2) !== void 0) rmSync3(adapterFolder(id2, home), { recursive: true, force: true });
26080
26574
  }
26081
26575
 
26082
26576
  // src/bridge.ts
26083
26577
  import { randomBytes } from "node:crypto";
26084
- import { existsSync as existsSync6 } from "node:fs";
26578
+ import { existsSync as existsSync8 } from "node:fs";
26085
26579
  import { mkdir as mkdir3, writeFile as writeFile3 } from "node:fs/promises";
26086
- import { homedir as homedir4 } from "node:os";
26087
- import { join as join7 } from "node:path";
26580
+ import { homedir as homedir6 } from "node:os";
26581
+ import { join as join10 } from "node:path";
26088
26582
 
26089
26583
  // src/claude-settings.ts
26090
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
26091
- import { join as join5 } from "node:path";
26584
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "node:fs";
26585
+ import { join as join8 } from "node:path";
26092
26586
  var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
26093
26587
  function readLayer(path) {
26094
- if (!existsSync5(path)) return void 0;
26588
+ if (!existsSync7(path)) return void 0;
26095
26589
  try {
26096
- const read = JSON.parse(readFileSync5(path, "utf8"));
26590
+ const read = JSON.parse(readFileSync7(path, "utf8"));
26097
26591
  return isRecord(read) ? read : void 0;
26098
26592
  } catch {
26099
26593
  return void 0;
@@ -26101,9 +26595,9 @@ function readLayer(path) {
26101
26595
  }
26102
26596
  function settingsLayers(claudeHome, folder2) {
26103
26597
  return [
26104
- join5(claudeHome, "settings.json"),
26105
- join5(folder2, ".claude", "settings.json"),
26106
- join5(folder2, ".claude", "settings.local.json")
26598
+ join8(claudeHome, "settings.json"),
26599
+ join8(folder2, ".claude", "settings.json"),
26600
+ join8(folder2, ".claude", "settings.local.json")
26107
26601
  ].flatMap((path) => {
26108
26602
  const layer = readLayer(path);
26109
26603
  return layer === void 0 ? [] : [layer];
@@ -26153,19 +26647,19 @@ function autoCompactWindowFromEnv(env2) {
26153
26647
  }
26154
26648
  function memoryPath(claudeHome, folder2) {
26155
26649
  const name = folder2.replace(/[^a-zA-Z0-9]/g, "-");
26156
- return name.length > 200 ? void 0 : join5(claudeHome, "projects", name, "memory", "MEMORY.md");
26650
+ return name.length > 200 ? void 0 : join8(claudeHome, "projects", name, "memory", "MEMORY.md");
26157
26651
  }
26158
26652
 
26159
26653
  // src/context.ts
26160
26654
  import { createHash as createHash2 } from "node:crypto";
26161
- import { readdirSync, readFileSync as readFileSync6, statSync } from "node:fs";
26655
+ import { readdirSync, readFileSync as readFileSync8, statSync } from "node:fs";
26162
26656
  import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
26163
- import { dirname as dirname4, join as join6, parse as parse3, relative, sep as sep2 } from "node:path";
26164
- function placesOf(env2, home) {
26657
+ import { dirname as dirname5, join as join9, parse as parse3, relative as relative2, sep as sep3 } from "node:path";
26658
+ function placesOf2(env2, home) {
26165
26659
  return {
26166
26660
  home,
26167
- claudeHome: env2["CLAUDE_CONFIG_DIR"] || join6(home, ".claude"),
26168
- codexHome: env2["CODEX_HOME"] || join6(home, ".codex")
26661
+ claudeHome: env2["CLAUDE_CONFIG_DIR"] || join9(home, ".claude"),
26662
+ codexHome: env2["CODEX_HOME"] || join9(home, ".codex")
26169
26663
  };
26170
26664
  }
26171
26665
  function hashOf(text) {
@@ -26180,13 +26674,13 @@ function isFile(path) {
26180
26674
  }
26181
26675
  function textOf(path) {
26182
26676
  try {
26183
- return readFileSync6(path, "utf8");
26677
+ return readFileSync8(path, "utf8");
26184
26678
  } catch {
26185
26679
  return void 0;
26186
26680
  }
26187
26681
  }
26188
26682
  function claudeFilesIn(dir) {
26189
- const rules = join6(dir, ".claude", "rules");
26683
+ const rules = join9(dir, ".claude", "rules");
26190
26684
  let named = [];
26191
26685
  try {
26192
26686
  named = readdirSync(rules).filter((name) => name.endsWith(".md")).sort();
@@ -26194,26 +26688,26 @@ function claudeFilesIn(dir) {
26194
26688
  named = [];
26195
26689
  }
26196
26690
  return [
26197
- join6(dir, "CLAUDE.md"),
26198
- join6(dir, "CLAUDE.local.md"),
26199
- join6(dir, ".claude", "CLAUDE.md"),
26200
- ...named.map((name) => join6(rules, name))
26691
+ join9(dir, "CLAUDE.md"),
26692
+ join9(dir, "CLAUDE.local.md"),
26693
+ join9(dir, ".claude", "CLAUDE.md"),
26694
+ ...named.map((name) => join9(rules, name))
26201
26695
  ];
26202
26696
  }
26203
26697
  function ownTitle(within3) {
26204
26698
  if (within3 === "CLAUDE.md") return "How it works";
26205
26699
  if (within3 === "CLAUDE.local.md") return "Its local instructions";
26206
- if (within3 === join6(".claude", "CLAUDE.md")) return "More of how it works";
26700
+ if (within3 === join9(".claude", "CLAUDE.md")) return "More of how it works";
26207
26701
  return `Rule: ${parse3(within3).name}`.slice(0, 80);
26208
26702
  }
26209
26703
  function readNote2(name) {
26210
26704
  return `${name} reads these when a conversation starts. A change made here applies from the next message.`;
26211
26705
  }
26212
- var within = (path, dir) => path === dir || path.startsWith(`${dir}${sep2}`);
26706
+ var within2 = (path, dir) => path === dir || path.startsWith(`${dir}${sep3}`);
26213
26707
  function* upFrom(dir) {
26214
- for (let at = dir; ; at = dirname4(at)) {
26708
+ for (let at = dir; ; at = dirname5(at)) {
26215
26709
  yield at;
26216
- if (dirname4(at) === at) return;
26710
+ if (dirname5(at) === at) return;
26217
26711
  }
26218
26712
  }
26219
26713
  var ContextFiles = class {
@@ -26230,19 +26724,19 @@ var ContextFiles = class {
26230
26724
  /** `~/Chips/Agents/claude-code/CLAUDE.md`, or the whole path where it isn't in the home. */
26231
26725
  tilde(path) {
26232
26726
  const { home } = this.places;
26233
- return within(path, home) ? `~${path.slice(home.length)}` : path;
26727
+ return within2(path, home) ? `~${path.slice(home.length)}` : path;
26234
26728
  }
26235
26729
  /** A shared file's name: where it is, a step at a time (`~ › .codex › AGENTS.md`), with no slash. */
26236
26730
  crumbs(path) {
26237
26731
  const { home } = this.places;
26238
- const steps = within(path, home) ? ["~", ...relative(home, path).split(sep2)] : ["/", ...path.split(sep2)];
26732
+ const steps = within2(path, home) ? ["~", ...relative2(home, path).split(sep3)] : ["/", ...path.split(sep3)];
26239
26733
  return steps.filter((step) => step !== "").join(" \u203A ").slice(0, 255);
26240
26734
  }
26241
26735
  /** The harness's own set: what every agent, or every agent below a folder, reads beside its own. */
26242
26736
  sharedSpots() {
26243
26737
  const { places, kind: kind2 } = this;
26244
26738
  if (this.id === "codex") {
26245
- const yours2 = [join6(places.codexHome, "AGENTS.override.md"), join6(places.codexHome, "AGENTS.md")].find(isFile);
26739
+ const yours2 = [join9(places.codexHome, "AGENTS.override.md"), join9(places.codexHome, "AGENTS.md")].find(isFile);
26246
26740
  if (yours2 === void 0) return [];
26247
26741
  return [
26248
26742
  {
@@ -26259,7 +26753,7 @@ var ContextFiles = class {
26259
26753
  }
26260
26754
  const spots = [];
26261
26755
  if (kind2.folder === void 0) {
26262
- const path = join6(kind2.folders, "CLAUDE.md");
26756
+ const path = join9(kind2.folders, "CLAUDE.md");
26263
26757
  spots.push({
26264
26758
  path,
26265
26759
  name: this.crumbs(path),
@@ -26271,8 +26765,8 @@ var ContextFiles = class {
26271
26765
  over: kind2.folders
26272
26766
  });
26273
26767
  }
26274
- const yours = join6(places.claudeHome, "CLAUDE.md");
26275
- for (const dir of upFrom(kind2.folder === void 0 ? kind2.folders : dirname4(kind2.folder))) {
26768
+ const yours = join9(places.claudeHome, "CLAUDE.md");
26769
+ for (const dir of upFrom(kind2.folder === void 0 ? kind2.folders : dirname5(kind2.folder))) {
26276
26770
  for (const path of claudeFilesIn(dir)) {
26277
26771
  if (path === yours || spots.some((spot) => spot.path === path) || !isFile(path)) continue;
26278
26772
  spots.push({
@@ -26305,13 +26799,13 @@ var ContextFiles = class {
26305
26799
  /** An agent's own files: its folder's, and for Claude Code its memory, last. */
26306
26800
  ownSpots(folder2) {
26307
26801
  if (this.id === "codex") {
26308
- const override = join6(folder2, "AGENTS.override.md");
26309
- const path = isFile(override) ? override : join6(folder2, "AGENTS.md");
26310
- return [{ path, name: relative(folder2, path), title: "How it works", role: "instructions", editable: true }];
26802
+ const override = join9(folder2, "AGENTS.override.md");
26803
+ const path = isFile(override) ? override : join9(folder2, "AGENTS.md");
26804
+ return [{ path, name: relative2(folder2, path), title: "How it works", role: "instructions", editable: true }];
26311
26805
  }
26312
26806
  const spots = claudeFilesIn(folder2).filter((path, at) => at === 0 || isFile(path)).map((path) => {
26313
- const where = relative(folder2, path);
26314
- return { path, name: where.split(sep2).join(" \u203A "), title: ownTitle(where), role: "instructions", editable: true };
26807
+ const where = relative2(folder2, path);
26808
+ return { path, name: where.split(sep3).join(" \u203A "), title: ownTitle(where), role: "instructions", editable: true };
26315
26809
  });
26316
26810
  const memory = memoryPath(this.places.claudeHome, folder2);
26317
26811
  if (memory !== void 0 && memoryOn(settingsLayers(this.places.claudeHome, folder2))) {
@@ -26328,7 +26822,7 @@ var ContextFiles = class {
26328
26822
  }
26329
26823
  /** The shared files an agent in `folder` reads. */
26330
26824
  readBy(folder2) {
26331
- return this.sharedSpots().filter((spot) => spot.over === void 0 || within(folder2, spot.over));
26825
+ return this.sharedSpots().filter((spot) => spot.over === void 0 || within2(folder2, spot.over));
26332
26826
  }
26333
26827
  /** An agent's copy: its own files and the shared ones it reads, eight at most, and when it reads them. */
26334
26828
  agentCopy(folder2) {
@@ -26402,7 +26896,7 @@ var ContextFiles = class {
26402
26896
  hash: hashOf(text),
26403
26897
  editable: spot.editable,
26404
26898
  ...spot.whyReadOnly === void 0 ? {} : { why_read_only: spot.whyReadOnly },
26405
- used_by: over === void 0 ? folders.length : folders.filter((folder2) => within(folder2, over)).length
26899
+ used_by: over === void 0 ? folders.length : folders.filter((folder2) => within2(folder2, over)).length
26406
26900
  });
26407
26901
  }
26408
26902
  return { shared, ...notShown.length === 0 ? {} : { not_shown: notShown } };
@@ -26445,7 +26939,7 @@ var ContextFiles = class {
26445
26939
  async write(spot, edit, now) {
26446
26940
  if (hashOf(textOf(spot.path) ?? "") !== edit.base_hash) throw new Refuse("", now(), "changed");
26447
26941
  try {
26448
- await mkdir2(dirname4(spot.path), { recursive: true });
26942
+ await mkdir2(dirname5(spot.path), { recursive: true });
26449
26943
  await writeFile2(spot.path, edit.text, "utf8");
26450
26944
  } catch (error62) {
26451
26945
  throw new Refuse(`It couldn't be saved: ${error62 instanceof Error ? error62.message : String(error62)}`.slice(0, 300), now(), "failed");
@@ -26453,94 +26947,6 @@ var ContextFiles = class {
26453
26947
  }
26454
26948
  };
26455
26949
 
26456
- // src/kinds.ts
26457
- var KNOWN2 = [
26458
- {
26459
- id: "claude-code",
26460
- name: "Claude Code",
26461
- program: "claude-agent-acp",
26462
- adapter: "@agentclientprotocol/claude-agent-acp",
26463
- mode: "default",
26464
- signIn: "run `claude`, then /login",
26465
- signInLine: "claude",
26466
- signInDoing: "Run this in a terminal, then /login, then try again."
26467
- },
26468
- {
26469
- id: "codex",
26470
- name: "Codex",
26471
- program: "codex-acp",
26472
- adapter: "@agentclientprotocol/codex-acp",
26473
- mode: "workspace-write",
26474
- signIn: "run `codex login`",
26475
- signInLine: "codex login",
26476
- signInDoing: "Run this in a terminal, then try again."
26477
- }
26478
- ];
26479
- function knownConfig(id2) {
26480
- const known = KNOWN2.find((each) => each.id === id2);
26481
- return known === void 0 ? void 0 : { name: known.name, command: [known.program], mode: known.mode };
26482
- }
26483
- var knownBy = (kind2) => {
26484
- const program = kind2.command[0]?.split("/").pop();
26485
- return KNOWN2.find((each) => each.program === program);
26486
- };
26487
- function knownIdOf(kind2) {
26488
- return knownBy(kind2)?.id;
26489
- }
26490
- var CODEX_DOC_BYTES = 65536;
26491
- function codexConfigOf(env2) {
26492
- const raw = env2["CODEX_CONFIG"];
26493
- if (raw === void 0 || raw.trim() === "") return void 0;
26494
- try {
26495
- const parsed = JSON.parse(raw);
26496
- return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : void 0;
26497
- } catch {
26498
- return void 0;
26499
- }
26500
- }
26501
- function adapterEnv(kind2, env2) {
26502
- if (knownIdOf(kind2) !== "codex") return env2;
26503
- const raw = env2["CODEX_CONFIG"];
26504
- const config2 = codexConfigOf(env2);
26505
- if (raw !== void 0 && raw.trim() !== "" && config2 === void 0) return env2;
26506
- if (config2?.["project_doc_max_bytes"] !== void 0) return env2;
26507
- return { ...env2, CODEX_CONFIG: JSON.stringify({ ...config2, project_doc_max_bytes: CODEX_DOC_BYTES }) };
26508
- }
26509
- function codexDocBytes(env2) {
26510
- const said = codexConfigOf(env2)?.["project_doc_max_bytes"];
26511
- return typeof said === "number" && Number.isFinite(said) && said > 0 ? said : 32768;
26512
- }
26513
- function installWords(kind2) {
26514
- const known = knownBy(kind2);
26515
- return known === void 0 ? "install the agent's ACP adapter its own way, or name it by its path in the config" : `install it with \`npm install -g ${known.adapter}\``;
26516
- }
26517
- function signedOutWords(kind2, info) {
26518
- const known = knownBy(kind2);
26519
- if (known !== void 0) return `${kind2.name} isn't signed in on this machine: ${known.signIn} in a terminal.`;
26520
- const ways = (info?.authMethods ?? []).map((method) => method.name);
26521
- return `${kind2.name} isn't signed in on this machine: sign it in its own way${ways.length > 0 ? ` (${ways.join(", ")})` : ""}.`;
26522
- }
26523
- function notInstalledStop(kind2, program) {
26524
- const known = knownBy(kind2);
26525
- return {
26526
- detail: `${program} isn't on this Mac`,
26527
- says: `${kind2.name}'s ACP adapter isn't installed.`,
26528
- ...known === void 0 ? { doing: "Install the agent's ACP adapter its own way, then try again." } : { doing: "Install it with npm, then try again.", copy: `npm install -g ${known.adapter}` }
26529
- };
26530
- }
26531
- function signedOutStop(kind2) {
26532
- const known = knownBy(kind2);
26533
- return {
26534
- detail: "Not signed in",
26535
- says: `${kind2.name} isn't signed in.`,
26536
- ...known === void 0 ? { doing: "Sign it in its own way, then try again." } : { doing: known.signInDoing, copy: known.signInLine }
26537
- };
26538
- }
26539
-
26540
- // src/version.ts
26541
- import { readFileSync as readFileSync7 } from "node:fs";
26542
- var VERSION = JSON.parse(readFileSync7(new URL("../package.json", import.meta.url), "utf8")).version;
26543
-
26544
26950
  // src/models.ts
26545
26951
  var SETTINGS_LEVEL = "default";
26546
26952
  var LEVEL_WORDS = { xhigh: "Extra high" };
@@ -26736,7 +27142,7 @@ var Bridge = class {
26736
27142
  this.knew = resolve5;
26737
27143
  });
26738
27144
  this.env = options.env ?? adapterEnv(options.kind, { ...process.env, ...options.kind.env });
26739
- this.places = placesOf(this.env, options.home ?? homedir4());
27145
+ this.places = placesOf2(this.env, options.home ?? homedir6());
26740
27146
  this.knownKind = knownIdOf(options.kind);
26741
27147
  this.files = this.knownKind === void 0 ? void 0 : new ContextFiles(this.knownKind, options.kind, this.places, codexDocBytes(this.env));
26742
27148
  }
@@ -26899,8 +27305,8 @@ var Bridge = class {
26899
27305
  const base = slugOf(name).replace(/_/g, "-") || "agent";
26900
27306
  const taken = new Set(this.records().map((record2) => record2.folder));
26901
27307
  for (let n = 1; ; n += 1) {
26902
- const folder2 = join7(kind2.folders, n === 1 ? base : `${base}-${n}`);
26903
- if (taken.has(folder2) || existsSync6(folder2)) continue;
27308
+ const folder2 = join10(kind2.folders, n === 1 ? base : `${base}-${n}`);
27309
+ if (taken.has(folder2) || existsSync8(folder2)) continue;
26904
27310
  await mkdir3(folder2, { recursive: true });
26905
27311
  return folder2;
26906
27312
  }
@@ -27441,9 +27847,9 @@ ${files.join("\n")}`;
27441
27847
  const lines2 = [];
27442
27848
  for (const file3 of message.attachments ?? []) {
27443
27849
  try {
27444
- const folder2 = join7(record2.folder, "chips-files", message.message_id);
27850
+ const folder2 = join10(record2.folder, "chips-files", message.message_id);
27445
27851
  await mkdir3(folder2, { recursive: true });
27446
- const path = join7(folder2, file3.filename.replace(/[/\\]/g, "_"));
27852
+ const path = join10(folder2, file3.filename.replace(/[/\\]/g, "_"));
27447
27853
  await writeFile3(path, await this.options.chips.download(file3));
27448
27854
  lines2.push(`(${file3.filename} is saved at ${path})`);
27449
27855
  } catch (error62) {
@@ -28228,12 +28634,12 @@ function goalOf(message, name) {
28228
28634
  const goal = named ? first.slice(name.length + 1).trim() : first.replace(/^@\S+\s*/, "");
28229
28635
  return (goal === "" ? `Answer ${message.from.display_name}` : goal).slice(0, 300);
28230
28636
  }
28231
- function lookAgainPrompt(who, reply, note) {
28637
+ function lookAgainPrompt(who2, reply, note) {
28232
28638
  const quoted2 = reply === void 0 || reply.trim() === "" ? void 0 : `Your reply:
28233
28639
  \xAB${cut(reply.trim(), QUOTED)}\xBB`;
28234
28640
  const wrong = note === void 0 ? "They didn't say what. Read your reply again and find what was wrong." : `What wasn't right: \xAB${note}\xBB`;
28235
28641
  return [
28236
- `${who} says your reply in this space wasn't right.`,
28642
+ `${who2} says your reply in this space wasn't right.`,
28237
28643
  quoted2,
28238
28644
  wrong,
28239
28645
  "Look at it again and answer properly in its place. If it is not clear what was wrong, ask them in one short line. Say plainly what you changed."
@@ -28339,65 +28745,17 @@ function forkName(original) {
28339
28745
  }
28340
28746
 
28341
28747
  // src/keep.ts
28342
- import { basename as basename3 } from "node:path";
28748
+ import { basename as basename4 } from "node:path";
28343
28749
  import { fileURLToPath as fileURLToPath2 } from "node:url";
28344
-
28345
- // src/places.ts
28346
- import { existsSync as existsSync7 } from "node:fs";
28347
- import { homedir as homedir5 } from "node:os";
28348
- import { isAbsolute as isAbsolute2, join as join8, relative as relative2, resolve as resolve2, sep as sep3 } from "node:path";
28349
- function placesOf2(home = homedir5()) {
28350
- return {
28351
- settings: join8(home, "Chips", ".bridges", "acp"),
28352
- agents: join8(home, "Chips", "Agents"),
28353
- oldSettings: join8(home, ".chips-acp"),
28354
- oldAgents: join8(home, "chips-acp")
28355
- };
28356
- }
28357
- var fromHome = (path, home = homedir5()) => path === "~" ? home : path.startsWith("~/") ? join8(home, path.slice(2)) : path;
28358
- function inside2(root, path) {
28359
- const under = relative2(root, path);
28360
- return under === "" || under === ".." || under.startsWith(`..${sep3}`) || isAbsolute2(under) ? void 0 : under;
28361
- }
28362
- function nowAt(path, before, after) {
28363
- const under = inside2(before, path);
28364
- if (under === void 0) return path;
28365
- const moved = join8(after, under);
28366
- return existsSync7(path) && !existsSync7(moved) ? path : moved;
28367
- }
28368
- function configTargetOf(word, home = homedir5()) {
28369
- const places = placesOf2(home);
28370
- const path = resolve2(fromHome(word ?? join8(places.settings, "config.json"), home));
28371
- const under = inside2(places.oldSettings, path);
28372
- return under === void 0 ? path : join8(places.settings, under);
28373
- }
28374
- function configPathOf(word, home = homedir5()) {
28375
- const places = placesOf2(home);
28376
- const target = configTargetOf(word, home);
28377
- const under = inside2(places.settings, target);
28378
- if (under === void 0) return target;
28379
- const old = join8(places.oldSettings, under);
28380
- const kept2 = (path) => existsSync7(path) || existsSync7(path.replace(/\.json$/, ""));
28381
- return kept2(old) && !kept2(target) ? old : target;
28382
- }
28383
- function foldersPathOf(path, home = homedir5()) {
28384
- const places = placesOf2(home);
28385
- const whole2 = resolve2(fromHome(path, home));
28386
- const under = inside2(places.agents, whole2);
28387
- const old = under === void 0 ? void 0 : join8(places.oldAgents, under);
28388
- if (old !== void 0 && existsSync7(old) && !existsSync7(whole2)) return old;
28389
- return nowAt(whole2, places.oldAgents, places.agents);
28390
- }
28391
-
28392
- // src/keep.ts
28393
28750
  var flags = process.argv.slice(2);
28394
28751
  var words3 = flags.filter((word) => !word.startsWith("--"));
28395
28752
  var handsOver = flags.includes("--keep");
28753
+ var stopping = flags.includes("--stop");
28396
28754
  var whole = (word) => configTargetOf(word);
28397
28755
  var here = fileURLToPath2(new URL("..", import.meta.url)).replace(/\/$/, "");
28398
28756
  var self = fileURLToPath2(import.meta.url);
28399
28757
  var run = self.endsWith(".js") ? [self] : ["--import", "tsx", "src/main.ts"];
28400
- var again = process.env["npm_lifecycle_event"] === "keep" ? "npm run keep --" : basename3(process.argv[1] ?? "chips");
28758
+ var again = process.env["npm_lifecycle_event"] === "keep" ? "npm run keep --" : basename4(process.argv[1] ?? "chips");
28401
28759
  var stopLine = process.env["CHIPS_STOP_COMMAND"] || [again, ...words3, "--stop"].join(" ");
28402
28760
  var end = (line, code) => {
28403
28761
  (code === 0 ? process.stdout : process.stderr).write(`${line}
@@ -28439,123 +28797,9 @@ function keepIfAsked(label2, url2, names, log2, before = () => void 0) {
28439
28797
  }
28440
28798
 
28441
28799
  // src/move.ts
28442
- import { lstatSync, mkdirSync as mkdirSync4, readdirSync as readdirSync2, readFileSync as readFileSync9, renameSync as renameSync2, rmdirSync, writeFileSync as writeFileSync4 } from "node:fs";
28443
- import { homedir as homedir6 } from "node:os";
28444
- import { basename as basename5, dirname as dirname5, join as join10, resolve as resolve4 } from "node:path";
28445
-
28446
- // src/setup.ts
28447
- import { accessSync as accessSync2, constants as constants2, existsSync as existsSync8, readFileSync as readFileSync8 } from "node:fs";
28448
- import { basename as basename4, delimiter as delimiter2, isAbsolute as isAbsolute3, join as join9, resolve as resolve3 } from "node:path";
28449
- var SetupError = class extends Error {
28450
- constructor(message, words4 = {}) {
28451
- super(message);
28452
- this.words = words4;
28453
- }
28454
- words;
28455
- name = "SetupError";
28456
- };
28457
- var STILL_GOOD = "The link is still good: run the same command again once that's done.";
28458
- var EXAMPLE = '{ "name": "Claude Code", "command": ["claude-agent-acp"], "folders": "~/Chips/Agents/claude-code" }';
28459
- function readConfig(path) {
28460
- const known = knownConfig(basename4(path, ".json"));
28461
- if (!existsSync8(path) && known === void 0) {
28462
- throw new SetupError(
28463
- `There is no config at ${path}. Write ${EXAMPLE} there, or name claude-code.json or codex.json, which need none. ${STILL_GOOD}`
28464
- );
28465
- }
28466
- const raw = existsSync8(path) ? JSON.parse(readFileSync8(path, "utf8")) : known;
28467
- const name = raw["name"];
28468
- const command = raw["command"];
28469
- if (typeof name !== "string" || name.trim() === "" || !Array.isArray(command) || command.length === 0) {
28470
- throw new SetupError(`${path} names a kind of agent and how to run it: ${EXAMPLE}. ${STILL_GOOD}`);
28471
- }
28472
- const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
28473
- return {
28474
- name,
28475
- command: command.map(String),
28476
- folders: foldersPathOf(typeof raw["folders"] === "string" ? raw["folders"] : `~/Chips/Agents/${slug}`),
28477
- ...typeof raw["folder"] === "string" ? { folder: foldersPathOf(raw["folder"]) } : {},
28478
- ...typeof raw["mode"] === "string" ? { mode: raw["mode"] } : {},
28479
- ...typeof raw["env"] === "object" && raw["env"] !== null ? { env: raw["env"] } : {}
28480
- };
28481
- }
28482
- var runnable = (path) => {
28483
- try {
28484
- accessSync2(path, constants2.X_OK);
28485
- return true;
28486
- } catch {
28487
- return false;
28488
- }
28489
- };
28490
- function checkCommand(kind2, env2 = process.env) {
28491
- const [program] = kind2.command;
28492
- if (program === void 0) throw new SetupError(`${kind2.name} has no command to run. ${STILL_GOOD}`);
28493
- const path = { ...env2, ...kind2.env }["PATH"] ?? "";
28494
- const found = program.includes("/") ? runnable(isAbsolute3(program) ? program : resolve3(fromHome(program))) : path.split(delimiter2).some((dir) => dir !== "" && runnable(join9(dir, program)));
28495
- if (!found) {
28496
- throw new SetupError(
28497
- `${kind2.name}'s command, ${program}, isn't on this machine's PATH: ${installWords(kind2)}. ${STILL_GOOD}`,
28498
- notInstalledStop(kind2, program)
28499
- );
28500
- }
28501
- }
28502
- var MINUTE = 6e4;
28503
- function within2(promise2, ms, what) {
28504
- let timer;
28505
- const late = new Promise((_, reject) => {
28506
- timer = setTimeout(() => reject(new Error(what)), ms);
28507
- });
28508
- return Promise.race([promise2, late]).finally(() => clearTimeout(timer));
28509
- }
28510
- var wordsOf2 = (error62) => error62 instanceof Error ? error62.message : String(error62);
28511
- async function checkSignIn(kind2, wire, cwd, options = {}) {
28512
- let status;
28513
- let heard = () => {
28514
- };
28515
- const said = new Promise((resolve5) => {
28516
- heard = resolve5;
28517
- });
28518
- const client = new AcpClient(wire, {
28519
- update: () => void 0,
28520
- request: async (request) => {
28521
- throw notOffered(request.method);
28522
- },
28523
- exit: () => heard(),
28524
- auth: (now) => {
28525
- status = now;
28526
- heard();
28527
- }
28528
- });
28529
- try {
28530
- let info;
28531
- try {
28532
- info = await within2(client.initialize({ name: "chips-acp", version: VERSION }), MINUTE, "it didn't answer within a minute");
28533
- } catch (error62) {
28534
- const last = options.stderr?.().slice(-3).join(" ") ?? "";
28535
- throw new SetupError(`${kind2.name} didn't start: ${wordsOf2(error62)}.${last === "" ? "" : ` It said: ${last}`} ${STILL_GOOD}`, {
28536
- detail: "Its ACP adapter didn't start",
28537
- says: `${kind2.name} didn't start: ${wordsOf2(error62)}.`,
28538
- ...last === "" ? {} : { doing: `It said: ${last}` }
28539
- });
28540
- }
28541
- try {
28542
- const { sessionId } = await within2(client.newSession(cwd), MINUTE, "it didn't answer within a minute");
28543
- if (info.closeSession) await client.closeSession(sessionId).catch(() => void 0);
28544
- } catch (error62) {
28545
- if (isAuthRequired(error62)) throw new SetupError(`${signedOutWords(kind2, info)} ${STILL_GOOD}`, signedOutStop(kind2));
28546
- throw new SetupError(`${kind2.name} couldn't open a session: ${wordsOf2(error62)}. ${STILL_GOOD}`, {
28547
- detail: "It couldn't open a session",
28548
- says: `${kind2.name} couldn't open a session: ${wordsOf2(error62)}.`
28549
- });
28550
- }
28551
- if (info.reportsAuth && status === void 0) await within2(said, options.waitMs ?? 6e3, "").catch(() => void 0);
28552
- if (status?.kind === "none") throw new SetupError(`${signedOutWords(kind2, info)} ${STILL_GOOD}`, signedOutStop(kind2));
28553
- } finally {
28554
- client.close();
28555
- }
28556
- }
28557
-
28558
- // src/move.ts
28800
+ import { lstatSync, mkdirSync as mkdirSync5, readdirSync as readdirSync2, readFileSync as readFileSync9, renameSync as renameSync2, rmdirSync, writeFileSync as writeFileSync4 } from "node:fs";
28801
+ import { homedir as homedir7 } from "node:os";
28802
+ import { basename as basename5, dirname as dirname6, join as join11, resolve as resolve4 } from "node:path";
28559
28803
  var there = (path) => {
28560
28804
  try {
28561
28805
  lstatSync(path);
@@ -28566,11 +28810,11 @@ var there = (path) => {
28566
28810
  };
28567
28811
  var isFolder = (path) => lstatSync(path).isDirectory();
28568
28812
  var shown = (path, home) => path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
28569
- function merge2(from, to, log2, home = homedir6(), quiet = false) {
28813
+ function merge2(from, to, log2, home = homedir7(), quiet = false) {
28570
28814
  if (!there(from)) return;
28571
28815
  try {
28572
28816
  if (!there(to)) {
28573
- mkdirSync4(dirname5(to), { recursive: true });
28817
+ mkdirSync5(dirname6(to), { recursive: true });
28574
28818
  renameSync2(from, to);
28575
28819
  if (!quiet) log2(`moved ${shown(from, home)} to ${shown(to, home)}`);
28576
28820
  return;
@@ -28579,7 +28823,7 @@ function merge2(from, to, log2, home = homedir6(), quiet = false) {
28579
28823
  log2(`${shown(from, home)} was left where it is: ${shown(to, home)} is there already`);
28580
28824
  return;
28581
28825
  }
28582
- for (const entry of readdirSync2(from)) merge2(join10(from, entry), join10(to, entry), log2, home, true);
28826
+ for (const entry of readdirSync2(from)) merge2(join11(from, entry), join11(to, entry), log2, home, true);
28583
28827
  if (readdirSync2(from).length === 0) rmdirSync(from);
28584
28828
  if (!quiet) log2(`moved what was in ${shown(from, home)} into ${shown(to, home)}`);
28585
28829
  } catch (error62) {
@@ -28592,16 +28836,16 @@ function removeIfEmpty(path) {
28592
28836
  } catch {
28593
28837
  }
28594
28838
  }
28595
- function claudeStoreOf(folder2, env2, home = homedir6()) {
28839
+ function claudeStoreOf(folder2, env2, home = homedir7()) {
28596
28840
  const name = folder2.replace(/[^a-zA-Z0-9]/g, "-");
28597
28841
  if (name.length > 200) return void 0;
28598
- return join10(env2["CLAUDE_CONFIG_DIR"] ? resolve4(fromHome(env2["CLAUDE_CONFIG_DIR"], home)) : join10(home, ".claude"), "projects", name);
28842
+ return join11(env2["CLAUDE_CONFIG_DIR"] ? resolve4(fromHome(env2["CLAUDE_CONFIG_DIR"], home)) : join11(home, ".claude"), "projects", name);
28599
28843
  }
28600
28844
  function pairOf(path, places) {
28601
28845
  const old = inside2(places.oldAgents, path);
28602
- if (old !== void 0) return { old: path, now: join10(places.agents, old) };
28846
+ if (old !== void 0) return { old: path, now: join11(places.agents, old) };
28603
28847
  const now = inside2(places.agents, path);
28604
- return now === void 0 ? void 0 : { old: join10(places.oldAgents, now), now: path };
28848
+ return now === void 0 ? void 0 : { old: join11(places.oldAgents, now), now: path };
28605
28849
  }
28606
28850
  function writeJson(path, value) {
28607
28851
  const next = `${path}.next`;
@@ -28617,15 +28861,15 @@ var readJson = (path) => {
28617
28861
  return void 0;
28618
28862
  }
28619
28863
  };
28620
- function moveOld(configPath2, log2, home = homedir6(), env2 = process.env) {
28621
- const places = placesOf2(home);
28622
- const keptIn = join10(dirname5(configPath2), basename5(configPath2, ".json"));
28864
+ function moveOld(configPath2, log2, home = homedir7(), env2 = process.env) {
28865
+ const places = placesOf(home);
28866
+ const keptIn = join11(dirname6(configPath2), basename5(configPath2, ".json"));
28623
28867
  const name = inside2(places.settings, configPath2);
28624
28868
  if (name !== void 0) {
28625
- mkdirSync4(dirname5(dirname5(places.settings)), { recursive: true });
28626
- mkdirSync4(places.settings, { recursive: true, mode: 448 });
28627
- merge2(join10(places.oldSettings, name), configPath2, log2, home);
28628
- merge2(join10(places.oldSettings, name.replace(/\.json$/, "")), keptIn, log2, home);
28869
+ mkdirSync5(dirname6(dirname6(places.settings)), { recursive: true });
28870
+ mkdirSync5(places.settings, { recursive: true, mode: 448 });
28871
+ merge2(join11(places.oldSettings, name), configPath2, log2, home);
28872
+ merge2(join11(places.oldSettings, name.replace(/\.json$/, "")), keptIn, log2, home);
28629
28873
  }
28630
28874
  let roots;
28631
28875
  let kindEnv;
@@ -28652,7 +28896,7 @@ function moveOld(configPath2, log2, home = homedir6(), env2 = process.env) {
28652
28896
  }
28653
28897
  if (changed) writeJson(configPath2, config2);
28654
28898
  }
28655
- const statePath2 = join10(keptIn, "state.json");
28899
+ const statePath2 = join11(keptIn, "state.json");
28656
28900
  const state2 = readJson(statePath2);
28657
28901
  const agents = state2?.["agents"];
28658
28902
  if (state2 !== void 0 && typeof agents === "object" && agents !== null) {
@@ -28672,7 +28916,7 @@ function moveOld(configPath2, log2, home = homedir6(), env2 = process.env) {
28672
28916
  if (there(old) || !there(now)) continue;
28673
28917
  const folders = [{ old, now }];
28674
28918
  for (const entry of readdirSync2(now)) {
28675
- if (isFolder(join10(now, entry))) folders.push({ old: join10(old, entry), now: join10(now, entry) });
28919
+ if (isFolder(join11(now, entry))) folders.push({ old: join11(old, entry), now: join11(now, entry) });
28676
28920
  }
28677
28921
  for (const folder2 of folders) {
28678
28922
  const from = claudeStoreOf(folder2.old, storeEnv, home);
@@ -28687,6 +28931,7 @@ function moveOld(configPath2, log2, home = homedir6(), env2 = process.env) {
28687
28931
  // src/main.ts
28688
28932
  var link = process.env["CHIPS_JOIN_LINK"] || void 0;
28689
28933
  var LABEL = `chat.chips.acp.${basename6(configTargetOf(words3[0]), ".json")}`;
28934
+ if (stopping) forgetAdapter(basename6(configTargetOf(words3[0]), ".json"));
28690
28935
  stopIfAsked(LABEL);
28691
28936
  var log = (line) => process.stdout.write(`${(/* @__PURE__ */ new Date()).toISOString()} ${line}
28692
28937
  `);
@@ -28694,10 +28939,11 @@ if (!handsOver) moveOld(configTargetOf(words3[0]), log);
28694
28939
  var configPath = configPathOf(words3[0]);
28695
28940
  var kind;
28696
28941
  try {
28697
- kind = readConfig(configPath);
28698
- mkdirSync5(kind.folder ?? kind.folders, { recursive: true });
28942
+ kind = withFetchedAdapter(readConfig(configPath));
28943
+ mkdirSync6(kind.folder ?? kind.folders, { recursive: true });
28699
28944
  if (link !== void 0) {
28700
- reportStep("checking", { detail: `Starting ${kind.name}'s ACP adapter` });
28945
+ reportStep("checking", { detail: `Looking for ${kind.name}` });
28946
+ kind = await readyAdapter(kind, { say: (detail) => reportStep("checking", { detail }) });
28701
28947
  checkCommand(kind);
28702
28948
  log(`checking that ${kind.name} starts and is signed in`);
28703
28949
  const cwd = kind.folder ?? kind.folders;
@@ -28713,9 +28959,9 @@ try {
28713
28959
  `);
28714
28960
  process.exit(1);
28715
28961
  }
28716
- var folder = join11(dirname6(configPath), basename6(configPath, ".json"));
28717
- var statePath = join11(folder, "state.json");
28718
- mkdirSync5(folder, { recursive: true, mode: 448 });
28962
+ var folder = join12(dirname7(configPath), basename6(configPath, ".json"));
28963
+ var statePath = join12(folder, "state.json");
28964
+ mkdirSync6(folder, { recursive: true, mode: 448 });
28719
28965
  var refused2 = (error62) => {
28720
28966
  if (!(error62 instanceof JoinError)) throw error62;
28721
28967
  process.stderr.write(`${error62.message}
@@ -28754,7 +29000,7 @@ var chips = await connect({
28754
29000
  url: joined.url,
28755
29001
  token: joined.token,
28756
29002
  client: { name: "chips-acp", version: VERSION },
28757
- store: fileStore(join11(folder, "chips-state.json")),
29003
+ store: fileStore(join12(folder, "chips-state.json")),
28758
29004
  onRestart: async () => {
28759
29005
  log("a person asked for a restart");
28760
29006
  await bridge?.restart();
@@ -28781,7 +29027,10 @@ await bridge.start();
28781
29027
  log(`connected as ${chips.harnessId} (${kind.name}), ${Object.keys(state.agents).length} agent(s)`);
28782
29028
  await helloOnce(joined, {
28783
29029
  name: kind.name,
28784
- say: (spaceId) => chips.post({ spaceId, text: `Hi, ${kind.name} here, through chips-acp. Make me an agent from any space, or ask me here.` })
29030
+ say: (spaceId) => (
29031
+ // In the shape every bridge's hello has: "Hi, I'm …", then what to do (the onboarding audit, item 39).
29032
+ chips.post({ spaceId, text: `Hi, I'm ${kind.name}. Ask me anything here, or make me an agent from any space.` })
29033
+ )
28785
29034
  }).catch((error62) => log(`hello not said: ${String(error62)}`));
28786
29035
  var stop = () => {
28787
29036
  bridge?.stop();