agent-yes 1.303.1 → 1.304.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/README.md +54 -0
- package/default.config.yaml +5 -5
- package/dist/{JsonlStore-BpYZZTap.js → JsonlStore-CB_0sfdT.js} +5 -4
- package/dist/{SUPPORTED_CLIS-Dq9Lq9WJ.js → SUPPORTED_CLIS-C_1IiOj3.js} +2 -2
- package/dist/SUPPORTED_CLIS-Do3GHAY1.js +12 -0
- package/dist/{agentShare-suB6yPgO.js → agentShare-BvpEm-Fr.js} +10 -9
- package/dist/{askCli-BU3CNCLU.js → askCli-KmMf-3wA.js} +6 -6
- package/dist/{browser-BmxN1Ur9.js → browser-BAFPmEvN.js} +2 -2
- package/dist/{callback-Ctj3_Wxp.js → callback-BiSUhjw7.js} +6 -6
- package/dist/callback-SqLD2mMX.js +17 -0
- package/dist/{callbackCore-DSJWhqAe.js → callbackCore-BZ_10zyc.js} +1 -1
- package/dist/{callbackCore-BesbQ6-Z.js → callbackCore-Deve5pv3.js} +1 -1
- package/dist/{channels-j5nWuzlQ.js → channels-Y36S0ccW.js} +2 -2
- package/dist/cli.js +118 -13
- package/dist/{cmdDsh-2LP0grim.js → cmdDsh-DZ8bLsH7.js} +1 -1
- package/dist/cmdKill-CzSBfWmx.js +116 -0
- package/dist/{cmdPs-wc1j85fi.js → cmdPs-DBt23Qz0.js} +11 -10
- package/dist/{cwdConflictWarn-skQSMwEh.js → cwdConflictWarn-y-epQyOj.js} +21 -5
- package/dist/{cwdPassthroughHint-BUbWMoz0.js → cwdPassthroughHint-CzWh0hrw.js} +1 -1
- package/dist/{expose-Dawq1LxC.js → expose-Bhsn5yUz.js} +2 -2
- package/dist/forceKill-BDqxx4uQ.js +44 -0
- package/dist/{forkNested-CavHyWzA.js → forkNested-3heLs5XC.js} +45 -5
- package/dist/{globalPidIndex-CRB5KtyL.js → globalPidIndex-BsjlId-h.js} +6 -5
- package/dist/{globalPidIndex-BftWlg2V.js → globalPidIndex-uoz8Esqz.js} +2 -2
- package/dist/{hist-Cs0KFSUW.js → hist-DY16wm7g.js} +1 -1
- package/dist/{identity-DA7YI9km.js → identity-C0MxfwI2.js} +1 -1
- package/dist/{identity-Bk-aG_xl.js → identity-Ckav3-Up.js} +1 -1
- package/dist/index.js +7 -7
- package/dist/{initMsg-CcTqFtsp.js → initMsg-BEVDWYnv.js} +1 -1
- package/dist/{initMsg-D9KJnfgC.js → initMsg-GPU52N-j.js} +1 -1
- package/dist/liagent/box-BSIrRRc_.js +2320 -0
- package/dist/liagent/box-DloywR57.d.ts +409 -0
- package/dist/liagent/box.d.ts +3 -0
- package/dist/liagent/box.js +3 -0
- package/dist/liagent/cli.d.ts +1 -0
- package/dist/liagent/cli.js +908 -0
- package/dist/liagent/client.d.ts +28 -0
- package/dist/liagent/client.js +240 -0
- package/dist/liagent/echo-BvzPSI0x.js +86 -0
- package/dist/liagent/echo-W2RcMEny.d.ts +38 -0
- package/dist/liagent/hub.d.ts +405 -0
- package/dist/liagent/hub.js +1831 -0
- package/dist/liagent/index.d.ts +14 -0
- package/dist/liagent/index.js +10 -0
- package/dist/liagent/liagent.js +339 -0
- package/dist/liagent/mic-audio-C3Shud_F.js +754 -0
- package/dist/liagent/mic-audio-DMCWtEI-.d.ts +317 -0
- package/dist/liagent/mic-button-CtZHFBSG.js +651 -0
- package/dist/liagent/mic-button-Y0ioPetQ.d.ts +248 -0
- package/dist/liagent/mic.d.ts +3 -0
- package/dist/liagent/mic.js +4 -0
- package/dist/liagent/progress-CJs08bXb.js +473 -0
- package/dist/liagent/progress-CfE-meHr.d.ts +205 -0
- package/dist/liagent/progress.d.ts +2 -0
- package/dist/liagent/progress.js +3 -0
- package/dist/liagent/protocol.d.ts +324 -0
- package/dist/liagent/protocol.js +504 -0
- package/dist/liagent/speech-rate-DXeJjRTc.js +42 -0
- package/dist/liagent/state-tree-BZCmAknI.js +353 -0
- package/dist/liagent/tree-BrR7NwMf.js +710 -0
- package/dist/liagent/tree-HB9RhX_H.d.ts +295 -0
- package/dist/liagent/tree.d.ts +2 -0
- package/dist/liagent/tree.js +4 -0
- package/dist/liagent/ui-strings-B03le3fh.d.ts +27 -0
- package/dist/liagent/ui-strings-CJIwW5Gf.js +794 -0
- package/dist/liagent/ui.d.ts +394 -0
- package/dist/liagent/ui.js +5 -0
- package/dist/liagent/voice-D7yeS9VM.js +802 -0
- package/dist/liagent/voice-Qo7SCgi8.d.ts +308 -0
- package/dist/liagent/voice.d.ts +3 -0
- package/dist/liagent/voice.js +4 -0
- package/dist/{notifyDaemon-C7GlfJ1E.js → notifyDaemon-DkUB7GV2.js} +10 -9
- package/dist/{openBrowser-1cIo4dJL.js → openBrowser-CQAOIrD6.js} +1 -1
- package/dist/oxmgrService-DlYHmqyI.js +37 -0
- package/dist/oxmgrService-o9L3I6FX.js +3 -0
- package/dist/{parentLink-DoEWVGld.js → parentLink-BcAYcO9L.js} +2 -2
- package/dist/{parentLink-B58V1RVd.js → parentLink-MBUD3oY2.js} +2 -2
- package/dist/{parentPingLoop-C73bbmCE.js → parentPingLoop-DDO592Wh.js} +5 -5
- package/dist/{pidStore-433kvh9D.js → pidStore-C50VPk3E.js} +3 -3
- package/dist/pidStore-COkPjpW8.js +6 -0
- package/dist/{procStats-BvmrBrOs.js → procStats-DwTxj3rs.js} +1 -1
- package/dist/{remotes-MfdV9M8u.js → remotes-BqLoB5GR.js} +2 -2
- package/dist/{remotes-DevcBeLl.js → remotes-BsMGvAay.js} +3 -3
- package/dist/{roomReplyAlias-DFqg_6IU.js → roomReplyAlias-B-v76TA8.js} +3 -3
- package/dist/roomReplyAlias-BzWUBkQy.js +6 -0
- package/dist/{rustBinary-7VK7oLlW.js → rustBinary-BrJ2p8wy.js} +2 -2
- package/dist/{rustBinary-BV4LxMMn.js → rustBinary-vpfpWj1q.js} +2 -2
- package/dist/{schedule-Dp0qkNO1.js → schedule-Bzjhl6-h.js} +15 -44
- package/dist/schedulesCli-CLqieyQZ.js +784 -0
- package/dist/senderAncestry-CVHeKk1Y.js +173 -0
- package/dist/senderAncestry-KhAUPCQs.js +3 -0
- package/dist/{serve-BpOIIOVc.js → serve-XwFYE0cE.js} +67 -69
- package/dist/{serveRust-CbBrcUrg.js → serveRust-BfWkeL6T.js} +31 -4
- package/dist/{setup-DdIBk6Iv.js → setup-D4-s2VZw.js} +5 -5
- package/dist/{share-w5oRbvlj.js → share-CbFetL5H.js} +1 -1
- package/dist/{share-DrS3LYqf.js → share-_TPYAGWC.js} +1 -1
- package/dist/{shareCmd-DDENkBW2.js → shareCmd-DUBsVI3e.js} +10 -10
- package/dist/spawnGate-Dfj9V76w.js +5 -0
- package/dist/{spawnGate-lr3tvA6U.js → spawnGate-Dj_WaS29.js} +3 -3
- package/dist/{subcommands-DxgvDmZX.js → subcommands-B7YZJL8n.js} +471 -307
- package/dist/subcommands-BZPxFgkT.js +15 -0
- package/dist/{systemPathLink-SjUzgSiq.js → systemPathLink-Y3iC7bYV.js} +1 -1
- package/dist/{terminal-C2h7tpe0.js → terminal-13cGj3h6.js} +2 -2
- package/dist/terminal.js +1 -1
- package/dist/{todoAutomation-TTp_Qz9G.js → todoAutomation-CKlrxuZv.js} +2 -2
- package/dist/{todoCli-BWm5nZE0.js → todoCli-CU9vSJSJ.js} +6 -6
- package/dist/{todoIdentity-BvXZKWJI.js → todoIdentity-CzS1e7VL.js} +2 -2
- package/dist/{todoStore-C9RTz0Vs.js → todoStore-msRCEUi1.js} +2 -2
- package/dist/{tray-BeRSozJz.js → tray-CLktEN3G.js} +1 -1
- package/dist/{trayApp-QQjqhDv1.js → trayApp-5_OlvQcz.js} +2 -2
- package/dist/trayApp-DkAPo0m6.js +5 -0
- package/dist/{ts-6LF7f4fx.js → ts-njuddXQz.js} +126 -57
- package/dist/{versionChecker-Bc62HNf6.js → versionChecker-BJycAanp.js} +2 -2
- package/dist/{webrtcLink-va_gAR77.js → webrtcLink-DcvacEci.js} +1 -1
- package/dist/{webrtcLink-SsInrVHU.js → webrtcLink-WxS1nTIs.js} +1 -1
- package/dist/{webrtcRemote-BlGyNZDC.js → webrtcRemote-C3xQyf3u.js} +2 -2
- package/dist/{widget-Crb5zeHL.js → widget-DmRwOlco.js} +3 -3
- package/dist/widgets.js +1 -1
- package/dist/{workspaceConfig-BLWB5Wu9.js → workspaceConfig-DBgsu81B.js} +1 -1
- package/dist/{ws-DIbwNz8Z.js → ws-ByO6JO6m.js} +3 -3
- package/dist/{ws-BRhPG1Vy.js → ws-D0-Jg88z.js} +9 -8
- package/lab/ui/index.html +1 -1
- package/lab/ui/lab/posts/2026-08-11-slack-term-safe-writes.md +1 -1
- package/package.json +73 -8
- package/ts/JsonlStore.ts +10 -3
- package/ts/cli-idle.bun.spec.ts +1 -1
- package/ts/cli-idle.spec.ts +1 -1
- package/ts/cli.ts +35 -0
- package/ts/cmdKill.bun.spec.ts +155 -0
- package/ts/cmdKill.spec.ts +155 -0
- package/ts/cmdKill.ts +183 -0
- package/ts/composerGuard.edges.spec.ts +91 -0
- package/ts/composerGuard.spec.ts +53 -6
- package/ts/composerGuard.ts +42 -13
- package/ts/conptyModeFilter.spec.ts +30 -0
- package/ts/conptyModeFilter.ts +53 -0
- package/ts/copyLiagent.ts +42 -0
- package/ts/cwdConflictWarn.io.spec.ts +50 -0
- package/ts/cwdConflictWarn.spec.ts +34 -1
- package/ts/cwdConflictWarn.ts +43 -5
- package/ts/cwdGuard.spec.ts +110 -0
- package/ts/cwdGuard.ts +118 -0
- package/ts/forceKill.ts +52 -0
- package/ts/forkNested.bun.spec.ts +41 -0
- package/ts/forkNested.spec.ts +41 -0
- package/ts/forkNested.ts +48 -1
- package/ts/globalPidIndex.edges.spec.ts +125 -0
- package/ts/globalPidIndex.ts +6 -2
- package/ts/index.ts +13 -1
- package/ts/interruptSend.bun.spec.ts +99 -0
- package/ts/interruptSend.spec.ts +99 -0
- package/ts/interruptSend.ts +51 -0
- package/ts/lockRegistry.spec.ts +49 -0
- package/ts/lsRenderCache.spec.ts +58 -0
- package/ts/needsInput.edges.spec.ts +23 -0
- package/ts/parseCliArgs.ts +7 -0
- package/ts/pushGatePlan.spec.ts +147 -0
- package/ts/roomReplyAlias.io.spec.ts +81 -0
- package/ts/schedule.ts +5 -1
- package/ts/schedules.bun.spec.ts +397 -0
- package/ts/schedules.spec.ts +397 -0
- package/ts/schedules.ts +517 -0
- package/ts/schedulesCli.ts +386 -0
- package/ts/sendControl.bun.spec.ts +12 -0
- package/ts/senderAncestry.ts +1 -3
- package/ts/serve.ts +22 -33
- package/ts/serveRust.spec.ts +29 -2
- package/ts/serveRust.ts +27 -2
- package/ts/sizeNego.bun.spec.ts +9 -2
- package/ts/sizeNego.spec.ts +9 -2
- package/ts/sizeNego.ts +10 -5
- package/ts/subcommands.spec.ts +348 -9
- package/ts/subcommands.ts +513 -93
- package/ts/suggestAgents.spec.ts +33 -0
- package/ts/terminal/browser.ts +1 -1
- package/ts/todoParse.spec.ts +22 -1
- package/ts/todoParse.ts +19 -0
- package/dist/SUPPORTED_CLIS-ByO5twge.js +0 -12
- package/dist/callback-D7qfh_7p.js +0 -16
- package/dist/pidStore-BRlKRHXY.js +0 -6
- package/dist/roomReplyAlias-DuEkSSDI.js +0 -6
- package/dist/spawnGate-DeQBTX-o.js +0 -5
- package/dist/subcommands-DmiswRy4.js +0 -14
- package/dist/trayApp-C4TAvRvU.js +0 -5
|
@@ -0,0 +1,908 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { PENDING_MS, ROOT_NODE, agentIdOf, nodePath, routeTo } from "./protocol.js";
|
|
3
|
+
import { C as parseTtl, S as parseProgressReport, d as PROGRESS_STATUSES, o as PROGRESS_KINDS, v as isProgressId } from "./progress-CJs08bXb.js";
|
|
4
|
+
import { homedir, hostname } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { appendFileSync, chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
|
|
8
|
+
//#region src/deliver.ts
|
|
9
|
+
/**
|
|
10
|
+
* `ay send` refuses more than 1024 chars per send, and a long paste into a
|
|
11
|
+
* live CLI gets mangled anyway: past this, the agent gets a preview and the
|
|
12
|
+
* path of a file with the whole message.
|
|
13
|
+
*/
|
|
14
|
+
const SEND_MAX = 900;
|
|
15
|
+
/** The text one chat message is delivered as: a header with the reply command, then the body. */
|
|
16
|
+
function deliveryText(hub, m, spill) {
|
|
17
|
+
const who = m.from === "friend" ? `friend ${m.email || m.thread}` : "the user";
|
|
18
|
+
const replyTo = m.from === "friend" ? ` --to ${m.email || m.thread}` : "";
|
|
19
|
+
const page = m.label.split(" ")[0] || "?";
|
|
20
|
+
const header = `[liagent ${m.id}] ${who} wrote in the chat box (${page}) — reply: liagent say ${hub}${replyTo} "..."\n`;
|
|
21
|
+
if (header.length + m.text.length <= SEND_MAX) return header + m.text;
|
|
22
|
+
const path = spill(m.id, m.text);
|
|
23
|
+
const room = Math.max(0, SEND_MAX - header.length - path.length - 40);
|
|
24
|
+
return `${header}${m.text.slice(0, room)}… (${m.text.length} chars; the whole message: ${path})`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/grants.ts
|
|
29
|
+
/**
|
|
30
|
+
* Create `dir` (and parents) 0700. An existing directory is left alone
|
|
31
|
+
* unless `tighten` (the CLI's own ~/.config/liagent, which older versions
|
|
32
|
+
* created 0755): a custom $LIAGENT_GRANTS may sit in $HOME or /tmp, whose
|
|
33
|
+
* mode is not ours to change.
|
|
34
|
+
*/
|
|
35
|
+
function privateDir(dir, tighten = false) {
|
|
36
|
+
if (mkdirSync(dir, {
|
|
37
|
+
recursive: true,
|
|
38
|
+
mode: 448
|
|
39
|
+
}) !== void 0 || tighten) chmodSync(dir, 448);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Write `text` to `path` as 0600. A file that already exists (left 0644 by an
|
|
43
|
+
* older version) is tightened before the write, so the new content is never
|
|
44
|
+
* readable by others, even for a moment.
|
|
45
|
+
*/
|
|
46
|
+
function privateWrite(path, text) {
|
|
47
|
+
try {
|
|
48
|
+
chmodSync(path, 384);
|
|
49
|
+
} catch (e) {
|
|
50
|
+
if (e.code !== "ENOENT") throw e;
|
|
51
|
+
}
|
|
52
|
+
writeFileSync(path, text, { mode: 384 });
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Append `text` to `path` (the `listen --out` log, which holds what the user
|
|
56
|
+
* and friends wrote) as a 0600 file: created that way, or tightened first if
|
|
57
|
+
* it already exists.
|
|
58
|
+
*/
|
|
59
|
+
function privateAppend(path, text) {
|
|
60
|
+
try {
|
|
61
|
+
chmodSync(path, 384);
|
|
62
|
+
} catch (e) {
|
|
63
|
+
if (e.code !== "ENOENT") throw e;
|
|
64
|
+
}
|
|
65
|
+
appendFileSync(path, text, { mode: 384 });
|
|
66
|
+
}
|
|
67
|
+
/** One grant per hub and scope: chat keys are the hub URL alone (as before), eval ones "<hub> eval". */
|
|
68
|
+
const grantKey = (hub, scope) => scope === "chat" ? hub : `${hub} eval`;
|
|
69
|
+
/** `ownDir`: the directory is the CLI's own (the default path), so tighten it even if it exists. */
|
|
70
|
+
function grantStore(file, ownDir = false) {
|
|
71
|
+
const read = () => {
|
|
72
|
+
try {
|
|
73
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
74
|
+
} catch {
|
|
75
|
+
return {};
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
const write = (g) => {
|
|
79
|
+
privateDir(dirname(file), ownDir);
|
|
80
|
+
privateWrite(file, JSON.stringify(g, null, 2));
|
|
81
|
+
};
|
|
82
|
+
return {
|
|
83
|
+
load: (hub, scope) => read()[grantKey(hub, scope)]?.token,
|
|
84
|
+
save(hub, scope, token, until) {
|
|
85
|
+
write({
|
|
86
|
+
...read(),
|
|
87
|
+
[grantKey(hub, scope)]: {
|
|
88
|
+
token,
|
|
89
|
+
until: new Date(until).toISOString()
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
},
|
|
93
|
+
forget(hub, scope) {
|
|
94
|
+
const g = read();
|
|
95
|
+
const k = grantKey(hub, scope);
|
|
96
|
+
if (!(k in g)) return;
|
|
97
|
+
delete g[k];
|
|
98
|
+
write(g);
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/** Save a long message to `<dir>/<id>.txt` (0600 in a 0700 dir) and return the path. */
|
|
103
|
+
function spillTo(dir, id, text, ownDir = false) {
|
|
104
|
+
privateDir(dir, ownDir);
|
|
105
|
+
const path = join(dir, `${id.replace(/[^A-Za-z0-9_-]/g, "_")}.txt`);
|
|
106
|
+
privateWrite(path, text);
|
|
107
|
+
return path;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
//#endregion
|
|
111
|
+
//#region src/place.ts
|
|
112
|
+
/** The node and assignee from the flags, else the environment; an error for a bad one. */
|
|
113
|
+
function placeOf(flags, env) {
|
|
114
|
+
const rawPath = flags.taskPath ?? env.LIAGENT_TASK_PATH;
|
|
115
|
+
const rawAgent = flags.agent ?? env.LIAGENT_AGENT;
|
|
116
|
+
const node = rawPath?.trim() ? nodePath(rawPath) : void 0;
|
|
117
|
+
if (rawPath?.trim() && !node) return { error: `not a node path: ${rawPath} (letters, digits, ._~- segments, ≤ 80 chars)` };
|
|
118
|
+
const agent = rawAgent?.trim() ? agentIdOf(rawAgent) : void 0;
|
|
119
|
+
if (rawAgent?.trim() && !agent) return { error: `not an agent id: ${rawAgent} (≤ 40 chars of letters, digits, ._@:+- )` };
|
|
120
|
+
const out = {};
|
|
121
|
+
if (node && node !== ROOT_NODE) out.node = node;
|
|
122
|
+
if (agent) out.agent = agent;
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Whether `listen` prints a chat line: the user's and friends' lines (all
|
|
127
|
+
* the hub routed here), and agent lines addressed to a node — never its own,
|
|
128
|
+
* nor the agents' replies to the main thread (as before node paths).
|
|
129
|
+
* `observed`: the hub's mark, or (for history) worked out from the routes.
|
|
130
|
+
*/
|
|
131
|
+
function listenLine(m, self, observed) {
|
|
132
|
+
if (m.from === "agent") {
|
|
133
|
+
if (typeof m.to !== "string") return null;
|
|
134
|
+
if ((m.taskPath ?? ROOT_NODE) === (self.node ?? ROOT_NODE) && m.agentId === self.agent) return null;
|
|
135
|
+
}
|
|
136
|
+
const seen = observed ?? routeTo(self.node, m.to) === "observed";
|
|
137
|
+
return {
|
|
138
|
+
type: "chat",
|
|
139
|
+
...m,
|
|
140
|
+
...seen ? { observed: true } : {}
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
//#endregion
|
|
145
|
+
//#region src/progress-args.ts
|
|
146
|
+
const PROGRESS_USAGE = `liagent progress — report to the live state tree (a progress hub, src/progress-hub.ts).
|
|
147
|
+
|
|
148
|
+
liagent progress [hub] --agent <name> --task "<text>" --status <${PROGRESS_STATUSES.join("|")}>
|
|
149
|
+
[--path /words/prefetch | --id <slug> [--parent <id>]] [--done] [--pct 40] [--eta 15m]
|
|
150
|
+
[--pr 299] [--note "..."] [--needs "approve PR #299"] [--kind <${PROGRESS_KINDS.join("|")}>]
|
|
151
|
+
[--ref <id>] [--action "<command or URL>"] [--link https://…] [--rev N] [--human]
|
|
152
|
+
liagent progress grant [hub] --node <id> --agent <name> [--ttl 8h]
|
|
153
|
+
Mint a token for <name> scoped to <id> and its subtree (inside your own
|
|
154
|
+
scope, never outliving your token); prints it.
|
|
155
|
+
liagent progress resolve [hub] --id <id> [--note "the answer"]
|
|
156
|
+
Check a node off as the owner (the root token only).
|
|
157
|
+
liagent progress show [hub]
|
|
158
|
+
The whole tree and the log, as JSON.
|
|
159
|
+
|
|
160
|
+
--agent defaults to $LIAGENT_AGENT and --path to $LIAGENT_TASK_PATH.
|
|
161
|
+
[hub] is the hub's URL, e.g. https://example.com/api/progress (or --hub;
|
|
162
|
+
default $LIAGENT_PROGRESS_HUB). The token is --token, else
|
|
163
|
+
$LIAGENT_PROGRESS_TOKEN: the hub's secret (the root) or a scoped token.
|
|
164
|
+
--repo owner/name (or $LIAGENT_REPO) prints --pr as a link.`;
|
|
165
|
+
const STRINGS = [
|
|
166
|
+
"agent",
|
|
167
|
+
"task",
|
|
168
|
+
"status",
|
|
169
|
+
"eta",
|
|
170
|
+
"note",
|
|
171
|
+
"id",
|
|
172
|
+
"parent",
|
|
173
|
+
"path",
|
|
174
|
+
"needs",
|
|
175
|
+
"kind",
|
|
176
|
+
"ref",
|
|
177
|
+
"action",
|
|
178
|
+
"link",
|
|
179
|
+
"token",
|
|
180
|
+
"node",
|
|
181
|
+
"ttl",
|
|
182
|
+
"hub",
|
|
183
|
+
"repo"
|
|
184
|
+
];
|
|
185
|
+
const NUMBERS = [
|
|
186
|
+
"pct",
|
|
187
|
+
"pr",
|
|
188
|
+
"rev"
|
|
189
|
+
];
|
|
190
|
+
const SWITCHES = ["done", "human"];
|
|
191
|
+
const SUBS = [
|
|
192
|
+
"grant",
|
|
193
|
+
"resolve",
|
|
194
|
+
"show"
|
|
195
|
+
];
|
|
196
|
+
/**
|
|
197
|
+
* argv (after `progress`) → the command, or an Error naming what is wrong.
|
|
198
|
+
* A first (or post-subcommand) argument that is a URL is the hub.
|
|
199
|
+
*/
|
|
200
|
+
function parseProgressArgs(argv, env = {}) {
|
|
201
|
+
const sub = SUBS.includes(argv[0] ?? "") ? argv[0] : "report";
|
|
202
|
+
const raw = {};
|
|
203
|
+
let i = sub === "report" ? 0 : 1;
|
|
204
|
+
if (argv[i] && /^(https?|wss?):\/\//.test(argv[i])) raw.hub = argv[i++];
|
|
205
|
+
for (; i < argv.length; i++) {
|
|
206
|
+
const arg = argv[i];
|
|
207
|
+
const m = /^--([a-z]+)(?:=(.*))?$/s.exec(arg);
|
|
208
|
+
if (!m) return /* @__PURE__ */ new Error(`unexpected argument: ${arg}`);
|
|
209
|
+
const name = m[1];
|
|
210
|
+
if (SWITCHES.includes(name)) {
|
|
211
|
+
raw[name] = true;
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
const value = m[2] ?? argv[++i];
|
|
215
|
+
if (value === void 0) return /* @__PURE__ */ new Error(`--${name} needs a value`);
|
|
216
|
+
if (STRINGS.includes(name)) raw[name] = value;
|
|
217
|
+
else if (NUMBERS.includes(name)) {
|
|
218
|
+
const n = Number(value.replace(/^#|%$/g, ""));
|
|
219
|
+
if (value.trim() === "" || !Number.isFinite(n)) return /* @__PURE__ */ new Error(`--${name} must be a number`);
|
|
220
|
+
raw[name] = n;
|
|
221
|
+
} else return /* @__PURE__ */ new Error(`unknown flag: --${name}`);
|
|
222
|
+
}
|
|
223
|
+
const str = (v) => typeof v === "string" && v.trim() ? v.trim() : void 0;
|
|
224
|
+
const common = {};
|
|
225
|
+
const token = str(raw.token) ?? str(env.LIAGENT_PROGRESS_TOKEN);
|
|
226
|
+
const hub = (str(raw.hub) ?? str(env.LIAGENT_PROGRESS_HUB))?.replace(/\/+$/, "");
|
|
227
|
+
const repo = str(raw.repo) ?? str(env.LIAGENT_REPO);
|
|
228
|
+
if (token) common.token = token;
|
|
229
|
+
if (hub) common.hub = hub;
|
|
230
|
+
if (repo) {
|
|
231
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) return /* @__PURE__ */ new Error("--repo must be owner/name");
|
|
232
|
+
common.repo = repo;
|
|
233
|
+
}
|
|
234
|
+
if (sub === "show") return {
|
|
235
|
+
cmd: "show",
|
|
236
|
+
...common
|
|
237
|
+
};
|
|
238
|
+
const agent = str(raw.agent) ?? str(env.LIAGENT_AGENT);
|
|
239
|
+
if (sub === "grant") {
|
|
240
|
+
if (!isProgressId(raw.node)) return /* @__PURE__ */ new Error("grant needs --node <id>");
|
|
241
|
+
if (typeof raw.agent !== "string" || !raw.agent) return /* @__PURE__ */ new Error("grant needs --agent <name>");
|
|
242
|
+
const ttl = typeof raw.ttl === "string" ? raw.ttl : "8h";
|
|
243
|
+
const ms = parseTtl(ttl);
|
|
244
|
+
if (ms instanceof Error) return /* @__PURE__ */ new Error(`--ttl: ${ms.message}`);
|
|
245
|
+
return {
|
|
246
|
+
cmd: "grant",
|
|
247
|
+
node: raw.node,
|
|
248
|
+
agent: raw.agent,
|
|
249
|
+
ttl,
|
|
250
|
+
...common
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
if (sub === "resolve") {
|
|
254
|
+
if (!isProgressId(raw.id)) return /* @__PURE__ */ new Error("resolve needs --id <id>");
|
|
255
|
+
return {
|
|
256
|
+
cmd: "resolve",
|
|
257
|
+
id: raw.id,
|
|
258
|
+
...typeof raw.note === "string" ? { note: raw.note } : {},
|
|
259
|
+
...common
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
if (raw.done) raw.status = "done";
|
|
263
|
+
if (raw.path === void 0 && raw.id === void 0 && str(env.LIAGENT_TASK_PATH)) raw.path = str(env.LIAGENT_TASK_PATH);
|
|
264
|
+
if (raw.path !== void 0) {
|
|
265
|
+
if (raw.id !== void 0 && raw.id !== raw.path) return /* @__PURE__ */ new Error("--path and --id differ");
|
|
266
|
+
raw.id = raw.path;
|
|
267
|
+
}
|
|
268
|
+
if (agent) raw.agent = agent;
|
|
269
|
+
if (raw.human) {
|
|
270
|
+
raw.assignee = {
|
|
271
|
+
type: "human",
|
|
272
|
+
name: raw.agent
|
|
273
|
+
};
|
|
274
|
+
delete raw.agent;
|
|
275
|
+
}
|
|
276
|
+
for (const k of [
|
|
277
|
+
"path",
|
|
278
|
+
"done",
|
|
279
|
+
"human",
|
|
280
|
+
"token",
|
|
281
|
+
"hub",
|
|
282
|
+
"repo"
|
|
283
|
+
]) delete raw[k];
|
|
284
|
+
const report = parseProgressReport(raw);
|
|
285
|
+
return report instanceof Error ? report : {
|
|
286
|
+
cmd: "report",
|
|
287
|
+
report,
|
|
288
|
+
...common
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
/** The request a command makes: a path below the hub URL and a body (none: GET). */
|
|
292
|
+
function progressRequest(c) {
|
|
293
|
+
if (c.cmd === "report") return {
|
|
294
|
+
path: "",
|
|
295
|
+
body: c.report
|
|
296
|
+
};
|
|
297
|
+
if (c.cmd === "grant") return {
|
|
298
|
+
path: "/grant",
|
|
299
|
+
body: {
|
|
300
|
+
node: c.node,
|
|
301
|
+
agent: c.agent,
|
|
302
|
+
ttl: c.ttl
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
if (c.cmd === "resolve") return {
|
|
306
|
+
path: "/resolve",
|
|
307
|
+
body: c.note ? {
|
|
308
|
+
id: c.id,
|
|
309
|
+
note: c.note
|
|
310
|
+
} : { id: c.id }
|
|
311
|
+
};
|
|
312
|
+
return { path: "" };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
//#endregion
|
|
316
|
+
//#region src/progress-cli.ts
|
|
317
|
+
/** POST `body` (or GET without one) to `<hub><path>`; the JSON answer, or an Error. */
|
|
318
|
+
async function callProgress(hub, token, path, body, fetchImpl = fetch) {
|
|
319
|
+
try {
|
|
320
|
+
const res = await fetchImpl(`${hub}${path}`, {
|
|
321
|
+
method: body === void 0 ? "GET" : "POST",
|
|
322
|
+
headers: {
|
|
323
|
+
authorization: `Bearer ${token}`,
|
|
324
|
+
"content-type": "application/json"
|
|
325
|
+
},
|
|
326
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
327
|
+
signal: AbortSignal.timeout(1e4)
|
|
328
|
+
});
|
|
329
|
+
const text = await res.text();
|
|
330
|
+
if (!res.ok) return /* @__PURE__ */ new Error(`${res.status} ${text.slice(0, 300)}`);
|
|
331
|
+
return JSON.parse(text);
|
|
332
|
+
} catch (e) {
|
|
333
|
+
return e instanceof Error ? e : new Error(String(e));
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
/** Run `liagent progress <argv>`; the exit code. */
|
|
337
|
+
async function runProgress(argv, env = process.env, out = console, fetchImpl = fetch) {
|
|
338
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
339
|
+
out.log(PROGRESS_USAGE);
|
|
340
|
+
return 0;
|
|
341
|
+
}
|
|
342
|
+
const cmd = parseProgressArgs(argv, env);
|
|
343
|
+
if (cmd instanceof Error) {
|
|
344
|
+
out.error(`liagent progress: ${cmd.message}\n\n${PROGRESS_USAGE}`);
|
|
345
|
+
return 2;
|
|
346
|
+
}
|
|
347
|
+
if (!cmd.hub) {
|
|
348
|
+
out.error("liagent progress: no hub — pass its URL, --hub, or set LIAGENT_PROGRESS_HUB");
|
|
349
|
+
return 2;
|
|
350
|
+
}
|
|
351
|
+
if (!cmd.token) {
|
|
352
|
+
out.error("liagent progress: no token — pass --token or set LIAGENT_PROGRESS_TOKEN");
|
|
353
|
+
return 2;
|
|
354
|
+
}
|
|
355
|
+
const { path, body } = progressRequest(cmd);
|
|
356
|
+
const res = await callProgress(cmd.hub, cmd.token, path, body, fetchImpl);
|
|
357
|
+
if (res instanceof Error) {
|
|
358
|
+
out.error(`liagent progress: ${res.message}`);
|
|
359
|
+
return 1;
|
|
360
|
+
}
|
|
361
|
+
if (cmd.cmd === "grant") out.log(String(res.token));
|
|
362
|
+
else if (cmd.cmd === "show") out.log(JSON.stringify(res, null, 2));
|
|
363
|
+
else if (cmd.cmd === "resolve") {
|
|
364
|
+
const ids = res.resolved ?? [];
|
|
365
|
+
out.log(`progress: resolved ${ids.join(", ") || "nothing (already done)"}`);
|
|
366
|
+
} else {
|
|
367
|
+
const e = res.entry;
|
|
368
|
+
const pr = e.pr && cmd.repo ? ` https://github.com/${cmd.repo}/pull/${e.pr}` : "";
|
|
369
|
+
out.log(`progress: ${e.id} ${e.status} (rev ${e.rev}, ${res.readers ?? 0} watching)${pr}`);
|
|
370
|
+
}
|
|
371
|
+
return 0;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
//#endregion
|
|
375
|
+
//#region src/cli.ts
|
|
376
|
+
const USAGE = `liagent — the agent's side of the user ⇄ agent chat (src/hub.ts).
|
|
377
|
+
|
|
378
|
+
liagent pair [hub] [--eval] [--label "…"]
|
|
379
|
+
Ask the user to approve this agent: prints a short code, which the
|
|
380
|
+
box shows too. Chat (the default) lasts 30 days on all of the user's
|
|
381
|
+
pages; --eval asks to run code (and chat) for 8 hours on the pages
|
|
382
|
+
the user ticks. Either way the grant token is saved, so later
|
|
383
|
+
commands resume it without asking.
|
|
384
|
+
|
|
385
|
+
liagent listen [hub] [--to <agent>] [--out <file>] [--label "…"]
|
|
386
|
+
Hold the chat. Each new message from the user (or a friend) is one
|
|
387
|
+
JSON line on stdout {type:"chat", id, from, label, text, at, thread?},
|
|
388
|
+
and so is each {type:"page-changed", label, thread, at} when one of
|
|
389
|
+
the user's pages navigates (all also appended to --out). With --to,
|
|
390
|
+
each message is also delivered into that agent-yes agent with
|
|
391
|
+
\`ay send\`, with the reply command in it, and while the agent works
|
|
392
|
+
(its \`ay ls\` status is "active") the box shows a spinner. It resumes
|
|
393
|
+
the saved grant and reconnects on network drops (backing off from 1 s
|
|
394
|
+
to a minute) without ever asking the user again; see "Pairing".
|
|
395
|
+
|
|
396
|
+
liagent say [hub] "text" | - [--to <email|user id>]
|
|
397
|
+
Reply in the box (the user's thread, or a friend's), then exit.
|
|
398
|
+
|
|
399
|
+
liagent say [hub] "text" --to /words/audio
|
|
400
|
+
Address a state-tree node instead (a --to starting with "/"): its
|
|
401
|
+
agent gets it, its ancestors observe it. Allowed into your own
|
|
402
|
+
subtree and upward; anything else needs a grant (below), else
|
|
403
|
+
{type:"error", reason:"out of scope: needs a grant from /words"}.
|
|
404
|
+
|
|
405
|
+
liagent edit [hub] (<msgId> | --last) "polished text" | -
|
|
406
|
+
Polish the user's latest line when it came from the box's mic (it
|
|
407
|
+
carries "source":"stt" in listen's output): STT gets words wrong and
|
|
408
|
+
has no context. The hub keeps the first STT text as raw, marks the
|
|
409
|
+
line edited, and updates it in place in the box (never read aloud
|
|
410
|
+
again). Only the user's LATEST line, only stt, at most 3 times;
|
|
411
|
+
friends' lines never. --last targets the user's latest line. Prints
|
|
412
|
+
{type:"edited", id, thread, text, raw, edited}, or the rule it broke.
|
|
413
|
+
|
|
414
|
+
liagent grant [hub] --from /words/prefetch --to /words/audio [--hours 8]
|
|
415
|
+
liagent ungrant [hub] --from /words/prefetch --to /words/audio
|
|
416
|
+
Let senders within one node address another (or take it back): only
|
|
417
|
+
from an agent whose node holds both — the main one ("/") always may.
|
|
418
|
+
|
|
419
|
+
--task-path /words/prefetch (or $LIAGENT_TASK_PATH)
|
|
420
|
+
--agent <name> (or $LIAGENT_AGENT)
|
|
421
|
+
Where this agent sits in the state tree. Messages are addressed to
|
|
422
|
+
state-tree nodes; a node's assignee (agent or human) receives them.
|
|
423
|
+
listen hears the lines addressed to that node (and, marked
|
|
424
|
+
"observed": true, to the nodes below it) instead of the main thread;
|
|
425
|
+
say lines carry it as taskPath and the name as agentId, which the box
|
|
426
|
+
shows under the avatar as "/words › prefetch". A sub-agent sets the
|
|
427
|
+
env vars once.
|
|
428
|
+
|
|
429
|
+
liagent busy [hub] [--to <email|user id>] [--every <seconds>]
|
|
430
|
+
One heartbeat: the box shows a spinner for 12 s, or until you reply.
|
|
431
|
+
With --every (e.g. 4, run it in the background), it keeps beating
|
|
432
|
+
until your next reply in that thread, and then exits (30 min at most).
|
|
433
|
+
|
|
434
|
+
liagent eval [hub] [--target <text>] '<code>' | -
|
|
435
|
+
Run code on the pages the user allowed (a hub with eval only),
|
|
436
|
+
resuming the saved eval grant, and print each page's result.
|
|
437
|
+
|
|
438
|
+
Pairing prompts the user, so it is rationed:
|
|
439
|
+
- A command resumes the saved grant for its scope (x-liagent-token).
|
|
440
|
+
- It pairs at most once per process, and never from a reconnect loop.
|
|
441
|
+
- A saved grant the hub rejects (4498) is forgotten, and the command
|
|
442
|
+
pairs once; if that fails too, it stops (listen stays idle).
|
|
443
|
+
- A pairing that fails is never retried: denied, expired (4408),
|
|
444
|
+
another request waiting (4429), no page open (4404), or no answer.
|
|
445
|
+
Only a network failure before the user was shown anything is retried
|
|
446
|
+
(listen backs off and tries again): no prompt was spent.
|
|
447
|
+
- --no-pair (any command): only ever resume; never ask.
|
|
448
|
+
|
|
449
|
+
liagent progress [hub] --agent <name> --path /words/prefetch --task "…" --status doing --pct 40
|
|
450
|
+
liagent progress [hub] … --done --pr 12
|
|
451
|
+
liagent progress grant|resolve|show [hub] …
|
|
452
|
+
Report to the live state tree (a progress hub, not the chat hub):
|
|
453
|
+
one HTTP request with a bearer token ($LIAGENT_PROGRESS_TOKEN), hub
|
|
454
|
+
$LIAGENT_PROGRESS_HUB. "liagent progress --help" has every flag.
|
|
455
|
+
|
|
456
|
+
[hub] is the hub's page-socket URL, e.g. https://dev.example.com/api/chat
|
|
457
|
+
(its agent socket is <hub>/control). Default: $LIAGENT_HUB. Grants are kept
|
|
458
|
+
in ~/.config/liagent/grants.json (mode 600; $LIAGENT_GRANTS overrides), one
|
|
459
|
+
per hub and scope. "End" in the box revokes a grant; the CLI then forgets it.`;
|
|
460
|
+
const GRANTS = process.env.LIAGENT_GRANTS ?? join(homedir(), ".config", "liagent", "grants.json");
|
|
461
|
+
const RESULT_MS = 2e4;
|
|
462
|
+
/** How often `listen --to` checks the agent's status and beats (pages time a beat out after 12 s). */
|
|
463
|
+
const BEAT_MS = 5e3;
|
|
464
|
+
function usage(code = 0) {
|
|
465
|
+
(code ? console.error : console.log)(USAGE);
|
|
466
|
+
process.exit(code);
|
|
467
|
+
}
|
|
468
|
+
const args = process.argv.slice(2);
|
|
469
|
+
const cmd = args.shift();
|
|
470
|
+
if (!cmd || cmd === "--help" || cmd === "-h" || cmd === "help") usage();
|
|
471
|
+
if (cmd === "progress") process.exit(await runProgress(args));
|
|
472
|
+
const flag = (name) => {
|
|
473
|
+
const i = args.indexOf(name);
|
|
474
|
+
if (i === -1) return void 0;
|
|
475
|
+
const v = args[i + 1];
|
|
476
|
+
args.splice(i, 2);
|
|
477
|
+
return v;
|
|
478
|
+
};
|
|
479
|
+
const labelFlag = flag("--label");
|
|
480
|
+
const label = labelFlag ?? `agent on ${hostname()}`;
|
|
481
|
+
const placed = placeOf({
|
|
482
|
+
taskPath: flag("--task-path"),
|
|
483
|
+
agent: flag("--agent")
|
|
484
|
+
}, process.env);
|
|
485
|
+
if ("error" in placed) {
|
|
486
|
+
console.error(`liagent: ${placed.error}`);
|
|
487
|
+
process.exit(2);
|
|
488
|
+
}
|
|
489
|
+
const place = placed;
|
|
490
|
+
/** The hub: the first argument if it is a URL, else $LIAGENT_HUB. */
|
|
491
|
+
function takeHub() {
|
|
492
|
+
if (args[0] && /^(https?|wss?):\/\//.test(args[0])) return args.shift().replace(/\/+$/, "");
|
|
493
|
+
const env = process.env.LIAGENT_HUB?.replace(/\/+$/, "");
|
|
494
|
+
if (!env) {
|
|
495
|
+
console.error("liagent: no hub — pass its URL or set LIAGENT_HUB");
|
|
496
|
+
process.exit(2);
|
|
497
|
+
}
|
|
498
|
+
return env;
|
|
499
|
+
}
|
|
500
|
+
/** The default location is ours to tighten; a custom $LIAGENT_GRANTS's folder is not. */
|
|
501
|
+
const ownGrantsDir = !process.env.LIAGENT_GRANTS;
|
|
502
|
+
const grants = grantStore(GRANTS, ownGrantsDir);
|
|
503
|
+
const loadToken = grants.load;
|
|
504
|
+
const saveToken = grants.save;
|
|
505
|
+
const forgetToken = grants.forget;
|
|
506
|
+
function controlUrl(hub, extra = {}) {
|
|
507
|
+
const u = new URL(`${hub}/control`);
|
|
508
|
+
if (u.protocol === "http:") u.protocol = "ws:";
|
|
509
|
+
if (u.protocol === "https:") u.protocol = "wss:";
|
|
510
|
+
const l = extra.token ? labelFlag ?? "" : label;
|
|
511
|
+
if (l) u.searchParams.set("label", l);
|
|
512
|
+
for (const [k, v] of Object.entries(extra)) if (k !== "token") u.searchParams.set(k, v);
|
|
513
|
+
if (place.node) u.searchParams.set("node", place.node);
|
|
514
|
+
if (place.agent) u.searchParams.set("agent", place.agent);
|
|
515
|
+
return u.toString();
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Bun's WebSocket takes headers, so the grant goes in one, never in the URL.
|
|
519
|
+
* Without a grant, the knock says what it asks for: chat (30 days) or eval (8 hours).
|
|
520
|
+
*/
|
|
521
|
+
function open(hub, scope, token) {
|
|
522
|
+
return token ? new WebSocket(controlUrl(hub, { token }), { headers: { "x-liagent-token": token } }) : new WebSocket(controlUrl(hub, { scope }));
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* Why a connection attempt failed. `code` is the close code (or 0); `fatal`
|
|
526
|
+
* means asking again would only prompt the user again: stop instead.
|
|
527
|
+
*/
|
|
528
|
+
var ConnectError = class extends Error {
|
|
529
|
+
constructor(message, code, fatal, prompted = false) {
|
|
530
|
+
super(message);
|
|
531
|
+
this.code = code;
|
|
532
|
+
this.fatal = fatal;
|
|
533
|
+
this.prompted = prompted;
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
/** --no-pair: only ever resume a saved grant; never ask the user. */
|
|
537
|
+
const noPair = args.includes("--no-pair");
|
|
538
|
+
if (noPair) args.splice(args.indexOf("--no-pair"), 1);
|
|
539
|
+
/** Pairing prompts the user, so a process asks at most once — never from a reconnect loop. */
|
|
540
|
+
let pairedOnce = false;
|
|
541
|
+
/** The history each approved socket was sent right after its approval (for `edit --last`). */
|
|
542
|
+
const histories = /* @__PURE__ */ new WeakMap();
|
|
543
|
+
/** One socket: resume with `token`, or knock without one. Resolves once approved. */
|
|
544
|
+
function attempt(hub, scope, token) {
|
|
545
|
+
return new Promise((resolve, reject) => {
|
|
546
|
+
const ws = open(hub, scope, token);
|
|
547
|
+
let settled = false;
|
|
548
|
+
let reason = "";
|
|
549
|
+
let prompted = false;
|
|
550
|
+
const done = (err) => {
|
|
551
|
+
if (settled) return;
|
|
552
|
+
settled = true;
|
|
553
|
+
clearTimeout(give);
|
|
554
|
+
if (err) {
|
|
555
|
+
ws.close();
|
|
556
|
+
reject(err);
|
|
557
|
+
} else resolve(ws);
|
|
558
|
+
};
|
|
559
|
+
const give = setTimeout(() => done(new ConnectError("no answer in the box within 2 minutes", 0, true, prompted)), PENDING_MS + 5e3);
|
|
560
|
+
ws.onmessage = (e) => {
|
|
561
|
+
const m = JSON.parse(String(e.data));
|
|
562
|
+
if (m.type === "pending") {
|
|
563
|
+
prompted = true;
|
|
564
|
+
console.error(`Pairing as "${label}" (${scope === "eval" ? "run code and chat, 8 hours" : "chat, 30 days"}). In the box, allow code ${m.code}`);
|
|
565
|
+
} else if (m.type === "approved") {
|
|
566
|
+
if (typeof m.token === "string") saveToken(hub, scope, m.token, Number(m.until));
|
|
567
|
+
if (!m.resumed) console.error(`Approved (${m.scope}${m.pages === "all" ? ", all pages" : Array.isArray(m.pages) ? `, ${m.pages.length} page(s)` : ""}) until ${new Date(Number(m.until)).toLocaleString()}.`);
|
|
568
|
+
histories.set(ws, new Promise((resolve) => {
|
|
569
|
+
const t = setTimeout(() => resolve([]), 5e3);
|
|
570
|
+
ws.onmessage = (h) => {
|
|
571
|
+
const x = JSON.parse(String(h.data));
|
|
572
|
+
if (x.type !== "history") return;
|
|
573
|
+
clearTimeout(t);
|
|
574
|
+
ws.onmessage = null;
|
|
575
|
+
resolve(Array.isArray(x.messages) ? x.messages : []);
|
|
576
|
+
};
|
|
577
|
+
}));
|
|
578
|
+
ws.onclose = null;
|
|
579
|
+
done();
|
|
580
|
+
} else if (m.type === "error" || m.type === "denied" || m.type === "expired") reason = String(m.error ?? m.type);
|
|
581
|
+
};
|
|
582
|
+
ws.onclose = (e) => done(new ConnectError(reason || `socket closed (${e.code}${e.reason ? ` ${e.reason}` : ""})`, e.code, false, prompted));
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* An approved socket for `scope`: resume the saved grant, or — once per
|
|
587
|
+
* process, and never with --no-pair — pair, which prompts the user. A
|
|
588
|
+
* rejected token (4498) is forgotten and leads to that one pairing. Any
|
|
589
|
+
* failure of the pairing itself (denied, 4408 expired, 4429 another request
|
|
590
|
+
* waiting, 4404 no page open, no answer) is fatal: it is not retried.
|
|
591
|
+
* A network failure while resuming is not fatal: the caller retries later.
|
|
592
|
+
*/
|
|
593
|
+
async function connect(hub, scope = "chat") {
|
|
594
|
+
const token = loadToken(hub, scope);
|
|
595
|
+
if (token) try {
|
|
596
|
+
return await attempt(hub, scope, token);
|
|
597
|
+
} catch (e) {
|
|
598
|
+
const err = e;
|
|
599
|
+
if (err.code !== 4498) throw err;
|
|
600
|
+
forgetToken(hub, scope);
|
|
601
|
+
console.error(`liagent: the saved ${scope} grant is no longer valid (${err.message}).`);
|
|
602
|
+
}
|
|
603
|
+
if (noPair) throw new ConnectError(`no valid ${scope} grant, and --no-pair was given`, 0, true);
|
|
604
|
+
if (pairedOnce) throw new ConnectError("already asked the user once in this process; not asking again", 0, true);
|
|
605
|
+
pairedOnce = true;
|
|
606
|
+
try {
|
|
607
|
+
return await attempt(hub, scope);
|
|
608
|
+
} catch (e) {
|
|
609
|
+
const err = e;
|
|
610
|
+
if (!err.prompted && err.code < 4e3) {
|
|
611
|
+
pairedOnce = false;
|
|
612
|
+
throw new ConnectError(`could not reach the hub to pair: ${err.message}`, err.code, false);
|
|
613
|
+
}
|
|
614
|
+
throw new ConnectError(`pairing failed: ${err.message}`, err.code, true, err.prompted);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
/** One-shot commands: an approved socket, or the error and exit 1. */
|
|
618
|
+
async function connectOrExit(hub, scope = "chat") {
|
|
619
|
+
try {
|
|
620
|
+
return await connect(hub, scope);
|
|
621
|
+
} catch (e) {
|
|
622
|
+
console.error(`liagent: ${e.message}`);
|
|
623
|
+
process.exit(1);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
/** Send one message and wait for the reply of `type` (or an error). */
|
|
627
|
+
function request(ws, msg, type, ms = RESULT_MS) {
|
|
628
|
+
return new Promise((resolve, reject) => {
|
|
629
|
+
const give = setTimeout(() => reject(/* @__PURE__ */ new Error(`no ${type} within ${ms / 1e3}s`)), ms);
|
|
630
|
+
const on = (e) => {
|
|
631
|
+
const m = JSON.parse(String(e.data));
|
|
632
|
+
if (m.type === type) {
|
|
633
|
+
clearTimeout(give);
|
|
634
|
+
ws.removeEventListener("message", on);
|
|
635
|
+
resolve(m);
|
|
636
|
+
} else if (m.type === "error" || m.type === "revoked" || m.type === "expired") {
|
|
637
|
+
clearTimeout(give);
|
|
638
|
+
ws.removeEventListener("message", on);
|
|
639
|
+
reject(new Error(String(m.reason ?? m.error ?? m.type)));
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
ws.addEventListener("message", on);
|
|
643
|
+
ws.send(JSON.stringify(msg));
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
async function readText() {
|
|
647
|
+
const rest = args.join(" ");
|
|
648
|
+
if (rest !== "-") return rest;
|
|
649
|
+
return (await new Response(Bun.stdin.stream()).text()).trim();
|
|
650
|
+
}
|
|
651
|
+
/** The agent-yes status of `to` (pid, agent id or its prefix), or undefined. */
|
|
652
|
+
function agentStatus(to) {
|
|
653
|
+
const r = Bun.spawnSync([
|
|
654
|
+
"ay",
|
|
655
|
+
"ls",
|
|
656
|
+
"--json"
|
|
657
|
+
], { stderr: "ignore" });
|
|
658
|
+
if (!r.success) return void 0;
|
|
659
|
+
try {
|
|
660
|
+
return JSON.parse(r.stdout.toString()).find((a) => String(a.pid) === to || a.agent_id && a.agent_id.startsWith(to))?.status;
|
|
661
|
+
} catch {
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
const INBOX = join(dirname(GRANTS), "inbox");
|
|
666
|
+
const spillToInbox = (id, text) => spillTo(INBOX, id, text, ownGrantsDir);
|
|
667
|
+
/**
|
|
668
|
+
* Deliver one message into an agent-yes agent. --force: the owner named the
|
|
669
|
+
* agent with --to, and an agent idle for a minute is the normal case here.
|
|
670
|
+
* --raw: our own header carries the reply route. Exit 4 (queued for the
|
|
671
|
+
* agent's input box) counts as delivered; anything else is retried.
|
|
672
|
+
*/
|
|
673
|
+
function deliver(to, text) {
|
|
674
|
+
const r = Bun.spawnSync([
|
|
675
|
+
"ay",
|
|
676
|
+
"send",
|
|
677
|
+
to,
|
|
678
|
+
text,
|
|
679
|
+
"--force",
|
|
680
|
+
"--raw"
|
|
681
|
+
], {
|
|
682
|
+
stdout: "ignore",
|
|
683
|
+
stderr: "pipe"
|
|
684
|
+
});
|
|
685
|
+
if (r.exitCode === 0 || r.exitCode === 4) return true;
|
|
686
|
+
console.error(`liagent: ay send ${to} failed (${r.exitCode}): ${r.stderr.toString().trim()}`);
|
|
687
|
+
return false;
|
|
688
|
+
}
|
|
689
|
+
/** Stay up without reconnecting or prompting: a supervisor restarting us would only ask again. */
|
|
690
|
+
function idle() {
|
|
691
|
+
console.error("liagent: idle. Fix the grant (or restart with `liagent pair`) and run listen again.");
|
|
692
|
+
setInterval(() => {}, 1 << 30);
|
|
693
|
+
return new Promise(() => {});
|
|
694
|
+
}
|
|
695
|
+
async function cmdListen(hub) {
|
|
696
|
+
const to = flag("--to");
|
|
697
|
+
const out = flag("--out");
|
|
698
|
+
let backoff = 1e3;
|
|
699
|
+
let beat;
|
|
700
|
+
/** Messages `ay send` refused (agent unreachable…), retried on every beat, in order. */
|
|
701
|
+
const undelivered = [];
|
|
702
|
+
const flush = () => {
|
|
703
|
+
while (to && undelivered.length && deliver(to, undelivered[0])) undelivered.shift();
|
|
704
|
+
};
|
|
705
|
+
for (;;) {
|
|
706
|
+
let ws;
|
|
707
|
+
try {
|
|
708
|
+
ws = await connect(hub);
|
|
709
|
+
} catch (e) {
|
|
710
|
+
const err = e;
|
|
711
|
+
console.error(`liagent: ${err.message}`);
|
|
712
|
+
if (err.fatal) return idle();
|
|
713
|
+
await Bun.sleep(backoff);
|
|
714
|
+
backoff = Math.min(backoff * 2, 6e4);
|
|
715
|
+
continue;
|
|
716
|
+
}
|
|
717
|
+
backoff = 1e3;
|
|
718
|
+
console.error(`Listening on ${hub}${to ? `, delivering to ${to}` : ""}.`);
|
|
719
|
+
if (to) beat = setInterval(() => {
|
|
720
|
+
flush();
|
|
721
|
+
if (agentStatus(to) === "active") ws.send(JSON.stringify({ type: "busy" }));
|
|
722
|
+
}, BEAT_MS);
|
|
723
|
+
const code = await new Promise((resolve) => {
|
|
724
|
+
ws.onmessage = (e) => {
|
|
725
|
+
const m = JSON.parse(String(e.data));
|
|
726
|
+
if (m.type === "chat") {
|
|
727
|
+
const c = m.message;
|
|
728
|
+
const shown = listenLine(c, place, m.observed === true);
|
|
729
|
+
if (!shown) return;
|
|
730
|
+
const line = JSON.stringify(shown);
|
|
731
|
+
console.log(line);
|
|
732
|
+
if (out) privateAppend(out, `${line}\n`);
|
|
733
|
+
if (to) {
|
|
734
|
+
undelivered.push(deliveryText(hub, c, spillToInbox));
|
|
735
|
+
flush();
|
|
736
|
+
ws.send(JSON.stringify(c.from === "friend" ? {
|
|
737
|
+
type: "busy",
|
|
738
|
+
to: c.thread
|
|
739
|
+
} : { type: "busy" }));
|
|
740
|
+
}
|
|
741
|
+
} else if (m.type === "friend-new" || m.type === "page-changed" || m.type === "edited") {
|
|
742
|
+
const line = JSON.stringify(m);
|
|
743
|
+
console.log(line);
|
|
744
|
+
if (out) privateAppend(out, `${line}\n`);
|
|
745
|
+
} else if (m.type === "error") console.error(`liagent: ${m.error}`);
|
|
746
|
+
else if (m.type === "revoked") {
|
|
747
|
+
console.error("liagent: the user ended this session.");
|
|
748
|
+
forgetToken(hub, "chat");
|
|
749
|
+
process.exit(0);
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
ws.onclose = (e) => resolve(e.code);
|
|
753
|
+
});
|
|
754
|
+
clearInterval(beat);
|
|
755
|
+
if (code === 4401) {
|
|
756
|
+
forgetToken(hub, "chat");
|
|
757
|
+
console.error("liagent: the user ended this session.");
|
|
758
|
+
process.exit(0);
|
|
759
|
+
}
|
|
760
|
+
console.error(`liagent: socket closed (${code}); reconnecting in ${backoff / 1e3}s`);
|
|
761
|
+
await Bun.sleep(backoff);
|
|
762
|
+
backoff = Math.min(backoff * 2, 6e4);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
async function main() {
|
|
766
|
+
const hub = takeHub();
|
|
767
|
+
if (cmd === "pair") {
|
|
768
|
+
(await connectOrExit(hub, args.includes("--eval") ? "eval" : "chat")).close();
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
if (cmd === "listen") return cmdListen(hub);
|
|
772
|
+
if (cmd === "edit") {
|
|
773
|
+
const last = args.includes("--last");
|
|
774
|
+
if (last) args.splice(args.indexOf("--last"), 1);
|
|
775
|
+
const id = last ? void 0 : args.shift();
|
|
776
|
+
const text = await readText();
|
|
777
|
+
if (!text || !last && !id) usage(2);
|
|
778
|
+
const ws = await connectOrExit(hub);
|
|
779
|
+
let target = id;
|
|
780
|
+
if (last) {
|
|
781
|
+
target = (await histories.get(ws) ?? []).filter((x) => x.from === "owner" && (x.thread ?? "owner") === "owner").at(-1)?.id;
|
|
782
|
+
if (!target) {
|
|
783
|
+
console.error("liagent: the user has no line to polish");
|
|
784
|
+
process.exit(1);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
try {
|
|
788
|
+
const r = await request(ws, {
|
|
789
|
+
type: "edit",
|
|
790
|
+
id: target,
|
|
791
|
+
text
|
|
792
|
+
}, "edited");
|
|
793
|
+
console.log(JSON.stringify(r));
|
|
794
|
+
} catch (e) {
|
|
795
|
+
console.error(`liagent: ${e.message}`);
|
|
796
|
+
process.exit(1);
|
|
797
|
+
}
|
|
798
|
+
ws.close();
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
if (cmd === "say") {
|
|
802
|
+
const to = flag("--to");
|
|
803
|
+
const text = await readText();
|
|
804
|
+
if (!text) usage(2);
|
|
805
|
+
const ws = await connectOrExit(hub);
|
|
806
|
+
const r = await request(ws, {
|
|
807
|
+
type: "say",
|
|
808
|
+
text,
|
|
809
|
+
...to ? { to } : {},
|
|
810
|
+
...place.node ? { taskPath: place.node } : {},
|
|
811
|
+
...place.agent ? { agentId: place.agent } : {}
|
|
812
|
+
}, "said");
|
|
813
|
+
console.error(`said ${r.id}`);
|
|
814
|
+
ws.close();
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
if (cmd === "grant" || cmd === "ungrant") {
|
|
818
|
+
const from = flag("--from");
|
|
819
|
+
const to = flag("--to");
|
|
820
|
+
const hours = Number(flag("--hours") ?? 0);
|
|
821
|
+
if (!from || !to) usage(2);
|
|
822
|
+
const ws = await connectOrExit(hub);
|
|
823
|
+
const r = await request(ws, {
|
|
824
|
+
type: cmd,
|
|
825
|
+
from,
|
|
826
|
+
to,
|
|
827
|
+
...hours > 0 ? { ms: Math.round(hours * 36e5) } : {}
|
|
828
|
+
}, cmd === "grant" ? "granted" : "ungranted");
|
|
829
|
+
console.log(JSON.stringify(r));
|
|
830
|
+
ws.close();
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
if (cmd === "busy") {
|
|
834
|
+
const to = flag("--to");
|
|
835
|
+
const every = Number(flag("--every") ?? 0);
|
|
836
|
+
const ws = await connectOrExit(hub);
|
|
837
|
+
const beat = () => ws.send(JSON.stringify(to ? {
|
|
838
|
+
type: "busy",
|
|
839
|
+
to
|
|
840
|
+
} : { type: "busy" }));
|
|
841
|
+
beat();
|
|
842
|
+
if (every > 0) {
|
|
843
|
+
const timer = setInterval(beat, Math.max(1, every) * 1e3);
|
|
844
|
+
await new Promise((resolve) => {
|
|
845
|
+
const stop = setTimeout(resolve, 30 * 6e4);
|
|
846
|
+
ws.onmessage = (e) => {
|
|
847
|
+
const m = JSON.parse(String(e.data));
|
|
848
|
+
if (m.type === "chat" && m.message.from === "agent") {
|
|
849
|
+
clearTimeout(stop);
|
|
850
|
+
resolve();
|
|
851
|
+
}
|
|
852
|
+
};
|
|
853
|
+
ws.onclose = () => resolve();
|
|
854
|
+
});
|
|
855
|
+
clearInterval(timer);
|
|
856
|
+
}
|
|
857
|
+
await Bun.sleep(200);
|
|
858
|
+
ws.close();
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
if (cmd === "eval") {
|
|
862
|
+
const target = flag("--target");
|
|
863
|
+
const code = await readText();
|
|
864
|
+
if (!code) usage(2);
|
|
865
|
+
const ws = await connectOrExit(hub, "eval");
|
|
866
|
+
const results = [];
|
|
867
|
+
await new Promise((resolve, reject) => {
|
|
868
|
+
let id = "";
|
|
869
|
+
let expected = Infinity;
|
|
870
|
+
const give = setTimeout(resolve, RESULT_MS);
|
|
871
|
+
ws.onmessage = (e) => {
|
|
872
|
+
const m = JSON.parse(String(e.data));
|
|
873
|
+
if (m.type === "sent") {
|
|
874
|
+
id = String(m.id);
|
|
875
|
+
expected = Number(m.delivered);
|
|
876
|
+
console.error(`eval ${id}: delivered to ${expected} page(s)`);
|
|
877
|
+
} else if (m.type === "result" && m.id === id) results.push(m);
|
|
878
|
+
else if (m.type === "error") {
|
|
879
|
+
clearTimeout(give);
|
|
880
|
+
return reject(new Error(String(m.error)));
|
|
881
|
+
}
|
|
882
|
+
if (results.length >= expected) {
|
|
883
|
+
clearTimeout(give);
|
|
884
|
+
resolve();
|
|
885
|
+
}
|
|
886
|
+
};
|
|
887
|
+
ws.send(JSON.stringify(target ? {
|
|
888
|
+
type: "eval",
|
|
889
|
+
code,
|
|
890
|
+
target
|
|
891
|
+
} : {
|
|
892
|
+
type: "eval",
|
|
893
|
+
code
|
|
894
|
+
}));
|
|
895
|
+
});
|
|
896
|
+
console.log(JSON.stringify(results, null, 2));
|
|
897
|
+
ws.close();
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
usage(2);
|
|
901
|
+
}
|
|
902
|
+
main().catch((e) => {
|
|
903
|
+
console.error(`liagent: ${e.message}`);
|
|
904
|
+
process.exit(1);
|
|
905
|
+
});
|
|
906
|
+
|
|
907
|
+
//#endregion
|
|
908
|
+
//# sourceMappingURL=cli.js.map
|