@harness-sdk/harnessd 0.0.1 → 0.0.2

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.
Files changed (66) hide show
  1. package/README.md +14 -13
  2. package/dist/accounts.d.ts +66 -0
  3. package/dist/accounts.d.ts.map +1 -0
  4. package/dist/accounts.js +166 -0
  5. package/dist/accounts.js.map +1 -0
  6. package/dist/bin.js +4 -0
  7. package/dist/bin.js.map +1 -1
  8. package/dist/channel.js +1 -1
  9. package/dist/claude.d.ts +12 -13
  10. package/dist/claude.d.ts.map +1 -1
  11. package/dist/claude.js +45 -59
  12. package/dist/claude.js.map +1 -1
  13. package/dist/cli.d.ts +5 -0
  14. package/dist/cli.d.ts.map +1 -1
  15. package/dist/cli.js +269 -114
  16. package/dist/cli.js.map +1 -1
  17. package/dist/config.d.ts +14 -1
  18. package/dist/config.d.ts.map +1 -1
  19. package/dist/config.js +53 -13
  20. package/dist/config.js.map +1 -1
  21. package/dist/daemon.d.ts +17 -4
  22. package/dist/daemon.d.ts.map +1 -1
  23. package/dist/daemon.js +112 -51
  24. package/dist/daemon.js.map +1 -1
  25. package/dist/launchd.d.ts +12 -16
  26. package/dist/launchd.d.ts.map +1 -1
  27. package/dist/launchd.js +28 -25
  28. package/dist/launchd.js.map +1 -1
  29. package/dist/prompts.d.ts +53 -0
  30. package/dist/prompts.d.ts.map +1 -0
  31. package/dist/prompts.js +171 -0
  32. package/dist/prompts.js.map +1 -0
  33. package/dist/service.d.ts +37 -0
  34. package/dist/service.d.ts.map +1 -0
  35. package/dist/service.js +71 -0
  36. package/dist/service.js.map +1 -0
  37. package/dist/setup.d.ts +37 -0
  38. package/dist/setup.d.ts.map +1 -0
  39. package/dist/setup.js +121 -0
  40. package/dist/setup.js.map +1 -0
  41. package/dist/system.d.ts +6 -0
  42. package/dist/system.d.ts.map +1 -0
  43. package/dist/system.js +16 -0
  44. package/dist/system.js.map +1 -0
  45. package/dist/systemd.d.ts +14 -0
  46. package/dist/systemd.d.ts.map +1 -0
  47. package/dist/systemd.js +62 -0
  48. package/dist/systemd.js.map +1 -0
  49. package/dist/watchdog.d.ts +14 -4
  50. package/dist/watchdog.d.ts.map +1 -1
  51. package/dist/watchdog.js +30 -24
  52. package/dist/watchdog.js.map +1 -1
  53. package/package.json +5 -3
  54. package/src/accounts.ts +242 -0
  55. package/src/bin.ts +6 -0
  56. package/src/claude.ts +65 -90
  57. package/src/cli.ts +413 -152
  58. package/src/config.ts +92 -14
  59. package/src/daemon.ts +131 -64
  60. package/src/launchd.ts +40 -35
  61. package/src/prompts.ts +255 -0
  62. package/src/service.ts +145 -0
  63. package/src/setup.ts +188 -0
  64. package/src/system.ts +11 -0
  65. package/src/systemd.ts +78 -0
  66. package/src/watchdog.ts +41 -33
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # harnessd
2
2
 
3
- harnessd keeps Claude Code running on your Mac, day and night, connected to the events of your agentic apps. Put it on a Mac mini and you have an agent that's always on.
3
+ harnessd keeps Claude Code running on your Mac or Linux machine, day and night, connected to the events of your agentic apps. Put it on a Mac mini and you have an agent that's always on.
4
4
 
5
5
  - It starts at login and after any crash, and picks up the same conversation.
6
6
  - Each agentic app you connect is a channel. Its events reach the agent as they happen, and its tools let the agent answer.
@@ -10,19 +10,19 @@ harnessd keeps Claude Code running on your Mac, day and night, connected to the
10
10
 
11
11
  ```sh
12
12
  npm install -g @harness-sdk/harnessd
13
- harnessd install
13
+ harnessd service install
14
14
  harnessd attach
15
15
  ```
16
16
 
17
- `harnessd attach` opens Claude Code's terminal. If Claude Code isn't signed in on this Mac yet, sign in there, then detach with Ctrl-\\. Claude Code keeps running.
17
+ `harnessd service install` checks that Claude Code is installed and signed in. If it isn't, it asks whether to install it with Anthropic's installer, and whether to sign in now. `harnessd attach` opens Claude Code's terminal; Ctrl-\\ detaches, and Claude Code keeps running.
18
18
 
19
- The agent works in `~/agent`, which harnessd marks as trusted in Claude Code. Its standing instructions go in `~/agent/CLAUDE.md`, the file Claude Code already reads. Permission prompts are skipped, since nobody is there to answer them, so give the agent a Mac of its own.
19
+ The agent works in `~/agent`, which harnessd marks as trusted in Claude Code. Its standing instructions go in `~/agent/CLAUDE.md`, the file Claude Code already reads. Claude Code runs in its auto permission mode, which decides each action itself. To turn permission prompts off instead, add `"args": ["--dangerously-skip-permissions"]` to the config file, and give the agent a machine of its own.
20
20
 
21
- Turn on automatic login (System Settings, Users & Groups), so the agent comes back after a power cut.
21
+ harnessd starts when you log in. On a Mac, turn on automatic login (System Settings, Users & Groups), so the agent comes back after a power cut. Or install it with `sudo harnessd service install`: it then starts at boot, with nobody logged in, and still runs as your user. Linux needs systemd, on x64 or arm64.
22
22
 
23
23
  ## Connect a channel
24
24
 
