@koalaauto/agentchannel 3.88.0 → 3.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/args.js CHANGED
@@ -165,7 +165,10 @@ export function helpFor(words) {
165
165
  }
166
166
  export const HELP = `ach - AgentChannel CLI
167
167
 
168
- Setup: npx -y @koalaauto/agentchannel@3 join <ach2.invite> [--name <n>] [--service] [--yes] [--dry-run] (run it in the
168
+ Setup: npx -y @koalaauto/agentchannel@3 join <ach2.line> (a line from the panel's "Connect a client": this machine's
169
+ Claude Code / Codex become windows to your Yoda; no agent is made, and a session speaks as you
170
+ everywhere but in a directory an agent was joined from)
171
+ npx -y @koalaauto/agentchannel@3 join <ach2.invite> [--name <n>] [--service] [--yes] [--dry-run] (run it in the
169
172
  project directory: a line from the panel's "Connect an agent" creates the agent there, named
170
173
  "<your name>-<directory>" (lowercase); --name replaces the part after "<your name>-"; a line from the panel or
171
174
  \`ach admin invite <agent>\`: stores the agent's key and adds the \`ach\` MCP server to the agent's own tool
package/dist/src/cli.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { hostname } from 'node:os';
2
3
  import { spawn } from 'node:child_process';
3
4
  import { randomBytes } from 'node:crypto';
4
5
  import { readFileSync, realpathSync, writeFileSync } from 'node:fs';
@@ -9,7 +10,7 @@ import { channelRef, Client, clientFromConfig, HubError, isZh, NetworkError, par
9
10
  import { guideHeader, GuideSectionUnknown, readGuide } from './guide.js';
10
11
  import { channelTails, closest, decisionTo, explainToUser, matchChannel, unreachedLines } from './names.js';
11
12
  import { refOf, untrustedBlock as wrapUntrusted } from './prompts.js';
12
- import { agentHome, homeForDir, loadConfig, readFileConfig, saveAgentKey, saveCfSecret, sessionHome, writeFileConfig } from './config.js';
13
+ import { agentHome, homeForDir, loadConfig, personHome, readFileConfig, saveAgentKey, saveCfSecret, sessionHome, sessionParts, writeFileConfig } from './config.js';
13
14
  import { achCommand, decodeInvite, mcpCommands, shadowHint } from './invite.js';
14
15
  import { AttachError, humanSize, isLinkRef, resolveAttachments, taskFiles } from './attachments.js';
15
16
  export { VERSION } from './version.js';
@@ -193,6 +194,73 @@ export async function main(argv, io = defaultIo()) {
193
194
  return 1;
194
195
  }
195
196
  }
197
+ /**
198
+ * `ach join <line>` with a line from "Connect a client": this machine's clients (Claude Code, Codex) become windows to the
199
+ * person's Yoda. The one-time code is exchanged for the client's token, kept in a home of its own (personHome) so no agent's key
200
+ * is touched, and the `ach` MCP server is added to the tools found here. A session then speaks as the person everywhere but in
201
+ * a directory an agent was joined from (config.ts sessionHome).
202
+ */
203
+ async function joinPerson(inv, o) {
204
+ const { env, io, out } = o;
205
+ const zh = isZh(env);
206
+ const hubHost = new URL(inv.hub).host;
207
+ const penv = { ...env, AGENTCHANNEL_HOME: personHome(env) };
208
+ let token;
209
+ let person = '';
210
+ try {
211
+ const ex = await new Client({ hub: inv.hub, cfId: inv.cfId, cfSecret: inv.cfSecret, fetch: io.fetch }).request('POST', '/api/ach/client-links/exchange', { link: inv.link, label: hostname().slice(0, 80) });
212
+ if (!ex?.token)
213
+ throw new Error('the hub returned no token');
214
+ token = String(ex.token);
215
+ person = String(ex.person?.name ?? '');
216
+ }
217
+ catch (e) {
218
+ if (e instanceof HubError && e.code === 'cf_access') {
219
+ io.err(zh ? `ach join:请求被 ${hubHost} 前面的 Cloudflare Access 拦下了,这行没有带可用的访问令牌。这行还没有用掉。请在面板重新生成(打开「包含 Cloudflare 访问令牌」)。` : `ach join: Cloudflare Access in front of ${hubHost} blocked the request: this line carries no working access token. The line is still unused. Make a new one in the panel (with "Include the Cloudflare access token" on).`);
220
+ return 1;
221
+ }
222
+ if (e instanceof HubError && (e.status === 410 || e.status === 401)) {
223
+ // run again on the same machine: keep the connection saved by the first run, when it still works
224
+ try {
225
+ const saved = loadConfig(penv);
226
+ if (saved.hub === inv.hub && saved.key) {
227
+ const me = await new Client({ hub: inv.hub, token: saved.key, cfId: saved.cfId ?? inv.cfId, cfSecret: saved.cfSecret ?? inv.cfSecret, fetch: io.fetch }).me();
228
+ io.err(zh ? `这一行已经用过;这台机器已经连接到 ${me.name} 的 Yoda,继续使用。` : `This line was already used; this machine is already connected to ${me.name}'s Yoda.`);
229
+ return 0;
230
+ }
231
+ }
232
+ catch {
233
+ /* nothing saved that works */
234
+ }
235
+ const why = e.code === 'client_line_expired' ? (zh ? '已过期' : 'has expired') : e.code === 'client_line_used' ? (zh ? '已经用过' : 'was already used') : zh ? '无效' : 'is not valid';
236
+ io.err(zh ? `ach join:这一行${why}。请在面板重新生成一行(连接客户端)。` : `ach join: this line ${why}. Make a new one in the panel (Connect a client).`);
237
+ return 1;
238
+ }
239
+ throw e;
240
+ }
241
+ const keepCf = !!(inv.cfId && inv.cfSecret);
242
+ writeFileConfig({ ...readFileConfig(penv), hub: inv.hub, ...(keepCf ? { cf_id: inv.cfId } : {}), person }, penv);
243
+ const where = saveAgentKey(token, penv);
244
+ if (keepCf)
245
+ saveCfSecret(inv.cfSecret, penv);
246
+ if (o.json) {
247
+ out({ person, hub: inv.hub, key_store: where, home: penv.AGENTCHANNEL_HOME });
248
+ return 0;
249
+ }
250
+ out(zh
251
+ ? `已连接 ${inv.hub}:这台机器上的客户端是 ${person} 的 Yoda 的窗口(没有建智能体);凭据保存在${where === 'keychain' ? '系统钥匙串' : ' ' + penv.AGENTCHANNEL_HOME + '(0600)'}。`
252
+ : `connected to ${inv.hub}: the clients on this machine are windows to ${person}'s Yoda (no agent was made); the token is stored in ${where === 'keychain' ? 'the OS keychain' : penv.AGENTCHANNEL_HOME + ' (0600)'}.`);
253
+ // the MCP entry is the user-wide one, with no home in it: a session picks who it is where it starts (an agent's own
254
+ // directory: that agent; anywhere else: the person)
255
+ const { runSetup } = await import('./onboard.js');
256
+ const { defaultExec } = await import('./doctor.js');
257
+ const cwd = io.cwd ?? process.cwd();
258
+ const r = await runSetup({ env, out: io.out, err: io.err, exec: io.exec ?? defaultExec, ask: io.ask, cwd, sandbox: async (tool) => ({ tool, ok: true }), ...(io.ask ? { runTty: (line) => runInTerminal(line, env) } : {}) }, { yes: o.yes, service: false, zh });
259
+ const names = [...new Set(r.tools)].map((k) => (k === 'claude' ? 'Claude Code' : 'Codex'));
260
+ const tools = names.length ? names.join(zh ? ' 或 ' : ' or ') : zh ? '你的 Claude Code 或 Codex' : 'your Claude Code or Codex';
261
+ out(r.failed.length ? (zh ? `部分步骤失败(${r.failed.join(', ')}):运行 ach doctor 查看怎么修。` : `Some steps failed (${r.failed.join(', ')}): run ach doctor to see how to fix them.`) : zh ? `完成。打开 ${tools},对它说:问问 Yoda 有什么在等我` : `Done. Open ${tools} and say: ask Yoda what waits for me`);
262
+ return r.failed.length ? 1 : 0;
263
+ }
196
264
  async function dispatch(p, io) {
197
265
  const env = io.env;
198
266
  const out = (v) => io.out(typeof v === 'string' ? v : JSON.stringify(v, null, 2));
@@ -302,6 +370,9 @@ async function dispatch(p, io) {
302
370
  /* nothing stored */
303
371
  }
304
372
  }
