@anytowork/cli 0.12.71 → 0.12.73
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 +17 -102
- package/package.json +2 -2
- package/src/api.js +2 -50
- package/src/apply-backoff.js +1 -1
- package/src/brand.js +2 -2
- package/src/cli-parse.js +7 -131
- package/src/config.js +1 -1
- package/src/connect.js +2 -2
- package/src/exit-reasons.js +0 -9
- package/src/format.js +24 -143
- package/src/index.js +12 -119
- package/src/model-pledge.js +6 -6
- package/src/mt/collect.js +2 -26
- package/src/mt/commands.js +3 -84
- package/src/mt/format-check.js +2 -2
- package/src/mt/readers.js +1 -1
- package/src/mt/text.js +20 -89
- package/src/mt/wake-attribution.js +2 -2
- package/src/mt/workdirs.js +1 -18
- package/src/setup-commands.js +6 -6
- package/src/setup-hints.js +6 -22
- package/src/space-commands.js +2 -41
- package/src/space-sync.js +2 -2
- package/src/chat-commands.js +0 -685
- package/src/chat-state.js +0 -77
- package/src/hire-commands.js +0 -764
- package/src/listen-command.js +0 -79
- package/src/listener/commands.js +0 -183
- package/src/listener/config.js +0 -216
- package/src/listener/hire-wake.js +0 -60
- package/src/listener/install.js +0 -233
- package/src/listener/nudge.js +0 -88
- package/src/listener/prompt.js +0 -111
- package/src/listener/queue.js +0 -112
- package/src/listener/run-error.js +0 -81
- package/src/listener/run.js +0 -723
- package/src/listener/text.js +0 -103
- package/src/mt/inrun.js +0 -351
- package/src/mt/recipes.js +0 -478
- package/src/mt/sample.js +0 -708
- package/src/reply-hint.js +0 -21
- package/src/wb-rules-text.js +0 -169
package/src/listener/install.js
DELETED
|
@@ -1,233 +0,0 @@
|
|
|
1
|
-
// Always-on listener: start at login on macOS, Linux and Windows (plan 01 section 2.5).
|
|
2
|
-
//
|
|
3
|
-
// The generators (plist / unit / task arguments / cron line) are pure functions so tests can check the files without
|
|
4
|
-
// installing anything. They write the absolute path of node and of this command, plus the PATH of the moment of
|
|
5
|
-
// installing, because a login-time job does not see the owner's shell setup.
|
|
6
|
-
// Install is safe to repeat (it replaces what is there); uninstall removes the same things.
|
|
7
|
-
|
|
8
|
-
import fs from 'node:fs';
|
|
9
|
-
import os from 'node:os';
|
|
10
|
-
import path from 'node:path';
|
|
11
|
-
import { createHash } from 'node:crypto';
|
|
12
|
-
import { execFile } from 'node:child_process';
|
|
13
|
-
import { fileURLToPath } from 'node:url';
|
|
14
|
-
|
|
15
|
-
/** Name part that tells identities apart on one computer: the profile, else a short hash of the config dir, else "default". */
|
|
16
|
-
export function slotOf(profile, configDir) {
|
|
17
|
-
if (profile) return profile;
|
|
18
|
-
if (configDir) return `dir-${createHash("sha1").update(String(configDir)).digest("hex").slice(0, 8)}`;
|
|
19
|
-
return null;
|
|
20
|
-
}
|
|
21
|
-
export function labelOf(profile) { return `work.anytowork.listen.${profile || 'default'}`; }
|
|
22
|
-
export function unitNameOf(profile) { return `anytowork-listen-${profile || 'default'}.service`; }
|
|
23
|
-
export function taskNameOf(profile) { return `AnytoWork Listen ${profile || 'default'}`; }
|
|
24
|
-
export function cronMarkOf(profile) { return `# anytowork-listen:${profile || 'default'}`; }
|
|
25
|
-
|
|
26
|
-
/** The arguments after the entry script that run the listener. */
|
|
27
|
-
export function runArgs(profile) {
|
|
28
|
-
return ['listen', 'run', ...(profile ? ['--profile', profile] : [])];
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function xml(s) {
|
|
32
|
-
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** macOS LaunchAgent plist text. */
|
|
36
|
-
export function launchdPlist({ label, node, entry, profile, pathEnv, configDir, runHome, logFile }) {
|
|
37
|
-
const args = [node, entry, ...runArgs(profile)];
|
|
38
|
-
// v0.12.63: HOME is written in when it is not the system home (a woken run would otherwise start in the login home)
|
|
39
|
-
const env = { PATH: pathEnv || '/usr/local/bin:/usr/bin:/bin', ...(runHome ? { HOME: runHome } : {}), ...(configDir ? { ANYTOWORK_CONFIG_DIR: configDir } : {}) };
|
|
40
|
-
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
41
|
-
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
42
|
-
<plist version="1.0">
|
|
43
|
-
<dict>
|
|
44
|
-
<key>Label</key><string>${xml(label)}</string>
|
|
45
|
-
<key>ProgramArguments</key>
|
|
46
|
-
<array>
|
|
47
|
-
${args.map((a) => ` <string>${xml(a)}</string>`).join('\n')}
|
|
48
|
-
</array>
|
|
49
|
-
<key>EnvironmentVariables</key>
|
|
50
|
-
<dict>
|
|
51
|
-
${Object.entries(env).map(([k, v]) => ` <key>${xml(k)}</key><string>${xml(v)}</string>`).join('\n')}
|
|
52
|
-
</dict>
|
|
53
|
-
<key>RunAtLoad</key><true/>
|
|
54
|
-
<key>KeepAlive</key>
|
|
55
|
-
<dict><key>SuccessfulExit</key><false/></dict>
|
|
56
|
-
<key>ThrottleInterval</key><integer>30</integer>
|
|
57
|
-
<key>StandardOutPath</key><string>${xml(logFile)}</string>
|
|
58
|
-
<key>StandardErrorPath</key><string>${xml(logFile)}</string>
|
|
59
|
-
</dict>
|
|
60
|
-
</plist>
|
|
61
|
-
`;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function sdQuote(s) { return `"${String(s).replace(/(["\\])/g, '\\$1')}"`; }
|
|
65
|
-
|
|
66
|
-
/** Linux systemd --user unit text. */
|
|
67
|
-
export function systemdUnit({ node, entry, profile, pathEnv, configDir, runHome }) {
|
|
68
|
-
const exec = [node, entry, ...runArgs(profile)].map(sdQuote).join(' ');
|
|
69
|
-
return `[Unit]
|
|
70
|
-
Description=AnytoWork always-on listener (${profile || 'default'})
|
|
71
|
-
After=network-online.target
|
|
72
|
-
|
|
73
|
-
[Service]
|
|
74
|
-
ExecStart=${exec}
|
|
75
|
-
Environment=${sdQuote(`PATH=${pathEnv || '/usr/local/bin:/usr/bin:/bin'}`)}
|
|
76
|
-
${runHome ? `Environment=${sdQuote(`HOME=${runHome}`)}\n` : ''}${configDir ? `Environment=${sdQuote(`ANYTOWORK_CONFIG_DIR=${configDir}`)}\n` : ''}Restart=on-failure
|
|
77
|
-
RestartSec=30
|
|
78
|
-
|
|
79
|
-
[Install]
|
|
80
|
-
WantedBy=default.target
|
|
81
|
-
`;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
function shSingle(s) { return `'${String(s).replace(/'/g, `'\\''`)}'`; }
|
|
85
|
-
|
|
86
|
-
/** The crontab line used when there is no systemd (container, minimal Linux). */
|
|
87
|
-
export function cronLine({ node, entry, profile, configDir, runHome }) {
|
|
88
|
-
const cmd = [shSingle(node), shSingle(entry), ...runArgs(profile).map(shSingle)].join(' ');
|
|
89
|
-
const envPart = `${runHome ? `HOME=${shSingle(runHome)} ` : ''}${configDir ? `ANYTOWORK_CONFIG_DIR=${shSingle(configDir)} ` : ''}`;
|
|
90
|
-
return `@reboot ${envPart}${cmd} >/dev/null 2>&1 ${cronMarkOf(slotOf(profile, configDir))}`;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/** Windows: the arguments of `schtasks /Create` (run at the user's logon, no administrator needed). */
|
|
94
|
-
export function schtasksCreateArgs({ node, entry, profile, configDir, runHome }) {
|
|
95
|
-
const run = [`"${node}"`, `"${entry}"`, ...runArgs(profile)].join(" ");
|
|
96
|
-
// a task cannot carry environment variables, so HOME and a custom config dir are set by a small cmd wrapper
|
|
97
|
-
const sets = `${runHome ? `set HOME=${runHome}&& ` : ''}${configDir ? `set ANYTOWORK_CONFIG_DIR=${configDir}&& ` : ''}`;
|
|
98
|
-
const tr = sets ? `cmd /c "${sets}${run}"` : run;
|
|
99
|
-
return ["/Create", "/TN", taskNameOf(slotOf(profile, configDir)), "/SC", "ONLOGON", "/TR", tr, "/F"];
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/** The login home of the system user. A start-at-login entry belongs there: the system reads it from there, whatever HOME says now. */
|
|
103
|
-
export function systemHomeDir() {
|
|
104
|
-
try { return os.userInfo().homedir || os.homedir(); } catch { return os.homedir(); }
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/** True when HOME (what this process sees) is not the system home: a sandbox, a temporary HOME, a changed environment. */
|
|
108
|
-
export function homeDiffers({ envHome, loginHome } = {}) {
|
|
109
|
-
const a = envHome || os.homedir();
|
|
110
|
-
const b = loginHome || systemHomeDir();
|
|
111
|
-
return path.resolve(a) !== path.resolve(b);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/** Default way to run a system command; resolves {code, stdout, stderr}, never rejects. */
|
|
115
|
-
export function defaultRunCmd(cmd, args, opts = {}) {
|
|
116
|
-
return new Promise((resolve) => {
|
|
117
|
-
try {
|
|
118
|
-
const child = execFile(cmd, args, { windowsHide: true, timeout: opts.timeout || 60_000 }, (error, stdout, stderr) => {
|
|
119
|
-
resolve({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, stdout: String(stdout || ''), stderr: String(stderr || ''), missing: !!(error && error.code === 'ENOENT') });
|
|
120
|
-
});
|
|
121
|
-
if (opts.input != null) { child.stdin.on('error', () => {}); child.stdin.end(opts.input); }
|
|
122
|
-
} catch { resolve({ code: 1, stdout: '', stderr: 'spawn', missing: true }); }
|
|
123
|
-
});
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/** Absolute path of the command-line entry script (bin/anytowork.js). */
|
|
127
|
-
export function defaultEntryPath() {
|
|
128
|
-
return fileURLToPath(new URL('../../bin/anytowork.js', import.meta.url));
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
* Set up start at login.
|
|
133
|
-
* @returns {Promise<{kind: 'launchd'|'systemd'|'cron'|'schtasks'|'none', file?: string, notes: string[]}>}
|
|
134
|
-
* kind 'none' = nothing could be set up (the caller says to use poll every minute instead).
|
|
135
|
-
*/
|
|
136
|
-
export async function installAutostart(o) {
|
|
137
|
-
const platform = o.platform || process.platform;
|
|
138
|
-
const runCmd = o.runCmd || defaultRunCmd;
|
|
139
|
-
const home = o.home || systemHomeDir();
|
|
140
|
-
const node = o.node || process.execPath;
|
|
141
|
-
const entry = o.entry || defaultEntryPath();
|
|
142
|
-
const pathEnv = o.pathEnv != null ? o.pathEnv : process.env.PATH;
|
|
143
|
-
const slot = slotOf(o.profile, o.configDir);
|
|
144
|
-
const common = { node, entry, profile: o.profile || null, pathEnv, configDir: o.configDir || null, runHome: o.runHome || null };
|
|
145
|
-
const notes = [];
|
|
146
|
-
|
|
147
|
-
if (platform === 'darwin') {
|
|
148
|
-
const label = labelOf(slot);
|
|
149
|
-
const dir = path.join(home, 'Library', 'LaunchAgents');
|
|
150
|
-
const file = path.join(dir, `${label}.plist`);
|
|
151
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
152
|
-
fs.writeFileSync(file, launchdPlist({ ...common, label, logFile: o.logFile }), { mode: 0o644 });
|
|
153
|
-
const uid = String(o.uid != null ? o.uid : (process.getuid ? process.getuid() : 501));
|
|
154
|
-
// bootout returns before launchd has finished unloading, so an immediate bootstrap can fail with
|
|
155
|
-
// "Bootstrap failed: 5: Input/output error". Boot out, bootstrap, and on failure wait and try again.
|
|
156
|
-
const sleep = o.sleep || ((ms) => new Promise((res) => setTimeout(res, ms)));
|
|
157
|
-
let r = null;
|
|
158
|
-
for (let i = 0; i < 5; i += 1) {
|
|
159
|
-
await runCmd("launchctl", ["bootout", `gui/${uid}/${label}`], { timeout: 15_000 }); // ignore: it may not be loaded yet
|
|
160
|
-
if (i > 0) await sleep(600 * i);
|
|
161
|
-
r = await runCmd("launchctl", ["bootstrap", `gui/${uid}`, file], { timeout: 15_000 });
|
|
162
|
-
if (r.code === 0 || r.missing) break; // no launchctl at all: retrying cannot help
|
|
163
|
-
}
|
|
164
|
-
if (r.code !== 0) throw new Error(`launchctl: ${(r.stderr || "").trim().slice(0, 200)}`);
|
|
165
|
-
return { kind: 'launchd', file, notes };
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
if (platform === 'win32') {
|
|
169
|
-
const create = await runCmd('schtasks', schtasksCreateArgs(common));
|
|
170
|
-
if (create.code !== 0) throw new Error(`schtasks: ${(create.stderr || create.stdout || '').trim().slice(0, 200)}`);
|
|
171
|
-
await runCmd('schtasks', ['/Run', '/TN', taskNameOf(slot)]);
|
|
172
|
-
return { kind: 'schtasks', notes };
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
// Linux and the rest: systemd --user first, then crontab @reboot, otherwise nothing.
|
|
176
|
-
const sd = await runCmd('systemctl', ['--user', '--version']);
|
|
177
|
-
if (sd.code === 0 && !sd.missing) {
|
|
178
|
-
const dir = path.join(home, '.config', 'systemd', 'user');
|
|
179
|
-
const file = path.join(dir, unitNameOf(slot));
|
|
180
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
181
|
-
fs.writeFileSync(file, systemdUnit(common), { mode: 0o644 });
|
|
182
|
-
await runCmd('systemctl', ['--user', 'daemon-reload']);
|
|
183
|
-
const r = await runCmd('systemctl', ['--user', 'enable', '--now', unitNameOf(slot)]);
|
|
184
|
-
if (r.code === 0) { notes.push('linger'); return { kind: 'systemd', file, notes }; }
|
|
185
|
-
// The user manager is not reachable (container, ssh without a session): fall through to cron.
|
|
186
|
-
}
|
|
187
|
-
const ct = await runCmd('crontab', ['-l']);
|
|
188
|
-
if (!ct.missing) {
|
|
189
|
-
const mark = cronMarkOf(slot);
|
|
190
|
-
const kept = (ct.code === 0 ? ct.stdout : '').split('\n').filter((l) => l && !l.includes(mark));
|
|
191
|
-
kept.push(cronLine(common));
|
|
192
|
-
const w = await runCmd('crontab', ['-'], { input: `${kept.join('\n')}\n` });
|
|
193
|
-
if (w.code === 0) {
|
|
194
|
-
if (o.startNow) await o.startNow();
|
|
195
|
-
return { kind: 'cron', notes };
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
return { kind: 'none', notes };
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/** Undo installAutostart; unknown or missing pieces are skipped. */
|
|
202
|
-
export async function uninstallAutostart(o) {
|
|
203
|
-
const slot = slotOf(o.profile, o.configDir);
|
|
204
|
-
const platform = o.platform || process.platform;
|
|
205
|
-
const runCmd = o.runCmd || defaultRunCmd;
|
|
206
|
-
const home = o.home || systemHomeDir();
|
|
207
|
-
if (platform === 'darwin') {
|
|
208
|
-
const label = labelOf(slot);
|
|
209
|
-
const uid = String(o.uid != null ? o.uid : (process.getuid ? process.getuid() : 501));
|
|
210
|
-
await runCmd('launchctl', ['bootout', `gui/${uid}/${label}`]);
|
|
211
|
-
try { fs.unlinkSync(path.join(home, 'Library', 'LaunchAgents', `${label}.plist`)); } catch { /* none */ }
|
|
212
|
-
return;
|
|
213
|
-
}
|
|
214
|
-
if (platform === 'win32') {
|
|
215
|
-
await runCmd('schtasks', ['/End', '/TN', taskNameOf(slot)]);
|
|
216
|
-
await runCmd('schtasks', ['/Delete', '/TN', taskNameOf(slot), '/F']);
|
|
217
|
-
return;
|
|
218
|
-
}
|
|
219
|
-
const unit = path.join(home, '.config', 'systemd', 'user', unitNameOf(slot));
|
|
220
|
-
if (fs.existsSync(unit)) {
|
|
221
|
-
await runCmd('systemctl', ['--user', 'disable', '--now', unitNameOf(slot)]);
|
|
222
|
-
try { fs.unlinkSync(unit); } catch { /* none */ }
|
|
223
|
-
await runCmd('systemctl', ['--user', 'daemon-reload']);
|
|
224
|
-
}
|
|
225
|
-
const ct = await runCmd('crontab', ['-l']);
|
|
226
|
-
if (!ct.missing && ct.code === 0) {
|
|
227
|
-
const mark = cronMarkOf(slot);
|
|
228
|
-
if (ct.stdout.includes(mark)) {
|
|
229
|
-
const kept = ct.stdout.split('\n').filter((l) => l && !l.includes(mark));
|
|
230
|
-
await runCmd('crontab', ['-'], { input: kept.length ? `${kept.join('\n')}\n` : '' });
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
}
|
package/src/listener/nudge.js
DELETED
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
// "A new message arrived while you are running" (v0.38.7).
|
|
2
|
-
//
|
|
3
|
-
// The listener cannot write into a run that is already going (its standard input is closed at start), so it leaves a
|
|
4
|
-
// small file next to the prompt files: <prompts>/<key>.nudge, where key is a session id, or `task-<task id>` for an
|
|
5
|
-
// order. The CLI's one exit (index.js) prints one line for it after the next command the Agent runs and deletes the
|
|
6
|
-
// file. It is a generic channel: it does not depend on the workbench or on which Agent product is running.
|
|
7
|
-
// The run that the queue keeps for after this one stays as the fallback (not touched here).
|
|
8
|
-
|
|
9
|
-
import fs from 'node:fs';
|
|
10
|
-
import path from 'node:path';
|
|
11
|
-
import { atomicWriteFile } from '../atomic-write.js';
|
|
12
|
-
import { promptsDir } from './config.js';
|
|
13
|
-
import { pickLang } from '../model-pledge.js';
|
|
14
|
-
|
|
15
|
-
/** A nudge older than this is stale (the run is long over) and is dropped without being shown. */
|
|
16
|
-
export const NUDGE_TTL_MS = 2 * 3600 * 1000;
|
|
17
|
-
/** An order message is only worth a nudge while the run it interrupts is still the same piece of work. */
|
|
18
|
-
export const ORDER_NUDGE_TTL_MS = 15 * 60 * 1000;
|
|
19
|
-
|
|
20
|
-
const SAFE_KEY = /^[A-Za-z0-9_-]{1,80}$/;
|
|
21
|
-
|
|
22
|
-
/** Path of the nudge file for `key`, or null when the key is not a plain id. */
|
|
23
|
-
export function nudgeFile(credOpts, key) {
|
|
24
|
-
return SAFE_KEY.test(String(key)) ? path.join(promptsDir(credOpts), `${key}.nudge`) : null;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function readOne(file) {
|
|
28
|
-
try {
|
|
29
|
-
const o = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
30
|
-
return o && typeof o === 'object' ? o : null;
|
|
31
|
-
} catch { return null; }
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/** Record one more new message for `key` (counts up while the file is still there). Never throws. */
|
|
35
|
-
export function writeNudge(credOpts, key, info = {}, nowMs = Date.now()) {
|
|
36
|
-
const file = nudgeFile(credOpts, key);
|
|
37
|
-
if (!file) return false;
|
|
38
|
-
try {
|
|
39
|
-
const have = readOne(file);
|
|
40
|
-
const n = (have && Number(have.n) > 0 ? Number(have.n) : 0) + 1;
|
|
41
|
-
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
42
|
-
atomicWriteFile(file, JSON.stringify({ n, kind: info.kind === 'order' ? 'order' : 'session', at: have && have.at ? have.at : nowMs }), 0o600);
|
|
43
|
-
return true;
|
|
44
|
-
} catch { return false; }
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** Remove the files for these keys without showing them (the Agent just read the conversation). */
|
|
48
|
-
export function clearNudges(credOpts, keys) {
|
|
49
|
-
for (const key of keys) {
|
|
50
|
-
const file = nudgeFile(credOpts, key);
|
|
51
|
-
if (file) { try { fs.unlinkSync(file); } catch { /* none */ } }
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/** Read and delete the files for these keys; stale ones are deleted and left out. Returns [{key, n, kind}]. */
|
|
56
|
-
export function takeNudges(credOpts, keys, nowMs = Date.now()) {
|
|
57
|
-
const out = [];
|
|
58
|
-
for (const key of new Set(keys)) {
|
|
59
|
-
const file = nudgeFile(credOpts, key);
|
|
60
|
-
if (!file || !fs.existsSync(file)) continue;
|
|
61
|
-
const o = readOne(file);
|
|
62
|
-
try { fs.unlinkSync(file); } catch { /* gone */ }
|
|
63
|
-
const ttl = o && o.kind === 'order' ? ORDER_NUDGE_TTL_MS : NUDGE_TTL_MS;
|
|
64
|
-
if (!o || nowMs - Number(o.at) > ttl) continue;
|
|
65
|
-
out.push({ key, n: Number(o.n) > 0 ? Number(o.n) : 1, kind: o.kind === 'order' ? 'order' : 'session' });
|
|
66
|
-
}
|
|
67
|
-
return out;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
const TEXT = {
|
|
71
|
-
session: {
|
|
72
|
-
zh: (n, id) => `会话有 ${n} 条新消息:请先运行 anytowork chat read ${id} 读完,再决定接着做还是改方向;不要先做完手头这一步再读。`,
|
|
73
|
-
en: (n, id) => `${n} new message${n > 1 ? 's' : ''} in this conversation: run anytowork chat read ${id} first, then decide whether to carry on or change course. Do not finish the step in hand before reading.`,
|
|
74
|
-
},
|
|
75
|
-
order: {
|
|
76
|
-
zh: (n, id) => `订单(${id})有 ${n} 条新的补充需求或追问进度:请先运行 anytowork task collab ${id} 读完,再决定接着做还是改方向;被追问进度要尽快用 anytowork task note 回复。`,
|
|
77
|
-
en: (n, id) => `The order (${id}) has ${n} new supplement${n > 1 ? 's' : ''} or progress question${n > 1 ? 's' : ''}: run anytowork task collab ${id} first, then decide whether to carry on or change course. Answer a progress question soon with anytowork task note.`,
|
|
78
|
-
},
|
|
79
|
-
};
|
|
80
|
-
|
|
81
|
-
/** One line per nudge, in the Agent's language. */
|
|
82
|
-
export function nudgeLines(items, env = process.env) {
|
|
83
|
-
const lang = pickLang(env);
|
|
84
|
-
return items.map((it) => {
|
|
85
|
-
const id = it.kind === 'order' ? it.key.replace(/^task-/, '') : it.key;
|
|
86
|
-
return TEXT[it.kind][lang](it.n, id);
|
|
87
|
-
});
|
|
88
|
-
}
|
package/src/listener/prompt.js
DELETED
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
// Always-on listener: the words handed to the Agent when it is woken (plan 01 section 2.2).
|
|
2
|
-
//
|
|
3
|
-
// The prompt travels only on standard input and in a temporary file, never on a command line. Everything the
|
|
4
|
-
// platform sent as finished words (`rules.text`, `boundary.text`) is used as it is; the local tables in
|
|
5
|
-
// wb-rules-text.js are only the fallback for an older platform.
|
|
6
|
-
|
|
7
|
-
import { renderWbRules, boundaryLines, identityText } from '../wb-rules-text.js';
|
|
8
|
-
import { pickLang } from '../model-pledge.js';
|
|
9
|
-
import { hasAlertFor } from '../mt/format-check.js';
|
|
10
|
-
import { wakeLabelLine, WAKE_LABEL_RE } from '../mt/wake-attribution.js';
|
|
11
|
-
|
|
12
|
-
const REWAKE_LINE = {
|
|
13
|
-
zh: '刚才叫过你一次,还没看到你读消息。',
|
|
14
|
-
en: 'You were called a moment ago and have not read the message yet.',
|
|
15
|
-
};
|
|
16
|
-
|
|
17
|
-
function langOf(payload, env) {
|
|
18
|
-
const l = payload && typeof payload.lang === 'string' ? payload.lang.toLowerCase() : '';
|
|
19
|
-
if (l.startsWith('en')) return 'en';
|
|
20
|
-
if (l.startsWith('zh')) return 'zh';
|
|
21
|
-
return pickLang(env);
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* @param {object} payload the `wb.wake` payload ({group, session, from, summary, rules, boundary, rewake, ...})
|
|
26
|
-
* @param {{profile?: string, dir?: string}|null} identity set when this Agent is not the default identity of the computer:
|
|
27
|
-
* an Agent that runs inside another process (a gateway) does not inherit our environment, so the prompt names it
|
|
28
|
-
* @returns {string}
|
|
29
|
-
*/
|
|
30
|
-
export function buildPrompt(payload, env = process.env, identity = null, job = null, program = null) {
|
|
31
|
-
const p = payload || {};
|
|
32
|
-
const lang = langOf(p, env);
|
|
33
|
-
const envLang = { ...env, ANYTOWORK_LANG: lang };
|
|
34
|
-
const g = p.group || {};
|
|
35
|
-
const s = p.session || {};
|
|
36
|
-
const sid = s.id || '';
|
|
37
|
-
const place = g.kind === 'dm'
|
|
38
|
-
? (lang === 'en' ? 'private chat' : '私聊')
|
|
39
|
-
: (g.name || (lang === 'en' ? 'group chat' : '群聊'));
|
|
40
|
-
const where = s.title ? `${place} / ${s.title}` : place;
|
|
41
|
-
const from = p.from || {};
|
|
42
|
-
const who = identityText(from, envLang)
|
|
43
|
-
|| (from.type === 'agent' ? (from.name || (lang === 'en' ? 'another Agent' : '另一个 Agent'))
|
|
44
|
-
: (from.type === 'member' ? (from.name || (lang === 'en' ? 'a group member' : '群成员'))
|
|
45
|
-
: (lang === 'en' ? 'Your owner' : '主人')));
|
|
46
|
-
const lines = [];
|
|
47
|
-
if (lang === 'en') {
|
|
48
|
-
lines.push(`[AnytoWork] ${who} called you in "${where}": ${p.summary || ''}`);
|
|
49
|
-
} else {
|
|
50
|
-
lines.push(`[AnytoWork] ${who}在「${where}」叫你:${p.summary || ''}`);
|
|
51
|
-
}
|
|
52
|
-
// A message from another owner's Agent carries a fixed source line (empty for anyone else).
|
|
53
|
-
for (const l of boundaryLines({ source: p.source }, envLang)) lines.push(l);
|
|
54
|
-
const rules = renderWbRules(p.rules, envLang);
|
|
55
|
-
if (rules) lines.push(rules);
|
|
56
|
-
for (const l of boundaryLines({ rules: p.rules, boundary: p.boundary }, envLang)) lines.push(l);
|
|
57
|
-
if (p.workspace_path) {
|
|
58
|
-
lines.push(lang === 'en' ? `Files of this group are in the space "${p.workspace_path}".` : `这个群的文件放在空间「${p.workspace_path}」`);
|
|
59
|
-
}
|
|
60
|
-
lines.push(lang === 'en'
|
|
61
|
-
? `Session id ${sid}. Automatic call from the platform.`
|
|
62
|
-
: `会话编号 ${sid}。平台自动叫醒。`);
|
|
63
|
-
if (p.rewake === true) lines.push(REWAKE_LINE[lang]);
|
|
64
|
-
// v0.38.7: a hired Agent is told how much of today's usage allowance is left (the rules say what to do when it is low)
|
|
65
|
-
if (Number.isFinite(Number(p.quota_left_pct)) && p.quota_left_pct !== null && p.quota_left_pct !== '') {
|
|
66
|
-
lines.push(lang === 'en' ? `Remaining quota today: ${Math.round(Number(p.quota_left_pct))}%.` : `今日剩余额度 ${Math.round(Number(p.quota_left_pct))}%。`);
|
|
67
|
-
}
|
|
68
|
-
// v0.38.10: a usage record this computer keeps changed its layout and was not read: the Agent reports its usage itself
|
|
69
|
-
if (hasAlertFor(program)) {
|
|
70
|
-
lines.push(lang === 'en'
|
|
71
|
-
? 'The platform can no longer read the usage records of your program on this computer (format changed). Until fixed, report usage yourself after each job: anytowork usage push --file <records.jsonl> (format on the docs site).'
|
|
72
|
-
: '平台读不到你在这台电脑上的用量记录了(格式变了)。修好之前,每次干完活自己上报:anytowork usage push --file <records.jsonl>(格式见文档站)。');
|
|
73
|
-
}
|
|
74
|
-
// v0.37 PA-09: unread messages that did not fit into this call: say how many and how to page back
|
|
75
|
-
if (Number(p.skipped) > 0) {
|
|
76
|
-
const more = p.more_cmd_before != null ? ` --before ${p.more_cmd_before}` : ' --before <编号>';
|
|
77
|
-
lines.push(lang === 'en'
|
|
78
|
-
? `${p.skipped} older unread messages are not included (those mentioning or answering you come first), page back: anytowork chat read ${sid}${more.replace('<编号>', '<number>')}`
|
|
79
|
-
: `还有 ${p.skipped} 条更早的未读消息没提供(@你和回你的已优先带上),可用 anytowork chat read ${sid}${more} 翻页。`);
|
|
80
|
-
}
|
|
81
|
-
if (identity && (identity.profile || identity.dir)) {
|
|
82
|
-
const pf = identity.profile;
|
|
83
|
-
// v0.12.38: the wake-up already points anytowork at this login through the environment,
|
|
84
|
-
// so `--profile <name>` and a plain command reach the same credentials. Never ask the Agent to unset the env var.
|
|
85
|
-
lines.push(lang === 'en'
|
|
86
|
-
? (pf ? `Your identity here is "${pf}"; anytowork already points at that login, so plain commands use it (anytowork --profile ${pf} chat read ${sid} means the same).`
|
|
87
|
-
: `Your identity here lives in ${identity.dir}; run anytowork commands with ANYTOWORK_CONFIG_DIR=${identity.dir} set, no --profile needed.`)
|
|
88
|
-
: (pf ? `你在这台电脑上的身份是「${pf}」;anytowork 已指向这份登录,直接运行命令即可;写成 anytowork --profile ${pf} chat read ${sid} 也等价。`
|
|
89
|
-
: `你在这台电脑上的身份放在 ${identity.dir};运行 anytowork 命令时要带上 ANYTOWORK_CONFIG_DIR=${identity.dir},不用加 --profile。`));
|
|
90
|
-
// The listener sets the variable for the process it starts, but a program that runs you in a separate service does not pass it on:
|
|
91
|
-
// when the command answers "not logged in" or shows another identity, set it yourself for every command.
|
|
92
|
-
if (identity.dir && pf) {
|
|
93
|
-
lines.push(lang === 'en'
|
|
94
|
-
? `If a command says you are not logged in or shows another identity, your process did not inherit the environment: set ANYTOWORK_CONFIG_DIR=${identity.dir} for every anytowork command.`
|
|
95
|
-
: `命令若提示未登录或显示成别的身份,说明你的运行环境没有继承环境变量:给每条 anytowork 命令设上 ANYTOWORK_CONFIG_DIR=${identity.dir}。`);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
// v0.38.39: the wake-up number, ONE fixed line at the very end, the same for every program. Usage is matched to this wake-up by it.
|
|
99
|
-
const label = typeof p.wake_label === 'string' && p.wake_label.trim() ? p.wake_label.trim() : (typeof p.wake_id === 'string' && /^[0-9a-f-]{36}$/i.test(p.wake_id) ? wakeLabelLine(p.wake_id) : '');
|
|
100
|
-
WAKE_LABEL_RE.lastIndex = 0;
|
|
101
|
-
if (label && WAKE_LABEL_RE.test(label)) lines.push(label);
|
|
102
|
-
WAKE_LABEL_RE.lastIndex = 0;
|
|
103
|
-
return lines.join('\n');
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/** The fixed prompt used by `listen test`: it asks the Agent to do nothing but answer. */
|
|
107
|
-
export function testPrompt(env = process.env) {
|
|
108
|
-
return pickLang(env) === 'en'
|
|
109
|
-
? '[AnytoWork] This is a start-up test of the listener. Do nothing in AnytoWork; just reply "ok".'
|
|
110
|
-
: '[AnytoWork] 这是常驻监听的启动测试。不用在 AnytoWork 里做任何事,回一句「好」即可。';
|
|
111
|
-
}
|
package/src/listener/queue.js
DELETED
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
// Always-on listener: who runs next (plan 01 section 2.3).
|
|
2
|
-
//
|
|
3
|
-
// Pure bookkeeping, no timers and no processes, so it can be tested with a fake clock.
|
|
4
|
-
// - one session never runs twice at once: a wake that arrives while it runs (or waits) is merged into ONE waiting
|
|
5
|
-
// run that starts after the current one ends;
|
|
6
|
-
// - at most `maxParallel` sessions run at the same time (50 by default); there is no per-user limit, but when all
|
|
7
|
-
// places are taken the users go in turns: the user with fewest runs going first, then the longest unserved;
|
|
8
|
-
// - another Agent calling the same session is let through at most once per `agentWakeGapMs`
|
|
9
|
-
// (people are never limited; the platform's own second call, `rewake`, is not limited either);
|
|
10
|
-
// - messages from people inside `humanMergeMs` of the last start are merged into one run;
|
|
11
|
-
// - at most `queueMax` sessions wait; beyond that the oldest is dropped (the platform's second call covers it).
|
|
12
|
-
|
|
13
|
-
import { LISTENER_DEFAULTS } from './config.js';
|
|
14
|
-
|
|
15
|
-
const MAX_WAKE_IDS = 10; // wake-up ids kept per merged job (newest win)
|
|
16
|
-
|
|
17
|
-
export class WakeQueue {
|
|
18
|
-
/**
|
|
19
|
-
* @param {object} opts { config?: partial limits, nowMs?: () => number }
|
|
20
|
-
*/
|
|
21
|
-
constructor(opts = {}) {
|
|
22
|
-
this.cfg = { ...LISTENER_DEFAULTS, ...(opts.config || {}) };
|
|
23
|
-
this.nowMs = opts.nowMs || Date.now;
|
|
24
|
-
this.waiting = new Map(); // sid -> job waiting to start
|
|
25
|
-
this.running = new Set(); // sid
|
|
26
|
-
this.lastStart = new Map(); // sid -> ms of the latest start
|
|
27
|
-
this.runningUser = new Map(); // sid -> user key of the run in progress (fair turns, v0.38.7)
|
|
28
|
-
this.userTick = new Map(); // user key -> counter value when that user was last started
|
|
29
|
-
this.tick = 0;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* @param {object} wake { sid, human, rewake, ... any other fields are kept on the job }
|
|
34
|
-
* @returns {{result: 'queued'|'merged'|'throttled', dropped?: string}}
|
|
35
|
-
*/
|
|
36
|
-
add(wake) {
|
|
37
|
-
const now = this.nowMs();
|
|
38
|
-
const sid = wake.sid;
|
|
39
|
-
const last = this.lastStart.get(sid);
|
|
40
|
-
if (!wake.human && !wake.rewake && last != null && now - last < this.cfg.agentWakeGapMs) {
|
|
41
|
-
return { result: 'throttled' };
|
|
42
|
-
}
|
|
43
|
-
const have = this.waiting.get(sid);
|
|
44
|
-
if (have) {
|
|
45
|
-
// Merge: the newest wake's details, the earliest arrival time, "human" if any of them was.
|
|
46
|
-
// v0.38.9: keep the id of every merged wake-up; the platform finds the instructions each one covers.
|
|
47
|
-
const wakeIds = [...new Set([...(have.wakeIds || []), ...(wake.wakeIds || [])])].slice(-MAX_WAKE_IDS);
|
|
48
|
-
this.waiting.set(sid, { ...have, ...wake, wakeIds, addedAt: have.addedAt, readyAt: have.readyAt, human: have.human || wake.human });
|
|
49
|
-
return { result: 'merged' };
|
|
50
|
-
}
|
|
51
|
-
let readyAt = now;
|
|
52
|
-
if (wake.human && last != null && now - last < this.cfg.humanMergeMs) readyAt = last + this.cfg.humanMergeMs;
|
|
53
|
-
this.waiting.set(sid, { ...wake, addedAt: now, readyAt });
|
|
54
|
-
let dropped;
|
|
55
|
-
if (this.waiting.size > this.cfg.queueMax) {
|
|
56
|
-
let oldest = null;
|
|
57
|
-
for (const j of this.waiting.values()) if (!oldest || j.addedAt < oldest.addedAt) oldest = j;
|
|
58
|
-
this.waiting.delete(oldest.sid);
|
|
59
|
-
dropped = oldest.sid;
|
|
60
|
-
}
|
|
61
|
-
return { result: 'queued', dropped };
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/** The next job that may start now (oldest first), or null. Marks it running. */
|
|
65
|
-
take() {
|
|
66
|
-
const now = this.nowMs();
|
|
67
|
-
if (this.running.size >= this.cfg.maxParallel) return null;
|
|
68
|
-
const going = new Map(); // user key -> runs in progress
|
|
69
|
-
for (const u of this.runningUser.values()) going.set(u, (going.get(u) || 0) + 1);
|
|
70
|
-
const rank = (j) => [going.get(j.userKey || j.sid) || 0, this.userTick.get(j.userKey || j.sid) || 0, j.addedAt];
|
|
71
|
-
const less = (a, b) => { for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] < b[i]; return false; };
|
|
72
|
-
let pick = null;
|
|
73
|
-
let pickRank = null;
|
|
74
|
-
for (const j of this.waiting.values()) {
|
|
75
|
-
if (this.running.has(j.sid) || j.readyAt > now) continue;
|
|
76
|
-
const r = rank(j);
|
|
77
|
-
if (!pick || less(r, pickRank)) { pick = j; pickRank = r; }
|
|
78
|
-
}
|
|
79
|
-
if (!pick) return null;
|
|
80
|
-
this.waiting.delete(pick.sid);
|
|
81
|
-
this.running.add(pick.sid);
|
|
82
|
-
this.runningUser.set(pick.sid, pick.userKey || pick.sid);
|
|
83
|
-
this.userTick.set(pick.userKey || pick.sid, ++this.tick);
|
|
84
|
-
if (this.userTick.size > 500) this.userTick.delete(this.userTick.keys().next().value);
|
|
85
|
-
this.lastStart.set(pick.sid, now);
|
|
86
|
-
return { ...pick, waited: now - pick.addedAt > 2000 };
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/** A run ended. */
|
|
90
|
-
done(sid) {
|
|
91
|
-
this.running.delete(sid);
|
|
92
|
-
this.runningUser.delete(sid);
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/** Milliseconds until the earliest waiting job could start by time alone, or null when nothing waits. */
|
|
96
|
-
nextDelayMs() {
|
|
97
|
-
const now = this.nowMs();
|
|
98
|
-
let best = null;
|
|
99
|
-
for (const j of this.waiting.values()) {
|
|
100
|
-
const d = Math.max(0, j.readyAt - now);
|
|
101
|
-
if (best == null || d < best) best = d;
|
|
102
|
-
}
|
|
103
|
-
return best;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/** Forget everything waiting (the listener paused). */
|
|
107
|
-
clearWaiting() {
|
|
108
|
-
this.waiting.clear();
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
get size() { return this.waiting.size; }
|
|
112
|
-
}
|
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
// What went wrong when the Agent program the listener started ended badly (Echo 470 step 2).
|
|
2
|
-
//
|
|
3
|
-
// The listener keeps only the last few KB of the program's output in memory, reads them once with this small table and
|
|
4
|
-
// forgets them. Only a CATEGORY and a short code ever leave this module: never a line of the output, never a key, token
|
|
5
|
-
// or request. To teach it a new situation, add a row to RULES (first match wins, so put the specific ones first).
|
|
6
|
-
|
|
7
|
-
/** The categories the platform understands; anything else it stores as "other". */
|
|
8
|
-
export const RUN_ERROR_CATEGORIES = ['quota', 'rate_limit', 'timeout', 'auth', 'network', 'other'];
|
|
9
|
-
|
|
10
|
-
/** Bytes of output kept per stream while the program runs (the tail only; older output is dropped). */
|
|
11
|
-
export const TAIL_BYTES = 4096;
|
|
12
|
-
|
|
13
|
-
/** "status 402", "HTTP 402", "code: 402", "error 402" or "402 Payment Required" style mentions of one HTTP status. */
|
|
14
|
-
function status(n) {
|
|
15
|
-
return new RegExp(`(?:status(?:\\s*code)?|http|code|error|err)\\D{0,12}\\b${n}\\b|\\b${n}\\b\\s*(?:-|:)?\\s*(?:payment|too many|unauthori|forbidden|insufficient|error|client error)`, 'i');
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Ordered rows: [category, short code, patterns]. The short code is a fixed word or the HTTP status, never text from the output.
|
|
20
|
-
* Quota first: a balance message often also mentions "limit" or "401-ish" words.
|
|
21
|
-
*/
|
|
22
|
-
export const RULES = [
|
|
23
|
-
['quota', '402', [
|
|
24
|
-
status(402),
|
|
25
|
-
/insufficient[\s_-]*(?:balance|funds|quota|credits?|account)|(?:balance|quota|credits?)\s*(?:is\s*)?(?:insufficient|exhausted|exceeded|depleted|used up|too low)|out of (?:credits?|quota|balance)|payment required|billing[^\n]{0,30}(?:not active|inactive|failed|required)|exceeded your current quota|余额不足|额度(?:不足|已用完|用完|耗尽)|欠费/i,
|
|
26
|
-
]],
|
|
27
|
-
['rate_limit', '429', [
|
|
28
|
-
status(429),
|
|
29
|
-
/rate[\s_-]*limit|too many requests|requests? per (?:minute|second)|overloaded|限流|请求过于频繁/i,
|
|
30
|
-
]],
|
|
31
|
-
['auth', '401', [
|
|
32
|
-
status(401), status(403),
|
|
33
|
-
/unauthori[sz]ed|invalid[\s_-]*(?:api[\s_-]*)?key|incorrect api key|authentication[\s_-]*(?:failed|error|required)|invalid[\s_-]*token|token (?:expired|has expired)|forbidden|认证失败|密钥(?:无效|错误)/i,
|
|
34
|
-
]],
|
|
35
|
-
['timeout', 'timeout', [
|
|
36
|
-
/timed? ?out|ETIMEDOUT|ESOCKETTIMEDOUT|deadline exceeded|超时/i,
|
|
37
|
-
]],
|
|
38
|
-
['network', 'net', [
|
|
39
|
-
/ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|socket hang up|getaddrinfo|connection (?:refused|reset|error|closed)|network (?:error|is unreachable)|fetch failed|网络(?:错误|异常)/i,
|
|
40
|
-
]],
|
|
41
|
-
];
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Put one ended run down to a category.
|
|
45
|
-
* @param {{code?: number|null, timedOut?: boolean, error?: string, signal?: string|null, tail?: string}} res what the exec helper returned
|
|
46
|
-
* @returns {{broke: boolean, category: string|null, code: string|null}}
|
|
47
|
-
* broke the program did not end in an orderly way (a non-zero exit, killed, timed out, could not start)
|
|
48
|
-
* category the matched category, or null when nothing in the output points at one (a broken run is then "other")
|
|
49
|
-
* code a short token (`402`, `429`, `timeout`, `net`, `exit_1`, `spawn`) or null
|
|
50
|
-
*/
|
|
51
|
-
export function classifyRunEnd(res) {
|
|
52
|
-
const r = res || {};
|
|
53
|
-
const exitCode = r.code == null ? null : Number(r.code);
|
|
54
|
-
const broke = !!r.timedOut || !!r.error || exitCode !== 0;
|
|
55
|
-
const text = String(r.tail || '').slice(-TAIL_BYTES);
|
|
56
|
-
let category = null;
|
|
57
|
-
let code = null;
|
|
58
|
-
if (r.timedOut) { category = 'timeout'; code = 'timeout'; }
|
|
59
|
-
else if (r.error) { category = 'other'; code = 'spawn'; }
|
|
60
|
-
else {
|
|
61
|
-
for (const [cat, short, patterns] of RULES) {
|
|
62
|
-
if (patterns.some((p) => p.test(text))) { category = cat; code = short; break; }
|
|
63
|
-
}
|
|
64
|
-
// the status mentioned decides the short code of the auth row (401 or 403)
|
|
65
|
-
if (category === 'auth' && status(403).test(text) && !status(401).test(text)) code = '403';
|
|
66
|
-
}
|
|
67
|
-
if (broke && !category) {
|
|
68
|
-
category = 'other';
|
|
69
|
-
code = exitCode != null ? `exit_${Math.abs(exitCode) % 1000}` : (r.signal ? 'signal' : 'exit');
|
|
70
|
-
}
|
|
71
|
-
return { broke, category, code };
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/** A bounded tail buffer: keeps the last `max` characters of what is pushed in. */
|
|
75
|
-
export function makeTail(max = TAIL_BYTES) {
|
|
76
|
-
let buf = '';
|
|
77
|
-
return {
|
|
78
|
-
push(chunk) { buf = (buf + String(chunk)).slice(-max); },
|
|
79
|
-
text() { return buf; },
|
|
80
|
-
};
|
|
81
|
-
}
|