25
- A channel is an MCP server that serves events, such as a [Statewire](https://www.npmjs.com/package/statewire) host. Name it in `~/.harnessd/config.json`:
25
+ A channel is an MCP server that serves events, such as a [Statewire](https://www.npmjs.com/package/statewire) host. Name it in `~/.config/harnessd/config.json`:
26
26
 
27
27
  ```json
28
28
  {
@@ -38,7 +38,7 @@ A channel is an MCP server that serves events, such as a [Statewire](https://www
38
38
 
39
39
  Each event reaches the conversation as `<channel source="plugin:harnessd:board" event="…">…</channel>`, and the server's tools sit beside it. If the agent restarts, the events it missed come when it's back.
40
40
 
41
- Claude Code lets a channel in only when the Mac's managed settings list it. `harnessd install` offers to add harnessd there, and `harnessd status` shows whether each channel's events arrive.
41
+ harnessd loads its channels with Claude Code's flag for local channels and answers its start-up warning. `harnessd status` shows whether each channel's events arrive, and says so when managed settings turn channels off.
42
42
 
43
43
  ## The config file
44
44
 
@@ -49,6 +49,7 @@ Claude Code lets a channel in only when the Mac's managed settings list it. `har
49
49
  | `env` | More environment for `claude`. |
50
50
  | `prestart` | A shell command run before each start. It prints `{ "env": {…}, "args": […] }` for that start, so a token is fetched fresh and never kept on disk. |
51
51
  | `channels` | MCP servers by name: a `url` (https, or http on this Mac), `headers` that read `${VAR}` from the environment, and `arguments` for event types that ask for them. |
52
+ | `accounts` | Claude accounts by name, each with the `env` that signs it in, such as a `claude setup-token` token in `CLAUDE_CODE_OAUTH_TOKEN`. When the one in use hits its usage limit or its sign-in fails, Claude Code goes on with the next, in the same conversation. |
52
53
 
53
54
  A change takes effect at the next start: `harnessd stop`, then `harnessd start`.
54
55
 
@@ -56,9 +57,9 @@ A change takes effect at the next start: `harnessd stop`, then `harnessd start`.
56
57
 
57
58
  | Command | What it does |
58
59
  | --- | --- |
59
- | `harnessd status` | What runs, which conversation, and whether events arrive. `--json` for scripts. |
60
- | `harnessd attach` | Claude Code's terminal. |
61
- | `harnessd new "<message>"` | A new conversation that opens with your message, such as a handoff from a long one. |
62
- | `harnessd stop`, `harnessd start` | Stop Claude Code until you start it again. |
63
- | `harnessd logs` | Follow harnessd's log. |
64
- | `harnessd uninstall` | Stop harnessd and remove it from login. Your settings and conversation stay. |
60
+ | `harnessd service install` | Start harnessd now and at every login. With `sudo`: at every boot, as your user (`--user <name>` for another). Run it again after an upgrade. |
61
+ | `harnessd service uninstall` | Stop harnessd and remove its service (with `sudo` for a boot service). Your settings and conversation stay. |
62
+ | `harnessd status` | What runs, which conversation, whether events arrive, and the log's last lines and path. `--json` for scripts. |
63
+ | `harnessd attach` | Claude Code's terminal. `/clear` there starts a new conversation, and restarts resume that one. |
64
+ | `harnessd stop`, `harnessd start` | Stop Claude Code until you start it again. harnessd itself stays up and answers `status`. |
65
+ | `harnessd --version` | harnessd's version. |
@@ -0,0 +1,66 @@
1
+ export declare namespace Accounts {
2
+ /** Why Claude Code can't go on with the account it runs on. */
3
+ type Stop = {
4
+ readonly why: "its usage limit" | "a failed sign-in";
5
+ /** When the account is worth another try (epoch ms). */
6
+ readonly until: number;
7
+ };
8
+ /** An account harnessd passes over, for now. */
9
+ type Mark = Stop & {
10
+ /** The account's environment when it stopped: a changed one (a new token) is tried again. */
11
+ readonly env: string;
12
+ };
13
+ type Options = {
14
+ /** The config's accounts, in its order. */
15
+ readonly accounts: () => Readonly<Record<string, Readonly<Record<string, string>>>>;
16
+ readonly now?: () => number;
17
+ };
18
+ type Rotation = {
19
+ /** The account the next start runs on: `current` while it can go on, else the first that can. All stopped: `current`. */
20
+ readonly pick: (current: string | undefined) => string | undefined;
21
+ readonly mark: (name: string, stop: Stop) => void;
22
+ /** The accounts passed over now. */
23
+ readonly marks: () => Readonly<Record<string, Stop>>;
24
+ };
25
+ }
26
+ /** Whether a line of Claude Code's transcript says the account can't go on: a usage limit, or a sign-in the API refused. */
27
+ export declare const accountStop: (entry: unknown, now?: number) => Accounts.Stop | undefined;
28
+ /** Which of the config's accounts Claude Code runs on, and which it passes over until they can go on again. */
29
+ export declare const rotation: (options: Accounts.Options) => Accounts.Rotation;
30
+ /**
31
+ * Calls `onEntry` with each line the conversation's transcript gains from now on; `file` says where it is once Claude
32
+ * Code has written it. When Claude Code moves to another conversation, its transcript is followed from then on.
33
+ */
34
+ export declare const followTranscript: (o: {
35
+ sessionId: () => string;
36
+ file: (sessionId: string) => string | undefined;
37
+ onEntry: (entry: unknown) => void;
38
+ /** After each look at the transcript, whether it gained lines or not. */
39
+ onRead?: () => void;
40
+ everyMs?: number;
41
+ }) => {
42
+ /** Reads what the transcript gained since the last look, then stops looking. */
43
+ finish: () => void;
44
+ };
45
+ /**
46
+ * One start of Claude Code on `account`, watched from before the start to after the exit: when the account stops and
47
+ * another can go on, Claude Code hands over to it in the same conversation.
48
+ */
49
+ export declare const accountRun: (o: {
50
+ account: string;
51
+ rotation: Accounts.Rotation;
52
+ /** The conversation Claude Code is in. */
53
+ sessionId: () => string;
54
+ /** Where a conversation's transcript is, once Claude Code has written it. */
55
+ file: (sessionId: string) => string | undefined;
56
+ /** Restarts the start with this pid, telling the conversation why. */
57
+ restart: (reason: string, pid: number) => void;
58
+ log: (line: string) => void;
59
+ everyMs?: number;
60
+ }) => {
61
+ /** Claude Code runs. */
62
+ started: (startedPid: number) => undefined;
63
+ /** Claude Code exited, or never started: reads the transcript's last lines. A reason: the next start goes on with another account, and is told this. */
64
+ exited: () => string | undefined;
65
+ };
66
+ //# sourceMappingURL=accounts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accounts.d.ts","sourceRoot":"","sources":["../src/accounts.ts"],"names":[],"mappings":"AAEA,yBAAiB,QAAQ,CAAC;IACxB,+DAA+D;IAC/D,KAAY,IAAI,GAAG;QACjB,QAAQ,CAAC,GAAG,EAAE,iBAAiB,GAAG,kBAAkB,CAAC;QACrD,wDAAwD;QACxD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;KACxB,CAAC;IAEF,gDAAgD;IAChD,KAAY,IAAI,GAAG,IAAI,GAAG;QACxB,6FAA6F;QAC7F,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;KACtB,CAAC;IAEF,KAAY,OAAO,GAAG;QACpB,2CAA2C;QAC3C,QAAQ,CAAC,QAAQ,EAAE,MAAM,QAAQ,CAC/B,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CACjD,CAAC;QACF,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;KAC7B,CAAC;IAEF,KAAY,QAAQ,GAAG;QACrB,yHAAyH;QACzH,QAAQ,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,KAAK,MAAM,GAAG,SAAS,CAAC;QACnE,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,KAAK,IAAI,CAAC;QAClD,oCAAoC;QACpC,QAAQ,CAAC,KAAK,EAAE,MAAM,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;KACtD,CAAC;CACH;AAKD,4HAA4H;AAC5H,eAAO,MAAM,WAAW,GACtB,OAAO,OAAO,EACd,YAAgB,KACf,QAAQ,CAAC,IAAI,GAAG,SA2BlB,CAAC;AAEF,+GAA+G;AAC/G,eAAO,MAAM,QAAQ,GAAI,SAAS,QAAQ,CAAC,OAAO,KAAG,QAAQ,CAAC,QAyC7D,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,GAAI,GAAG;IAClC,SAAS,EAAE,MAAM,MAAM,CAAC;IACxB,IAAI,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;IAChD,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IAClC,yEAAyE;IACzE,MAAM,CAAC,EAAE,MAAM,IAAI,CAAC;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;IAsDG,gFAAgF;;CAMnF,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,UAAU,GAAI,GAAG;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC;IAC5B,0CAA0C;IAC1C,SAAS,EAAE,MAAM,MAAM,CAAC;IACxB,6EAA6E;IAC7E,IAAI,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;IAChD,sEAAsE;IACtE,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAC/C,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC5B,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;IA+BG,wBAAwB;0BACF,MAAM;IAC5B,wJAAwJ;;CAO3J,CAAC"}
@@ -0,0 +1,166 @@
1
+ import { closeSync, fstatSync, openSync, readSync } from "node:fs";
2
+ // src/accounts.ts
3
+ const LIMIT_MS = 18e6;
4
+ const SIGN_IN_MS = 864e5;
5
+ /** Whether a line of Claude Code's transcript says the account can't go on: a usage limit, or a sign-in the API refused. */
6
+ const accountStop = (entry, now = Date.now()) => {
7
+ if (typeof entry !== "object" || entry === null) return void 0;
8
+ const e = entry;
9
+ if (e.type !== "assistant" || e.isApiErrorMessage !== true) return void 0;
10
+ if (e.error === "authentication_failed") return {
11
+ why: "a failed sign-in",
12
+ until: now + SIGN_IN_MS
13
+ };
14
+ if (e.error !== "rate_limit" || e.apiErrorStatus !== 429 || e.apiErrorIsTransient === true) return void 0;
15
+ const resetsAt = e.quotaLimits?.resetsAt;
16
+ return {
17
+ why: "its usage limit",
18
+ until: typeof resetsAt === "number" && resetsAt * 1e3 > now ? resetsAt * 1e3 : now + LIMIT_MS
19
+ };
20
+ };
21
+ /** Which of the config's accounts Claude Code runs on, and which it passes over until they can go on again. */
22
+ const rotation = (options) => {
23
+ const now = options.now ?? Date.now;
24
+ const marked = /* @__PURE__ */ new Map();
25
+ const stopped = (name, env) => {
26
+ const mark = marked.get(name);
27
+ if (!mark) return false;
28
+ if (mark.until > now() && mark.env === JSON.stringify(env)) return true;
29
+ marked.delete(name);
30
+ return false;
31
+ };
32
+ const open = () => Object.entries(options.accounts()).filter(([name, env]) => !stopped(name, env)).map(([name]) => name);
33
+ return {
34
+ pick: (current) => {
35
+ const accounts = options.accounts();
36
+ const names = Object.keys(accounts);
37
+ const free = open();
38
+ if (current !== void 0 && free.includes(current)) return current;
39
+ return free[0] ?? (current !== void 0 && current in accounts ? current : names[0]);
40
+ },
41
+ mark: (name, stop) => {
42
+ const env = options.accounts()[name];
43
+ if (env) marked.set(name, {
44
+ ...stop,
45
+ env: JSON.stringify(env)
46
+ });
47
+ },
48
+ marks: () => {
49
+ const accounts = options.accounts();
50
+ for (const name of marked.keys()) if (!(name in accounts)) marked.delete(name);
51
+ const free = new Set(open());
52
+ return Object.fromEntries([...marked].filter(([name]) => !free.has(name)).map(([name, { why, until }]) => [name, {
53
+ why,
54
+ until
55
+ }]));
56
+ }
57
+ };
58
+ };
59
+ /**
60
+ * Calls `onEntry` with each line the conversation's transcript gains from now on; `file` says where it is once Claude
61
+ * Code has written it. When Claude Code moves to another conversation, its transcript is followed from then on.
62
+ */
63
+ const followTranscript = (o) => {
64
+ let sessionId;
65
+ let path;
66
+ let offset;
67
+ let rest = "";
68
+ const read = () => {
69
+ if (o.sessionId() !== sessionId) {
70
+ sessionId = o.sessionId();
71
+ path = void 0;
72
+ offset = void 0;
73
+ rest = "";
74
+ }
75
+ path ??= o.file(sessionId);
76
+ if (path === void 0) {
77
+ offset = 0;
78
+ return;
79
+ }
80
+ let fd;
81
+ try {
82
+ fd = openSync(path, "r");
83
+ } catch {
84
+ return;
85
+ }
86
+ try {
87
+ const { size } = fstatSync(fd);
88
+ offset ??= size;
89
+ if (size <= offset) return;
90
+ const chunk = Buffer.alloc(size - offset);
91
+ readSync(fd, chunk, 0, chunk.length, offset);
92
+ offset = size;
93
+ const lines = (rest + chunk.toString("utf8")).split("\n");
94
+ rest = lines.pop() ?? "";
95
+ for (const line of lines) {
96
+ if (!line.trim()) continue;
97
+ let entry;
98
+ try {
99
+ entry = JSON.parse(line);
100
+ } catch {
101
+ continue;
102
+ }
103
+ o.onEntry(entry);
104
+ }
105
+ } finally {
106
+ closeSync(fd);
107
+ }
108
+ };
109
+ const look = () => {
110
+ read();
111
+ o.onRead?.();
112
+ };
113
+ look();
114
+ const timer = setInterval(look, o.everyMs ?? 1e4);
115
+ return {
116
+ /** Reads what the transcript gained since the last look, then stops looking. */
117
+ finish: () => {
118
+ clearInterval(timer);
119
+ read();
120
+ } };
121
+ };
122
+ /**
123
+ * One start of Claude Code on `account`, watched from before the start to after the exit: when the account stops and
124
+ * another can go on, Claude Code hands over to it in the same conversation.
125
+ */
126
+ const accountRun = (o) => {
127
+ let pid;
128
+ let handed = false;
129
+ const handover = () => {
130
+ const why = o.rotation.marks()[o.account]?.why;
131
+ const next = o.rotation.pick(o.account);
132
+ if (handed || !why || next === void 0 || next === o.account) return void 0;
133
+ handed = true;
134
+ o.log(`switching from account ${o.account} to ${next}`);
135
+ return `account ${o.account} stopped at ${why}, so Claude Code now runs on account ${next}`;
136
+ };
137
+ const follow = followTranscript({
138
+ sessionId: o.sessionId,
139
+ file: o.file,
140
+ onEntry: (entry) => {
141
+ const stop = accountStop(entry);
142
+ if (!stop) return;
143
+ if (!(o.account in o.rotation.marks())) o.log(`account ${o.account} stopped at ${stop.why}`);
144
+ o.rotation.mark(o.account, stop);
145
+ },
146
+ onRead: () => {
147
+ if (pid === void 0) return;
148
+ const reason = handover();
149
+ if (reason !== void 0) o.restart(reason, pid);
150
+ },
151
+ ...o.everyMs !== void 0 && { everyMs: o.everyMs }
152
+ });
153
+ return {
154
+ /** Claude Code runs. */
155
+ started: (startedPid) => void (pid = startedPid),
156
+ /** Claude Code exited, or never started: reads the transcript's last lines. A reason: the next start goes on with another account, and is told this. */
157
+ exited: () => {
158
+ pid = void 0;
159
+ follow.finish();
160
+ return handover();
161
+ }
162
+ };
163
+ };
164
+ export { accountRun, accountStop, followTranscript, rotation };
165
+
166
+ //# sourceMappingURL=accounts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accounts.js","names":[],"sources":["../src/accounts.ts"],"sourcesContent":["import { closeSync, fstatSync, openSync, readSync } from \"node:fs\";\n\nexport namespace Accounts {\n /** Why Claude Code can't go on with the account it runs on. */\n export type Stop = {\n readonly why: \"its usage limit\" | \"a failed sign-in\";\n /** When the account is worth another try (epoch ms). */\n readonly until: number;\n };\n\n /** An account harnessd passes over, for now. */\n export type Mark = Stop & {\n /** The account's environment when it stopped: a changed one (a new token) is tried again. */\n readonly env: string;\n };\n\n export type Options = {\n /** The config's accounts, in its order. */\n readonly accounts: () => Readonly<\n Record<string, Readonly<Record<string, string>>>\n >;\n readonly now?: () => number;\n };\n\n export type Rotation = {\n /** The account the next start runs on: `current` while it can go on, else the first that can. All stopped: `current`. */\n readonly pick: (current: string | undefined) => string | undefined;\n readonly mark: (name: string, stop: Stop) => void;\n /** The accounts passed over now. */\n readonly marks: () => Readonly<Record<string, Stop>>;\n };\n}\n\nconst LIMIT_MS = 5 * 60 * 60_000;\nconst SIGN_IN_MS = 24 * 60 * 60_000;\n\n/** Whether a line of Claude Code's transcript says the account can't go on: a usage limit, or a sign-in the API refused. */\nexport const accountStop = (\n entry: unknown,\n now = Date.now(),\n): Accounts.Stop | undefined => {\n if (typeof entry !== \"object\" || entry === null) return undefined;\n const e = entry as {\n type?: unknown;\n isApiErrorMessage?: unknown;\n error?: unknown;\n apiErrorStatus?: unknown;\n apiErrorIsTransient?: unknown;\n quotaLimits?: { resetsAt?: unknown };\n };\n if (e.type !== \"assistant\" || e.isApiErrorMessage !== true) return undefined;\n if (e.error === \"authentication_failed\")\n return { why: \"a failed sign-in\", until: now + SIGN_IN_MS };\n if (\n e.error !== \"rate_limit\" ||\n e.apiErrorStatus !== 429 ||\n e.apiErrorIsTransient === true\n )\n return undefined;\n const resetsAt = e.quotaLimits?.resetsAt;\n return {\n why: \"its usage limit\",\n until:\n typeof resetsAt === \"number\" && resetsAt * 1000 > now\n ? resetsAt * 1000\n : now + LIMIT_MS,\n };\n};\n\n/** Which of the config's accounts Claude Code runs on, and which it passes over until they can go on again. */\nexport const rotation = (options: Accounts.Options): Accounts.Rotation => {\n const now = options.now ?? Date.now;\n const marked = new Map<string, Accounts.Mark>();\n const stopped = (name: string, env: Readonly<Record<string, string>>) => {\n const mark = marked.get(name);\n if (!mark) return false;\n if (mark.until > now() && mark.env === JSON.stringify(env)) return true;\n marked.delete(name);\n return false;\n };\n const open = () =>\n Object.entries(options.accounts())\n .filter(([name, env]) => !stopped(name, env))\n .map(([name]) => name);\n return {\n pick: (current) => {\n const accounts = options.accounts();\n const names = Object.keys(accounts);\n const free = open();\n if (current !== undefined && free.includes(current)) return current;\n return (\n free[0] ??\n (current !== undefined && current in accounts ? current : names[0])\n );\n },\n mark: (name, stop) => {\n const env = options.accounts()[name];\n if (env) marked.set(name, { ...stop, env: JSON.stringify(env) });\n },\n marks: () => {\n const accounts = options.accounts();\n for (const name of marked.keys())\n if (!(name in accounts)) marked.delete(name);\n const free = new Set(open());\n return Object.fromEntries(\n [...marked]\n .filter(([name]) => !free.has(name))\n .map(([name, { why, until }]) => [name, { why, until }]),\n );\n },\n };\n};\n\n/**\n * Calls `onEntry` with each line the conversation's transcript gains from now on; `file` says where it is once Claude\n * Code has written it. When Claude Code moves to another conversation, its transcript is followed from then on.\n */\nexport const followTranscript = (o: {\n sessionId: () => string;\n file: (sessionId: string) => string | undefined;\n onEntry: (entry: unknown) => void;\n /** After each look at the transcript, whether it gained lines or not. */\n onRead?: () => void;\n everyMs?: number;\n}) => {\n let sessionId: string | undefined;\n let path: string | undefined;\n let offset: number | undefined;\n let rest = \"\";\n const read = () => {\n if (o.sessionId() !== sessionId) {\n sessionId = o.sessionId();\n path = undefined;\n offset = undefined;\n rest = \"\";\n }\n path ??= o.file(sessionId);\n if (path === undefined) {\n // a transcript that appears after the start, or after a move to another conversation, is read from its first line\n offset = 0;\n return;\n }\n let fd: number;\n try {\n fd = openSync(path, \"r\");\n } catch {\n return;\n }\n try {\n const { size } = fstatSync(fd);\n offset ??= size;\n if (size <= offset) return;\n const chunk = Buffer.alloc(size - offset);\n readSync(fd, chunk, 0, chunk.length, offset);\n offset = size;\n const lines = (rest + chunk.toString(\"utf8\")).split(\"\\n\");\n rest = lines.pop() ?? \"\";\n for (const line of lines) {\n if (!line.trim()) continue;\n let entry: unknown;\n try {\n entry = JSON.parse(line);\n } catch {\n continue;\n }\n o.onEntry(entry);\n }\n } finally {\n closeSync(fd);\n }\n };\n const look = () => {\n read();\n o.onRead?.();\n };\n look();\n const timer = setInterval(look, o.everyMs ?? 10_000);\n return {\n /** Reads what the transcript gained since the last look, then stops looking. */\n finish: () => {\n clearInterval(timer);\n read();\n },\n };\n};\n\n/**\n * One start of Claude Code on `account`, watched from before the start to after the exit: when the account stops and\n * another can go on, Claude Code hands over to it in the same conversation.\n */\nexport const accountRun = (o: {\n account: string;\n rotation: Accounts.Rotation;\n /** The conversation Claude Code is in. */\n sessionId: () => string;\n /** Where a conversation's transcript is, once Claude Code has written it. */\n file: (sessionId: string) => string | undefined;\n /** Restarts the start with this pid, telling the conversation why. */\n restart: (reason: string, pid: number) => void;\n log: (line: string) => void;\n everyMs?: number;\n}) => {\n let pid: number | undefined;\n let handed = false;\n const handover = () => {\n const why = o.rotation.marks()[o.account]?.why;\n const next = o.rotation.pick(o.account);\n if (handed || !why || next === undefined || next === o.account)\n return undefined;\n handed = true;\n o.log(`switching from account ${o.account} to ${next}`);\n return `account ${o.account} stopped at ${why}, so Claude Code now runs on account ${next}`;\n };\n const follow = followTranscript({\n sessionId: o.sessionId,\n file: o.file,\n onEntry: (entry) => {\n const stop = accountStop(entry);\n if (!stop) return;\n if (!(o.account in o.rotation.marks()))\n o.log(`account ${o.account} stopped at ${stop.why}`);\n o.rotation.mark(o.account, stop);\n },\n // after each look: a stopped account hands over as soon as another can go on, now or once that one's limit resets\n onRead: () => {\n if (pid === undefined) return;\n const reason = handover();\n if (reason !== undefined) o.restart(reason, pid);\n },\n ...(o.everyMs !== undefined && { everyMs: o.everyMs }),\n });\n return {\n /** Claude Code runs. */\n started: (startedPid: number) => void (pid = startedPid),\n /** Claude Code exited, or never started: reads the transcript's last lines. A reason: the next start goes on with another account, and is told this. */\n exited: () => {\n pid = undefined;\n follow.finish();\n return handover();\n },\n };\n};\n"],"mappings":";;AAiCA,MAAM,WAAW;AACjB,MAAM,aAAa;;AAGnB,MAAa,eACX,OACA,MAAM,KAAK,IAAI,MACe;CAC9B,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO,KAAA;CACxD,MAAM,IAAI;CAQV,IAAI,EAAE,SAAS,eAAe,EAAE,sBAAsB,MAAM,OAAO,KAAA;CACnE,IAAI,EAAE,UAAU,yBACd,OAAO;EAAE,KAAK;EAAoB,OAAO,MAAM;CAAW;CAC5D,IACE,EAAE,UAAU,gBACZ,EAAE,mBAAmB,OACrB,EAAE,wBAAwB,MAE1B,OAAO,KAAA;CACT,MAAM,WAAW,EAAE,aAAa;CAChC,OAAO;EACL,KAAK;EACL,OACE,OAAO,aAAa,YAAY,WAAW,MAAO,MAC9C,WAAW,MACX,MAAM;CACd;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AE,QAAQ,EAAE;EAC3C,MAAM,OAAO,EAAE,SAAS,KAAK,EAAE,OAAO;EACtC,IAAI,UAAU,CAAC,OAAO,SAAS,KAAA,KAAa,SAAS,EAAE,SACrD,OAAO,KAAA;EACT,SAAS;EACT,EAAE,IAAI,0BAA0B,EAAE,QAAQ,MAAM,MAAM;EACtD,OAAO,WAAW,EAAE,QAAQ,cAAc,IAAI,uCAAuC;CACvF;CACA,MAAM,SAAS,iBAAiB;EAC9B,WAAW,EAAE;EACb,MAAM,EAAE;EACR,UAAU,UAAU;GAClB,MAAM,OAAO,YAAY,KAAK;GAC9B,IAAI,CAAC,MAAM;GACX,IAAI,EAAE,EAAE,WAAW,EAAE,SAAS,MAAM,IAClC,EAAE,IAAI,WAAW,EAAE,QAAQ,cAAc,KAAK,KAAK;GACrD,EAAE,SAAS,KAAK,EAAE,SAAS,IAAI;EACjC;EAEA,cAAc;GACZ,IAAI,QAAQ,KAAA,GAAW;GACvB,MAAM,SAAS,SAAS;GACxB,IAAI,WAAW,KAAA,GAAW,EAAE,QAAQ,QAAQ,GAAG;EACjD;EACA,GAAI,EAAE,YAAY,KAAA,KAAa,EAAE,SAAS,EAAE,QAAQ;CACtD,CAAC;CACD,OAAO;;EAEL,UAAU,eAAuB,MAAM,MAAM;;EAE7C,cAAc;GACZ,MAAM,KAAA;GACN,OAAO,OAAO;GACd,OAAO,SAAS;EAClB;CACF;AACF"}
package/dist/bin.js CHANGED
@@ -5,6 +5,10 @@ import { realpathSync } from "node:fs";
5
5
  console.log = console.error.bind(console);
6
6
  console.info = console.error.bind(console);
7
7
  console.debug = console.error.bind(console);
8
+ process.stdout.on("error", (error) => {
9
+ if (error.code !== "EPIPE") throw error;
10
+ process.exit(0);
11
+ });
8
12
  try {
9
13
  process.exitCode = await runHarnessd(process.argv.slice(2), realpathSync(process.argv[1]));
10
14
  } catch (error) {
package/dist/bin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { realpathSync } from \"node:fs\";\nimport { runHarnessd } from \"./cli\";\n\n// stdout belongs to the command (for `harnessd channel`, to Claude Code)\nconsole.log = console.error.bind(console);\nconsole.info = console.error.bind(console);\nconsole.debug = console.error.bind(console);\n\ntry {\n process.exitCode = await runHarnessd(\n process.argv.slice(2),\n realpathSync(process.argv[1]!),\n );\n} catch (error) {\n console.error(error instanceof Error ? error.message : String(error));\n process.exitCode = 1;\n}\n"],"mappings":";;;;AAKA,QAAQ,MAAM,QAAQ,MAAM,KAAK,OAAO;AACxC,QAAQ,OAAO,QAAQ,MAAM,KAAK,OAAO;AACzC,QAAQ,QAAQ,QAAQ,MAAM,KAAK,OAAO;AAE1C,IAAI;CACF,QAAQ,WAAW,MAAM,YACvB,QAAQ,KAAK,MAAM,CAAC,GACpB,aAAa,QAAQ,KAAK,EAAG,CAC/B;AACF,SAAS,OAAO;CACd,QAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;CACpE,QAAQ,WAAW;AACrB"}
1
+ {"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { realpathSync } from \"node:fs\";\nimport { runHarnessd } from \"./cli\";\n\n// stdout belongs to the command (for `harnessd channel`, to Claude Code)\nconsole.log = console.error.bind(console);\nconsole.info = console.error.bind(console);\nconsole.debug = console.error.bind(console);\n\n// a reader that closes early (harnessd status | head) ends the command quietly\nprocess.stdout.on(\"error\", (error: NodeJS.ErrnoException) => {\n if (error.code !== \"EPIPE\") throw error;\n process.exit(0);\n});\n\ntry {\n process.exitCode = await runHarnessd(\n process.argv.slice(2),\n realpathSync(process.argv[1]!),\n );\n} catch (error) {\n console.error(error instanceof Error ? error.message : String(error));\n process.exitCode = 1;\n}\n"],"mappings":";;;;AAKA,QAAQ,MAAM,QAAQ,MAAM,KAAK,OAAO;AACxC,QAAQ,OAAO,QAAQ,MAAM,KAAK,OAAO;AACzC,QAAQ,QAAQ,QAAQ,MAAM,KAAK,OAAO;AAG1C,QAAQ,OAAO,GAAG,UAAU,UAAiC;CAC3D,IAAI,MAAM,SAAS,SAAS,MAAM;CAClC,QAAQ,KAAK,CAAC;AAChB,CAAC;AAED,IAAI;CACF,QAAQ,WAAW,MAAM,YACvB,QAAQ,KAAK,MAAM,CAAC,GACpB,aAAa,QAAQ,KAAK,EAAG,CAC/B;AACF,SAAS,OAAO;CACd,QAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;CACpE,QAAQ,WAAW;AACrB"}
package/dist/channel.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { findTranscript } from "./claude.js";
2
2
  import { headersOf } from "./config.js";
