@cydm/pie 4.8.0 → 4.10.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 +51 -27
- package/dist/builtin/extensions/ask-user/index.js +4 -4
- package/dist/builtin/extensions/cron/index.js +906 -158
- package/dist/builtin/extensions/im-forward/README.md +4 -2
- package/dist/builtin/extensions/im-forward/index.js +6875 -3972
- package/dist/builtin/extensions/memory/index.js +76 -28
- package/dist/builtin/extensions/pie-ipc/README.md +2 -2
- package/dist/builtin/extensions/pie-ipc/index.js +285 -61
- package/dist/builtin/extensions/pie-proc/README.md +7 -7
- package/dist/builtin/extensions/pie-proc/index.js +493 -107
- package/dist/builtin/extensions/plan-mode/index.js +5 -5
- package/dist/builtin/extensions/subagent/index.js +8 -8
- package/dist/builtin/extensions/todo/index.js +4 -4
- package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +26 -24
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +199 -121
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
- package/dist/builtin/skills/chrome-devtools-axi/chunk-HAUDUMDO.js +795 -0
- package/dist/builtin/skills/chrome-devtools-axi/{cli-ZE754CTH.js → cli-K7ESY3XD.js} +433 -255
- package/dist/builtin/skills/computer-use-axi/SKILL.md +25 -8
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +367 -65
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +2 -2
- package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +451 -43
- package/dist/chunks/{chunk-Y3I2UV5Y.js → chunk-5QMS6RQC.js} +353 -287
- package/dist/chunks/chunk-6WKBQZWM.js +19 -0
- package/dist/chunks/{chunk-LAJXWOKS.js → chunk-7LICWWUE.js} +11 -9
- package/dist/chunks/{chunk-5KI4Y4LA.js → chunk-BQWHLYYZ.js} +4 -3
- package/dist/chunks/{chunk-4PR34UZF.js → chunk-BTUMBUDU.js} +159 -145
- package/dist/chunks/{chunk-NHV2CALB.js → chunk-FC5AN5QP.js} +409 -32
- package/dist/chunks/{chunk-3W3SXVPB.js → chunk-G2K4GY6N.js} +993 -371
- package/dist/chunks/{chunk-BLDI2GRF.js → chunk-HK3FHIAH.js} +1364 -446
- package/dist/chunks/chunk-IZKHSUNQ.js +30 -0
- package/dist/chunks/{chunk-CGSFBWOM.js → chunk-KWK7KTSZ.js} +4 -3
- package/dist/chunks/chunk-OU33ROFD.js +717 -0
- package/dist/chunks/{chunk-Z2FKA2ZH.js → chunk-XMTRKMBG.js} +104 -22
- package/dist/chunks/{host-image-fallback-N7RHNPYN.js → host-image-fallback-3TEMOQM5.js} +1 -1
- package/dist/chunks/{manager-cli-NEZA46M5.js → manager-cli-Y6HM3MHA.js} +5 -5
- package/dist/chunks/{model-registry-3XAHXXTA.js → model-registry-QKJ3YVDS.js} +2 -2
- package/dist/chunks/{read-file-understanding-FMPXR6EJ.js → read-file-understanding-N2ZZQLTZ.js} +5 -5
- package/dist/chunks/{src-EGXFJ3WA.js → src-3PSR2AAX.js} +3 -3
- package/dist/chunks/{src-B44QWSGM.js → src-D5GN4Q5O.js} +2 -2
- package/dist/chunks/{src-CLE5ILN4.js → src-F5N6O2HR.js} +20 -4
- package/dist/chunks/{src-Q7LU27C2.js → src-TIDKYA5F.js} +31 -1
- package/dist/chunks/{test-stream-OR3EJBNF.js → test-stream-JAJHK44G.js} +2 -2
- package/dist/cli.js +4123 -2389
- package/models.schema.json +271 -0
- package/package.json +2 -2
- package/dist/builtin/skills/chrome-devtools-axi/chunk-Z2A5LA5A.js +0 -407
- package/dist/chunks/chunk-EGZ5TZRM.js +0 -1444
- package/dist/chunks/{manager-upgrade-CTU3ISCW.js → manager-upgrade-LSTOHBUV.js} +3 -3
|
@@ -1,1444 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
claimOwnership,
|
|
4
|
-
pidDefinitelyDead,
|
|
5
|
-
readOwnership
|
|
6
|
-
} from "./chunk-ZPJ3BNQB.js";
|
|
7
|
-
|
|
8
|
-
// builtin/extensions/im-forward/helpers.ts
|
|
9
|
-
import * as nodeCrypto from "node:crypto";
|
|
10
|
-
var MAX_INPUT_HEADER_CHARS = 200;
|
|
11
|
-
function isRecord(value) {
|
|
12
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
13
|
-
}
|
|
14
|
-
function assistantForwardText(message) {
|
|
15
|
-
if (message?.role !== "assistant" || !Array.isArray(message.content)) return "";
|
|
16
|
-
let text = "";
|
|
17
|
-
let hasToolCalls = false;
|
|
18
|
-
for (const block of message.content) {
|
|
19
|
-
if (!isRecord(block)) continue;
|
|
20
|
-
if (block.type === "text" && typeof block.text === "string") text += block.text;
|
|
21
|
-
else if (block.type === "toolCall") hasToolCalls = true;
|
|
22
|
-
}
|
|
23
|
-
if (hasToolCalls) return "";
|
|
24
|
-
return text.trim();
|
|
25
|
-
}
|
|
26
|
-
function sessionLabel(sessionId, sessionName) {
|
|
27
|
-
if (sessionName && sessionName.trim()) return sessionName.trim();
|
|
28
|
-
return sessionId.length > 8 ? sessionId.slice(0, 8) : sessionId;
|
|
29
|
-
}
|
|
30
|
-
function escapeMarkdownInline(text) {
|
|
31
|
-
return text.replace(/\\/g, "\\\\").replace(/`/g, "\\`");
|
|
32
|
-
}
|
|
33
|
-
function inputHeaderLine(userInput) {
|
|
34
|
-
if (!userInput) return null;
|
|
35
|
-
const collapsed = userInput.replace(/\s+/g, " ").trim();
|
|
36
|
-
if (!collapsed) return null;
|
|
37
|
-
let escaped = escapeMarkdownInline(collapsed);
|
|
38
|
-
if (escaped.length > MAX_INPUT_HEADER_CHARS) {
|
|
39
|
-
let clipped = stripDanglingHighSurrogate(escaped.slice(0, MAX_INPUT_HEADER_CHARS));
|
|
40
|
-
if (/(?:^|[^\\])(?:\\\\)*\\$/.test(clipped)) clipped = clipped.slice(0, -1);
|
|
41
|
-
escaped = clipped + "\u2026";
|
|
42
|
-
}
|
|
43
|
-
return `> [UserInput] ${escaped}`;
|
|
44
|
-
}
|
|
45
|
-
function composeForwardBody(sessionId, sessionName, userInput, text, mode = "topic-root") {
|
|
46
|
-
const lines = [];
|
|
47
|
-
lines.push(`**[Pie] \xB7 ${sessionLabel(sessionId, sessionName)}**`);
|
|
48
|
-
const input = inputHeaderLine(userInput);
|
|
49
|
-
if (input) lines.push(input);
|
|
50
|
-
if (lines.length > 0) lines.push("");
|
|
51
|
-
lines.push(text);
|
|
52
|
-
return lines.join("\n");
|
|
53
|
-
}
|
|
54
|
-
var FEISHU_POST_REQUEST_LIMIT_BYTES = 3e4;
|
|
55
|
-
var MAX_BODY_BYTES = FEISHU_POST_REQUEST_LIMIT_BYTES - 6e3;
|
|
56
|
-
var MAX_BODY_UTF16_CHARS = 3e4;
|
|
57
|
-
var POST_PARAGRAPH_OVERHEAD_BYTES = 150;
|
|
58
|
-
var POST_LINE_OVERHEAD_BYTES = 12;
|
|
59
|
-
var POST_ENVELOPE_OVERHEAD_BYTES = 256;
|
|
60
|
-
var textEncoder = new TextEncoder();
|
|
61
|
-
function utf8Bytes(text) {
|
|
62
|
-
return textEncoder.encode(text).length;
|
|
63
|
-
}
|
|
64
|
-
function utf16LengthBudget(text, maxChars) {
|
|
65
|
-
if (text.length <= maxChars) return text;
|
|
66
|
-
return stripDanglingHighSurrogate(text.slice(0, maxChars));
|
|
67
|
-
}
|
|
68
|
-
function stripDanglingHighSurrogate(text) {
|
|
69
|
-
return /[\uD800-\uDBFF]$/.test(text) ? text.slice(0, -1) : text;
|
|
70
|
-
}
|
|
71
|
-
function estimatePostRequestBytes(markdown) {
|
|
72
|
-
const escaped = utf8Bytes(JSON.stringify(markdown).slice(1, -1));
|
|
73
|
-
const paragraphs = markdown.split(/\n{2,}/).filter((part) => part.trim().length > 0).length;
|
|
74
|
-
const lines = markdown.length === 0 ? 0 : markdown.split("\n").length;
|
|
75
|
-
return escaped + paragraphs * POST_PARAGRAPH_OVERHEAD_BYTES + lines * POST_LINE_OVERHEAD_BYTES + POST_ENVELOPE_OVERHEAD_BYTES;
|
|
76
|
-
}
|
|
77
|
-
function truncateMarkdown(text, maxBytes = MAX_BODY_BYTES) {
|
|
78
|
-
const bounded = utf16LengthBudget(text, MAX_BODY_UTF16_CHARS);
|
|
79
|
-
const charCapped = bounded !== text;
|
|
80
|
-
if (!charCapped && estimatePostRequestBytes(text) <= maxBytes) return text;
|
|
81
|
-
const suffix = "\n\n\u2026(truncated)";
|
|
82
|
-
const suffixCost = estimatePostRequestBytes(suffix) - POST_ENVELOPE_OVERHEAD_BYTES;
|
|
83
|
-
const budget = charCapped ? Math.min(maxBytes - suffixCost, bounded.length - suffix.length) : maxBytes - suffixCost;
|
|
84
|
-
const snapForward = (candidate) => {
|
|
85
|
-
const newline = candidate.lastIndexOf("\n");
|
|
86
|
-
if (newline < Math.floor(candidate.length * 0.85)) return candidate;
|
|
87
|
-
const snapped = candidate.slice(0, newline);
|
|
88
|
-
return snapped.trim().length > 0 ? snapped : candidate;
|
|
89
|
-
};
|
|
90
|
-
const fit = (limit) => {
|
|
91
|
-
let lo = 0;
|
|
92
|
-
let hi = text.length;
|
|
93
|
-
while (lo < hi) {
|
|
94
|
-
const mid = Math.ceil((lo + hi) / 2);
|
|
95
|
-
if (estimatePostRequestBytes(text.slice(0, mid)) <= limit) lo = mid;
|
|
96
|
-
else hi = mid - 1;
|
|
97
|
-
}
|
|
98
|
-
return text.slice(0, lo);
|
|
99
|
-
};
|
|
100
|
-
let cut = snapForward(stripDanglingHighSurrogate(fit(Math.max(0, budget))));
|
|
101
|
-
if ((cut.match(/```/g)?.length ?? 0) % 2 === 1) {
|
|
102
|
-
const closeCost = estimatePostRequestBytes("\n```") - POST_ENVELOPE_OVERHEAD_BYTES;
|
|
103
|
-
const refit = snapForward(stripDanglingHighSurrogate(fit(Math.max(0, budget - closeCost))));
|
|
104
|
-
cut = (refit.match(/```/g)?.length ?? 0) % 2 === 1 ? refit + "\n```" : refit;
|
|
105
|
-
}
|
|
106
|
-
return cut + suffix;
|
|
107
|
-
}
|
|
108
|
-
function scanFenceLines(text) {
|
|
109
|
-
const lines = text.split("\n");
|
|
110
|
-
const stateAtLineStart = [];
|
|
111
|
-
const stateAtLineEnd = [];
|
|
112
|
-
const openedBy = [];
|
|
113
|
-
const closedBy = [];
|
|
114
|
-
let open = null;
|
|
115
|
-
let listIndent = 0;
|
|
116
|
-
const expandLeadingTabs = (value) => {
|
|
117
|
-
const match = /^([ \t]+)/.exec(value);
|
|
118
|
-
if (!match || !match[1].includes(" ")) return value;
|
|
119
|
-
let column = 0;
|
|
120
|
-
for (const ch of match[1]) column = ch === " " ? Math.ceil((column + 1) / 4) * 4 : column + 1;
|
|
121
|
-
return " ".repeat(column) + value.slice(match[0].length);
|
|
122
|
-
};
|
|
123
|
-
for (let i = 0; i < lines.length; i++) {
|
|
124
|
-
const source = lines[i].replace(/^(?: {0,3}> ?)+/, "");
|
|
125
|
-
let line = expandLeadingTabs(source);
|
|
126
|
-
const marker = !open && /^( {0,3})(?:[-*+]|\d{1,9}[.)])(?:\t| {1,4})(?=\S)/.exec(line);
|
|
127
|
-
if (marker) {
|
|
128
|
-
listIndent = marker[0].length;
|
|
129
|
-
line = line.slice(listIndent);
|
|
130
|
-
} else if (listIndent && line.startsWith(" ".repeat(listIndent))) {
|
|
131
|
-
line = line.slice(listIndent);
|
|
132
|
-
} else if (line.trim() && !open) {
|
|
133
|
-
listIndent = 0;
|
|
134
|
-
}
|
|
135
|
-
stateAtLineStart.push(open);
|
|
136
|
-
let opened = null;
|
|
137
|
-
let closed = null;
|
|
138
|
-
if (!open) {
|
|
139
|
-
const m = /^( {0,3})(`{3,}|~{3,})(.*)$/.exec(line);
|
|
140
|
-
if (m && (m[2][0] === "~" || !m[3].includes("`"))) {
|
|
141
|
-
open = { delimiter: m[2], info: m[3].trim() };
|
|
142
|
-
opened = open;
|
|
143
|
-
}
|
|
144
|
-
} else {
|
|
145
|
-
const m = /^( {0,3})(`+|~+)[ \t]*$/.exec(line);
|
|
146
|
-
if (m && m[2][0] === open.delimiter[0] && m[2].length >= open.delimiter.length) {
|
|
147
|
-
closed = open;
|
|
148
|
-
open = null;
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
const isListMarker = marker !== null;
|
|
152
|
-
const isListContinuation = !isListMarker && listIndent > 0 && source.startsWith(" ".repeat(listIndent));
|
|
153
|
-
const isContainerContent = isListMarker || isListContinuation || open !== null || opened !== null && open !== null;
|
|
154
|
-
const rawLine = lines[i];
|
|
155
|
-
const quotePrefix = /^(?: {0,3}> ?)+/.exec(rawLine)?.[0] ?? "";
|
|
156
|
-
const emitSource = isContainerContent || quotePrefix === "" ? source : rawLine;
|
|
157
|
-
const dedentColumns = expandLeadingTabs(emitSource).length - line.length;
|
|
158
|
-
const rawDedent = (raw, columns) => {
|
|
159
|
-
if (columns <= 0) return raw;
|
|
160
|
-
if (!raw.includes(" ")) return raw.slice(columns);
|
|
161
|
-
let column = 0, index = 0;
|
|
162
|
-
while (index < raw.length && column < columns) {
|
|
163
|
-
const ch = raw[index];
|
|
164
|
-
const next = ch === " " ? Math.ceil((column + 1) / 4) * 4 : column + 1;
|
|
165
|
-
if (ch === " " && next > columns) break;
|
|
166
|
-
column = next;
|
|
167
|
-
index++;
|
|
168
|
-
}
|
|
169
|
-
return raw.slice(index);
|
|
170
|
-
};
|
|
171
|
-
lines[i] = stateAtLineStart[i] || opened ? rawDedent(emitSource, dedentColumns) : emitSource;
|
|
172
|
-
openedBy.push(opened);
|
|
173
|
-
closedBy.push(closed);
|
|
174
|
-
stateAtLineEnd.push(open);
|
|
175
|
-
}
|
|
176
|
-
return { stateAtLineStart, stateAtLineEnd, openedBy, closedBy, lines };
|
|
177
|
-
}
|
|
178
|
-
function chunkKey(base, index, tag = "part", digest = sha256Digest19) {
|
|
179
|
-
if (index === 0 && tag === "part" && base.length <= 50) return base;
|
|
180
|
-
const candidate = `${base}-${tag}${index + 1}`;
|
|
181
|
-
if (candidate.length <= 50) return candidate;
|
|
182
|
-
return `${base.slice(0, 30)}-${digest(`${tag}:${index}:${base}`)}`.slice(0, 50);
|
|
183
|
-
}
|
|
184
|
-
var sha256Digest19 = (input) => nodeCrypto.createHash("sha256").update(input).digest("hex").slice(0, 19);
|
|
185
|
-
function chunkMarkdown(text, maxBytes = MAX_BODY_BYTES) {
|
|
186
|
-
const MIN_FEASIBLE_BUDGET = 320;
|
|
187
|
-
if (maxBytes < MIN_FEASIBLE_BUDGET) return [[text], false];
|
|
188
|
-
if (utf16LengthBudget(text, MAX_BODY_UTF16_CHARS) === text && estimatePostRequestBytes(text) <= maxBytes) {
|
|
189
|
-
return [[text], false];
|
|
190
|
-
}
|
|
191
|
-
const scan = scanFenceLines(text);
|
|
192
|
-
const lines = scan.lines.slice();
|
|
193
|
-
const fits = (candidate) => candidate.length <= MAX_BODY_UTF16_CHARS && estimatePostRequestBytes(candidate) <= maxBytes;
|
|
194
|
-
const MAX_SYNTHETIC_INFO_CHARS = 32;
|
|
195
|
-
const closeMarker = (f) => f.delimiter;
|
|
196
|
-
const midLineCloseMarker = (f) => "\n" + f.delimiter;
|
|
197
|
-
const reopenMarker = (f) => f.delimiter + (f.info.length > MAX_SYNTHETIC_INFO_CHARS ? f.info.slice(0, MAX_SYNTHETIC_INFO_CHARS) : f.info) + "\n";
|
|
198
|
-
const chunks = [];
|
|
199
|
-
let lineIndex = 0;
|
|
200
|
-
let pendingPrefix = "";
|
|
201
|
-
while (lineIndex < lines.length) {
|
|
202
|
-
if (lines[lineIndex] === "" && lineIndex === lines.length - 1) {
|
|
203
|
-
lineIndex++;
|
|
204
|
-
continue;
|
|
205
|
-
}
|
|
206
|
-
const assemble = (endLine) => {
|
|
207
|
-
const separator = endLine < lines.length - 1 ? "\n" : "";
|
|
208
|
-
const body = pendingPrefix + lines.slice(lineIndex, endLine + 1).join("\n") + separator;
|
|
209
|
-
const fence = scan.stateAtLineEnd[endLine] ?? null;
|
|
210
|
-
const chunk = body + (fence ? body.endsWith("\n") || body === "" ? fence.delimiter : "\n" + fence.delimiter : "");
|
|
211
|
-
return fits(chunk) ? { chunk, fence, endLine } : null;
|
|
212
|
-
};
|
|
213
|
-
let lo = lineIndex, hi = lines.length - 1;
|
|
214
|
-
let best = null;
|
|
215
|
-
while (lo <= hi) {
|
|
216
|
-
const mid = lo + Math.ceil((hi - lo) / 2);
|
|
217
|
-
const built = assemble(mid);
|
|
218
|
-
if (built) {
|
|
219
|
-
best = built;
|
|
220
|
-
lo = mid + 1;
|
|
221
|
-
} else hi = mid - 1;
|
|
222
|
-
}
|
|
223
|
-
if (best) {
|
|
224
|
-
for (let j = best.endLine - 1; j > lineIndex + Math.floor((best.endLine - lineIndex) / 2); j--) {
|
|
225
|
-
if (lines[j + 1] === "" && scan.stateAtLineEnd[j] === null && !scan.openedBy[j]) {
|
|
226
|
-
const snapped = assemble(j);
|
|
227
|
-
if (snapped) best = snapped;
|
|
228
|
-
break;
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
chunks.push(best.chunk);
|
|
232
|
-
lineIndex = best.endLine + 1;
|
|
233
|
-
pendingPrefix = best.fence ? reopenMarker(best.fence) : "";
|
|
234
|
-
continue;
|
|
235
|
-
}
|
|
236
|
-
const firstLine = lines[lineIndex];
|
|
237
|
-
if (firstLine.length === 0) {
|
|
238
|
-
lineIndex++;
|
|
239
|
-
continue;
|
|
240
|
-
}
|
|
241
|
-
const pFence = scan.stateAtLineEnd[lineIndex] ?? null;
|
|
242
|
-
let plo = 1, phi = firstLine.length, pbest = 0;
|
|
243
|
-
while (plo <= phi) {
|
|
244
|
-
const mid = plo + Math.ceil((phi - plo) / 2);
|
|
245
|
-
const prefix = stripDanglingHighSurrogate(firstLine.slice(0, mid));
|
|
246
|
-
const chunk = pendingPrefix + prefix + (pFence ? midLineCloseMarker(pFence) : "");
|
|
247
|
-
if (fits(chunk)) {
|
|
248
|
-
pbest = prefix.length;
|
|
249
|
-
plo = mid + 1;
|
|
250
|
-
} else phi = mid - 1;
|
|
251
|
-
}
|
|
252
|
-
if (pbest > 0) {
|
|
253
|
-
chunks.push(pendingPrefix + stripDanglingHighSurrogate(firstLine.slice(0, pbest)) + (pFence ? midLineCloseMarker(pFence) : ""));
|
|
254
|
-
lines[lineIndex] = firstLine.slice(pbest);
|
|
255
|
-
pendingPrefix = pFence ? reopenMarker(pFence) : "";
|
|
256
|
-
continue;
|
|
257
|
-
}
|
|
258
|
-
const one = stripDanglingHighSurrogate(firstLine.slice(0, 2));
|
|
259
|
-
chunks.push(one.length > 0 ? one : firstLine.slice(0, 1));
|
|
260
|
-
lines[lineIndex] = firstLine.slice(one.length > 0 ? one.length : 1);
|
|
261
|
-
pendingPrefix = "";
|
|
262
|
-
}
|
|
263
|
-
return [chunks, chunks.length > 1];
|
|
264
|
-
}
|
|
265
|
-
var ATTACHABLE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
266
|
-
"ts",
|
|
267
|
-
"tsx",
|
|
268
|
-
"js",
|
|
269
|
-
"jsx",
|
|
270
|
-
"mjs",
|
|
271
|
-
"cjs",
|
|
272
|
-
"json",
|
|
273
|
-
"md",
|
|
274
|
-
"txt",
|
|
275
|
-
"log",
|
|
276
|
-
"py",
|
|
277
|
-
"cs",
|
|
278
|
-
"css",
|
|
279
|
-
"scss",
|
|
280
|
-
"html",
|
|
281
|
-
"xml",
|
|
282
|
-
"yaml",
|
|
283
|
-
"yml",
|
|
284
|
-
"toml",
|
|
285
|
-
"sh",
|
|
286
|
-
"sql",
|
|
287
|
-
"java",
|
|
288
|
-
"kt",
|
|
289
|
-
"swift",
|
|
290
|
-
"go",
|
|
291
|
-
"rs",
|
|
292
|
-
"rb",
|
|
293
|
-
"php",
|
|
294
|
-
"c",
|
|
295
|
-
"h",
|
|
296
|
-
"cpp",
|
|
297
|
-
"hpp"
|
|
298
|
-
]);
|
|
299
|
-
var MAX_ATTACHMENT_BYTES = 2 * 1024 * 1024;
|
|
300
|
-
var MAX_ATTACHMENTS_PER_FORWARD = 5;
|
|
301
|
-
function collectFileReferences(text, cwd, fsStat, options) {
|
|
302
|
-
const maxFiles = options?.maxFiles ?? MAX_ATTACHMENTS_PER_FORWARD;
|
|
303
|
-
const maxBytes = options?.maxBytes ?? MAX_ATTACHMENT_BYTES;
|
|
304
|
-
const canonicalRoot = options?.canonicalize ? options.canonicalize(cwd) : cwd;
|
|
305
|
-
if (canonicalRoot === null) return [];
|
|
306
|
-
const rootSegments = canonicalRoot.split(/[\\/]+/).filter((segment) => segment.length > 0);
|
|
307
|
-
const driveRoot = /^[A-Za-z]:$/.test(rootSegments[0] ?? "");
|
|
308
|
-
const isInsideRoot = (candidate) => {
|
|
309
|
-
if (candidate === canonicalRoot) return true;
|
|
310
|
-
const segments = candidate.split(/[\\/]+/).filter((segment) => segment.length > 0);
|
|
311
|
-
if (segments.length <= rootSegments.length) return false;
|
|
312
|
-
for (let index = 0; index < rootSegments.length; index++) {
|
|
313
|
-
const a = rootSegments[index], b = segments[index];
|
|
314
|
-
if (driveRoot ? a.toLowerCase() !== b.toLowerCase() : a !== b) return false;
|
|
315
|
-
}
|
|
316
|
-
return true;
|
|
317
|
-
};
|
|
318
|
-
const seen = /* @__PURE__ */ new Set();
|
|
319
|
-
const results = [];
|
|
320
|
-
const scan = scanFenceLines(text);
|
|
321
|
-
let outside = "";
|
|
322
|
-
const indentColumns = (line) => {
|
|
323
|
-
let column = 0;
|
|
324
|
-
for (const ch of line) {
|
|
325
|
-
if (ch === " ") column += 1;
|
|
326
|
-
else if (ch === " ") column = 4 * Math.ceil((column + 1) / 4);
|
|
327
|
-
else break;
|
|
328
|
-
}
|
|
329
|
-
return column;
|
|
330
|
-
};
|
|
331
|
-
for (let i = 0; i < scan.lines.length; i++) {
|
|
332
|
-
const line = scan.lines[i];
|
|
333
|
-
const insideFence = scan.stateAtLineStart[i] !== null || scan.openedBy[i] !== null;
|
|
334
|
-
const indentedCode = indentColumns(line) >= 4;
|
|
335
|
-
if (!insideFence && !indentedCode) outside += line + "\n";
|
|
336
|
-
}
|
|
337
|
-
const candidates = [];
|
|
338
|
-
for (const match of outside.matchAll(/\[[^\]\n]*\]\(([^)\n]+)\)/g)) candidates.push(match[1]);
|
|
339
|
-
for (const match of outside.matchAll(/`([^`\n]+)`/g)) {
|
|
340
|
-
const code = match[1].trim();
|
|
341
|
-
if (code.includes("/") || /\.[a-z0-9]{1,8}$/i.test(code)) candidates.push(code);
|
|
342
|
-
}
|
|
343
|
-
for (const candidate of candidates) {
|
|
344
|
-
if (results.length >= maxFiles) break;
|
|
345
|
-
let path4 = candidate.trim();
|
|
346
|
-
if (!path4 || path4.startsWith("/") || path4.startsWith("~") || /^[a-z]+:/i.test(path4) || path4.includes("://")) continue;
|
|
347
|
-
const clean = path4.replace(/^\.\//, "").split("#")[0].split("?")[0];
|
|
348
|
-
if (clean.includes("..")) continue;
|
|
349
|
-
const extension = clean.split(".").pop().toLowerCase();
|
|
350
|
-
if (!extension || !ATTACHABLE_EXTENSIONS.has(extension)) continue;
|
|
351
|
-
const absolute = nodePathResolve(cwd, clean);
|
|
352
|
-
if (seen.has(absolute)) continue;
|
|
353
|
-
const stat = fsStat(absolute);
|
|
354
|
-
if (!stat || !stat.isFile || stat.size > maxBytes || stat.size === 0) continue;
|
|
355
|
-
const canonical = options?.canonicalize ? options.canonicalize(absolute) : absolute;
|
|
356
|
-
if (canonical === null) continue;
|
|
357
|
-
if (!isInsideRoot(canonical)) continue;
|
|
358
|
-
if (seen.has(canonical)) continue;
|
|
359
|
-
seen.add(absolute);
|
|
360
|
-
seen.add(canonical);
|
|
361
|
-
results.push(absolute);
|
|
362
|
-
}
|
|
363
|
-
return results;
|
|
364
|
-
}
|
|
365
|
-
function nodePathResolve(cwd, relative) {
|
|
366
|
-
const separator = cwd.includes("\\") && !cwd.includes("/") ? "\\" : "/";
|
|
367
|
-
const normalized = relative.split("/").filter((part) => part.length > 0);
|
|
368
|
-
const base = cwd.replace(/[\\/]$/, "").split(/[\\/]/);
|
|
369
|
-
for (const part of normalized) {
|
|
370
|
-
if (part === ".") continue;
|
|
371
|
-
base.push(part);
|
|
372
|
-
}
|
|
373
|
-
return base.join(separator);
|
|
374
|
-
}
|
|
375
|
-
function failureReason(message) {
|
|
376
|
-
const detail = message.errorMessage?.trim();
|
|
377
|
-
if (detail) {
|
|
378
|
-
const collapsed = detail.replace(/\s+/g, " ");
|
|
379
|
-
return collapsed.length > 400 ? `${collapsed.slice(0, 400)}\u2026` : collapsed;
|
|
380
|
-
}
|
|
381
|
-
switch (message.stopReason) {
|
|
382
|
-
case "aborted":
|
|
383
|
-
return "turn aborted";
|
|
384
|
-
case "error":
|
|
385
|
-
return "model/provider error (no detail)";
|
|
386
|
-
case "length":
|
|
387
|
-
return "output length limit reached";
|
|
388
|
-
default:
|
|
389
|
-
return message.stopReason ? `stop reason: ${message.stopReason}` : "unknown failure";
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
// builtin/extensions/im-forward/config.ts
|
|
394
|
-
import * as fs from "node:fs";
|
|
395
|
-
import * as path from "node:path";
|
|
396
|
-
import * as os from "node:os";
|
|
397
|
-
import { randomUUID } from "node:crypto";
|
|
398
|
-
function resolveConfigDir() {
|
|
399
|
-
const value = process.env.PIE_CODING_AGENT_DIR?.trim();
|
|
400
|
-
return value === "~" ? os.homedir() : value?.startsWith("~/") ? os.homedir() + value.slice(1) : value || path.join(os.homedir(), ".pie");
|
|
401
|
-
}
|
|
402
|
-
function configPaths(cwd, dir) {
|
|
403
|
-
return [.../* @__PURE__ */ new Set([path.join(dir, "im-forward.json"), path.join(cwd, ".pie", "im-forward.json")])];
|
|
404
|
-
}
|
|
405
|
-
var configCache = /* @__PURE__ */ new Map();
|
|
406
|
-
function layerStamp(file) {
|
|
407
|
-
try {
|
|
408
|
-
const stat = fs.statSync(file);
|
|
409
|
-
return `${stat.mtimeMs}:${stat.size}`;
|
|
410
|
-
} catch {
|
|
411
|
-
return "-";
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
function cachedResolveConfig(cwd, dir) {
|
|
415
|
-
const cacheKey = `${cwd}\0${dir}`;
|
|
416
|
-
const stamp = JSON.stringify(configPaths(cwd, dir).map(layerStamp));
|
|
417
|
-
const cached = configCache.get(cacheKey);
|
|
418
|
-
if (cached && cached.stamp === stamp) return cached.result;
|
|
419
|
-
const result = resolveConfig(cwd, dir);
|
|
420
|
-
configCache.set(cacheKey, { stamp, result });
|
|
421
|
-
return result;
|
|
422
|
-
}
|
|
423
|
-
function invalidateConfigCache() {
|
|
424
|
-
configCache.clear();
|
|
425
|
-
}
|
|
426
|
-
function readLayer(file) {
|
|
427
|
-
let text;
|
|
428
|
-
try {
|
|
429
|
-
text = fs.readFileSync(file, "utf8");
|
|
430
|
-
} catch (error) {
|
|
431
|
-
if (error.code === "ENOENT") return {};
|
|
432
|
-
throw new Error(`Cannot read IM configuration: ${file}`);
|
|
433
|
-
}
|
|
434
|
-
try {
|
|
435
|
-
const value = JSON.parse(text);
|
|
436
|
-
if (isRecord(value)) return value;
|
|
437
|
-
} catch {
|
|
438
|
-
}
|
|
439
|
-
throw new Error(`Invalid IM configuration: ${file}. Repair this file before setup; it will not be overwritten.`);
|
|
440
|
-
}
|
|
441
|
-
function resolveConfig(cwd, dir) {
|
|
442
|
-
try {
|
|
443
|
-
let present = false;
|
|
444
|
-
let merged = {};
|
|
445
|
-
const providers = {};
|
|
446
|
-
for (const file of configPaths(cwd, dir)) {
|
|
447
|
-
const layer = readLayer(file);
|
|
448
|
-
if (Object.keys(layer).length) present = true;
|
|
449
|
-
const legacy = ["chatId", "receiveId", "openId", "larkCli", "allowUsers", "groupAccess"].some((key2) => key2 in layer);
|
|
450
|
-
if (legacy && !layer.provider) {
|
|
451
|
-
const previous = providers.feishu ?? {};
|
|
452
|
-
providers.feishu = { ...previous, ...Object.fromEntries(["chatId", "openId", "larkCli", "allowUsers", "groupAccess"].filter((key2) => key2 in layer).map((key2) => [key2, layer[key2]])), ...layer.receiveId && !layer.chatId ? { chatId: layer.receiveId } : {} };
|
|
453
|
-
merged.provider = "feishu";
|
|
454
|
-
}
|
|
455
|
-
if (isRecord(layer.providers)) {
|
|
456
|
-
for (const [id, settings] of Object.entries(layer.providers)) if (isRecord(settings)) providers[id] = { ...providers[id], ...settings };
|
|
457
|
-
}
|
|
458
|
-
merged = { ...merged, ...layer };
|
|
459
|
-
}
|
|
460
|
-
if (!present) return { config: null, problems: [] };
|
|
461
|
-
if ("provider" in merged && (typeof merged.provider !== "string" || !merged.provider.trim())) throw new Error("Invalid IM provider field. Run setup or repair the configuration; no provider fallback was used.");
|
|
462
|
-
const provider = typeof merged.provider === "string" ? merged.provider : "feishu";
|
|
463
|
-
const retry = merged.retryBackoffMs;
|
|
464
|
-
return { config: { enabled: merged.enabled === true, provider, settings: providers[provider] ?? {}, retryBackoffMs: typeof retry === "number" && Number.isFinite(retry) ? Math.min(6e4, Math.max(20, Math.round(retry))) : void 0 }, problems: [] };
|
|
465
|
-
} catch (error) {
|
|
466
|
-
return { config: null, problems: [error.message] };
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
function configurationIdentity(config) {
|
|
470
|
-
return JSON.stringify([config.provider, config.settings, config.retryBackoffMs]);
|
|
471
|
-
}
|
|
472
|
-
function configSnapshot(cwd, dir) {
|
|
473
|
-
return JSON.stringify(configPaths(cwd, dir).map((file) => {
|
|
474
|
-
try {
|
|
475
|
-
return fs.readFileSync(file, "utf8");
|
|
476
|
-
} catch (error) {
|
|
477
|
-
if (error.code === "ENOENT") return null;
|
|
478
|
-
throw new Error(`Cannot read IM configuration: ${file}`);
|
|
479
|
-
}
|
|
480
|
-
}));
|
|
481
|
-
}
|
|
482
|
-
function saveLocation(cwd, dir) {
|
|
483
|
-
const files = configPaths(cwd, dir);
|
|
484
|
-
return fs.existsSync(files[files.length - 1]) ? files[files.length - 1] : files[0];
|
|
485
|
-
}
|
|
486
|
-
function writeConfig(cwd, dir, update, expected) {
|
|
487
|
-
for (const file of configPaths(cwd, dir)) readLayer(file);
|
|
488
|
-
if (expected !== void 0 && configSnapshot(cwd, dir) !== expected) throw new Error("IM configuration changed during setup. Please retry.");
|
|
489
|
-
const target = saveLocation(cwd, dir);
|
|
490
|
-
const value = readLayer(target);
|
|
491
|
-
value.enabled = update.enabled;
|
|
492
|
-
if (update.provider) {
|
|
493
|
-
value.provider = update.provider;
|
|
494
|
-
value.providers = { ...isRecord(value.providers) ? value.providers : {}, [update.provider]: update.settings ?? {} };
|
|
495
|
-
}
|
|
496
|
-
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
497
|
-
invalidateConfigCache();
|
|
498
|
-
const temporary = path.join(path.dirname(target), `.im-forward-${randomUUID()}.tmp`);
|
|
499
|
-
try {
|
|
500
|
-
const fd = fs.openSync(temporary, "wx", 384);
|
|
501
|
-
try {
|
|
502
|
-
fs.writeFileSync(fd, JSON.stringify(value, null, " ") + "\n");
|
|
503
|
-
fs.fsyncSync(fd);
|
|
504
|
-
} finally {
|
|
505
|
-
fs.closeSync(fd);
|
|
506
|
-
}
|
|
507
|
-
fs.renameSync(temporary, target);
|
|
508
|
-
} finally {
|
|
509
|
-
try {
|
|
510
|
-
fs.unlinkSync(temporary);
|
|
511
|
-
} catch {
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
function hasConfigLayers(cwd, dir) {
|
|
516
|
-
return configPaths(cwd, dir).some((file) => fs.existsSync(file));
|
|
517
|
-
}
|
|
518
|
-
async function clearImConfig(cwd, dir, confirm) {
|
|
519
|
-
const files = configPaths(cwd, dir).filter((file) => fs.existsSync(file));
|
|
520
|
-
if (!files.length) return false;
|
|
521
|
-
for (const file of files) readLayer(file);
|
|
522
|
-
const snapshot = configSnapshot(cwd, dir);
|
|
523
|
-
if (!await confirm(`Delete the IM forwarding configuration file(s)?
|
|
524
|
-
|
|
525
|
-
${files.join("\n")}
|
|
526
|
-
|
|
527
|
-
Forwarding stops immediately and this cannot be undone.`)) return false;
|
|
528
|
-
if (configSnapshot(cwd, dir) !== snapshot) throw new Error("IM configuration changed during clear. Please retry.");
|
|
529
|
-
for (const file of files) {
|
|
530
|
-
try {
|
|
531
|
-
fs.unlinkSync(file);
|
|
532
|
-
} catch (error) {
|
|
533
|
-
if (error.code !== "ENOENT") throw error;
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
invalidateConfigCache();
|
|
537
|
-
return true;
|
|
538
|
-
}
|
|
539
|
-
function readLiveEnabled(cwd, dir, _cache) {
|
|
540
|
-
return cachedResolveConfig(cwd, dir).config?.enabled === true;
|
|
541
|
-
}
|
|
542
|
-
function readLiveConfig(cwd, dir) {
|
|
543
|
-
try {
|
|
544
|
-
return cachedResolveConfig(cwd, dir);
|
|
545
|
-
} catch {
|
|
546
|
-
return resolveConfig(cwd, dir);
|
|
547
|
-
}
|
|
548
|
-
}
|
|
549
|
-
function resolveImForwardConfig(cwd, dir) {
|
|
550
|
-
const result = resolveConfig(cwd, dir);
|
|
551
|
-
const cfg = result.config;
|
|
552
|
-
if (!cfg) return { config: null, problems: result.problems };
|
|
553
|
-
if (cfg.provider !== "feishu") return { config: null, problems: [`Unsupported IM provider: ${cfg.provider}`] };
|
|
554
|
-
const raw = cfg.settings;
|
|
555
|
-
const chatId = typeof raw.chatId === "string" ? raw.chatId.trim() : "";
|
|
556
|
-
if (!chatId) return { config: null, problems: cfg.enabled ? ["im-forward: enabled requires chatId"] : [] };
|
|
557
|
-
const allowUsers = Array.isArray(raw.allowUsers) ? raw.allowUsers.filter((id) => typeof id === "string" && !!id.trim()) : void 0;
|
|
558
|
-
return { config: { enabled: cfg.enabled, chatId, allowUsers: allowUsers?.length ? allowUsers : void 0, larkCli: typeof raw.larkCli === "string" && raw.larkCli.trim() ? raw.larkCli.trim() : void 0, retryBackoffMs: cfg.retryBackoffMs }, problems: chatId.startsWith("oc_") ? [] : ["im-forward: chatId does not look like a chat id (oc_...)"] };
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
// builtin/extensions/pie-ipc/runtime-registry.ts
|
|
562
|
-
var runtimes = /* @__PURE__ */ new Map();
|
|
563
|
-
function key(root) {
|
|
564
|
-
return root.replace(/[\\/]+$/, "");
|
|
565
|
-
}
|
|
566
|
-
function registerIpcRuntime(root, runtime) {
|
|
567
|
-
const k = key(root);
|
|
568
|
-
runtimes.set(k, runtime);
|
|
569
|
-
return () => {
|
|
570
|
-
if (runtimes.get(k) === runtime) runtimes.delete(k);
|
|
571
|
-
};
|
|
572
|
-
}
|
|
573
|
-
function currentIpcRuntime(root) {
|
|
574
|
-
return runtimes.get(key(root));
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
// builtin/extensions/pie-ipc/pure.ts
|
|
578
|
-
import { randomBytes } from "node:crypto";
|
|
579
|
-
var IPC_PROTOCOL_VERSION = 2;
|
|
580
|
-
var INSTANCE_ID_PATTERN = /^pie-[a-z0-9]{12}$/;
|
|
581
|
-
var MAX_STATUS_FILE_BYTES = 128 * 1024;
|
|
582
|
-
var MAX_DISPLAY_NAME_CHARS = 64;
|
|
583
|
-
var MAX_STATUS_TEXT_FIELD_CHARS = 4096;
|
|
584
|
-
var MAX_BODY_CHARS = 8e3;
|
|
585
|
-
var STATUS_FILE_STALE_MS = 12e4;
|
|
586
|
-
var HEARTBEAT_INTERVAL_MS = 2e4;
|
|
587
|
-
var DEFAULT_SEND_WAIT_MS = 12e4;
|
|
588
|
-
var MAX_SEEN_ENVELOPE_IDS = 1e3;
|
|
589
|
-
var MAX_INBOX_MESSAGES = 100;
|
|
590
|
-
var MAX_INFLIGHT_SENDS = 8;
|
|
591
|
-
var INSTANCE_ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
592
|
-
function generateInstanceId(randomSource = defaultRandomBytes) {
|
|
593
|
-
const bytes = randomSource(12);
|
|
594
|
-
let id = "";
|
|
595
|
-
for (const byte of bytes) {
|
|
596
|
-
id += INSTANCE_ID_ALPHABET[byte % INSTANCE_ID_ALPHABET.length];
|
|
597
|
-
}
|
|
598
|
-
return `pie-${id}`;
|
|
599
|
-
}
|
|
600
|
-
function defaultRandomBytes(count) {
|
|
601
|
-
return randomBytes(count);
|
|
602
|
-
}
|
|
603
|
-
function isValidInstanceId(id) {
|
|
604
|
-
return INSTANCE_ID_PATTERN.test(id);
|
|
605
|
-
}
|
|
606
|
-
function peerLabel(instanceId, displayName) {
|
|
607
|
-
const name = displayName?.trim();
|
|
608
|
-
if (name) return name;
|
|
609
|
-
return instanceId.length > 12 ? instanceId.slice(0, 12) : instanceId;
|
|
610
|
-
}
|
|
611
|
-
var ENVELOPE_KINDS = /* @__PURE__ */ new Set([
|
|
612
|
-
"message",
|
|
613
|
-
"ack",
|
|
614
|
-
"result",
|
|
615
|
-
"state.get",
|
|
616
|
-
"state",
|
|
617
|
-
"result.get",
|
|
618
|
-
"control"
|
|
619
|
-
]);
|
|
620
|
-
var LIFECYCLE_STATES = /* @__PURE__ */ new Set(["working", "idle", "blocked"]);
|
|
621
|
-
function parseEnvelope(raw) {
|
|
622
|
-
let parsed;
|
|
623
|
-
try {
|
|
624
|
-
parsed = JSON.parse(raw);
|
|
625
|
-
} catch {
|
|
626
|
-
return null;
|
|
627
|
-
}
|
|
628
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
|
|
629
|
-
const record = parsed;
|
|
630
|
-
if (typeof record.v !== "number" || record.v !== IPC_PROTOCOL_VERSION) return null;
|
|
631
|
-
if (typeof record.id !== "string" || !/^[a-zA-Z0-9:-]{1,128}$/.test(record.id)) return null;
|
|
632
|
-
if (typeof record.from !== "string" || !isValidInstanceId(record.from)) return null;
|
|
633
|
-
if (typeof record.to !== "string" || !isValidInstanceId(record.to)) return null;
|
|
634
|
-
if (record.text !== void 0 && (typeof record.text !== "string" || record.text.length > MAX_BODY_CHARS + 100)) return null;
|
|
635
|
-
if (record.sessionId !== void 0 && (typeof record.sessionId !== "string" || record.sessionId.length > 256)) return null;
|
|
636
|
-
if (record.replyTo !== void 0 && (typeof record.replyTo !== "string" || !/^[a-zA-Z0-9:-]{1,128}$/.test(record.replyTo))) return null;
|
|
637
|
-
if (record.waitMs !== void 0 && (typeof record.waitMs !== "number" || !Number.isFinite(record.waitMs) || record.waitMs < 0 || record.waitMs > 6e5)) return null;
|
|
638
|
-
if (record.notifyCompletion !== void 0 && typeof record.notifyCompletion !== "boolean") return null;
|
|
639
|
-
if (record.subscriberSession !== void 0 && (typeof record.subscriberSession !== "string" || record.subscriberSession.length > 256)) return null;
|
|
640
|
-
if (typeof record.kind !== "string" || !ENVELOPE_KINDS.has(record.kind)) return null;
|
|
641
|
-
if (typeof record.createdAt !== "number" || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0) return null;
|
|
642
|
-
const envelope = {
|
|
643
|
-
v: record.v,
|
|
644
|
-
id: record.id,
|
|
645
|
-
from: record.from,
|
|
646
|
-
to: record.to,
|
|
647
|
-
kind: record.kind,
|
|
648
|
-
createdAt: record.createdAt
|
|
649
|
-
};
|
|
650
|
-
if (typeof record.auth === "string" && /^[a-f0-9]{64}$/.test(record.auth)) envelope.auth = record.auth;
|
|
651
|
-
if (typeof record.sessionId === "string") envelope.sessionId = record.sessionId;
|
|
652
|
-
if (typeof record.text === "string") envelope.text = record.text;
|
|
653
|
-
if (typeof record.replyTo === "string") envelope.replyTo = record.replyTo;
|
|
654
|
-
if (typeof record.waitMs === "number" && Number.isFinite(record.waitMs)) envelope.waitMs = record.waitMs;
|
|
655
|
-
if (record.notifyCompletion === true) envelope.notifyCompletion = true;
|
|
656
|
-
if (record.control === true) envelope.control = true;
|
|
657
|
-
if (record.userAssigned === true) envelope.userAssigned = true;
|
|
658
|
-
if (typeof record.subscriberSession === "string") envelope.subscriberSession = record.subscriberSession;
|
|
659
|
-
return envelope;
|
|
660
|
-
}
|
|
661
|
-
var FrameTooLargeError = class extends Error {
|
|
662
|
-
constructor() {
|
|
663
|
-
super("pie-ipc frame exceeds byte cap");
|
|
664
|
-
this.name = "FrameTooLargeError";
|
|
665
|
-
}
|
|
666
|
-
};
|
|
667
|
-
var FrameDecoder = class {
|
|
668
|
-
buffer = "";
|
|
669
|
-
get partial() {
|
|
670
|
-
return this.buffer.length > 0;
|
|
671
|
-
}
|
|
672
|
-
push(chunk) {
|
|
673
|
-
this.buffer += chunk;
|
|
674
|
-
if (this.buffer.split("\n").some((line) => Buffer.byteLength(line, "utf8") > 64 * 1024)) {
|
|
675
|
-
this.buffer = "";
|
|
676
|
-
throw new FrameTooLargeError();
|
|
677
|
-
}
|
|
678
|
-
const envelopes = [];
|
|
679
|
-
let newline = this.buffer.indexOf("\n");
|
|
680
|
-
while (newline !== -1) {
|
|
681
|
-
const line = this.buffer.slice(0, newline).trim();
|
|
682
|
-
this.buffer = this.buffer.slice(newline + 1);
|
|
683
|
-
if (line) {
|
|
684
|
-
const envelope = parseEnvelope(line);
|
|
685
|
-
if (envelope) envelopes.push(envelope);
|
|
686
|
-
}
|
|
687
|
-
newline = this.buffer.indexOf("\n");
|
|
688
|
-
}
|
|
689
|
-
return envelopes;
|
|
690
|
-
}
|
|
691
|
-
};
|
|
692
|
-
var WRAP_PREFIX = "[pie-ipc]";
|
|
693
|
-
function wrapInboundText(fromLabel, text, at = Date.now(), messageId) {
|
|
694
|
-
const stamp = new Date(at).toISOString().slice(11, 19);
|
|
695
|
-
const marker = messageId ? ` #${clipMarker(messageId)} ` : " ";
|
|
696
|
-
return `${WRAP_PREFIX} ${stamp}${marker}peer "${clipLabel(fromLabel)}" says:
|
|
697
|
-
${clipBody(text, MAX_BODY_CHARS)}`;
|
|
698
|
-
}
|
|
699
|
-
function isWrappedInboundText(text) {
|
|
700
|
-
return text.startsWith(`${WRAP_PREFIX} `);
|
|
701
|
-
}
|
|
702
|
-
function wrappedMessageMarker(text) {
|
|
703
|
-
if (!isWrappedInboundText(text)) return null;
|
|
704
|
-
const firstLine = text.split("\n", 1)[0];
|
|
705
|
-
const match = / #(\S+) peer "/.exec(firstLine);
|
|
706
|
-
return match ? match[1] : null;
|
|
707
|
-
}
|
|
708
|
-
function clipMarker(id) {
|
|
709
|
-
const clipped = id;
|
|
710
|
-
return clipped || "noid";
|
|
711
|
-
}
|
|
712
|
-
function clipLabel(label) {
|
|
713
|
-
const collapsed = label.replace(/\s+/g, " ").trim().slice(0, 60);
|
|
714
|
-
return collapsed || "unknown";
|
|
715
|
-
}
|
|
716
|
-
function clipBody(text, maxChars = MAX_BODY_CHARS) {
|
|
717
|
-
if (text.length <= maxChars) return text;
|
|
718
|
-
return `${text.slice(0, maxChars)}\u2026[truncated ${text.length - maxChars} chars]`;
|
|
719
|
-
}
|
|
720
|
-
var BoundedIdSet = class {
|
|
721
|
-
constructor(max = MAX_SEEN_ENVELOPE_IDS) {
|
|
722
|
-
this.max = max;
|
|
723
|
-
}
|
|
724
|
-
max;
|
|
725
|
-
seen = /* @__PURE__ */ new Map();
|
|
726
|
-
/** Returns true when the id is new (and records it). */
|
|
727
|
-
add(id, now = Date.now()) {
|
|
728
|
-
if (this.seen.has(id)) return false;
|
|
729
|
-
this.seen.set(id, now);
|
|
730
|
-
if (this.seen.size > this.max) {
|
|
731
|
-
const drop = Math.max(1, Math.floor(this.max / 4));
|
|
732
|
-
let dropped = 0;
|
|
733
|
-
for (const key2 of this.seen.keys()) {
|
|
734
|
-
if (dropped >= drop) break;
|
|
735
|
-
this.seen.delete(key2);
|
|
736
|
-
dropped += 1;
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
return true;
|
|
740
|
-
}
|
|
741
|
-
has(id) {
|
|
742
|
-
return this.seen.has(id);
|
|
743
|
-
}
|
|
744
|
-
get size() {
|
|
745
|
-
return this.seen.size;
|
|
746
|
-
}
|
|
747
|
-
};
|
|
748
|
-
var signalAliveCheck = (pid) => {
|
|
749
|
-
try {
|
|
750
|
-
process.kill(pid, 0);
|
|
751
|
-
return true;
|
|
752
|
-
} catch (error) {
|
|
753
|
-
return error.code === "EPERM";
|
|
754
|
-
}
|
|
755
|
-
};
|
|
756
|
-
function peerHealth(file, now = Date.now(), aliveCheck = signalAliveCheck) {
|
|
757
|
-
if (Number.isInteger(file.pid) && file.pid > 0 && !aliveCheck(file.pid)) return "dead";
|
|
758
|
-
if (now - file.updatedAt > STATUS_FILE_STALE_MS) return "stale";
|
|
759
|
-
return "alive";
|
|
760
|
-
}
|
|
761
|
-
function parseStatusFile(raw) {
|
|
762
|
-
let parsed;
|
|
763
|
-
try {
|
|
764
|
-
parsed = JSON.parse(raw);
|
|
765
|
-
} catch {
|
|
766
|
-
return null;
|
|
767
|
-
}
|
|
768
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
|
|
769
|
-
const record = parsed;
|
|
770
|
-
if (record.schema !== 1) return null;
|
|
771
|
-
if (typeof record.instanceId !== "string" || !isValidInstanceId(record.instanceId)) return null;
|
|
772
|
-
if (typeof record.pid !== "number" || !Number.isInteger(record.pid) || record.pid <= 0 || record.pid > 99999999) return null;
|
|
773
|
-
if (typeof record.protocol !== "number" || record.protocol !== IPC_PROTOCOL_VERSION) return null;
|
|
774
|
-
if (typeof record.displayName !== "string" || !record.displayName || record.displayName.length > MAX_DISPLAY_NAME_CHARS) return null;
|
|
775
|
-
if (hasControlChars(record.displayName)) return null;
|
|
776
|
-
if (record.sessionId !== null && (typeof record.sessionId !== "string" || record.sessionId.length > 256 || hasControlChars(record.sessionId))) return null;
|
|
777
|
-
if (typeof record.cwd !== "string" || record.cwd.length > MAX_STATUS_TEXT_FIELD_CHARS || hasControlChars(record.cwd)) return null;
|
|
778
|
-
if (typeof record.startedAt !== "number" || !Number.isSafeInteger(record.startedAt) || record.startedAt < 0) return null;
|
|
779
|
-
if (typeof record.updatedAt !== "number" || !Number.isSafeInteger(record.updatedAt) || record.updatedAt < 0) return null;
|
|
780
|
-
if (typeof record.state !== "string" || !LIFECYCLE_STATES.has(record.state)) return null;
|
|
781
|
-
const file = {
|
|
782
|
-
schema: 1,
|
|
783
|
-
instanceId: record.instanceId,
|
|
784
|
-
pid: record.pid,
|
|
785
|
-
protocol: record.protocol,
|
|
786
|
-
displayName: record.displayName,
|
|
787
|
-
sessionId: record.sessionId,
|
|
788
|
-
cwd: record.cwd,
|
|
789
|
-
startedAt: record.startedAt,
|
|
790
|
-
updatedAt: record.updatedAt,
|
|
791
|
-
state: record.state
|
|
792
|
-
};
|
|
793
|
-
if (typeof record.unattended === "boolean") file.unattended = record.unattended;
|
|
794
|
-
if (typeof record.isManager === "boolean") file.isManager = record.isManager;
|
|
795
|
-
if (typeof record.sessionControls === "boolean") file.sessionControls = record.sessionControls;
|
|
796
|
-
if (typeof record.workerPeek === "boolean") file.workerPeek = record.workerPeek;
|
|
797
|
-
if (typeof record.version === "string" && record.version.length <= 64 && !hasControlChars(record.version)) file.version = record.version;
|
|
798
|
-
if (typeof record.imBinding === "string" && record.imBinding.length <= 512 && !hasControlChars(record.imBinding)) file.imBinding = record.imBinding;
|
|
799
|
-
if (Array.isArray(record.allowPeers) && record.allowPeers.length <= 1e3 && record.allowPeers.every((id) => typeof id === "string" && (id === "*" || isValidInstanceId(id)))) file.allowPeers = record.allowPeers;
|
|
800
|
-
if (typeof record.secret === "string" && /^[a-f0-9]{64}$/.test(record.secret)) file.secret = record.secret;
|
|
801
|
-
if (typeof record.sessionName === "string" && !hasControlChars(record.sessionName) && record.sessionName.length <= MAX_DISPLAY_NAME_CHARS) file.sessionName = record.sessionName;
|
|
802
|
-
if (typeof record.currentTool === "string" && !hasControlChars(record.currentTool) && record.currentTool.length <= 200) file.currentTool = record.currentTool;
|
|
803
|
-
if (typeof record.blockedSince === "number" && Number.isSafeInteger(record.blockedSince) && record.blockedSince >= 0) file.blockedSince = record.blockedSince;
|
|
804
|
-
if (typeof record.turnStartedAt === "number" && Number.isSafeInteger(record.turnStartedAt) && record.turnStartedAt >= 0) file.turnStartedAt = record.turnStartedAt;
|
|
805
|
-
if (typeof record.undeliveredInjections === "number" && Number.isFinite(record.undeliveredInjections)) file.undeliveredInjections = Math.min(100, Math.max(0, Math.floor(record.undeliveredInjections)));
|
|
806
|
-
if (typeof record.port === "number" && Number.isInteger(record.port) && record.port > 0 && record.port <= 65535) file.port = record.port;
|
|
807
|
-
return file;
|
|
808
|
-
}
|
|
809
|
-
function hasControlChars(text) {
|
|
810
|
-
return /[\u0000-\u001f\u007f]/.test(text);
|
|
811
|
-
}
|
|
812
|
-
var BLOCKING_TOOL_NAMES = /* @__PURE__ */ new Set(["ask_user_multi"]);
|
|
813
|
-
function isBlockingTool(toolName) {
|
|
814
|
-
return BLOCKING_TOOL_NAMES.has(toolName);
|
|
815
|
-
}
|
|
816
|
-
function foldLifecycleEvent(current, event, now = Date.now()) {
|
|
817
|
-
switch (event.type) {
|
|
818
|
-
case "turn:start":
|
|
819
|
-
case "agent:start": {
|
|
820
|
-
const next = { state: "working", turnStartedAt: now };
|
|
821
|
-
if (current.blockedSince !== void 0) next.blockedSince = current.blockedSince;
|
|
822
|
-
return next;
|
|
823
|
-
}
|
|
824
|
-
case "tool:execution:start": {
|
|
825
|
-
if (current.state === "idle") return { ...current, state: "working", turnStartedAt: current.turnStartedAt ?? now };
|
|
826
|
-
if (event.toolName && isBlockingTool(event.toolName) && current.state !== "blocked") {
|
|
827
|
-
return { ...current, state: "blocked", blockedSince: now, currentTool: event.toolName };
|
|
828
|
-
}
|
|
829
|
-
return { ...current, currentTool: event.toolName };
|
|
830
|
-
}
|
|
831
|
-
case "tool:execution:end": {
|
|
832
|
-
if (current.state === "blocked" && (!event.toolName || isBlockingTool(event.toolName))) {
|
|
833
|
-
return { ...current, state: "working", blockedSince: void 0, currentTool: void 0 };
|
|
834
|
-
}
|
|
835
|
-
return current;
|
|
836
|
-
}
|
|
837
|
-
case "turn:completed":
|
|
838
|
-
case "turn:failed":
|
|
839
|
-
case "turn:cancelled":
|
|
840
|
-
case "agent:end": {
|
|
841
|
-
if (current.state === "idle") return current;
|
|
842
|
-
return { state: "idle" };
|
|
843
|
-
}
|
|
844
|
-
default:
|
|
845
|
-
return current;
|
|
846
|
-
}
|
|
847
|
-
}
|
|
848
|
-
function resolveIpcConfig(configLayers) {
|
|
849
|
-
const problems = [];
|
|
850
|
-
let invalidConfig = false;
|
|
851
|
-
const merged = {};
|
|
852
|
-
for (const layer of configLayers) {
|
|
853
|
-
if (layer.content === void 0) continue;
|
|
854
|
-
try {
|
|
855
|
-
const parsed = JSON.parse(layer.content);
|
|
856
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
857
|
-
problems.push(`${layer.file}: root is not an object`);
|
|
858
|
-
invalidConfig = true;
|
|
859
|
-
continue;
|
|
860
|
-
}
|
|
861
|
-
Object.assign(merged, parsed);
|
|
862
|
-
} catch (error) {
|
|
863
|
-
problems.push(`${layer.file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
864
|
-
invalidConfig = true;
|
|
865
|
-
}
|
|
866
|
-
}
|
|
867
|
-
if (merged.enabled !== void 0 && typeof merged.enabled !== "boolean") {
|
|
868
|
-
problems.push("pie-ipc: enabled must be a boolean");
|
|
869
|
-
invalidConfig = true;
|
|
870
|
-
}
|
|
871
|
-
if (invalidConfig || merged.enabled === false) return { config: null, problems };
|
|
872
|
-
const config = { enabled: true, allowPeers: ["*"], autoInject: true };
|
|
873
|
-
if (typeof merged.displayName === "string" && merged.displayName.trim()) {
|
|
874
|
-
config.displayName = merged.displayName.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 60);
|
|
875
|
-
}
|
|
876
|
-
const envName = process.env.PIE_IPC_DISPLAY_NAME;
|
|
877
|
-
if (typeof envName === "string" && envName.trim()) {
|
|
878
|
-
config.displayName = envName.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 60);
|
|
879
|
-
}
|
|
880
|
-
if (Array.isArray(merged.allowPeers)) {
|
|
881
|
-
config.allowPeers = merged.allowPeers.filter((id) => typeof id === "string" && (id === "*" || isValidInstanceId(id))).slice(0, 1e3);
|
|
882
|
-
} else if (merged.allowPeers !== void 0) {
|
|
883
|
-
config.allowPeers = [];
|
|
884
|
-
problems.push("pie-ipc: allowPeers must be an array");
|
|
885
|
-
}
|
|
886
|
-
if (merged.autoInject !== void 0) config.autoInject = merged.autoInject === true;
|
|
887
|
-
if (typeof merged.maxBodyChars === "number" && Number.isFinite(merged.maxBodyChars)) {
|
|
888
|
-
const bounded = Math.min(Math.max(Math.floor(merged.maxBodyChars), 100), MAX_BODY_CHARS);
|
|
889
|
-
if (bounded !== merged.maxBodyChars) {
|
|
890
|
-
problems.push(`pie-ipc: maxBodyChars clamped to ${bounded}`);
|
|
891
|
-
}
|
|
892
|
-
config.maxBodyChars = bounded;
|
|
893
|
-
}
|
|
894
|
-
return { config, problems };
|
|
895
|
-
}
|
|
896
|
-
function assistantBodyText(message) {
|
|
897
|
-
if (message?.role !== "assistant" || !Array.isArray(message.content)) return "";
|
|
898
|
-
let text = "";
|
|
899
|
-
let hasToolCalls = false;
|
|
900
|
-
for (const block of message.content) {
|
|
901
|
-
if (typeof block !== "object" || block === null) continue;
|
|
902
|
-
const record = block;
|
|
903
|
-
if (record.type === "text" && typeof record.text === "string") text += record.text;
|
|
904
|
-
else if (record.type === "toolCall") hasToolCalls = true;
|
|
905
|
-
}
|
|
906
|
-
if (hasToolCalls) return "";
|
|
907
|
-
return text.trim();
|
|
908
|
-
}
|
|
909
|
-
|
|
910
|
-
// builtin/extensions/pie-ipc/transport.ts
|
|
911
|
-
import * as net from "node:net";
|
|
912
|
-
import { createHmac, randomBytes as randomBytes2, randomUUID as randomUUID2, timingSafeEqual } from "node:crypto";
|
|
913
|
-
import { StringDecoder } from "node:string_decoder";
|
|
914
|
-
var CLOSE_FLUSH_TIMEOUT_MS = 1e3;
|
|
915
|
-
function signEnvelope(e, secret) {
|
|
916
|
-
const payload = [e.v, e.id, e.from, e.to, e.kind, e.createdAt, e.sessionId ?? null, e.text ?? null, e.replyTo ?? null, e.waitMs ?? null, e.notifyCompletion ?? null, e.control ?? null, e.userAssigned ?? null, e.subscriberSession ?? null];
|
|
917
|
-
return { ...e, auth: createHmac("sha256", secret).update(JSON.stringify(payload)).digest("hex") };
|
|
918
|
-
}
|
|
919
|
-
function verified(e, secret) {
|
|
920
|
-
if (!e.auth || !/^[a-f0-9]{64}$/.test(e.auth)) return false;
|
|
921
|
-
return timingSafeEqual(Buffer.from(e.auth, "hex"), Buffer.from(signEnvelope(e, secret).auth, "hex"));
|
|
922
|
-
}
|
|
923
|
-
var IpcTransport = class {
|
|
924
|
-
constructor(host) {
|
|
925
|
-
this.host = host;
|
|
926
|
-
this.instanceId = host.instanceId;
|
|
927
|
-
this.secret = host.secret ?? randomBytes2(32).toString("hex");
|
|
928
|
-
this.server = net.createServer((socket) => this.accept(socket));
|
|
929
|
-
this.server.on("error", () => {
|
|
930
|
-
});
|
|
931
|
-
this.server.unref();
|
|
932
|
-
}
|
|
933
|
-
host;
|
|
934
|
-
instanceId;
|
|
935
|
-
secret;
|
|
936
|
-
server;
|
|
937
|
-
sockets = /* @__PURE__ */ new Set();
|
|
938
|
-
cancels = /* @__PURE__ */ new Set();
|
|
939
|
-
seen = new BoundedIdSet();
|
|
940
|
-
closed = false;
|
|
941
|
-
inflight = 0;
|
|
942
|
-
inbound = 0;
|
|
943
|
-
rateWindow = Date.now();
|
|
944
|
-
rateCount = 0;
|
|
945
|
-
port = null;
|
|
946
|
-
get listenPort() {
|
|
947
|
-
return this.port;
|
|
948
|
-
}
|
|
949
|
-
listen() {
|
|
950
|
-
if (this.closed) return Promise.reject(new Error("closed"));
|
|
951
|
-
return new Promise((resolve2, reject) => {
|
|
952
|
-
const cancel = () => {
|
|
953
|
-
this.cancels.delete(cancel);
|
|
954
|
-
reject(new Error("closed"));
|
|
955
|
-
};
|
|
956
|
-
this.cancels.add(cancel);
|
|
957
|
-
const error = (e) => {
|
|
958
|
-
this.cancels.delete(cancel);
|
|
959
|
-
reject(e);
|
|
960
|
-
};
|
|
961
|
-
this.server.once("error", error);
|
|
962
|
-
this.server.listen(0, "127.0.0.1", () => {
|
|
963
|
-
this.server.off("error", error);
|
|
964
|
-
this.cancels.delete(cancel);
|
|
965
|
-
if (this.closed) {
|
|
966
|
-
this.server.close();
|
|
967
|
-
reject(new Error("closed"));
|
|
968
|
-
return;
|
|
969
|
-
}
|
|
970
|
-
const address = this.server.address();
|
|
971
|
-
if (!address || typeof address === "string") {
|
|
972
|
-
reject(new Error("closed"));
|
|
973
|
-
return;
|
|
974
|
-
}
|
|
975
|
-
this.port = address.port;
|
|
976
|
-
resolve2(address.port);
|
|
977
|
-
});
|
|
978
|
-
});
|
|
979
|
-
}
|
|
980
|
-
write(socket, envelope, secret) {
|
|
981
|
-
if (socket.destroyed) return false;
|
|
982
|
-
const data = JSON.stringify(signEnvelope(envelope, secret)) + "\n";
|
|
983
|
-
if (socket.writableLength + Buffer.byteLength(data) > 512 * 1024) {
|
|
984
|
-
socket.destroy();
|
|
985
|
-
return false;
|
|
986
|
-
}
|
|
987
|
-
try {
|
|
988
|
-
socket.write(data);
|
|
989
|
-
return true;
|
|
990
|
-
} catch {
|
|
991
|
-
socket.destroy();
|
|
992
|
-
return false;
|
|
993
|
-
}
|
|
994
|
-
}
|
|
995
|
-
read(socket, receive, idleMs) {
|
|
996
|
-
const decoder = new FrameDecoder();
|
|
997
|
-
const utf8 = new StringDecoder("utf8");
|
|
998
|
-
let frameTimer;
|
|
999
|
-
let frames = 0;
|
|
1000
|
-
socket.setTimeout(idleMs, () => socket.destroy());
|
|
1001
|
-
socket.on("error", () => socket.destroy());
|
|
1002
|
-
socket.on("close", () => {
|
|
1003
|
-
if (frameTimer) clearTimeout(frameTimer);
|
|
1004
|
-
this.sockets.delete(socket);
|
|
1005
|
-
});
|
|
1006
|
-
socket.on("data", (chunk) => {
|
|
1007
|
-
try {
|
|
1008
|
-
frames += chunk.reduce((n, b) => n + (b === 10 ? 1 : 0), 0);
|
|
1009
|
-
if (frames > 128) {
|
|
1010
|
-
socket.destroy();
|
|
1011
|
-
return;
|
|
1012
|
-
}
|
|
1013
|
-
const envelopes = decoder.push(utf8.write(chunk));
|
|
1014
|
-
const partial = decoder.partial || chunk.at(-1) !== 10;
|
|
1015
|
-
if (frameTimer && (!partial || chunk.includes(10))) {
|
|
1016
|
-
clearTimeout(frameTimer);
|
|
1017
|
-
frameTimer = void 0;
|
|
1018
|
-
}
|
|
1019
|
-
if (partial && !frameTimer) {
|
|
1020
|
-
frameTimer = setTimeout(() => socket.destroy(), 15e3);
|
|
1021
|
-
frameTimer.unref();
|
|
1022
|
-
}
|
|
1023
|
-
for (const e of envelopes) {
|
|
1024
|
-
if (socket.destroyed) break;
|
|
1025
|
-
receive(e);
|
|
1026
|
-
}
|
|
1027
|
-
} catch {
|
|
1028
|
-
socket.destroy();
|
|
1029
|
-
}
|
|
1030
|
-
});
|
|
1031
|
-
}
|
|
1032
|
-
accept(socket) {
|
|
1033
|
-
if (this.closed || this.inbound >= 16) {
|
|
1034
|
-
socket.destroy();
|
|
1035
|
-
return;
|
|
1036
|
-
}
|
|
1037
|
-
this.inbound++;
|
|
1038
|
-
this.sockets.add(socket);
|
|
1039
|
-
socket.setNoDelay(true);
|
|
1040
|
-
socket.once("close", () => {
|
|
1041
|
-
this.inbound--;
|
|
1042
|
-
});
|
|
1043
|
-
const lifecycle = new AbortController();
|
|
1044
|
-
socket.once("close", () => lifecycle.abort());
|
|
1045
|
-
let sender;
|
|
1046
|
-
this.read(socket, (e) => {
|
|
1047
|
-
if (e.to !== this.instanceId || !verified(e, this.secret) || sender && sender !== e.from) {
|
|
1048
|
-
socket.destroy();
|
|
1049
|
-
return;
|
|
1050
|
-
}
|
|
1051
|
-
sender = e.from;
|
|
1052
|
-
if (Date.now() - this.rateWindow >= 1e3) {
|
|
1053
|
-
this.rateWindow = Date.now();
|
|
1054
|
-
this.rateCount = 0;
|
|
1055
|
-
}
|
|
1056
|
-
if (++this.rateCount > 128) {
|
|
1057
|
-
socket.destroy();
|
|
1058
|
-
return;
|
|
1059
|
-
}
|
|
1060
|
-
if (e.waitMs) socket.setTimeout(Math.max(6e4, e.waitMs + 1e3));
|
|
1061
|
-
if (!this.seen.add(`${e.from}:${e.id}`)) return;
|
|
1062
|
-
try {
|
|
1063
|
-
if (this.closed) return;
|
|
1064
|
-
void Promise.resolve(this.host.onEnvelope(e, (reply) => {
|
|
1065
|
-
if (reply.from === this.instanceId && reply.to === e.from && reply.replyTo === e.id) this.write(socket, reply, this.secret);
|
|
1066
|
-
}, lifecycle.signal)).catch(() => socket.destroy());
|
|
1067
|
-
} catch {
|
|
1068
|
-
socket.destroy();
|
|
1069
|
-
}
|
|
1070
|
-
}, 6e4);
|
|
1071
|
-
}
|
|
1072
|
-
/** Synchronous CAPACITY probe (review r3): transport.send is async, so a
|
|
1073
|
-
* capacity rejection still yields a truthy Promise resolving null — callers
|
|
1074
|
-
* distinguishing 'never left the process' from 'sent, outcome unknown' must
|
|
1075
|
-
* check this BEFORE awaiting send. Scope: closed/inflight ONLY (capacity &
|
|
1076
|
-
* lifecycle), NOT send()'s full validation (signal/secret/port/waitMs can
|
|
1077
|
-
* still null-reject after a true probe — those are peer/discovery outcomes,
|
|
1078
|
-
* covered by the best-effort contract). */
|
|
1079
|
-
canSendNow() {
|
|
1080
|
-
return !this.closed && this.inflight < MAX_INFLIGHT_SENDS;
|
|
1081
|
-
}
|
|
1082
|
-
async send(peerInstanceId, port, kind, options = {}) {
|
|
1083
|
-
if (this.closed || options.signal?.aborted || this.inflight >= MAX_INFLIGHT_SENDS) return null;
|
|
1084
|
-
let secret;
|
|
1085
|
-
try {
|
|
1086
|
-
secret = this.host.resolveSecret?.(peerInstanceId);
|
|
1087
|
-
} catch {
|
|
1088
|
-
return null;
|
|
1089
|
-
}
|
|
1090
|
-
if (!secret || !/^[a-f0-9]{64}$/.test(secret) || !Number.isInteger(port) || port < 1 || port > 65535) return null;
|
|
1091
|
-
const waitMs = options.waitMs ?? DEFAULT_SEND_WAIT_MS;
|
|
1092
|
-
if (!Number.isFinite(waitMs) || waitMs < 0 || waitMs > 6e5) return null;
|
|
1093
|
-
const holdOpen = options.expectReply === true || options.awaitAck === true;
|
|
1094
|
-
this.inflight++;
|
|
1095
|
-
return new Promise((resolve2) => {
|
|
1096
|
-
const socket = new net.Socket();
|
|
1097
|
-
this.sockets.add(socket);
|
|
1098
|
-
const envelope = { v: IPC_PROTOCOL_VERSION, id: options.requestId ?? randomUUID2(), from: this.instanceId, to: peerInstanceId, kind, createdAt: Date.now(), ...options.text !== void 0 ? { text: clipBody(options.text) } : {}, ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}, ...options.replyTo ? { replyTo: options.replyTo } : {}, waitMs: options.expectReply ? waitMs : 0, ...options.notifyCompletion === true ? { notifyCompletion: true } : {}, ...options.subscriberSession !== void 0 ? { subscriberSession: options.subscriberSession } : {}, ...options.userAssigned === true ? { userAssigned: true } : {} };
|
|
1099
|
-
let done = false;
|
|
1100
|
-
const finish = (value) => {
|
|
1101
|
-
if (done) return;
|
|
1102
|
-
done = true;
|
|
1103
|
-
clearTimeout(timer);
|
|
1104
|
-
clearTimeout(dialTimer);
|
|
1105
|
-
options.signal?.removeEventListener("abort", abort);
|
|
1106
|
-
this.cancels.delete(abort);
|
|
1107
|
-
this.inflight--;
|
|
1108
|
-
socket.destroy();
|
|
1109
|
-
resolve2(value);
|
|
1110
|
-
};
|
|
1111
|
-
const abort = () => finish(null);
|
|
1112
|
-
const timer = setTimeout(abort, holdOpen ? waitMs : 3e3);
|
|
1113
|
-
const dialTimer = setTimeout(abort, 3e3);
|
|
1114
|
-
this.cancels.add(abort);
|
|
1115
|
-
options.signal?.addEventListener("abort", abort, { once: true });
|
|
1116
|
-
socket.once("close", abort);
|
|
1117
|
-
this.read(socket, (e) => {
|
|
1118
|
-
if (e.to !== this.instanceId || e.from !== peerInstanceId || e.replyTo !== envelope.id || !verified(e, secret)) {
|
|
1119
|
-
finish(null);
|
|
1120
|
-
return;
|
|
1121
|
-
}
|
|
1122
|
-
if ((options.replyKinds ?? /* @__PURE__ */ new Set(["result", "ack", "state"])).has(e.kind)) finish(e);
|
|
1123
|
-
}, Math.max(waitMs, 3e3));
|
|
1124
|
-
socket.once("connect", () => {
|
|
1125
|
-
clearTimeout(dialTimer);
|
|
1126
|
-
if (done || options.signal?.aborted || this.closed) {
|
|
1127
|
-
finish(null);
|
|
1128
|
-
return;
|
|
1129
|
-
}
|
|
1130
|
-
if (!this.write(socket, envelope, secret)) {
|
|
1131
|
-
finish(null);
|
|
1132
|
-
return;
|
|
1133
|
-
}
|
|
1134
|
-
if (!holdOpen) {
|
|
1135
|
-
socket.end(() => finish(envelope));
|
|
1136
|
-
}
|
|
1137
|
-
});
|
|
1138
|
-
try {
|
|
1139
|
-
socket.connect(port, "127.0.0.1");
|
|
1140
|
-
} catch {
|
|
1141
|
-
finish(null);
|
|
1142
|
-
}
|
|
1143
|
-
});
|
|
1144
|
-
}
|
|
1145
|
-
close() {
|
|
1146
|
-
if (this.closed) return;
|
|
1147
|
-
this.closed = true;
|
|
1148
|
-
for (const cancel of [...this.cancels]) cancel();
|
|
1149
|
-
for (const socket of this.sockets) {
|
|
1150
|
-
if (socket.destroyed) continue;
|
|
1151
|
-
socket.end();
|
|
1152
|
-
const timer = setTimeout(() => socket.destroy(), CLOSE_FLUSH_TIMEOUT_MS);
|
|
1153
|
-
timer.unref();
|
|
1154
|
-
}
|
|
1155
|
-
this.sockets.clear();
|
|
1156
|
-
this.server.close();
|
|
1157
|
-
this.port = null;
|
|
1158
|
-
}
|
|
1159
|
-
};
|
|
1160
|
-
|
|
1161
|
-
// builtin/extensions/im-forward/event-hub.ts
|
|
1162
|
-
import * as path3 from "node:path";
|
|
1163
|
-
|
|
1164
|
-
// builtin/extensions/im-forward/address-book.ts
|
|
1165
|
-
import * as fs2 from "node:fs";
|
|
1166
|
-
import * as os2 from "node:os";
|
|
1167
|
-
import * as path2 from "node:path";
|
|
1168
|
-
var MAX_ADDRESS_HEAD = 64;
|
|
1169
|
-
function addressBookRoot() {
|
|
1170
|
-
const raw = process.env.PIE_IPC_CONFIG_DIR;
|
|
1171
|
-
if (raw !== void 0) {
|
|
1172
|
-
if (raw.length > 0) {
|
|
1173
|
-
const expanded = raw === "~" ? os2.homedir() : raw.startsWith("~/") ? path2.join(os2.homedir(), raw.slice(2)) : raw;
|
|
1174
|
-
return path2.resolve(expanded);
|
|
1175
|
-
}
|
|
1176
|
-
return path2.resolve("");
|
|
1177
|
-
}
|
|
1178
|
-
return path2.resolve(resolveConfigDir());
|
|
1179
|
-
}
|
|
1180
|
-
function pidAlive(pid) {
|
|
1181
|
-
if (!Number.isInteger(pid) || pid <= 0) return true;
|
|
1182
|
-
try {
|
|
1183
|
-
process.kill(pid, 0);
|
|
1184
|
-
return true;
|
|
1185
|
-
} catch (error) {
|
|
1186
|
-
return error.code === "EPERM";
|
|
1187
|
-
}
|
|
1188
|
-
}
|
|
1189
|
-
function scanAddressBook() {
|
|
1190
|
-
const names = /* @__PURE__ */ new Map();
|
|
1191
|
-
let complete = true;
|
|
1192
|
-
let selfPublished;
|
|
1193
|
-
let dirExists = false;
|
|
1194
|
-
const dir = path2.join(addressBookRoot(), "run", "ipc");
|
|
1195
|
-
let entries;
|
|
1196
|
-
try {
|
|
1197
|
-
entries = fs2.readdirSync(dir);
|
|
1198
|
-
dirExists = true;
|
|
1199
|
-
} catch (error) {
|
|
1200
|
-
if (error.code === "ENOENT") return { names, complete: true, dirExists: false };
|
|
1201
|
-
return { names, complete: false, dirExists: true };
|
|
1202
|
-
}
|
|
1203
|
-
for (const [index, file] of entries.entries()) {
|
|
1204
|
-
if (!file.endsWith(".json")) continue;
|
|
1205
|
-
try {
|
|
1206
|
-
const status = JSON.parse(fs2.readFileSync(path2.join(dir, file), "utf8"));
|
|
1207
|
-
dirExists = true;
|
|
1208
|
-
const name = typeof status.sessionName === "string" ? status.sessionName.trim() : "";
|
|
1209
|
-
const pid = typeof status.pid === "number" ? status.pid : void 0;
|
|
1210
|
-
if (!name) continue;
|
|
1211
|
-
if (pid === process.pid) {
|
|
1212
|
-
selfPublished = name;
|
|
1213
|
-
continue;
|
|
1214
|
-
}
|
|
1215
|
-
if (pid !== void 0 && !pidAlive(pid)) continue;
|
|
1216
|
-
const owners = names.get(name) ?? /* @__PURE__ */ new Set();
|
|
1217
|
-
owners.add(pid ?? -(index + 1));
|
|
1218
|
-
names.set(name, owners);
|
|
1219
|
-
} catch {
|
|
1220
|
-
complete = false;
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
return { names, selfPublished, complete, dirExists };
|
|
1224
|
-
}
|
|
1225
|
-
var SEPARATORS = [":", "\uFF1A"];
|
|
1226
|
-
function matchAddressName(text, candidates) {
|
|
1227
|
-
const trimmed = text.trimStart();
|
|
1228
|
-
let best;
|
|
1229
|
-
for (const name of candidates) {
|
|
1230
|
-
const value = name?.trim();
|
|
1231
|
-
if (!value) continue;
|
|
1232
|
-
if (!SEPARATORS.some((sep) => trimmed.startsWith(`${value}${sep}`))) continue;
|
|
1233
|
-
if (!best || value.length > best.length) best = value;
|
|
1234
|
-
}
|
|
1235
|
-
return best;
|
|
1236
|
-
}
|
|
1237
|
-
function resolveAddress(text, ownLiveName, book) {
|
|
1238
|
-
if (!/[::]/.test(text)) return { kind: "none" };
|
|
1239
|
-
const resolvedBook = book ?? scanAddressBook();
|
|
1240
|
-
const candidates = new Set(resolvedBook.names.keys());
|
|
1241
|
-
if (resolvedBook.selfPublished) candidates.add(resolvedBook.selfPublished);
|
|
1242
|
-
const live = ownLiveName?.trim();
|
|
1243
|
-
if (live) candidates.add(live);
|
|
1244
|
-
const name = matchAddressName(text, candidates);
|
|
1245
|
-
if (!name) {
|
|
1246
|
-
if (!resolvedBook.complete) {
|
|
1247
|
-
return { kind: "ambiguous", name: text.trim().slice(0, MAX_ADDRESS_HEAD), reason: "address book unreadable" };
|
|
1248
|
-
}
|
|
1249
|
-
return { kind: "none" };
|
|
1250
|
-
}
|
|
1251
|
-
const body = text.trimStart().slice(name.length + 1).trim();
|
|
1252
|
-
if (!resolvedBook.complete) return { kind: "ambiguous", name, reason: "address book unreadable" };
|
|
1253
|
-
const foreignOwners = resolvedBook.names.get(name);
|
|
1254
|
-
if (foreignOwners && foreignOwners.size > 0) {
|
|
1255
|
-
if (foreignOwners.size > 1) return { kind: "ambiguous", name, reason: "duplicate live session name" };
|
|
1256
|
-
if (resolvedBook.selfPublished === name || live === name) return { kind: "ambiguous", name, reason: "duplicate live session name" };
|
|
1257
|
-
return { kind: "other", name };
|
|
1258
|
-
}
|
|
1259
|
-
if (!resolvedBook.complete) return { kind: "ambiguous", name, reason: "address book unreadable" };
|
|
1260
|
-
const acceptName = resolvedBook.selfPublished ?? (resolvedBook.dirExists ? void 0 : live);
|
|
1261
|
-
if (!acceptName) return { kind: "ambiguous", name, reason: "own advertisement not published" };
|
|
1262
|
-
if (name === acceptName) return { kind: "self", body };
|
|
1263
|
-
return { kind: "ambiguous", name, reason: "unpublished address" };
|
|
1264
|
-
}
|
|
1265
|
-
|
|
1266
|
-
// builtin/extensions/im-forward/event-hub.ts
|
|
1267
|
-
var DISPATCH_PREFIX = "[im-forward-dispatch]";
|
|
1268
|
-
var dispatchReceiver;
|
|
1269
|
-
var imBinding;
|
|
1270
|
-
var bindingListeners = /* @__PURE__ */ new Set();
|
|
1271
|
-
function bindingChanged() {
|
|
1272
|
-
for (const fn of bindingListeners) {
|
|
1273
|
-
try {
|
|
1274
|
-
fn();
|
|
1275
|
-
} catch {
|
|
1276
|
-
}
|
|
1277
|
-
}
|
|
1278
|
-
}
|
|
1279
|
-
function onImBindingChanged(fn) {
|
|
1280
|
-
bindingListeners.add(fn);
|
|
1281
|
-
return () => {
|
|
1282
|
-
bindingListeners.delete(fn);
|
|
1283
|
-
};
|
|
1284
|
-
}
|
|
1285
|
-
function registerImBinding(value) {
|
|
1286
|
-
const token = Symbol(value);
|
|
1287
|
-
imBinding = { value, token };
|
|
1288
|
-
bindingChanged();
|
|
1289
|
-
return () => {
|
|
1290
|
-
if (imBinding?.token === token) {
|
|
1291
|
-
imBinding = void 0;
|
|
1292
|
-
bindingChanged();
|
|
1293
|
-
}
|
|
1294
|
-
};
|
|
1295
|
-
}
|
|
1296
|
-
function currentImBinding() {
|
|
1297
|
-
return imBinding?.value;
|
|
1298
|
-
}
|
|
1299
|
-
var turnImDriverOracle;
|
|
1300
|
-
function registerTurnImDriver(oracle) {
|
|
1301
|
-
turnImDriverOracle = oracle;
|
|
1302
|
-
}
|
|
1303
|
-
function isTurnUserImDriven() {
|
|
1304
|
-
try {
|
|
1305
|
-
return turnImDriverOracle?.() === true;
|
|
1306
|
-
} catch {
|
|
1307
|
-
return false;
|
|
1308
|
-
}
|
|
1309
|
-
}
|
|
1310
|
-
function registerDispatchReceiver(receiver) {
|
|
1311
|
-
dispatchReceiver = receiver;
|
|
1312
|
-
}
|
|
1313
|
-
function takeDispatchFrame(text) {
|
|
1314
|
-
if (!dispatchReceiver) return false;
|
|
1315
|
-
try {
|
|
1316
|
-
return dispatchReceiver(text);
|
|
1317
|
-
} catch {
|
|
1318
|
-
return true;
|
|
1319
|
-
}
|
|
1320
|
-
}
|
|
1321
|
-
function hubDir() {
|
|
1322
|
-
return path3.join(addressBookRoot(), "im-forward");
|
|
1323
|
-
}
|
|
1324
|
-
function lockPath(binding) {
|
|
1325
|
-
const safe = binding.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
1326
|
-
return path3.join(hubDir(), `consumer-${safe}.lock`);
|
|
1327
|
-
}
|
|
1328
|
-
function readLock(binding) {
|
|
1329
|
-
return readOwnership(lockPath(binding), (v) => v.binding === binding);
|
|
1330
|
-
}
|
|
1331
|
-
function lockAlive(info, _now = Date.now()) {
|
|
1332
|
-
return !!info && !pidDefinitelyDead(info.pid);
|
|
1333
|
-
}
|
|
1334
|
-
function tryClaimConsumer(binding, holder, onLost, shouldYield) {
|
|
1335
|
-
try {
|
|
1336
|
-
const result = claimOwnership(
|
|
1337
|
-
lockPath(binding),
|
|
1338
|
-
{ pid: process.pid, holder, heartbeatAt: Date.now(), binding },
|
|
1339
|
-
(v) => v.binding === binding
|
|
1340
|
-
);
|
|
1341
|
-
if ("holder" in result) return void 0;
|
|
1342
|
-
let stopped = false;
|
|
1343
|
-
let retiring = false;
|
|
1344
|
-
const release = () => {
|
|
1345
|
-
if (retiring) return;
|
|
1346
|
-
stopped = true;
|
|
1347
|
-
clearInterval(timer);
|
|
1348
|
-
try {
|
|
1349
|
-
result.handle.release();
|
|
1350
|
-
} catch {
|
|
1351
|
-
}
|
|
1352
|
-
};
|
|
1353
|
-
const retire = () => {
|
|
1354
|
-
stopped = true;
|
|
1355
|
-
retiring = true;
|
|
1356
|
-
clearInterval(timer);
|
|
1357
|
-
if (!onLost) return;
|
|
1358
|
-
void Promise.resolve().then(onLost).then(() => {
|
|
1359
|
-
retiring = false;
|
|
1360
|
-
release();
|
|
1361
|
-
}).catch(() => {
|
|
1362
|
-
});
|
|
1363
|
-
};
|
|
1364
|
-
const heartbeat = () => {
|
|
1365
|
-
if (stopped) return;
|
|
1366
|
-
try {
|
|
1367
|
-
if (shouldYield?.() === true || !result.handle.heartbeat()) retire();
|
|
1368
|
-
} catch {
|
|
1369
|
-
retire();
|
|
1370
|
-
}
|
|
1371
|
-
};
|
|
1372
|
-
const timer = setInterval(heartbeat, 5e3);
|
|
1373
|
-
timer.unref();
|
|
1374
|
-
return { heartbeat, release };
|
|
1375
|
-
} catch {
|
|
1376
|
-
return void 0;
|
|
1377
|
-
}
|
|
1378
|
-
}
|
|
1379
|
-
function currentConsumer(binding) {
|
|
1380
|
-
try {
|
|
1381
|
-
const info = readLock(binding);
|
|
1382
|
-
return { info, alive: lockAlive(info) };
|
|
1383
|
-
} catch {
|
|
1384
|
-
return { info: void 0, alive: true };
|
|
1385
|
-
}
|
|
1386
|
-
}
|
|
1387
|
-
|
|
1388
|
-
export {
|
|
1389
|
-
isRecord,
|
|
1390
|
-
assistantForwardText,
|
|
1391
|
-
sessionLabel,
|
|
1392
|
-
inputHeaderLine,
|
|
1393
|
-
composeForwardBody,
|
|
1394
|
-
estimatePostRequestBytes,
|
|
1395
|
-
truncateMarkdown,
|
|
1396
|
-
chunkKey,
|
|
1397
|
-
chunkMarkdown,
|
|
1398
|
-
collectFileReferences,
|
|
1399
|
-
failureReason,
|
|
1400
|
-
resolveConfigDir,
|
|
1401
|
-
resolveConfig,
|
|
1402
|
-
configurationIdentity,
|
|
1403
|
-
configSnapshot,
|
|
1404
|
-
saveLocation,
|
|
1405
|
-
writeConfig,
|
|
1406
|
-
hasConfigLayers,
|
|
1407
|
-
clearImConfig,
|
|
1408
|
-
readLiveEnabled,
|
|
1409
|
-
readLiveConfig,
|
|
1410
|
-
resolveImForwardConfig,
|
|
1411
|
-
addressBookRoot,
|
|
1412
|
-
resolveAddress,
|
|
1413
|
-
registerIpcRuntime,
|
|
1414
|
-
currentIpcRuntime,
|
|
1415
|
-
IPC_PROTOCOL_VERSION,
|
|
1416
|
-
MAX_STATUS_FILE_BYTES,
|
|
1417
|
-
MAX_BODY_CHARS,
|
|
1418
|
-
HEARTBEAT_INTERVAL_MS,
|
|
1419
|
-
DEFAULT_SEND_WAIT_MS,
|
|
1420
|
-
MAX_INBOX_MESSAGES,
|
|
1421
|
-
generateInstanceId,
|
|
1422
|
-
isValidInstanceId,
|
|
1423
|
-
peerLabel,
|
|
1424
|
-
wrapInboundText,
|
|
1425
|
-
isWrappedInboundText,
|
|
1426
|
-
wrappedMessageMarker,
|
|
1427
|
-
clipBody,
|
|
1428
|
-
peerHealth,
|
|
1429
|
-
parseStatusFile,
|
|
1430
|
-
foldLifecycleEvent,
|
|
1431
|
-
resolveIpcConfig,
|
|
1432
|
-
assistantBodyText,
|
|
1433
|
-
IpcTransport,
|
|
1434
|
-
DISPATCH_PREFIX,
|
|
1435
|
-
onImBindingChanged,
|
|
1436
|
-
registerImBinding,
|
|
1437
|
-
currentImBinding,
|
|
1438
|
-
registerTurnImDriver,
|
|
1439
|
-
isTurnUserImDriven,
|
|
1440
|
-
registerDispatchReceiver,
|
|
1441
|
-
takeDispatchFrame,
|
|
1442
|
-
tryClaimConsumer,
|
|
1443
|
-
currentConsumer
|
|
1444
|
-
};
|