373
+ // a line that connects this machine's clients to a person's Yoda: no agent is made (docs/specs/one-yoda.md)
374
+ if (inv.link)
375
+ return joinPerson({ link: inv.link, hub: inv.hub, cfId, cfSecret }, { env, io, out, json: !!v.json, yes: !!v.yes });
305
376
  // the home this join writes: the default one, unless this directory's agent already has a home of its own
306
377
  const cwd = io.cwd ?? process.cwd();
307
378
  const ownHome = env.AGENTCHANNEL_HOME ? undefined : homeForDir(cwd, env);
@@ -1041,14 +1112,18 @@ async function dispatch(p, io) {
1041
1112
  }
1042
1113
  case 'mcp': {
1043
1114
  const { startMcp } = await import('./mcp.js');
1044
- // a project with an agent of its own speaks as that agent, even from the user-wide MCP entry
1045
1115
  const cwd = io.cwd ?? process.cwd();
1046
- const sess = sessionHome(cwd, env);
1047
- const menv = sess.how === 'dir' ? { ...env, AGENTCHANNEL_HOME: sess.home } : env;
1116
+ // who the session is (config.ts sessionParts): the person wherever this machine is connected to their Yoda, with the
1117
+ // agent of this directory beside them when there is one; else that agent, as before
1118
+ const parts = sessionParts(cwd, env);
1119
+ const menv = { ...env, AGENTCHANNEL_HOME: parts.person ?? parts.agent };
1048
1120
  // every answer names the newest release: this machine's install moves on to it even with no runner here (mcpupdate.ts)
1049
1121
  const { mcpUpdater } = await import('./mcpupdate.js');
1050
1122
  const upd = mcpUpdater({ env: menv, log: (s) => process.stderr.write(`[ach mcp] ${s}\n`) });
1051
- await startMcp(clientFromConfig(loadConfig(menv), { fetch: io.fetch, onLatestClient: (latest) => void upd.heard(latest)?.catch(() => { }) }), { cwd, dir: sess.dir });
1123
+ const main = clientFromConfig(loadConfig(menv), { fetch: io.fetch, onLatestClient: (latest) => void upd.heard(latest)?.catch(() => { }) });
1124
+ const aenv = parts.person && parts.agent ? { ...env, AGENTCHANNEL_HOME: parts.agent } : undefined;
1125
+ const acfg = aenv ? loadConfig(aenv) : undefined;
1126
+ await startMcp(main, { cwd, dir: parts.dir, ...(acfg?.key ? { hand: clientFromConfig(acfg, { fetch: io.fetch }) } : {}) });
1052
1127
  return await new Promise(() => { }); // stdio server runs until killed
1053
1128
  }