3
3
  import { closeSync, mkdirSync, openSync, readFileSync, readSync, renameSync, statSync, writeFileSync } from "node:fs";
4
- import { createInterface } from "node:readline";
5
4
  import { dirname, join } from "node:path";
5
+ import { createInterface } from "node:readline";
6
6
  import { randomBytes } from "node:crypto";
7
7
  import { runCli } from "toolport/cli";
8
8
  import { handleMcpMessage } from "toolport/mcp";
package/dist/claude.d.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  import type { Harnessd } from "./config.js";
2
2
  import type { Watchdog } from "./watchdog.js";
3
- /** How Claude Code names a `--plugin-dir` plugin, and what `--channels` takes. */
3
+ /** How Claude Code names a `--plugin-dir` plugin. */
4
4
  export declare const PLUGIN = "harnessd@inline";
5
- export declare const MANAGED_SETTINGS = "/Library/Application Support/ClaudeCode/managed-settings.json";
6
5
  /**
7
6
  * Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's
8
7
  * `projects[<folder>].hasTrustDialogAccepted`), so an unattended start doesn't stop at that dialog. Only that field
@@ -14,18 +13,22 @@ export declare const findTranscript: (sessionId: string, env?: NodeJS.ProcessEnv
14
13
  /** The first `name` on `path` that can run. */
