polygram 0.8.0-rc.4 → 0.8.0-rc.40
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/.claude-plugin/plugin.json +1 -1
- package/lib/abort-grace.js +62 -0
- package/lib/agent-loader.js +235 -64
- package/lib/approval-ui.js +135 -0
- package/lib/approval-waiters.js +7 -0
- package/lib/approvals.js +9 -1
- package/lib/async-lock.js +11 -3
- package/lib/autosteer-buffer.js +155 -0
- package/lib/autosteered-refs.js +100 -0
- package/lib/canonical-json.js +62 -0
- package/lib/context-format.js +79 -0
- package/lib/error-classify.js +38 -9
- package/lib/history-preload.js +160 -0
- package/lib/parse-response.js +76 -11
- package/lib/pm-interface.js +95 -0
- package/lib/pm-router.js +191 -0
- package/lib/process-manager-sdk.js +75 -7
- package/lib/process-manager.js +47 -1
- package/lib/status-reactions.js +256 -42
- package/lib/telegram-prompt.js +119 -0
- package/package.json +1 -1
- package/polygram.js +558 -261
- package/scripts/doctor.js +6 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://anthropic.com/claude-code/plugin.schema.json",
|
|
3
3
|
"name": "polygram",
|
|
4
|
-
"version": "0.8.0-rc.
|
|
4
|
+
"version": "0.8.0-rc.40",
|
|
5
5
|
"description": "Telegram integration for Claude Code that preserves the OpenClaw per-chat session model. Migration target for OpenClaw users. Multi-bot, multi-chat, per-topic isolation; SQLite transcripts; inline-keyboard approvals. Bundles /polygram:status|logs|pair-code|approvals admin commands and a history skill.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"telegram",
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Abort-grace tracker — per-session timestamps marking "user just
|
|
3
|
+
* /stop'd this session, suppress the next batch of generic error
|
|
4
|
+
* replies".
|
|
5
|
+
*
|
|
6
|
+
* Why this exists: when the user types /stop (or natural-language
|
|
7
|
+
* "стоп"), polygram calls pm.kill(sessionKey). The kill SIGTERM's
|
|
8
|
+
* the in-flight process — every pending in the queue rejects with
|
|
9
|
+
* "Process killed" or INTERRUPTED. WITHOUT abort-grace, polygram
|
|
10
|
+
* would post "💥 Hit a snag" for each rejected pending, even though
|
|
11
|
+
* the user already saw the /stop ack and these errors are caused
|
|
12
|
+
* by their own action.
|
|
13
|
+
*
|
|
14
|
+
* Timestamp model (vs the earlier "delete after first read" Set):
|
|
15
|
+
* a single /stop can drain many pendings, so we mark a TS and let
|
|
16
|
+
* every error within ABORT_GRACE_MS see "yes, aborted, stay quiet".
|
|
17
|
+
*
|
|
18
|
+
* Closes v6 plan §7.1 G11 unit gate.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
'use strict';
|
|
22
|
+
|
|
23
|
+
const DEFAULT_ABORT_GRACE_MS = 15_000;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {object} [opts]
|
|
27
|
+
* @param {number} [opts.windowMs] — grace window (default 15s)
|
|
28
|
+
* @param {() => number} [opts.now] — clock injection for tests
|
|
29
|
+
*/
|
|
30
|
+
function createAbortGrace({ windowMs = DEFAULT_ABORT_GRACE_MS, now = () => Date.now() } = {}) {
|
|
31
|
+
const aborted = new Map(); // sessionKey → ts of abort
|
|
32
|
+
|
|
33
|
+
function mark(sessionKey) {
|
|
34
|
+
if (!sessionKey) return;
|
|
35
|
+
const ts = now();
|
|
36
|
+
aborted.set(sessionKey, ts);
|
|
37
|
+
// Sweep old entries opportunistically. Use 2× window so a
|
|
38
|
+
// session that's marked-and-checked at the boundary doesn't
|
|
39
|
+
// disappear before the check completes.
|
|
40
|
+
for (const [k, t] of aborted) {
|
|
41
|
+
if (ts - t > windowMs * 2) aborted.delete(k);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function isRecent(sessionKey) {
|
|
46
|
+
const ts = aborted.get(sessionKey);
|
|
47
|
+
return ts != null && (now() - ts) < windowMs;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function clear(sessionKey) {
|
|
51
|
+
aborted.delete(sessionKey);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
mark,
|
|
56
|
+
isRecent,
|
|
57
|
+
clear,
|
|
58
|
+
get size() { return aborted.size; },
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
module.exports = { createAbortGrace, DEFAULT_ABORT_GRACE_MS };
|
package/lib/agent-loader.js
CHANGED
|
@@ -3,18 +3,26 @@
|
|
|
3
3
|
* v4 plan §6.5.5).
|
|
4
4
|
*
|
|
5
5
|
* Background: today's CLI pm passes `--agent <name>` on spawn; the
|
|
6
|
-
* Claude CLI then loads that agent's
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* the
|
|
10
|
-
*
|
|
6
|
+
* Claude CLI then loads that agent's content. Phase 0 gate 15 was
|
|
7
|
+
* DEFER — the SDK's `Options.agents` is for in-memory subagent
|
|
8
|
+
* definitions (the Task tool), NOT a "run THIS query AS this agent"
|
|
9
|
+
* mechanism. So polygram reads the agent file itself and passes its
|
|
10
|
+
* content as `systemPrompt`.
|
|
11
11
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
12
|
+
* Search order (rc.13+ — supports BOTH Claude Code's standard
|
|
13
|
+
* single-file convention AND polygram's pre-0.8.0 directory layout):
|
|
14
|
+
*
|
|
15
|
+
* 1. `<cwd>/.claude/agents/<name>.md` — Claude Code project-level
|
|
16
|
+
* 2. `<homeDir>/.claude/agents/<name>.md` — Claude Code user-level
|
|
17
|
+
* 3. `<cwd>/.claude/agents/<name>/CLAUDE.md` — polygram convention
|
|
18
|
+
* (also `AGENTS.md`, `system-prompt.txt`)
|
|
19
|
+
* 4. `<homeDir>/.claude/agents/<name>/CLAUDE.md` — polygram legacy
|
|
20
|
+
* (also `AGENTS.md`, `system-prompt.txt`)
|
|
21
|
+
*
|
|
22
|
+
* Single-file Claude Code agents may have YAML frontmatter; we strip
|
|
23
|
+
* it before using the body as systemPrompt. Frontmatter `model` /
|
|
24
|
+
* `effort` are merged into the bundle.raw so composeSdkOptions can
|
|
25
|
+
* use them as agent-level defaults.
|
|
18
26
|
*
|
|
19
27
|
* Used by `polygram.js` `buildSdkOptions(sessionKey, ctx)` —
|
|
20
28
|
* Phase 1 step 14.
|
|
@@ -31,92 +39,245 @@
|
|
|
31
39
|
const fs = require('fs');
|
|
32
40
|
const path = require('path');
|
|
33
41
|
|
|
34
|
-
const cache = new Map(); //
|
|
42
|
+
const cache = new Map(); // cacheKey → AgentBundle
|
|
43
|
+
|
|
44
|
+
// Resolve agent file by checking each search path in order.
|
|
45
|
+
// Returns { kind: 'file'|'dir', path, dir | null } or null.
|
|
46
|
+
// Restrict agent names to a conservative charset so they can't
|
|
47
|
+
// path-traverse out of the `.claude/agents/` directory. Pre-fix, an
|
|
48
|
+
// agent name like `../../etc/passwd` silently resolved to whatever
|
|
49
|
+
// existed at that path, loading arbitrary file content as the
|
|
50
|
+
// system prompt. Chat configs are operator-controlled (not user
|
|
51
|
+
// input), so the practical threat is operator typos — but pinning
|
|
52
|
+
// the contract removes the foot-gun.
|
|
53
|
+
//
|
|
54
|
+
// Allowed: alphanumerics, hyphen, underscore, single dots inside
|
|
55
|
+
// (e.g. "shumabit-finance.v2"). Forbidden: leading/trailing dot,
|
|
56
|
+
// consecutive dots, slashes, NUL.
|
|
57
|
+
const AGENT_NAME_RE = /^[A-Za-z0-9_]+(?:[.-][A-Za-z0-9_]+)*$/;
|
|
58
|
+
|
|
59
|
+
function resolveAgentLocation(agentName, homeDir, cwd) {
|
|
60
|
+
if (typeof agentName !== 'string' || !AGENT_NAME_RE.test(agentName)) {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
const fileCandidates = [];
|
|
64
|
+
if (cwd) fileCandidates.push(path.join(cwd, '.claude', 'agents', agentName + '.md'));
|
|
65
|
+
fileCandidates.push(path.join(homeDir, '.claude', 'agents', agentName + '.md'));
|
|
66
|
+
for (const p of fileCandidates) {
|
|
67
|
+
if (fs.existsSync(p)) return { kind: 'file', path: p, dir: null };
|
|
68
|
+
}
|
|
69
|
+
const dirCandidates = [];
|
|
70
|
+
if (cwd) dirCandidates.push(path.join(cwd, '.claude', 'agents', agentName));
|
|
71
|
+
dirCandidates.push(path.join(homeDir, '.claude', 'agents', agentName));
|
|
72
|
+
for (const d of dirCandidates) {
|
|
73
|
+
if (fs.existsSync(d) && fs.statSync(d).isDirectory()) {
|
|
74
|
+
return { kind: 'dir', path: d, dir: d };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Strip leading YAML frontmatter (---\n...\n---\n) from markdown.
|
|
81
|
+
function stripFrontmatter(content) {
|
|
82
|
+
if (typeof content !== 'string' || !content.startsWith('---\n')) return content;
|
|
83
|
+
const end = content.indexOf('\n---\n', 4);
|
|
84
|
+
if (end === -1) return content;
|
|
85
|
+
return content.slice(end + 5);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Recursively expand Claude Code @<file> import directives. A line
|
|
89
|
+
// starting with `@<path>` is replaced with the file's contents
|
|
90
|
+
// (frontmatter stripped, imports recursively expanded). Paths
|
|
91
|
+
// resolve relative to the importing file's directory FIRST, then
|
|
92
|
+
// fall back to cwd. Cycle detection via visited Set.
|
|
93
|
+
//
|
|
94
|
+
// rc.15: pre-rc.15 the literal "@_shumabit-base.md" reached the
|
|
95
|
+
// model verbatim because polygram's loader didn't process imports.
|
|
96
|
+
// Symptom: agent appeared loaded but the system prompt was
|
|
97
|
+
// effectively empty (just an unresolved import directive).
|
|
98
|
+
function expandImports(content, importingFile, cwd, visited, logger) {
|
|
99
|
+
if (typeof content !== 'string' || !content) return content;
|
|
100
|
+
const lines = content.split('\n');
|
|
101
|
+
const out = [];
|
|
102
|
+
for (const line of lines) {
|
|
103
|
+
const m = /^@(\S+)\s*$/.exec(line);
|
|
104
|
+
if (!m) {
|
|
105
|
+
out.push(line);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const ref = m[1];
|
|
109
|
+
const importingDir = path.dirname(importingFile);
|
|
110
|
+
// Resolution order: relative to importing file's dir; relative
|
|
111
|
+
// to cwd; absolute path as-is.
|
|
112
|
+
const candidates = [];
|
|
113
|
+
if (path.isAbsolute(ref)) {
|
|
114
|
+
candidates.push(ref);
|
|
115
|
+
} else {
|
|
116
|
+
candidates.push(path.join(importingDir, ref));
|
|
117
|
+
if (cwd) candidates.push(path.join(cwd, ref));
|
|
118
|
+
}
|
|
119
|
+
let resolved = null;
|
|
120
|
+
for (const c of candidates) {
|
|
121
|
+
if (fs.existsSync(c)) { resolved = c; break; }
|
|
122
|
+
}
|
|
123
|
+
if (!resolved) {
|
|
124
|
+
logger?.warn?.(`[agent-loader] @-import not found: ${ref} (in ${importingFile})`);
|
|
125
|
+
out.push(line);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (visited.has(resolved)) {
|
|
129
|
+
logger?.warn?.(`[agent-loader] @-import cycle: ${resolved}`);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
visited.add(resolved);
|
|
133
|
+
let imported = '';
|
|
134
|
+
try {
|
|
135
|
+
imported = fs.readFileSync(resolved, 'utf8');
|
|
136
|
+
} catch (err) {
|
|
137
|
+
logger?.error?.(`[agent-loader] reading @-import ${resolved}: ${err.message}`);
|
|
138
|
+
out.push(line);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
// Strip frontmatter from imported file (same convention as
|
|
142
|
+
// top-level agent file) and recursively expand its imports.
|
|
143
|
+
imported = stripFrontmatter(imported);
|
|
144
|
+
imported = expandImports(imported, resolved, cwd, visited, logger);
|
|
145
|
+
out.push(imported);
|
|
146
|
+
}
|
|
147
|
+
return out.join('\n');
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Parse a tiny subset of YAML frontmatter (key: value lines).
|
|
151
|
+
function parseFrontmatter(content) {
|
|
152
|
+
if (typeof content !== 'string' || !content.startsWith('---\n')) return {};
|
|
153
|
+
const end = content.indexOf('\n---\n', 4);
|
|
154
|
+
if (end === -1) return {};
|
|
155
|
+
const block = content.slice(4, end);
|
|
156
|
+
const out = {};
|
|
157
|
+
for (const line of block.split('\n')) {
|
|
158
|
+
const m = /^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/.exec(line);
|
|
159
|
+
if (!m) continue;
|
|
160
|
+
let v = m[2].trim();
|
|
161
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
|
|
162
|
+
v = v.slice(1, -1);
|
|
163
|
+
}
|
|
164
|
+
out[m[1]] = v;
|
|
165
|
+
}
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
35
168
|
|
|
36
169
|
/**
|
|
37
170
|
* Load an agent bundle from disk.
|
|
38
171
|
*
|
|
39
|
-
* @param {string} agentName
|
|
172
|
+
* @param {string} agentName
|
|
40
173
|
* @param {object} opts
|
|
41
174
|
* @param {string} [opts.homeDir] — defaults to process.env.HOME.
|
|
42
|
-
*
|
|
175
|
+
* @param {string} [opts.cwd] — chat's working directory; checked
|
|
176
|
+
* FIRST for Claude Code project-level agent discovery.
|
|
43
177
|
* @param {object} [opts.logger] — error logger.
|
|
44
|
-
*
|
|
45
|
-
* @returns {AgentBundle}
|
|
46
|
-
* { agentName, agentDir, systemPrompt, skills: string[],
|
|
47
|
-
* mcpServers: object, raw: settingsJson }
|
|
48
|
-
*
|
|
49
|
-
* Throws `{ code: 'AGENT_NOT_FOUND' }` if the agent dir doesn't
|
|
50
|
-
* exist. Does NOT throw on partial agents (missing CLAUDE.md or
|
|
51
|
-
* skills/ etc — fields just default to null/empty).
|
|
52
178
|
*/
|
|
53
|
-
function loadAgent(agentName, { homeDir = process.env.HOME, logger = console } = {}) {
|
|
54
|
-
|
|
179
|
+
function loadAgent(agentName, { homeDir = process.env.HOME, cwd = null, logger = console } = {}) {
|
|
180
|
+
// Cache key includes cwd because the same agentName can resolve
|
|
181
|
+
// to different files when called from different chats with
|
|
182
|
+
// different cwds (e.g. shumabit-claude vs shumabit-partners).
|
|
183
|
+
const cacheKey = agentName + '\x00' + (cwd || '');
|
|
184
|
+
if (cache.has(cacheKey)) return cache.get(cacheKey);
|
|
55
185
|
|
|
56
|
-
const
|
|
57
|
-
if (!
|
|
186
|
+
const loc = resolveAgentLocation(agentName, homeDir, cwd);
|
|
187
|
+
if (!loc) {
|
|
188
|
+
const looked = [
|
|
189
|
+
cwd ? cwd + '/.claude/agents/' + agentName + '.md' : null,
|
|
190
|
+
homeDir + '/.claude/agents/' + agentName + '.md',
|
|
191
|
+
cwd ? cwd + '/.claude/agents/' + agentName + '/' : null,
|
|
192
|
+
homeDir + '/.claude/agents/' + agentName + '/',
|
|
193
|
+
].filter(Boolean).join(', ');
|
|
58
194
|
throw Object.assign(
|
|
59
|
-
new Error(
|
|
60
|
-
{ code: 'AGENT_NOT_FOUND',
|
|
195
|
+
new Error('agent not found: ' + agentName + ' (looked in ' + looked + ')'),
|
|
196
|
+
{ code: 'AGENT_NOT_FOUND', searchPaths: looked },
|
|
61
197
|
);
|
|
62
198
|
}
|
|
63
199
|
|
|
64
|
-
// System prompt: prefer CLAUDE.md (the standard polygram convention),
|
|
65
|
-
// fall back to AGENTS.md (OpenClaw legacy), then to a single-line
|
|
66
|
-
// file `system-prompt.txt` if either of the markdown files is
|
|
67
|
-
// absent. Whichever is present, read as UTF-8 string.
|
|
68
200
|
let systemPrompt = null;
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
201
|
+
let frontmatter = {};
|
|
202
|
+
let agentPath = loc.path;
|
|
203
|
+
|
|
204
|
+
if (loc.kind === 'file') {
|
|
205
|
+
// Claude Code single-file format. Read whole file, parse and
|
|
206
|
+
// strip frontmatter, body becomes systemPrompt. Then expand
|
|
207
|
+
// any @<file> import directives recursively (rc.15).
|
|
208
|
+
try {
|
|
209
|
+
const raw = fs.readFileSync(loc.path, 'utf8');
|
|
210
|
+
frontmatter = parseFrontmatter(raw);
|
|
211
|
+
const stripped = stripFrontmatter(raw);
|
|
212
|
+
const visited = new Set([loc.path]);
|
|
213
|
+
systemPrompt = expandImports(stripped, loc.path, cwd, visited, logger);
|
|
214
|
+
} catch (err) {
|
|
215
|
+
logger.error?.('[agent-loader] reading ' + loc.path + ': ' + err.message);
|
|
216
|
+
}
|
|
217
|
+
} else {
|
|
218
|
+
// polygram directory layout. CLAUDE.md > AGENTS.md > system-prompt.txt.
|
|
219
|
+
for (const fname of ['CLAUDE.md', 'AGENTS.md', 'system-prompt.txt']) {
|
|
220
|
+
const p = path.join(loc.dir, fname);
|
|
221
|
+
if (fs.existsSync(p)) {
|
|
222
|
+
try {
|
|
223
|
+
const raw = fs.readFileSync(p, 'utf8');
|
|
224
|
+
// Expand @-imports for directory-layout agents too —
|
|
225
|
+
// their content might also reference shared base files.
|
|
226
|
+
const visited = new Set([p]);
|
|
227
|
+
systemPrompt = expandImports(raw, p, cwd, visited, logger);
|
|
228
|
+
agentPath = p;
|
|
229
|
+
break;
|
|
230
|
+
} catch (err) {
|
|
231
|
+
logger.error?.('[agent-loader] reading ' + p + ': ' + err.message);
|
|
232
|
+
}
|
|
77
233
|
}
|
|
78
234
|
}
|
|
79
235
|
}
|
|
80
236
|
|
|
81
|
-
// Settings
|
|
82
|
-
// (mcpServers, model, effort defaults, etc.).
|
|
237
|
+
// Settings.json — only meaningful for directory-layout agents.
|
|
83
238
|
let settings = {};
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
239
|
+
if (loc.dir) {
|
|
240
|
+
const settingsPath = path.join(loc.dir, 'settings.json');
|
|
241
|
+
if (fs.existsSync(settingsPath)) {
|
|
242
|
+
try {
|
|
243
|
+
settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
|
|
244
|
+
} catch (err) {
|
|
245
|
+
logger.error?.('[agent-loader] parsing ' + settingsPath + ': ' + err.message);
|
|
246
|
+
}
|
|
90
247
|
}
|
|
91
248
|
}
|
|
92
249
|
|
|
93
|
-
// Skills
|
|
94
|
-
// `Options.skills` accepts a string[] of skill names.
|
|
95
|
-
const skillsDir = path.join(agentDir, 'skills');
|
|
250
|
+
// Skills (only for directory layout).
|
|
96
251
|
let skills = [];
|
|
97
|
-
if (
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
.
|
|
102
|
-
|
|
103
|
-
|
|
252
|
+
if (loc.dir) {
|
|
253
|
+
const skillsDir = path.join(loc.dir, 'skills');
|
|
254
|
+
if (fs.existsSync(skillsDir)) {
|
|
255
|
+
try {
|
|
256
|
+
skills = fs.readdirSync(skillsDir, { withFileTypes: true })
|
|
257
|
+
.filter((d) => d.isDirectory())
|
|
258
|
+
.map((d) => d.name);
|
|
259
|
+
} catch (err) {
|
|
260
|
+
logger.error?.('[agent-loader] enumerating ' + skillsDir + ': ' + err.message);
|
|
261
|
+
}
|
|
104
262
|
}
|
|
105
263
|
}
|
|
106
264
|
|
|
107
265
|
const mcpServers = settings.mcpServers ?? {};
|
|
108
266
|
|
|
267
|
+
// Frontmatter merged with settings — composeSdkOptions can pick up
|
|
268
|
+
// model/effort overrides from either source.
|
|
269
|
+
const raw = { ...frontmatter, ...settings };
|
|
270
|
+
|
|
109
271
|
const bundle = {
|
|
110
272
|
agentName,
|
|
111
|
-
|
|
273
|
+
agentPath,
|
|
274
|
+
agentDir: loc.dir,
|
|
112
275
|
systemPrompt,
|
|
113
276
|
skills,
|
|
114
277
|
mcpServers,
|
|
115
|
-
|
|
116
|
-
// (e.g. agent-level model/effort defaults).
|
|
117
|
-
raw: settings,
|
|
278
|
+
raw,
|
|
118
279
|
};
|
|
119
|
-
cache.set(
|
|
280
|
+
cache.set(cacheKey, bundle);
|
|
120
281
|
return bundle;
|
|
121
282
|
}
|
|
122
283
|
|
|
@@ -166,4 +327,14 @@ function clearCache() {
|
|
|
166
327
|
cache.clear();
|
|
167
328
|
}
|
|
168
329
|
|
|
169
|
-
module.exports = {
|
|
330
|
+
module.exports = {
|
|
331
|
+
loadAgent,
|
|
332
|
+
composeSdkOptions,
|
|
333
|
+
clearCache,
|
|
334
|
+
// Internals for tests.
|
|
335
|
+
_resolveAgentLocation: resolveAgentLocation,
|
|
336
|
+
_stripFrontmatter: stripFrontmatter,
|
|
337
|
+
_parseFrontmatter: parseFrontmatter,
|
|
338
|
+
_expandImports: expandImports,
|
|
339
|
+
_cache: cache,
|
|
340
|
+
};
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure UI builders for the approval flow's Telegram surface.
|
|
3
|
+
*
|
|
4
|
+
* - 2-button keyboard (CLI pm IPC approval-hook flow)
|
|
5
|
+
* - 4-button keyboard (rc.6 SDK pm canUseTool flow with persisted
|
|
6
|
+
* "Always allow / Always deny" via chat_tool_decisions)
|
|
7
|
+
* - Card text with friendly heading + clipped tool_input body
|
|
8
|
+
*
|
|
9
|
+
* No runtime dependencies — these are pure transforms suitable for
|
|
10
|
+
* unit-testing in isolation. The polygram.js side wires them to
|
|
11
|
+
* `tg(bot, 'sendMessage', ...)` / `editMessageText`.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
'use strict';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 2-button keyboard for the legacy IPC approval flow.
|
|
18
|
+
* @param {number|string} approvalId
|
|
19
|
+
* @param {string} token
|
|
20
|
+
*/
|
|
21
|
+
function buildApprovalKeyboard(approvalId, token) {
|
|
22
|
+
return {
|
|
23
|
+
inline_keyboard: [[
|
|
24
|
+
{ text: '✅ Approve', callback_data: `approve:${approvalId}:${token}` },
|
|
25
|
+
{ text: '❌ Deny', callback_data: `deny:${approvalId}:${token}` },
|
|
26
|
+
]],
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 4-button keyboard for the SDK canUseTool flow (rc.6 Phase 2 step 6).
|
|
32
|
+
* "Always allow" / "Always deny" rows persist the decision into
|
|
33
|
+
* `chat_tool_decisions` so subsequent invocations of the same tool
|
|
34
|
+
* with the same input short-circuit.
|
|
35
|
+
*
|
|
36
|
+
* Callback_data conventions:
|
|
37
|
+
* approve:<id>:<token> — one-time allow
|
|
38
|
+
* deny:<id>:<token> — one-time deny
|
|
39
|
+
* approve-always:<id>:<token> — allow + persist
|
|
40
|
+
* deny-always:<id>:<token> — deny + persist
|
|
41
|
+
*
|
|
42
|
+
* @param {number|string} approvalId
|
|
43
|
+
* @param {string} token
|
|
44
|
+
*/
|
|
45
|
+
function buildApprovalKeyboardWithAlways(approvalId, token) {
|
|
46
|
+
return {
|
|
47
|
+
inline_keyboard: [
|
|
48
|
+
[
|
|
49
|
+
{ text: '✅ Approve', callback_data: `approve:${approvalId}:${token}` },
|
|
50
|
+
{ text: '❌ Deny', callback_data: `deny:${approvalId}:${token}` },
|
|
51
|
+
],
|
|
52
|
+
[
|
|
53
|
+
{ text: '🔁 Always allow', callback_data: `approve-always:${approvalId}:${token}` },
|
|
54
|
+
{ text: '🚫 Always deny', callback_data: `deny-always:${approvalId}:${token}` },
|
|
55
|
+
],
|
|
56
|
+
],
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Format a tool_input value for the inline-keyboard card body.
|
|
62
|
+
* Clips aggressively so the whole card stays under Telegram's
|
|
63
|
+
* 4096-char limit (approval card has surrounding metadata too).
|
|
64
|
+
*
|
|
65
|
+
* @param {unknown} input — string OR any JSON-able object
|
|
66
|
+
* @returns {string}
|
|
67
|
+
*/
|
|
68
|
+
function formatToolInputForCard(input) {
|
|
69
|
+
let s;
|
|
70
|
+
try {
|
|
71
|
+
s = typeof input === 'string' ? input : JSON.stringify(input, null, 2);
|
|
72
|
+
} catch {
|
|
73
|
+
s = String(input);
|
|
74
|
+
}
|
|
75
|
+
// JSON.stringify(undefined) returns undefined, and objects with
|
|
76
|
+
// a circular toJSON could surface odd values too. Fall back to
|
|
77
|
+
// String() so we always operate on a real string.
|
|
78
|
+
if (typeof s !== 'string') s = String(input);
|
|
79
|
+
if (s.length <= 1200) return s;
|
|
80
|
+
return s.slice(0, 900) + '\n…[clipped]…\n' + s.slice(-200);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Approval card text. Plain-text only (NO parse_mode) — tool_input
|
|
85
|
+
* originates from Claude and could contain Markdown specials or
|
|
86
|
+
* tg:// links crafted for phishing.
|
|
87
|
+
*
|
|
88
|
+
* @param {object} row — approval row from the approvals store
|
|
89
|
+
* @param {string} row.tool_name
|
|
90
|
+
* @param {number|string|null} row.turn_id
|
|
91
|
+
* @param {string} row.requester_chat_id
|
|
92
|
+
* @param {object|string|null} [row.tool_input_json]
|
|
93
|
+
* @param {object|string|null} [row.tool_input] — alias for tool_input_json
|
|
94
|
+
* @param {number} row.timeout_ts — unix ms when the row expires
|
|
95
|
+
* @param {object} [opts]
|
|
96
|
+
* @param {string} [opts.resolvedBy] — heading override for resolved cards
|
|
97
|
+
* (e.g. "✓ Approved by ivan").
|
|
98
|
+
* When set, footer is dropped.
|
|
99
|
+
* When unset, heading is "Approval needed — <tool>"
|
|
100
|
+
* and footer shows seconds-to-expire.
|
|
101
|
+
* @param {() => number} [opts.now] — clock injection for tests
|
|
102
|
+
*
|
|
103
|
+
* @returns {string}
|
|
104
|
+
*/
|
|
105
|
+
function approvalCardText(row, opts = {}) {
|
|
106
|
+
const now = (typeof opts.now === 'function' ? opts.now : Date.now)();
|
|
107
|
+
const heading = opts.resolvedBy
|
|
108
|
+
? opts.resolvedBy
|
|
109
|
+
: `Approval needed — ${row.tool_name}`;
|
|
110
|
+
// tool_input may arrive as a parsed object OR a JSON string under
|
|
111
|
+
// either key name depending on the call site.
|
|
112
|
+
const inputSource = row.tool_input_json !== undefined
|
|
113
|
+
? row.tool_input_json
|
|
114
|
+
: row.tool_input;
|
|
115
|
+
const parsed = typeof inputSource === 'string'
|
|
116
|
+
? safeParse(inputSource)
|
|
117
|
+
: inputSource;
|
|
118
|
+
const body = formatToolInputForCard(parsed);
|
|
119
|
+
const ttl = Math.max(0, Math.round((row.timeout_ts - now) / 1000));
|
|
120
|
+
const footer = opts.resolvedBy ? '' : `\n\n⏱ expires in ${ttl}s`;
|
|
121
|
+
return `${heading}\nChat: ${row.requester_chat_id}\nTurn: ${row.turn_id || '-'}\n\n${body}${footer}`;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function safeParse(s) {
|
|
125
|
+
try { return JSON.parse(s); } catch { return s; }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
module.exports = {
|
|
129
|
+
buildApprovalKeyboard,
|
|
130
|
+
buildApprovalKeyboardWithAlways,
|
|
131
|
+
formatToolInputForCard,
|
|
132
|
+
approvalCardText,
|
|
133
|
+
// Internals exposed for tests
|
|
134
|
+
_safeParse: safeParse,
|
|
135
|
+
};
|
package/lib/approval-waiters.js
CHANGED
|
@@ -110,6 +110,13 @@ function createApprovalWaiters({
|
|
|
110
110
|
parkedAt: Date.now(),
|
|
111
111
|
sessionKey,
|
|
112
112
|
});
|
|
113
|
+
|
|
114
|
+
// If the signal was ALREADY aborted before we attached the
|
|
115
|
+
// listener, addEventListener never fires — the waiter would
|
|
116
|
+
// sit in the map until timeout-sweep / shutdown picked it up.
|
|
117
|
+
// Trigger the cleanup manually so the parked promise rejects
|
|
118
|
+
// immediately (matches "abort fired during park" semantics).
|
|
119
|
+
if (signal && signal.aborted) sigCleanup();
|
|
113
120
|
});
|
|
114
121
|
}
|
|
115
122
|
|
package/lib/approvals.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
const crypto = require('crypto');
|
|
14
|
+
const { canonicalizeToolInput } = require('./canonical-json');
|
|
14
15
|
|
|
15
16
|
const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;
|
|
16
17
|
// 16 random bytes → 22 base64url chars ≈ 128 bits of entropy. Prevents
|
|
@@ -19,7 +20,14 @@ const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;
|
|
|
19
20
|
const TOKEN_BYTES = 16;
|
|
20
21
|
|
|
21
22
|
function digestInput(input) {
|
|
22
|
-
|
|
23
|
+
// Canonicalise object inputs so key-order doesn't change the digest.
|
|
24
|
+
// Pre-fix `JSON.stringify({a:1,b:2})` and `JSON.stringify({b:2,a:1})`
|
|
25
|
+
// produced different hashes — the dedup contract assumed logical
|
|
26
|
+
// equivalence but the impl was order-sensitive, so an SDK that
|
|
27
|
+
// re-serialised the input between turns would dedup-miss.
|
|
28
|
+
const json = typeof input === 'string'
|
|
29
|
+
? input
|
|
30
|
+
: JSON.stringify(canonicalizeToolInput(input));
|
|
23
31
|
return crypto.createHash('sha256').update(json).digest('hex').slice(0, 16);
|
|
24
32
|
}
|
|
25
33
|
|
package/lib/async-lock.js
CHANGED
|
@@ -22,13 +22,21 @@ function createAsyncLock() {
|
|
|
22
22
|
const prev = chains.get(key) || Promise.resolve();
|
|
23
23
|
let release;
|
|
24
24
|
const next = new Promise((resolve) => { release = resolve; });
|
|
25
|
-
|
|
25
|
+
// Save the chain-entry promise so the cleanup branch can compare
|
|
26
|
+
// against the SAME reference. Pre-fix this re-evaluated
|
|
27
|
+
// `prev.then(() => next)` (a fresh promise each call), so the
|
|
28
|
+
// === compare was always false and the Map leaked one entry per
|
|
29
|
+
// unique key.
|
|
30
|
+
const myEntry = prev.then(() => next);
|
|
31
|
+
chains.set(key, myEntry);
|
|
26
32
|
await prev;
|
|
27
33
|
// Return a wrapper that also clears the chain entry when this is
|
|
28
34
|
// the last holder — avoids the Map growing unbounded across the
|
|
29
|
-
// lifetime of the process.
|
|
35
|
+
// lifetime of the process. Idempotent: a double-release call is
|
|
36
|
+
// harmless (release() is a Promise resolver; calling resolve
|
|
37
|
+
// twice is a no-op).
|
|
30
38
|
return () => {
|
|
31
|
-
if (chains.get(key) ===
|
|
39
|
+
if (chains.get(key) === myEntry) {
|
|
32
40
|
chains.delete(key);
|
|
33
41
|
}
|
|
34
42
|
release();
|