1054
1129
  case 'caps': {
@@ -107,6 +107,8 @@ export interface GithubToken {
107
107
  export interface Task {
108
108
  id: string;
109
109
  title: string;
110
+ /** 'read': a read-only task, its run gets read access only (an older hub leaves it out) */
111
+ perm?: string;
110
112
  priority?: string;
111
113
  purpose?: string;
112
114
  money?: string;
@@ -653,6 +655,11 @@ export declare class Client {
653
655
  running: boolean;
654
656
  };
655
657
  }>;
658
+ /**
659
+ * A session connected as a person, opened in the directory of one of their agents: that agent's name, sent with what the
660
+ * session says to Yoda so Yoda knows which project the person is in (docs/specs/one-yoda.md §10).
661
+ */
662
+ yodaFrom?: string;
656
663
  /** What came in the owner's Yoda session after `after`, whether Yoda is still at it, and the cards waiting on the owner. */
657
664
  yoda(after?: number): Promise<{
658
665
  session: {
@@ -406,8 +406,13 @@ export class Client {
406
406
  }
407
407
  /** Say something to the owner's Yoda (this key must be one of their environments, and they must have a Yoda). */
408
408
  async yodaSay(body) {
409
- return this.ach('POST', '/yoda/messages', { body });
409
+ return this.ach('POST', '/yoda/messages', { body, ...(this.yodaFrom ? { from: this.yodaFrom } : {}) });
410
410
  }
411
+ /**
412
+ * A session connected as a person, opened in the directory of one of their agents: that agent's name, sent with what the
413
+ * session says to Yoda so Yoda knows which project the person is in (docs/specs/one-yoda.md §10).
414
+ */
415
+ yodaFrom;
411
416
  /** What came in the owner's Yoda session after `after`, whether Yoda is still at it, and the cards waiting on the owner. */
412
417
  async yoda(after) {
413
418
  return this.ach('GET', `/yoda${after !== undefined ? `?after=${after}` : ''}`);
@@ -14,6 +14,8 @@ export interface FileConfig {
14
14
  * In a home of its own (agentHome) a later join or MCP session there finds it again; in any home the MCP says it.
15
15
  */
16
16
  dir?: string;
17
+ /** This home holds a person's client connection, not an agent (docs/specs/one-yoda.md): whose (their name). */
18
+ person?: string;
17
19
  }
18
20
  export interface Config {
19
21
  hub?: string;
@@ -42,6 +44,11 @@ export declare function resolveClaimDelay(o: {
42
44
  export declare function defaultHome(env?: NodeJS.ProcessEnv): string;
43
45
  /** Root dir for config and runner state. AGENTCHANNEL_HOME overrides (used by tests). */
44
46
  export declare function achHome(env?: NodeJS.ProcessEnv): string;
47
+ /**
48
+ * The home of this machine's connection to a person's Yoda (docs/specs/one-yoda.md): the client's token, with no agent. Apart
49
+ * from every agent's home, so connecting never touches an agent's key.
50
+ */
51
+ export declare function personHome(env?: NodeJS.ProcessEnv): string;
45
52
  /**
46
53
  * One home holds one agent's key. The first agent on a machine lives in the default home; another agent joined on the same
47
54
  * machine (another project) gets a home of its own here, so joining it never replaces the first one's key (2026-11-06: a second
@@ -55,12 +62,27 @@ export declare function homeForDir(dir: string, env?: NodeJS.ProcessEnv): string
55
62
  * AGENTCHANNEL_HOME or ACH_KEY set: that one, as before. Else the nearest directory, `cwd` or above, that an agent was
56
63
  * joined from, so a session in a project with an agent of its own is that agent even when only the user-wide MCP entry
57
64
  * (default home) loaded (2026-11-13: a session in a reela-r3 checkout sent tasks as the default home's agent).
65
+ * Else, on a machine connected to a person's Yoda (personHome), that connection: a session anywhere but in an agent's own
66
+ * directory is the person's window to their Yoda. The default home's agent keeps the directory it was joined from (and below).
58
67
  * Else the default home.
59
68
  */
60
69
  export declare function sessionHome(cwd: string, env?: NodeJS.ProcessEnv): {
61
70
  home: string;
62
71
  dir?: string;
63
- how: 'env' | 'dir' | 'default';
72
+ how: 'env' | 'dir' | 'default' | 'person';
73
+ };
74
+ /**
75
+ * Who an `ach mcp` started in `cwd` is (docs/specs/one-yoda.md §10). On a machine connected to its person's Yoda the session is
76
+ * the person in any directory (`person`: that connection's home); in a directory an agent was joined from, or below, it also
77
+ * holds that agent (`agent`: its home), whose key works that agent's tasks and nothing else. The MCP entry `ach join` writes
78
+ * for an agent with a home of its own names that home (AGENTCHANNEL_HOME): it is read as "the agent of this directory", not as
79
+ * an override. A home outside this machine's own (a test, a deliberate override), a key in the environment, and a machine
80
+ * never connected are as before: the session is that agent.
81
+ */
82
+ export declare function sessionParts(cwd: string, env?: NodeJS.ProcessEnv): {
83
+ person?: string;
84
+ agent?: string;
85
+ dir?: string;
64
86
  };
65
87
  export declare function configPath(env?: NodeJS.ProcessEnv): string;
66
88
  /** Write JSON atomically with mode 0600 (dir 0700). */
@@ -1,6 +1,6 @@
1
1
  import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
- import { dirname, join, resolve } from 'node:path';
3
+ import { dirname, join, resolve, sep } from 'node:path';
4
4
  import { cfSecretPath, FileKeyStore, keyFilePath, openAdminSessionStore, openCfSecretStore, openKeyStore } from './keystore.js';
5
5
  /** Claim delay used by `ach run --interactive-first` (or "interactive_first": true in config.json). */
6
6
  export const INTERACTIVE_FIRST_DELAY_SEC = 60;
@@ -22,6 +22,13 @@ export function defaultHome(env = process.env) {
22
22
  export function achHome(env = process.env) {
23
23
  return env.AGENTCHANNEL_HOME || defaultHome(env);
24
24
  }
25
+ /**
26
+ * The home of this machine's connection to a person's Yoda (docs/specs/one-yoda.md): the client's token, with no agent. Apart
27
+ * from every agent's home, so connecting never touches an agent's key.
28
+ */
29
+ export function personHome(env = process.env) {
30
+ return join(defaultHome(env), 'person');
31
+ }
25
32
  /**
26
33
  * One home holds one agent's key. The first agent on a machine lives in the default home; another agent joined on the same
27
34
  * machine (another project) gets a home of its own here, so joining it never replaces the first one's key (2026-11-06: a second
@@ -50,6 +57,8 @@ export function homeForDir(dir, env = process.env) {
50
57
  * AGENTCHANNEL_HOME or ACH_KEY set: that one, as before. Else the nearest directory, `cwd` or above, that an agent was
51
58
  * joined from, so a session in a project with an agent of its own is that agent even when only the user-wide MCP entry
52
59
  * (default home) loaded (2026-11-13: a session in a reela-r3 checkout sent tasks as the default home's agent).
60
+ * Else, on a machine connected to a person's Yoda (personHome), that connection: a session anywhere but in an agent's own
61
+ * directory is the person's window to their Yoda. The default home's agent keeps the directory it was joined from (and below).
53
62
  * Else the default home.
54
63
  */
55
64
  export function sessionHome(cwd, env = process.env) {
@@ -62,7 +71,41 @@ export function sessionHome(cwd, env = process.env) {
62
71
  if (dirname(d) === d)
63
72
  break;
64
73
  }
65
- return { home: defaultHome(env), dir: readFileConfig(env).dir, how: 'default' };
74
+ const own = readFileConfig(env).dir;
75
+ if (readJson(join(personHome(env), 'config.json'), {}).hub) {
76
+ const at = resolve(cwd);
77
+ const inside = !!own && (at === resolve(own) || at.startsWith(resolve(own) + sep));
78
+ if (!inside)
79
+ return { home: personHome(env), how: 'person' };
80
+ }
81
+ return { home: defaultHome(env), dir: own, how: 'default' };
82
+ }
83
+ const within = (at, dir) => !!dir && (resolve(at) === resolve(dir) || resolve(at).startsWith(resolve(dir) + sep));
84
+ /**
85
+ * Who an `ach mcp` started in `cwd` is (docs/specs/one-yoda.md §10). On a machine connected to its person's Yoda the session is
86
+ * the person in any directory (`person`: that connection's home); in a directory an agent was joined from, or below, it also
87
+ * holds that agent (`agent`: its home), whose key works that agent's tasks and nothing else. The MCP entry `ach join` writes
88
+ * for an agent with a home of its own names that home (AGENTCHANNEL_HOME): it is read as "the agent of this directory", not as
89
+ * an override. A home outside this machine's own (a test, a deliberate override), a key in the environment, and a machine
90
+ * never connected are as before: the session is that agent.
91
+ */
92
+ export function sessionParts(cwd, env = process.env) {
93
+ const s = sessionHome(cwd, env);
94
+ const connected = !!readJson(join(personHome(env), 'config.json'), {}).hub;
95
+ if (!connected || env.ACH_KEY)
96
+ return { agent: s.home, dir: s.dir };
97
+ if (s.how === 'person')
98
+ return { person: s.home };
99
+ if (s.how === 'env') {
100
+ const root = resolve(defaultHome(env));
101
+ const home = resolve(s.home);
102
+ if (home === resolve(personHome(env)))
103
+ return { person: s.home };
104
+ if (home !== root && !home.startsWith(join(root, 'agents') + sep))
105
+ return { agent: s.home, dir: s.dir };
106
+ return within(cwd, s.dir) ? { person: personHome(env), agent: s.home, dir: s.dir } : { person: personHome(env) };
107
+ }
108
+ return { person: personHome(env), agent: s.home, dir: s.dir };
66
109
  }
67
110
  export function configPath(env = process.env) {
68
111
  return join(achHome(env), 'config.json');