15
14
  export declare const which: (name: string, path?: string) => string;
16
15
  /**
17
- * harnessd's plugin, written before each start from the config's channels: one MCP server per channel, each
18
- * `harnessd channel <name>`. None: no plugin.
16
+ * harnessd's plugin, written before each start: one MCP server per channel of the config, each
17
+ * `harnessd channel <name>`, and a SessionStart hook that tells harnessd which conversation Claude Code is in, so a
18
+ * /clear or a /resume is the conversation the next start resumes.
19
19
  */
20
- export declare const writePlugin: (paths: Harnessd.Paths, config: Harnessd.Config, bin: string) => boolean;
20
+ export declare const writePlugin: (paths: Harnessd.Paths, config: Harnessd.Config, bin: string) => void;
21
+ /** Whether these claude arguments turn permission prompts off: the config's `args` (or prestart's) ask for it, harnessd never does. */
22
+ export declare const skipsPermissions: (args: readonly string[]) => boolean;
21
23
  /**
22
- * The claude command line for one start (after the binary). `--channels` names the plugin only when the managed
23
- * settings let it in: a refused entry there also shuts out the same plugin loaded with the development flag.
24
+ * The claude command line for one start (after the binary). Claude Code runs in its auto permission mode, which
25
+ * decides each action itself, unless the config's arguments pick another mode. harnessd's plugin is written on this Mac at each start, so
26
+ * its channels load with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude
27
+ * Code then asks once per start whether this is local development; harnessd answers that (see prompts.ts).
24
28
  */
25
29
  export declare const claudeArgs: (o: {
26
30
  start: Watchdog.Start;
27
- plugin: string | undefined;
28
- allowed: boolean;
31
+ plugin: string;
29
32
  config: Harnessd.Config;
30
33
  extra: readonly string[];
31
34
  }) => string[];
@@ -35,8 +38,4 @@ export type Prestart = {
35
38
  };
36
39
  /** Runs the config's prestart command in the agent's folder: its stdout is JSON `{ env?, args? }`, or nothing. */
37
40
  export declare const prestart: (command: string, folder: string, env: NodeJS.ProcessEnv, log: (line: string) => void) => Promise<Prestart>;
38
- /** What keeps harnessd's channels out of Claude Code on this Mac: its managed settings must let `harnessd@inline` in. */
39
- export declare const channelBlockers: (file?: string) => string[];
40
- /** The managed settings with harnessd's channel let in; a list that wasn't there starts with Anthropic's own channels. */
41
- export declare const allowChannel: (file?: string) => Record<string, unknown>;
42
41
  //# sourceMappingURL=claude.d.ts.map
@@ -1 +1 @@
1
- {"version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AAE,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAEvE,kHAAkH;AAClH,eAAO,MAAM,QAAQ,GACnB,SAAS,MAAM,EACf,QAAQ,MAAM,EACd,KAAK,MAAM,CAAC,UAAU,EACtB,KAAK,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,sBAyDzB,CAAC"}
package/dist/claude.js CHANGED
@@ -3,9 +3,8 @@ import { execFile } from "node:child_process";
3
3
  import { homedir } from "node:os";
4
4
  import { delimiter, join } from "node:path";
5
5
  // src/claude.ts
6
- /** How Claude Code names a `--plugin-dir` plugin, and what `--channels` takes. */
6
+ /** How Claude Code names a `--plugin-dir` plugin. */
7
7
  const PLUGIN = "harnessd@inline";
8
- const MANAGED_SETTINGS = "/Library/Application Support/ClaudeCode/managed-settings.json";
9
8
  const claudeDir = (env) => env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
10
9
  /**
11
10
  * Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's
@@ -54,47 +53,66 @@ const which = (name, path = process.env.PATH ?? "") => {
54
53
  }
55
54
  throw new Error(`${name} isn't on PATH (${path}); install Claude Code: curl -fsSL https://claude.ai/install.sh | bash`);
56
55
  };
56
+ const shellQuote = (text) => `'${text.replaceAll("'", "'\\''")}'`;
57
57
  /**
58
- * harnessd's plugin, written before each start from the config's channels: one MCP server per channel, each
59
- * `harnessd channel <name>`. None: no plugin.
58
+ * harnessd's plugin, written before each start: one MCP server per channel of the config, each
59
+ * `harnessd channel <name>`, and a SessionStart hook that tells harnessd which conversation Claude Code is in, so a
60
+ * /clear or a /resume is the conversation the next start resumes.
60
61
  */
61
62
  const writePlugin = (paths, config, bin) => {
62
63
  rmSync(paths.plugin, {
63
64
  recursive: true,
64
65
  force: true
65
66
  });
66
- const names = Object.keys(config.channels);
67
- if (names.length === 0) return false;
68
67
  mkdirSync(join(paths.plugin, ".claude-plugin"), { recursive: true });
68
+ const names = Object.keys(config.channels);
69
+ const sessionStart = [
70
+ ...Object.entries(paths.env).map(([name, value]) => `${name}=${shellQuote(value)}`),
71
+ shellQuote(process.execPath),
72
+ shellQuote(bin),
73
+ "session-start"
74
+ ].join(" ");
69
75
  const manifest = {
70
76
  name: "harnessd",
71
77
  version: "1.0.0",
72
- description: "harnessd's channels: each one's events, and its tools",
73
- mcpServers: Object.fromEntries(names.map((name) => [name, {
74
- command: process.execPath,
75
- args: [
76
- bin,
77
- "channel",
78
- name
79
- ],
80
- env: { HARNESSD_HOME: paths.home }
81
- }])),
82
- channels: names.map((name) => ({
83
- server: name,
84
- displayName: name
85
- }))
78
+ description: "harnessd's channels, each one's events and tools, and its SessionStart hook",
79
+ ...names.length > 0 && {
80
+ mcpServers: Object.fromEntries(names.map((name) => [name, {
81
+ command: process.execPath,
82
+ args: [
83
+ bin,
84
+ "channel",
85
+ name
86
+ ],
87
+ env: paths.env
88
+ }])),
89
+ channels: names.map((name) => ({
90
+ server: name,
91
+ displayName: name
92
+ }))
93
+ },
94
+ hooks: { SessionStart: [{ hooks: [{
95
+ type: "command",
96
+ command: sessionStart
97
+ }] }] }
86
98
  };
87
99
  writeFileSync(join(paths.plugin, ".claude-plugin", "plugin.json"), `${JSON.stringify(manifest, null, 2)}\n`);
88
- return true;
89
100
  };
101
+ /** Whether these claude arguments pick a permission mode themselves. */
102
+ const picksPermissionMode = (args) => args.some((arg) => arg === "--dangerously-skip-permissions" || arg === "--permission-mode" || arg.startsWith("--permission-mode="));
103
+ /** Whether these claude arguments turn permission prompts off: the config's `args` (or prestart's) ask for it, harnessd never does. */
104
+ const skipsPermissions = (args) => args.some((arg, i) => arg === "--dangerously-skip-permissions" || arg === "--permission-mode=bypassPermissions" || arg === "bypassPermissions" && args[i - 1] === "--permission-mode");
90
105
  /**
91
- * The claude command line for one start (after the binary). `--channels` names the plugin only when the managed
92
- * settings let it in: a refused entry there also shuts out the same plugin loaded with the development flag.
106
+ * The claude command line for one start (after the binary). Claude Code runs in its auto permission mode, which
107
+ * decides each action itself, unless the config's arguments pick another mode. harnessd's plugin is written on this Mac at each start, so
108
+ * its channels load with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude
109
+ * Code then asks once per start whether this is local development; harnessd answers that (see prompts.ts).
93
110
  */
94
111
  const claudeArgs = (o) => [
95
- "--dangerously-skip-permissions",
96
- ...o.plugin ? ["--plugin-dir", o.plugin] : [],
97
- ...o.plugin && o.allowed ? ["--channels", `plugin:${PLUGIN}`] : [],
112
+ ...picksPermissionMode([...o.config.args, ...o.extra]) ? [] : ["--permission-mode", "auto"],
113
+ "--plugin-dir",
114
+ o.plugin,
115
+ ...Object.keys(o.config.channels).length > 0 ? ["--dangerously-load-development-channels", `plugin:${PLUGIN}`] : [],
98
116
  ...o.start.resume ? ["--resume", o.start.sessionId] : ["--session-id", o.start.sessionId],
99
117
  ...o.start.prompt ? [o.start.prompt] : [],
100
118
  ...o.config.args,
@@ -129,38 +147,6 @@ const prestart = (command, folder, env, log) => new Promise((resolve, reject) =>
129
147
  });
130
148
  });
131
149
  });
132
- /** What keeps harnessd's channels out of Claude Code on this Mac: its managed settings must let `harnessd@inline` in. */
133
- const channelBlockers = (file = MANAGED_SETTINGS) => {
134
- let settings = {};
135
- try {
136
- const parsed = JSON.parse(readFileSync(file, "utf8"));
137
- if (typeof parsed === "object" && parsed !== null) settings = parsed;
138
- } catch {}
139
- const listed = Array.isArray(settings.allowedChannelPlugins) && settings.allowedChannelPlugins.some((entry) => entry === "harnessd@inline" || typeof entry === "object" && entry !== null && entry.plugin === "harnessd" && entry.marketplace === "inline");
140
- return [...settings.channelsEnabled === true ? [] : [`${file} doesn't set channelsEnabled: true`], ...listed ? [] : [`${file} doesn't list ${PLUGIN} in allowedChannelPlugins`]];
141
- };
142
- /** The managed settings with harnessd's channel let in; a list that wasn't there starts with Anthropic's own channels. */
143
- const allowChannel = (file = MANAGED_SETTINGS) => {
144
- const settings = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
145
- if (typeof settings !== "object" || settings === null || Array.isArray(settings)) throw new Error(`${file} isn't a JSON object; harnessd won't write over it`);
146
- const list = Array.isArray(settings.allowedChannelPlugins) ? settings.allowedChannelPlugins : [
147
- "telegram",
148
- "discord",
149
- "imessage",
150
- "fakechat"
151
- ].map((plugin) => ({
152
- marketplace: "claude-plugins-official",
153
- plugin
154
- }));
155
- return {
156
- ...settings,
157
- channelsEnabled: true,
158
- allowedChannelPlugins: [...list.filter((entry) => !(typeof entry === "object" && entry?.plugin === "harnessd")), {
159
- marketplace: "inline",
160
- plugin: "harnessd"
161
- }]
162
- };
163
- };
164
- export { MANAGED_SETTINGS, PLUGIN, allowChannel, channelBlockers, claudeArgs, findTranscript, prestart, trustFolder, which, writePlugin };
150
+ export { PLUGIN, claudeArgs, findTranscript, prestart, skipsPermissions, trustFolder, which, writePlugin };
165
151
 
166
152
  //# sourceMappingURL=claude.js.map