@cydm/pie 4.3.2 → 4.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builtin/extensions/im-forward/index.js +171 -759
- package/dist/builtin/extensions/pie-ipc/index.js +27 -4
- package/dist/chunks/chunk-HT6J4QOC.js +1054 -0
- package/dist/chunks/{concierge-cli-CQMIAGWJ.js → concierge-cli-MCHXTFBA.js} +11 -4
- package/dist/cli.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/chunk-GJLSYBFN.js +0 -359
|
@@ -1,7 +1,32 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
DISPATCH_PREFIX,
|
|
4
|
+
IPC_PROTOCOL_VERSION,
|
|
5
|
+
assistantForwardText,
|
|
6
|
+
chunkKey,
|
|
7
|
+
chunkMarkdown,
|
|
8
|
+
clearImConfig,
|
|
9
|
+
collectFileReferences,
|
|
10
|
+
composeForwardBody,
|
|
11
|
+
configSnapshot,
|
|
12
|
+
configurationIdentity,
|
|
13
|
+
estimatePostRequestBytes,
|
|
14
|
+
failureReason,
|
|
15
|
+
hasConfigLayers,
|
|
16
|
+
inputHeaderLine,
|
|
17
|
+
isRecord,
|
|
18
|
+
readLiveConfig,
|
|
19
|
+
readLiveEnabled,
|
|
20
|
+
registerDispatchReceiver,
|
|
21
|
+
resolveConfig,
|
|
22
|
+
resolveConfigDir,
|
|
23
|
+
resolveImForwardConfig,
|
|
24
|
+
saveLocation,
|
|
25
|
+
sessionLabel,
|
|
26
|
+
truncateMarkdown,
|
|
27
|
+
tryClaimConsumer,
|
|
28
|
+
writeConfig
|
|
29
|
+
} from "../../../chunks/chunk-HT6J4QOC.js";
|
|
5
30
|
import {
|
|
6
31
|
detectImageMime,
|
|
7
32
|
readImageFormat
|
|
@@ -11,569 +36,21 @@ import {
|
|
|
11
36
|
} from "../../../chunks/chunk-XXGYUYXI.js";
|
|
12
37
|
import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
13
38
|
|
|
14
|
-
// builtin/extensions/im-forward/config.ts
|
|
15
|
-
import * as fs from "node:fs";
|
|
16
|
-
import * as path from "node:path";
|
|
17
|
-
import * as os from "node:os";
|
|
18
|
-
import { randomUUID } from "node:crypto";
|
|
19
|
-
|
|
20
|
-
// builtin/extensions/im-forward/helpers.ts
|
|
21
|
-
import * as nodeCrypto from "node:crypto";
|
|
22
|
-
var MAX_INPUT_HEADER_CHARS = 200;
|
|
23
|
-
function isRecord(value) {
|
|
24
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
25
|
-
}
|
|
26
|
-
function assistantForwardText(message) {
|
|
27
|
-
if (message?.role !== "assistant" || !Array.isArray(message.content)) return "";
|
|
28
|
-
let text = "";
|
|
29
|
-
let hasToolCalls = false;
|
|
30
|
-
for (const block of message.content) {
|
|
31
|
-
if (!isRecord(block)) continue;
|
|
32
|
-
if (block.type === "text" && typeof block.text === "string") text += block.text;
|
|
33
|
-
else if (block.type === "toolCall") hasToolCalls = true;
|
|
34
|
-
}
|
|
35
|
-
if (hasToolCalls) return "";
|
|
36
|
-
return text.trim();
|
|
37
|
-
}
|
|
38
|
-
function sessionLabel(sessionId, sessionName) {
|
|
39
|
-
if (sessionName && sessionName.trim()) return sessionName.trim();
|
|
40
|
-
return sessionId.length > 8 ? sessionId.slice(0, 8) : sessionId;
|
|
41
|
-
}
|
|
42
|
-
function escapeMarkdownInline(text) {
|
|
43
|
-
return text.replace(/\\/g, "\\\\").replace(/`/g, "\\`");
|
|
44
|
-
}
|
|
45
|
-
function inputHeaderLine(userInput) {
|
|
46
|
-
if (!userInput) return null;
|
|
47
|
-
const collapsed = userInput.replace(/\s+/g, " ").trim();
|
|
48
|
-
if (!collapsed) return null;
|
|
49
|
-
let escaped = escapeMarkdownInline(collapsed);
|
|
50
|
-
if (escaped.length > MAX_INPUT_HEADER_CHARS) {
|
|
51
|
-
let clipped = stripDanglingHighSurrogate(escaped.slice(0, MAX_INPUT_HEADER_CHARS));
|
|
52
|
-
if (/(?:^|[^\\])(?:\\\\)*\\$/.test(clipped)) clipped = clipped.slice(0, -1);
|
|
53
|
-
escaped = clipped + "\u2026";
|
|
54
|
-
}
|
|
55
|
-
return `> [UserInput] ${escaped}`;
|
|
56
|
-
}
|
|
57
|
-
function composeForwardBody(sessionId, sessionName, userInput, text) {
|
|
58
|
-
const lines = [`**[Pie] \xB7 ${sessionLabel(sessionId, sessionName)}**`];
|
|
59
|
-
const input = inputHeaderLine(userInput);
|
|
60
|
-
if (input) lines.push(input);
|
|
61
|
-
lines.push("");
|
|
62
|
-
lines.push(text);
|
|
63
|
-
return lines.join("\n");
|
|
64
|
-
}
|
|
65
|
-
var FEISHU_POST_REQUEST_LIMIT_BYTES = 3e4;
|
|
66
|
-
var MAX_BODY_BYTES = FEISHU_POST_REQUEST_LIMIT_BYTES - 6e3;
|
|
67
|
-
var MAX_BODY_UTF16_CHARS = 3e4;
|
|
68
|
-
var POST_PARAGRAPH_OVERHEAD_BYTES = 150;
|
|
69
|
-
var POST_LINE_OVERHEAD_BYTES = 12;
|
|
70
|
-
var POST_ENVELOPE_OVERHEAD_BYTES = 256;
|
|
71
|
-
var textEncoder = new TextEncoder();
|
|
72
|
-
function utf8Bytes(text) {
|
|
73
|
-
return textEncoder.encode(text).length;
|
|
74
|
-
}
|
|
75
|
-
function utf16LengthBudget(text, maxChars) {
|
|
76
|
-
if (text.length <= maxChars) return text;
|
|
77
|
-
return stripDanglingHighSurrogate(text.slice(0, maxChars));
|
|
78
|
-
}
|
|
79
|
-
function stripDanglingHighSurrogate(text) {
|
|
80
|
-
return /[\uD800-\uDBFF]$/.test(text) ? text.slice(0, -1) : text;
|
|
81
|
-
}
|
|
82
|
-
function estimatePostRequestBytes(markdown) {
|
|
83
|
-
const escaped = utf8Bytes(JSON.stringify(markdown).slice(1, -1));
|
|
84
|
-
const paragraphs = markdown.split(/\n{2,}/).filter((part) => part.trim().length > 0).length;
|
|
85
|
-
const lines = markdown.length === 0 ? 0 : markdown.split("\n").length;
|
|
86
|
-
return escaped + paragraphs * POST_PARAGRAPH_OVERHEAD_BYTES + lines * POST_LINE_OVERHEAD_BYTES + POST_ENVELOPE_OVERHEAD_BYTES;
|
|
87
|
-
}
|
|
88
|
-
function truncateMarkdown(text, maxBytes = MAX_BODY_BYTES) {
|
|
89
|
-
const bounded = utf16LengthBudget(text, MAX_BODY_UTF16_CHARS);
|
|
90
|
-
const charCapped = bounded !== text;
|
|
91
|
-
if (!charCapped && estimatePostRequestBytes(text) <= maxBytes) return text;
|
|
92
|
-
const suffix = "\n\n\u2026(truncated)";
|
|
93
|
-
const suffixCost = estimatePostRequestBytes(suffix) - POST_ENVELOPE_OVERHEAD_BYTES;
|
|
94
|
-
const budget = charCapped ? Math.min(maxBytes - suffixCost, bounded.length - suffix.length) : maxBytes - suffixCost;
|
|
95
|
-
const snapForward = (candidate) => {
|
|
96
|
-
const newline = candidate.lastIndexOf("\n");
|
|
97
|
-
if (newline < Math.floor(candidate.length * 0.85)) return candidate;
|
|
98
|
-
const snapped = candidate.slice(0, newline);
|
|
99
|
-
return snapped.trim().length > 0 ? snapped : candidate;
|
|
100
|
-
};
|
|
101
|
-
const fit = (limit) => {
|
|
102
|
-
let lo = 0;
|
|
103
|
-
let hi = text.length;
|
|
104
|
-
while (lo < hi) {
|
|
105
|
-
const mid = Math.ceil((lo + hi) / 2);
|
|
106
|
-
if (estimatePostRequestBytes(text.slice(0, mid)) <= limit) lo = mid;
|
|
107
|
-
else hi = mid - 1;
|
|
108
|
-
}
|
|
109
|
-
return text.slice(0, lo);
|
|
110
|
-
};
|
|
111
|
-
let cut = snapForward(stripDanglingHighSurrogate(fit(Math.max(0, budget))));
|
|
112
|
-
if ((cut.match(/```/g)?.length ?? 0) % 2 === 1) {
|
|
113
|
-
const closeCost = estimatePostRequestBytes("\n```") - POST_ENVELOPE_OVERHEAD_BYTES;
|
|
114
|
-
const refit = snapForward(stripDanglingHighSurrogate(fit(Math.max(0, budget - closeCost))));
|
|
115
|
-
cut = (refit.match(/```/g)?.length ?? 0) % 2 === 1 ? refit + "\n```" : refit;
|
|
116
|
-
}
|
|
117
|
-
return cut + suffix;
|
|
118
|
-
}
|
|
119
|
-
function scanFenceLines(text) {
|
|
120
|
-
const lines = text.split("\n");
|
|
121
|
-
const stateAtLineStart = [];
|
|
122
|
-
const stateAtLineEnd = [];
|
|
123
|
-
const openedBy = [];
|
|
124
|
-
const closedBy = [];
|
|
125
|
-
let open = null;
|
|
126
|
-
let listIndent = 0;
|
|
127
|
-
const expandLeadingTabs = (value) => {
|
|
128
|
-
const match = /^([ \t]+)/.exec(value);
|
|
129
|
-
if (!match || !match[1].includes(" ")) return value;
|
|
130
|
-
let column = 0;
|
|
131
|
-
for (const ch of match[1]) column = ch === " " ? Math.ceil((column + 1) / 4) * 4 : column + 1;
|
|
132
|
-
return " ".repeat(column) + value.slice(match[0].length);
|
|
133
|
-
};
|
|
134
|
-
for (let i = 0; i < lines.length; i++) {
|
|
135
|
-
const source = lines[i].replace(/^(?: {0,3}> ?)+/, "");
|
|
136
|
-
let line = expandLeadingTabs(source);
|
|
137
|
-
const marker = !open && /^( {0,3})(?:[-*+]|\d{1,9}[.)])(?:\t| {1,4})(?=\S)/.exec(line);
|
|
138
|
-
if (marker) {
|
|
139
|
-
listIndent = marker[0].length;
|
|
140
|
-
line = line.slice(listIndent);
|
|
141
|
-
} else if (listIndent && line.startsWith(" ".repeat(listIndent))) {
|
|
142
|
-
line = line.slice(listIndent);
|
|
143
|
-
} else if (line.trim() && !open) {
|
|
144
|
-
listIndent = 0;
|
|
145
|
-
}
|
|
146
|
-
stateAtLineStart.push(open);
|
|
147
|
-
let opened = null;
|
|
148
|
-
let closed = null;
|
|
149
|
-
if (!open) {
|
|
150
|
-
const m = /^( {0,3})(`{3,}|~{3,})(.*)$/.exec(line);
|
|
151
|
-
if (m && (m[2][0] === "~" || !m[3].includes("`"))) {
|
|
152
|
-
open = { delimiter: m[2], info: m[3].trim() };
|
|
153
|
-
opened = open;
|
|
154
|
-
}
|
|
155
|
-
} else {
|
|
156
|
-
const m = /^( {0,3})(`+|~+)[ \t]*$/.exec(line);
|
|
157
|
-
if (m && m[2][0] === open.delimiter[0] && m[2].length >= open.delimiter.length) {
|
|
158
|
-
closed = open;
|
|
159
|
-
open = null;
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
const dedentColumns = expandLeadingTabs(source).length - line.length;
|
|
163
|
-
const rawDedent = (raw, columns) => {
|
|
164
|
-
if (columns <= 0) return raw;
|
|
165
|
-
if (!raw.includes(" ")) return raw.slice(columns);
|
|
166
|
-
let column = 0, index = 0;
|
|
167
|
-
while (index < raw.length && column < columns) {
|
|
168
|
-
const ch = raw[index];
|
|
169
|
-
const next = ch === " " ? Math.ceil((column + 1) / 4) * 4 : column + 1;
|
|
170
|
-
if (ch === " " && next > columns) break;
|
|
171
|
-
column = next;
|
|
172
|
-
index++;
|
|
173
|
-
}
|
|
174
|
-
return raw.slice(index);
|
|
175
|
-
};
|
|
176
|
-
lines[i] = stateAtLineStart[i] || opened ? rawDedent(source, dedentColumns) : source;
|
|
177
|
-
openedBy.push(opened);
|
|
178
|
-
closedBy.push(closed);
|
|
179
|
-
stateAtLineEnd.push(open);
|
|
180
|
-
}
|
|
181
|
-
return { stateAtLineStart, stateAtLineEnd, openedBy, closedBy, lines };
|
|
182
|
-
}
|
|
183
|
-
function chunkKey(base, index, tag = "part", digest = sha256Digest19) {
|
|
184
|
-
if (index === 0 && tag === "part" && base.length <= 50) return base;
|
|
185
|
-
const candidate = `${base}-${tag}${index + 1}`;
|
|
186
|
-
if (candidate.length <= 50) return candidate;
|
|
187
|
-
return `${base.slice(0, 30)}-${digest(`${tag}:${index}:${base}`)}`.slice(0, 50);
|
|
188
|
-
}
|
|
189
|
-
var sha256Digest19 = (input) => nodeCrypto.createHash("sha256").update(input).digest("hex").slice(0, 19);
|
|
190
|
-
function chunkMarkdown(text, maxBytes = MAX_BODY_BYTES) {
|
|
191
|
-
const MIN_FEASIBLE_BUDGET = 320;
|
|
192
|
-
if (maxBytes < MIN_FEASIBLE_BUDGET) return [[text], false];
|
|
193
|
-
if (utf16LengthBudget(text, MAX_BODY_UTF16_CHARS) === text && estimatePostRequestBytes(text) <= maxBytes) {
|
|
194
|
-
return [[text], false];
|
|
195
|
-
}
|
|
196
|
-
const scan = scanFenceLines(text);
|
|
197
|
-
const lines = scan.lines.slice();
|
|
198
|
-
const fits = (candidate) => candidate.length <= MAX_BODY_UTF16_CHARS && estimatePostRequestBytes(candidate) <= maxBytes;
|
|
199
|
-
const MAX_SYNTHETIC_INFO_CHARS = 32;
|
|
200
|
-
const closeMarker = (f) => f.delimiter;
|
|
201
|
-
const midLineCloseMarker = (f) => "\n" + f.delimiter;
|
|
202
|
-
const reopenMarker = (f) => f.delimiter + (f.info.length > MAX_SYNTHETIC_INFO_CHARS ? f.info.slice(0, MAX_SYNTHETIC_INFO_CHARS) : f.info) + "\n";
|
|
203
|
-
const chunks = [];
|
|
204
|
-
let lineIndex = 0;
|
|
205
|
-
let pendingPrefix = "";
|
|
206
|
-
while (lineIndex < lines.length) {
|
|
207
|
-
if (lines[lineIndex] === "" && lineIndex === lines.length - 1) {
|
|
208
|
-
lineIndex++;
|
|
209
|
-
continue;
|
|
210
|
-
}
|
|
211
|
-
const assemble = (endLine) => {
|
|
212
|
-
const separator = endLine < lines.length - 1 ? "\n" : "";
|
|
213
|
-
const body = pendingPrefix + lines.slice(lineIndex, endLine + 1).join("\n") + separator;
|
|
214
|
-
const fence = scan.stateAtLineEnd[endLine] ?? null;
|
|
215
|
-
const chunk = body + (fence ? body.endsWith("\n") || body === "" ? fence.delimiter : "\n" + fence.delimiter : "");
|
|
216
|
-
return fits(chunk) ? { chunk, fence, endLine } : null;
|
|
217
|
-
};
|
|
218
|
-
let lo = lineIndex, hi = lines.length - 1;
|
|
219
|
-
let best = null;
|
|
220
|
-
while (lo <= hi) {
|
|
221
|
-
const mid = lo + Math.ceil((hi - lo) / 2);
|
|
222
|
-
const built = assemble(mid);
|
|
223
|
-
if (built) {
|
|
224
|
-
best = built;
|
|
225
|
-
lo = mid + 1;
|
|
226
|
-
} else hi = mid - 1;
|
|
227
|
-
}
|
|
228
|
-
if (best) {
|
|
229
|
-
for (let j = best.endLine - 1; j > lineIndex + Math.floor((best.endLine - lineIndex) / 2); j--) {
|
|
230
|
-
if (lines[j + 1] === "" && scan.stateAtLineEnd[j] === null && !scan.openedBy[j]) {
|
|
231
|
-
const snapped = assemble(j);
|
|
232
|
-
if (snapped) best = snapped;
|
|
233
|
-
break;
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
chunks.push(best.chunk);
|
|
237
|
-
lineIndex = best.endLine + 1;
|
|
238
|
-
pendingPrefix = best.fence ? reopenMarker(best.fence) : "";
|
|
239
|
-
continue;
|
|
240
|
-
}
|
|
241
|
-
const firstLine = lines[lineIndex];
|
|
242
|
-
if (firstLine.length === 0) {
|
|
243
|
-
lineIndex++;
|
|
244
|
-
continue;
|
|
245
|
-
}
|
|
246
|
-
const pFence = scan.stateAtLineEnd[lineIndex] ?? null;
|
|
247
|
-
let plo = 1, phi = firstLine.length, pbest = 0;
|
|
248
|
-
while (plo <= phi) {
|
|
249
|
-
const mid = plo + Math.ceil((phi - plo) / 2);
|
|
250
|
-
const prefix = stripDanglingHighSurrogate(firstLine.slice(0, mid));
|
|
251
|
-
const chunk = pendingPrefix + prefix + (pFence ? midLineCloseMarker(pFence) : "");
|
|
252
|
-
if (fits(chunk)) {
|
|
253
|
-
pbest = prefix.length;
|
|
254
|
-
plo = mid + 1;
|
|
255
|
-
} else phi = mid - 1;
|
|
256
|
-
}
|
|
257
|
-
if (pbest > 0) {
|
|
258
|
-
chunks.push(pendingPrefix + stripDanglingHighSurrogate(firstLine.slice(0, pbest)) + (pFence ? midLineCloseMarker(pFence) : ""));
|
|
259
|
-
lines[lineIndex] = firstLine.slice(pbest);
|
|
260
|
-
pendingPrefix = pFence ? reopenMarker(pFence) : "";
|
|
261
|
-
continue;
|
|
262
|
-
}
|
|
263
|
-
const one = stripDanglingHighSurrogate(firstLine.slice(0, 2));
|
|
264
|
-
chunks.push(one.length > 0 ? one : firstLine.slice(0, 1));
|
|
265
|
-
lines[lineIndex] = firstLine.slice(one.length > 0 ? one.length : 1);
|
|
266
|
-
pendingPrefix = "";
|
|
267
|
-
}
|
|
268
|
-
return [chunks, chunks.length > 1];
|
|
269
|
-
}
|
|
270
|
-
var ATTACHABLE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
271
|
-
"ts",
|
|
272
|
-
"tsx",
|
|
273
|
-
"js",
|
|
274
|
-
"jsx",
|
|
275
|
-
"mjs",
|
|
276
|
-
"cjs",
|
|
277
|
-
"json",
|
|
278
|
-
"md",
|
|
279
|
-
"txt",
|
|
280
|
-
"log",
|
|
281
|
-
"py",
|
|
282
|
-
"cs",
|
|
283
|
-
"css",
|
|
284
|
-
"scss",
|
|
285
|
-
"html",
|
|
286
|
-
"xml",
|
|
287
|
-
"yaml",
|
|
288
|
-
"yml",
|
|
289
|
-
"toml",
|
|
290
|
-
"sh",
|
|
291
|
-
"sql",
|
|
292
|
-
"java",
|
|
293
|
-
"kt",
|
|
294
|
-
"swift",
|
|
295
|
-
"go",
|
|
296
|
-
"rs",
|
|
297
|
-
"rb",
|
|
298
|
-
"php",
|
|
299
|
-
"c",
|
|
300
|
-
"h",
|
|
301
|
-
"cpp",
|
|
302
|
-
"hpp"
|
|
303
|
-
]);
|
|
304
|
-
var MAX_ATTACHMENT_BYTES = 2 * 1024 * 1024;
|
|
305
|
-
var MAX_ATTACHMENTS_PER_FORWARD = 5;
|
|
306
|
-
function collectFileReferences(text, cwd, fsStat, options) {
|
|
307
|
-
const maxFiles = options?.maxFiles ?? MAX_ATTACHMENTS_PER_FORWARD;
|
|
308
|
-
const maxBytes = options?.maxBytes ?? MAX_ATTACHMENT_BYTES;
|
|
309
|
-
const canonicalRoot = options?.canonicalize ? options.canonicalize(cwd) : cwd;
|
|
310
|
-
if (canonicalRoot === null) return [];
|
|
311
|
-
const rootSegments = canonicalRoot.split(/[\\/]+/).filter((segment) => segment.length > 0);
|
|
312
|
-
const driveRoot = /^[A-Za-z]:$/.test(rootSegments[0] ?? "");
|
|
313
|
-
const isInsideRoot = (candidate) => {
|
|
314
|
-
if (candidate === canonicalRoot) return true;
|
|
315
|
-
const segments = candidate.split(/[\\/]+/).filter((segment) => segment.length > 0);
|
|
316
|
-
if (segments.length <= rootSegments.length) return false;
|
|
317
|
-
for (let index = 0; index < rootSegments.length; index++) {
|
|
318
|
-
const a = rootSegments[index], b = segments[index];
|
|
319
|
-
if (driveRoot ? a.toLowerCase() !== b.toLowerCase() : a !== b) return false;
|
|
320
|
-
}
|
|
321
|
-
return true;
|
|
322
|
-
};
|
|
323
|
-
const seen = /* @__PURE__ */ new Set();
|
|
324
|
-
const results = [];
|
|
325
|
-
const scan = scanFenceLines(text);
|
|
326
|
-
let outside = "";
|
|
327
|
-
const indentColumns = (line) => {
|
|
328
|
-
let column = 0;
|
|
329
|
-
for (const ch of line) {
|
|
330
|
-
if (ch === " ") column += 1;
|
|
331
|
-
else if (ch === " ") column = 4 * Math.ceil((column + 1) / 4);
|
|
332
|
-
else break;
|
|
333
|
-
}
|
|
334
|
-
return column;
|
|
335
|
-
};
|
|
336
|
-
for (let i = 0; i < scan.lines.length; i++) {
|
|
337
|
-
const line = scan.lines[i];
|
|
338
|
-
const insideFence = scan.stateAtLineStart[i] !== null || scan.openedBy[i] !== null;
|
|
339
|
-
const indentedCode = indentColumns(line) >= 4;
|
|
340
|
-
if (!insideFence && !indentedCode) outside += line + "\n";
|
|
341
|
-
}
|
|
342
|
-
const candidates = [];
|
|
343
|
-
for (const match of outside.matchAll(/\[[^\]\n]*\]\(([^)\n]+)\)/g)) candidates.push(match[1]);
|
|
344
|
-
for (const match of outside.matchAll(/`([^`\n]+)`/g)) {
|
|
345
|
-
const code = match[1].trim();
|
|
346
|
-
if (code.includes("/") || /\.[a-z0-9]{1,8}$/i.test(code)) candidates.push(code);
|
|
347
|
-
}
|
|
348
|
-
for (const candidate of candidates) {
|
|
349
|
-
if (results.length >= maxFiles) break;
|
|
350
|
-
let path13 = candidate.trim();
|
|
351
|
-
if (!path13 || path13.startsWith("/") || path13.startsWith("~") || /^[a-z]+:/i.test(path13) || path13.includes("://")) continue;
|
|
352
|
-
const clean = path13.replace(/^\.\//, "").split("#")[0].split("?")[0];
|
|
353
|
-
if (clean.includes("..")) continue;
|
|
354
|
-
const extension = clean.split(".").pop().toLowerCase();
|
|
355
|
-
if (!extension || !ATTACHABLE_EXTENSIONS.has(extension)) continue;
|
|
356
|
-
const absolute = nodePathResolve(cwd, clean);
|
|
357
|
-
if (seen.has(absolute)) continue;
|
|
358
|
-
const stat = fsStat(absolute);
|
|
359
|
-
if (!stat || !stat.isFile || stat.size > maxBytes || stat.size === 0) continue;
|
|
360
|
-
const canonical = options?.canonicalize ? options.canonicalize(absolute) : absolute;
|
|
361
|
-
if (canonical === null) continue;
|
|
362
|
-
if (!isInsideRoot(canonical)) continue;
|
|
363
|
-
if (seen.has(canonical)) continue;
|
|
364
|
-
seen.add(absolute);
|
|
365
|
-
seen.add(canonical);
|
|
366
|
-
results.push(absolute);
|
|
367
|
-
}
|
|
368
|
-
return results;
|
|
369
|
-
}
|
|
370
|
-
function nodePathResolve(cwd, relative) {
|
|
371
|
-
const separator = cwd.includes("\\") && !cwd.includes("/") ? "\\" : "/";
|
|
372
|
-
const normalized = relative.split("/").filter((part) => part.length > 0);
|
|
373
|
-
const base = cwd.replace(/[\\/]$/, "").split(/[\\/]/);
|
|
374
|
-
for (const part of normalized) {
|
|
375
|
-
if (part === ".") continue;
|
|
376
|
-
base.push(part);
|
|
377
|
-
}
|
|
378
|
-
return base.join(separator);
|
|
379
|
-
}
|
|
380
|
-
function failureReason(message) {
|
|
381
|
-
const detail = message.errorMessage?.trim();
|
|
382
|
-
if (detail) {
|
|
383
|
-
const collapsed = detail.replace(/\s+/g, " ");
|
|
384
|
-
return collapsed.length > 400 ? `${collapsed.slice(0, 400)}\u2026` : collapsed;
|
|
385
|
-
}
|
|
386
|
-
switch (message.stopReason) {
|
|
387
|
-
case "aborted":
|
|
388
|
-
return "turn aborted";
|
|
389
|
-
case "error":
|
|
390
|
-
return "model/provider error (no detail)";
|
|
391
|
-
case "length":
|
|
392
|
-
return "output length limit reached";
|
|
393
|
-
default:
|
|
394
|
-
return message.stopReason ? `stop reason: ${message.stopReason}` : "unknown failure";
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
// builtin/extensions/im-forward/config.ts
|
|
399
|
-
function resolveConfigDir() {
|
|
400
|
-
const value = process.env.PIE_CODING_AGENT_DIR?.trim();
|
|
401
|
-
return value === "~" ? os.homedir() : value?.startsWith("~/") ? os.homedir() + value.slice(1) : value || path.join(os.homedir(), ".pie");
|
|
402
|
-
}
|
|
403
|
-
function configPaths(cwd, dir) {
|
|
404
|
-
return [.../* @__PURE__ */ new Set([path.join(dir, "im-forward.json"), path.join(cwd, ".pie", "im-forward.json")])];
|
|
405
|
-
}
|
|
406
|
-
var configCache = /* @__PURE__ */ new Map();
|
|
407
|
-
function layerStamp(file) {
|
|
408
|
-
try {
|
|
409
|
-
const stat = fs.statSync(file);
|
|
410
|
-
return `${stat.mtimeMs}:${stat.size}`;
|
|
411
|
-
} catch {
|
|
412
|
-
return "-";
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
function cachedResolveConfig(cwd, dir) {
|
|
416
|
-
const cacheKey = `${cwd}\0${dir}`;
|
|
417
|
-
const stamp = JSON.stringify(configPaths(cwd, dir).map(layerStamp));
|
|
418
|
-
const cached = configCache.get(cacheKey);
|
|
419
|
-
if (cached && cached.stamp === stamp) return cached.result;
|
|
420
|
-
const result = resolveConfig(cwd, dir);
|
|
421
|
-
configCache.set(cacheKey, { stamp, result });
|
|
422
|
-
return result;
|
|
423
|
-
}
|
|
424
|
-
function invalidateConfigCache() {
|
|
425
|
-
configCache.clear();
|
|
426
|
-
}
|
|
427
|
-
function readLayer(file) {
|
|
428
|
-
let text;
|
|
429
|
-
try {
|
|
430
|
-
text = fs.readFileSync(file, "utf8");
|
|
431
|
-
} catch (error) {
|
|
432
|
-
if (error.code === "ENOENT") return {};
|
|
433
|
-
throw new Error(`Cannot read IM configuration: ${file}`);
|
|
434
|
-
}
|
|
435
|
-
try {
|
|
436
|
-
const value = JSON.parse(text);
|
|
437
|
-
if (isRecord(value)) return value;
|
|
438
|
-
} catch {
|
|
439
|
-
}
|
|
440
|
-
throw new Error(`Invalid IM configuration: ${file}. Repair this file before setup; it will not be overwritten.`);
|
|
441
|
-
}
|
|
442
|
-
function resolveConfig(cwd, dir) {
|
|
443
|
-
try {
|
|
444
|
-
let present = false;
|
|
445
|
-
let merged = {};
|
|
446
|
-
const providers = {};
|
|
447
|
-
for (const file of configPaths(cwd, dir)) {
|
|
448
|
-
const layer = readLayer(file);
|
|
449
|
-
if (Object.keys(layer).length) present = true;
|
|
450
|
-
const legacy = ["chatId", "receiveId", "openId", "larkCli", "allowUsers", "groupAccess"].some((key) => key in layer);
|
|
451
|
-
if (legacy && !layer.provider) {
|
|
452
|
-
const previous = providers.feishu ?? {};
|
|
453
|
-
providers.feishu = { ...previous, ...Object.fromEntries(["chatId", "openId", "larkCli", "allowUsers", "groupAccess"].filter((key) => key in layer).map((key) => [key, layer[key]])), ...layer.receiveId && !layer.chatId ? { chatId: layer.receiveId } : {} };
|
|
454
|
-
merged.provider = "feishu";
|
|
455
|
-
}
|
|
456
|
-
if (isRecord(layer.providers)) {
|
|
457
|
-
for (const [id, settings] of Object.entries(layer.providers)) if (isRecord(settings)) providers[id] = { ...providers[id], ...settings };
|
|
458
|
-
}
|
|
459
|
-
merged = { ...merged, ...layer };
|
|
460
|
-
}
|
|
461
|
-
if (!present) return { config: null, problems: [] };
|
|
462
|
-
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.");
|
|
463
|
-
const provider = typeof merged.provider === "string" ? merged.provider : "feishu";
|
|
464
|
-
const retry = merged.retryBackoffMs;
|
|
465
|
-
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: [] };
|
|
466
|
-
} catch (error) {
|
|
467
|
-
return { config: null, problems: [error.message] };
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
function configurationIdentity(config) {
|
|
471
|
-
return JSON.stringify([config.provider, config.settings, config.retryBackoffMs]);
|
|
472
|
-
}
|
|
473
|
-
function configSnapshot(cwd, dir) {
|
|
474
|
-
return JSON.stringify(configPaths(cwd, dir).map((file) => {
|
|
475
|
-
try {
|
|
476
|
-
return fs.readFileSync(file, "utf8");
|
|
477
|
-
} catch (error) {
|
|
478
|
-
if (error.code === "ENOENT") return null;
|
|
479
|
-
throw new Error(`Cannot read IM configuration: ${file}`);
|
|
480
|
-
}
|
|
481
|
-
}));
|
|
482
|
-
}
|
|
483
|
-
function saveLocation(cwd, dir) {
|
|
484
|
-
const files = configPaths(cwd, dir);
|
|
485
|
-
return fs.existsSync(files[files.length - 1]) ? files[files.length - 1] : files[0];
|
|
486
|
-
}
|
|
487
|
-
function writeConfig(cwd, dir, update, expected) {
|
|
488
|
-
for (const file of configPaths(cwd, dir)) readLayer(file);
|
|
489
|
-
if (expected !== void 0 && configSnapshot(cwd, dir) !== expected) throw new Error("IM configuration changed during setup. Please retry.");
|
|
490
|
-
const target = saveLocation(cwd, dir);
|
|
491
|
-
const value = readLayer(target);
|
|
492
|
-
value.enabled = update.enabled;
|
|
493
|
-
if (update.provider) {
|
|
494
|
-
value.provider = update.provider;
|
|
495
|
-
value.providers = { ...isRecord(value.providers) ? value.providers : {}, [update.provider]: update.settings ?? {} };
|
|
496
|
-
}
|
|
497
|
-
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
498
|
-
invalidateConfigCache();
|
|
499
|
-
const temporary = path.join(path.dirname(target), `.im-forward-${randomUUID()}.tmp`);
|
|
500
|
-
try {
|
|
501
|
-
const fd = fs.openSync(temporary, "wx", 384);
|
|
502
|
-
try {
|
|
503
|
-
fs.writeFileSync(fd, JSON.stringify(value, null, " ") + "\n");
|
|
504
|
-
fs.fsyncSync(fd);
|
|
505
|
-
} finally {
|
|
506
|
-
fs.closeSync(fd);
|
|
507
|
-
}
|
|
508
|
-
fs.renameSync(temporary, target);
|
|
509
|
-
} finally {
|
|
510
|
-
try {
|
|
511
|
-
fs.unlinkSync(temporary);
|
|
512
|
-
} catch {
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
}
|
|
516
|
-
function hasConfigLayers(cwd, dir) {
|
|
517
|
-
return configPaths(cwd, dir).some((file) => fs.existsSync(file));
|
|
518
|
-
}
|
|
519
|
-
async function clearImConfig(cwd, dir, confirm) {
|
|
520
|
-
const files = configPaths(cwd, dir).filter((file) => fs.existsSync(file));
|
|
521
|
-
if (!files.length) return false;
|
|
522
|
-
for (const file of files) readLayer(file);
|
|
523
|
-
const snapshot = configSnapshot(cwd, dir);
|
|
524
|
-
if (!await confirm(`Delete the IM forwarding configuration file(s)?
|
|
525
|
-
|
|
526
|
-
${files.join("\n")}
|
|
527
|
-
|
|
528
|
-
Forwarding stops immediately and this cannot be undone.`)) return false;
|
|
529
|
-
if (configSnapshot(cwd, dir) !== snapshot) throw new Error("IM configuration changed during clear. Please retry.");
|
|
530
|
-
for (const file of files) {
|
|
531
|
-
try {
|
|
532
|
-
fs.unlinkSync(file);
|
|
533
|
-
} catch (error) {
|
|
534
|
-
if (error.code !== "ENOENT") throw error;
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
invalidateConfigCache();
|
|
538
|
-
return true;
|
|
539
|
-
}
|
|
540
|
-
function readLiveEnabled(cwd, dir, _cache) {
|
|
541
|
-
return cachedResolveConfig(cwd, dir).config?.enabled === true;
|
|
542
|
-
}
|
|
543
|
-
function readLiveConfig(cwd, dir) {
|
|
544
|
-
try {
|
|
545
|
-
return cachedResolveConfig(cwd, dir);
|
|
546
|
-
} catch {
|
|
547
|
-
return resolveConfig(cwd, dir);
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
function resolveImForwardConfig(cwd, dir) {
|
|
551
|
-
const result = resolveConfig(cwd, dir);
|
|
552
|
-
const cfg = result.config;
|
|
553
|
-
if (!cfg) return { config: null, problems: result.problems };
|
|
554
|
-
if (cfg.provider !== "feishu") return { config: null, problems: [`Unsupported IM provider: ${cfg.provider}`] };
|
|
555
|
-
const raw = cfg.settings;
|
|
556
|
-
const chatId = typeof raw.chatId === "string" ? raw.chatId.trim() : "";
|
|
557
|
-
if (!chatId) return { config: null, problems: cfg.enabled ? ["im-forward: enabled requires chatId"] : [] };
|
|
558
|
-
const allowUsers = Array.isArray(raw.allowUsers) ? raw.allowUsers.filter((id) => typeof id === "string" && !!id.trim()) : void 0;
|
|
559
|
-
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_...)"] };
|
|
560
|
-
}
|
|
561
|
-
|
|
562
39
|
// builtin/extensions/im-forward/runtime.ts
|
|
563
40
|
import * as crypto from "node:crypto";
|
|
564
|
-
import * as
|
|
41
|
+
import * as fs6 from "node:fs";
|
|
565
42
|
import { basename } from "node:path";
|
|
566
43
|
|
|
567
44
|
// builtin/extensions/im-forward/address-book.ts
|
|
568
|
-
import * as
|
|
569
|
-
import * as
|
|
45
|
+
import * as fs from "node:fs";
|
|
46
|
+
import * as os from "node:os";
|
|
570
47
|
import * as path2 from "node:path";
|
|
571
48
|
var MAX_ADDRESS_HEAD = 64;
|
|
572
49
|
function addressBookRoot() {
|
|
573
50
|
const raw = process.env.PIE_IPC_CONFIG_DIR;
|
|
574
51
|
if (raw && raw.trim()) {
|
|
575
52
|
const value = raw.trim();
|
|
576
|
-
const expanded = value === "~" ?
|
|
53
|
+
const expanded = value === "~" ? os.homedir() : value.startsWith("~/") ? path2.join(os.homedir(), value.slice(2)) : value;
|
|
577
54
|
return path2.resolve(expanded);
|
|
578
55
|
}
|
|
579
56
|
return path2.resolve(resolveConfigDir());
|
|
@@ -595,7 +72,7 @@ function scanAddressBook() {
|
|
|
595
72
|
const dir = path2.join(addressBookRoot(), "run", "ipc");
|
|
596
73
|
let entries;
|
|
597
74
|
try {
|
|
598
|
-
entries =
|
|
75
|
+
entries = fs.readdirSync(dir);
|
|
599
76
|
dirExists = true;
|
|
600
77
|
} catch (error) {
|
|
601
78
|
if (error.code === "ENOENT") return { names, complete: true, dirExists: false };
|
|
@@ -604,7 +81,7 @@ function scanAddressBook() {
|
|
|
604
81
|
for (const [index, file] of entries.entries()) {
|
|
605
82
|
if (!file.endsWith(".json")) continue;
|
|
606
83
|
try {
|
|
607
|
-
const status = JSON.parse(
|
|
84
|
+
const status = JSON.parse(fs.readFileSync(path2.join(dir, file), "utf8"));
|
|
608
85
|
dirExists = true;
|
|
609
86
|
const name = typeof status.sessionName === "string" ? status.sessionName.trim() : "";
|
|
610
87
|
const pid = typeof status.pid === "number" ? status.pid : void 0;
|
|
@@ -663,11 +140,11 @@ function resolveAddress(text, ownLiveName, book) {
|
|
|
663
140
|
}
|
|
664
141
|
|
|
665
142
|
// builtin/extensions/im-forward/thread-registry.ts
|
|
666
|
-
import * as
|
|
143
|
+
import * as fs2 from "node:fs";
|
|
667
144
|
import * as path3 from "node:path";
|
|
668
|
-
import { randomUUID
|
|
145
|
+
import { randomUUID } from "node:crypto";
|
|
669
146
|
var SCHEMA = 1;
|
|
670
|
-
var RUNTIME_ID =
|
|
147
|
+
var RUNTIME_ID = randomUUID();
|
|
671
148
|
function encodeThreadKey(input) {
|
|
672
149
|
const raw = `${input.provider}\0${input.threadId}`;
|
|
673
150
|
return Buffer.from(raw, "utf8").toString("base64url");
|
|
@@ -691,7 +168,7 @@ function readOwner(threadKey) {
|
|
|
691
168
|
const file = ownerPath(threadKey);
|
|
692
169
|
let raw;
|
|
693
170
|
try {
|
|
694
|
-
raw = JSON.parse(
|
|
171
|
+
raw = JSON.parse(fs2.readFileSync(file, "utf8"));
|
|
695
172
|
} catch (error) {
|
|
696
173
|
const code = error.code;
|
|
697
174
|
if (code === "ENOENT") return {};
|
|
@@ -718,7 +195,7 @@ function recordFor(threadKey, sessionId) {
|
|
|
718
195
|
function takeOver(threadKey, _dead, sessionId) {
|
|
719
196
|
const file = ownerPath(threadKey);
|
|
720
197
|
try {
|
|
721
|
-
|
|
198
|
+
fs2.rmSync(file, { force: true });
|
|
722
199
|
} catch {
|
|
723
200
|
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
724
201
|
}
|
|
@@ -740,32 +217,32 @@ function decide(owner, threadKey, sessionId) {
|
|
|
740
217
|
function writeNew(threadKey, sessionId) {
|
|
741
218
|
const file = ownerPath(threadKey);
|
|
742
219
|
const record = recordFor(threadKey, sessionId);
|
|
743
|
-
const tmp = path3.join(threadsDir(), `.new-${
|
|
220
|
+
const tmp = path3.join(threadsDir(), `.new-${randomUUID()}.json`);
|
|
744
221
|
try {
|
|
745
|
-
const fd =
|
|
222
|
+
const fd = fs2.openSync(tmp, "wx", 384);
|
|
746
223
|
try {
|
|
747
|
-
|
|
224
|
+
fs2.writeFileSync(fd, JSON.stringify(record));
|
|
748
225
|
try {
|
|
749
|
-
|
|
226
|
+
fs2.fsyncSync(fd);
|
|
750
227
|
} catch (error) {
|
|
751
228
|
try {
|
|
752
|
-
|
|
229
|
+
fs2.closeSync(fd);
|
|
753
230
|
} catch {
|
|
754
231
|
}
|
|
755
232
|
try {
|
|
756
|
-
|
|
233
|
+
fs2.rmSync(tmp, { force: true });
|
|
757
234
|
} catch {
|
|
758
235
|
}
|
|
759
236
|
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
760
237
|
}
|
|
761
238
|
} finally {
|
|
762
|
-
|
|
239
|
+
fs2.closeSync(fd);
|
|
763
240
|
}
|
|
764
241
|
} catch {
|
|
765
242
|
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
766
243
|
}
|
|
767
244
|
try {
|
|
768
|
-
|
|
245
|
+
fs2.linkSync(tmp, file);
|
|
769
246
|
return { claimed: true, ownerSessionId: sessionId };
|
|
770
247
|
} catch (error) {
|
|
771
248
|
const code = error.code;
|
|
@@ -778,7 +255,7 @@ function writeNew(threadKey, sessionId) {
|
|
|
778
255
|
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
779
256
|
} finally {
|
|
780
257
|
try {
|
|
781
|
-
|
|
258
|
+
fs2.rmSync(tmp, { force: true });
|
|
782
259
|
} catch {
|
|
783
260
|
}
|
|
784
261
|
}
|
|
@@ -788,7 +265,7 @@ function claimThreadOwnership(input, sessionId) {
|
|
|
788
265
|
const threadKey = encodeThreadKey(input);
|
|
789
266
|
let stat;
|
|
790
267
|
try {
|
|
791
|
-
stat =
|
|
268
|
+
stat = fs2.statSync(threadsDir());
|
|
792
269
|
} catch (error) {
|
|
793
270
|
if (error.code !== "ENOENT") {
|
|
794
271
|
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
@@ -797,7 +274,7 @@ function claimThreadOwnership(input, sessionId) {
|
|
|
797
274
|
}
|
|
798
275
|
if (stat && !stat.isDirectory()) return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
799
276
|
try {
|
|
800
|
-
|
|
277
|
+
fs2.mkdirSync(threadsDir(), { recursive: true, mode: 448 });
|
|
801
278
|
} catch {
|
|
802
279
|
return { claimed: false, reason: "thread registry unavailable", transient: true };
|
|
803
280
|
}
|
|
@@ -818,12 +295,12 @@ function lockDirPath(threadKey) {
|
|
|
818
295
|
return path3.join(threadsDir(), `${threadKey}.lock`);
|
|
819
296
|
}
|
|
820
297
|
function writeHolderEntry(dir, token) {
|
|
821
|
-
|
|
298
|
+
fs2.writeFileSync(path3.join(dir, `held.${token}`), JSON.stringify({ version: 1, pid: process.pid, createdAt: Date.now() }), { mode: 384, flag: "wx" });
|
|
822
299
|
}
|
|
823
300
|
function retireStaleLock(lock) {
|
|
824
301
|
let entries;
|
|
825
302
|
try {
|
|
826
|
-
entries =
|
|
303
|
+
entries = fs2.readdirSync(lock);
|
|
827
304
|
} catch {
|
|
828
305
|
return false;
|
|
829
306
|
}
|
|
@@ -831,7 +308,7 @@ function retireStaleLock(lock) {
|
|
|
831
308
|
if (holders.length === 0) {
|
|
832
309
|
if (entries.length !== 0) return false;
|
|
833
310
|
try {
|
|
834
|
-
|
|
311
|
+
fs2.rmdirSync(lock);
|
|
835
312
|
return true;
|
|
836
313
|
} catch {
|
|
837
314
|
return false;
|
|
@@ -840,7 +317,7 @@ function retireStaleLock(lock) {
|
|
|
840
317
|
for (const name of holders) {
|
|
841
318
|
let pid;
|
|
842
319
|
try {
|
|
843
|
-
const parsed = JSON.parse(
|
|
320
|
+
const parsed = JSON.parse(fs2.readFileSync(path3.join(lock, name), "utf8"));
|
|
844
321
|
if (parsed?.version !== 1 || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return false;
|
|
845
322
|
pid = parsed.pid;
|
|
846
323
|
} catch {
|
|
@@ -855,13 +332,13 @@ function retireStaleLock(lock) {
|
|
|
855
332
|
}
|
|
856
333
|
for (const name of holders) {
|
|
857
334
|
try {
|
|
858
|
-
|
|
335
|
+
fs2.unlinkSync(path3.join(lock, name));
|
|
859
336
|
} catch (error) {
|
|
860
337
|
if (error.code !== "ENOENT") return false;
|
|
861
338
|
}
|
|
862
339
|
}
|
|
863
340
|
try {
|
|
864
|
-
|
|
341
|
+
fs2.rmdirSync(lock);
|
|
865
342
|
return true;
|
|
866
343
|
} catch {
|
|
867
344
|
return false;
|
|
@@ -871,11 +348,11 @@ var acquiredLocks = /* @__PURE__ */ new Map();
|
|
|
871
348
|
function acquireThreadLock(threadKey) {
|
|
872
349
|
if (acquiredLocks.has(threadKey)) return { acquired: true };
|
|
873
350
|
const lock = lockDirPath(threadKey);
|
|
874
|
-
const token =
|
|
351
|
+
const token = randomUUID();
|
|
875
352
|
const candidate = path3.join(threadsDir(), `lock.acquire.${token}`);
|
|
876
353
|
try {
|
|
877
354
|
try {
|
|
878
|
-
|
|
355
|
+
fs2.mkdirSync(candidate, { mode: 448 });
|
|
879
356
|
} catch {
|
|
880
357
|
return { acquired: false, reason: "thread registry unavailable", transient: true };
|
|
881
358
|
}
|
|
@@ -883,7 +360,7 @@ function acquireThreadLock(threadKey) {
|
|
|
883
360
|
writeHolderEntry(candidate, token);
|
|
884
361
|
} catch {
|
|
885
362
|
try {
|
|
886
|
-
|
|
363
|
+
fs2.rmSync(candidate, { recursive: true, force: true });
|
|
887
364
|
} catch {
|
|
888
365
|
}
|
|
889
366
|
return { acquired: false, reason: "thread registry unavailable", transient: true };
|
|
@@ -891,7 +368,7 @@ function acquireThreadLock(threadKey) {
|
|
|
891
368
|
const deadline = Date.now() + 5e3;
|
|
892
369
|
for (; ; ) {
|
|
893
370
|
try {
|
|
894
|
-
|
|
371
|
+
fs2.renameSync(candidate, lock);
|
|
895
372
|
acquiredLocks.set(threadKey, token);
|
|
896
373
|
return { acquired: true };
|
|
897
374
|
} catch (error) {
|
|
@@ -909,7 +386,7 @@ function acquireThreadLock(threadKey) {
|
|
|
909
386
|
}
|
|
910
387
|
} finally {
|
|
911
388
|
try {
|
|
912
|
-
|
|
389
|
+
fs2.rmSync(candidate, { recursive: true, force: true });
|
|
913
390
|
} catch {
|
|
914
391
|
}
|
|
915
392
|
}
|
|
@@ -920,12 +397,12 @@ function releaseThreadLock(threadKey) {
|
|
|
920
397
|
acquiredLocks.delete(threadKey);
|
|
921
398
|
const lock = lockDirPath(threadKey);
|
|
922
399
|
try {
|
|
923
|
-
|
|
400
|
+
fs2.unlinkSync(path3.join(lock, `held.${token}`));
|
|
924
401
|
} catch {
|
|
925
402
|
}
|
|
926
403
|
try {
|
|
927
|
-
const remaining =
|
|
928
|
-
if (remaining.length === 0)
|
|
404
|
+
const remaining = fs2.readdirSync(lock);
|
|
405
|
+
if (remaining.length === 0) fs2.rmdirSync(lock);
|
|
929
406
|
} catch {
|
|
930
407
|
}
|
|
931
408
|
}
|
|
@@ -945,125 +422,15 @@ function threadOwner(input) {
|
|
|
945
422
|
return { sessionId: read.owner.sessionId };
|
|
946
423
|
}
|
|
947
424
|
|
|
948
|
-
// builtin/extensions/im-forward/event-hub.ts
|
|
949
|
-
import * as fs4 from "node:fs";
|
|
950
|
-
import * as path4 from "node:path";
|
|
951
|
-
var DISPATCH_PREFIX = "[im-forward-dispatch]";
|
|
952
|
-
var LOCK_STALE_MS = 2e4;
|
|
953
|
-
function hubDir() {
|
|
954
|
-
return path4.join(resolveConfigDir(), "im-forward");
|
|
955
|
-
}
|
|
956
|
-
function lockPath(binding) {
|
|
957
|
-
const safe = binding.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
958
|
-
return path4.join(hubDir(), `consumer-${safe}.lock`);
|
|
959
|
-
}
|
|
960
|
-
function pidAlive3(pid) {
|
|
961
|
-
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
962
|
-
try {
|
|
963
|
-
process.kill(pid, 0);
|
|
964
|
-
return true;
|
|
965
|
-
} catch (error) {
|
|
966
|
-
return error.code === "EPERM";
|
|
967
|
-
}
|
|
968
|
-
}
|
|
969
|
-
function readLock(binding) {
|
|
970
|
-
try {
|
|
971
|
-
const parsed = JSON.parse(fs4.readFileSync(lockPath(binding), "utf8"));
|
|
972
|
-
if (typeof parsed.pid === "number" && typeof parsed.holder === "string" && typeof parsed.heartbeatAt === "number" && typeof parsed.binding === "string") {
|
|
973
|
-
return {
|
|
974
|
-
pid: parsed.pid,
|
|
975
|
-
holder: parsed.holder,
|
|
976
|
-
heartbeatAt: parsed.heartbeatAt,
|
|
977
|
-
binding: parsed.binding
|
|
978
|
-
};
|
|
979
|
-
}
|
|
980
|
-
return void 0;
|
|
981
|
-
} catch {
|
|
982
|
-
return void 0;
|
|
983
|
-
}
|
|
984
|
-
}
|
|
985
|
-
function lockAlive(info, now = Date.now()) {
|
|
986
|
-
if (!info) return false;
|
|
987
|
-
return pidAlive3(info.pid) && now - info.heartbeatAt < LOCK_STALE_MS;
|
|
988
|
-
}
|
|
989
|
-
function tryClaimConsumer(binding, holder, onLost) {
|
|
990
|
-
const target = lockPath(binding);
|
|
991
|
-
const mine = JSON.stringify({ pid: process.pid, holder, heartbeatAt: Date.now(), binding });
|
|
992
|
-
const takeOver2 = () => {
|
|
993
|
-
const tmp = `${target}.${process.pid}.${Date.now()}.tmp`;
|
|
994
|
-
try {
|
|
995
|
-
fs4.mkdirSync(hubDir(), { recursive: true, mode: 448 });
|
|
996
|
-
fs4.writeFileSync(tmp, `${mine}
|
|
997
|
-
`);
|
|
998
|
-
try {
|
|
999
|
-
fs4.linkSync(tmp, target);
|
|
1000
|
-
fs4.rmSync(tmp, { force: true });
|
|
1001
|
-
return true;
|
|
1002
|
-
} catch (error) {
|
|
1003
|
-
fs4.rmSync(tmp, { force: true });
|
|
1004
|
-
if (error.code !== "EEXIST") throw error;
|
|
1005
|
-
return false;
|
|
1006
|
-
}
|
|
1007
|
-
} catch {
|
|
1008
|
-
return false;
|
|
1009
|
-
}
|
|
1010
|
-
};
|
|
1011
|
-
const existing = readLock(binding);
|
|
1012
|
-
if (existing && lockAlive(existing)) return void 0;
|
|
1013
|
-
if (existing) {
|
|
1014
|
-
try {
|
|
1015
|
-
fs4.rmSync(target, { force: true });
|
|
1016
|
-
} catch {
|
|
1017
|
-
}
|
|
1018
|
-
}
|
|
1019
|
-
if (!takeOver2()) return void 0;
|
|
1020
|
-
let released = false;
|
|
1021
|
-
const heartbeatTimer = setInterval(() => {
|
|
1022
|
-
if (released) return;
|
|
1023
|
-
try {
|
|
1024
|
-
const current = readLock(binding);
|
|
1025
|
-
if (current && current.pid !== process.pid) {
|
|
1026
|
-
released = true;
|
|
1027
|
-
clearInterval(heartbeatTimer);
|
|
1028
|
-
onLost?.();
|
|
1029
|
-
return;
|
|
1030
|
-
}
|
|
1031
|
-
fs4.writeFileSync(target, `${JSON.stringify({ pid: process.pid, holder, heartbeatAt: Date.now(), binding })}
|
|
1032
|
-
`);
|
|
1033
|
-
} catch {
|
|
1034
|
-
}
|
|
1035
|
-
}, 5e3);
|
|
1036
|
-
heartbeatTimer.unref();
|
|
1037
|
-
return {
|
|
1038
|
-
heartbeat: () => {
|
|
1039
|
-
try {
|
|
1040
|
-
fs4.writeFileSync(target, `${JSON.stringify({ pid: process.pid, holder, heartbeatAt: Date.now(), binding })}
|
|
1041
|
-
`);
|
|
1042
|
-
} catch {
|
|
1043
|
-
}
|
|
1044
|
-
},
|
|
1045
|
-
release: () => {
|
|
1046
|
-
if (released) return;
|
|
1047
|
-
released = true;
|
|
1048
|
-
clearInterval(heartbeatTimer);
|
|
1049
|
-
try {
|
|
1050
|
-
const current = readLock(binding);
|
|
1051
|
-
if (current && current.pid === process.pid) fs4.rmSync(target, { force: true });
|
|
1052
|
-
} catch {
|
|
1053
|
-
}
|
|
1054
|
-
}
|
|
1055
|
-
};
|
|
1056
|
-
}
|
|
1057
|
-
|
|
1058
425
|
// builtin/extensions/im-forward/event-dispatch.ts
|
|
1059
426
|
import * as net from "node:net";
|
|
1060
|
-
import * as
|
|
1061
|
-
import * as
|
|
1062
|
-
import { createHmac, randomUUID as
|
|
427
|
+
import * as fs3 from "node:fs";
|
|
428
|
+
import * as path4 from "node:path";
|
|
429
|
+
import { createHmac, randomUUID as randomUUID2 } from "node:crypto";
|
|
1063
430
|
function discoveryDir() {
|
|
1064
|
-
return
|
|
431
|
+
return path4.join(addressBookRoot(), "run", "ipc");
|
|
1065
432
|
}
|
|
1066
|
-
function
|
|
433
|
+
function pidAlive3(pid) {
|
|
1067
434
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
1068
435
|
try {
|
|
1069
436
|
process.kill(pid, 0);
|
|
@@ -1075,7 +442,7 @@ function pidAlive4(pid) {
|
|
|
1075
442
|
function findOwnerInstance(sessionId) {
|
|
1076
443
|
let entries;
|
|
1077
444
|
try {
|
|
1078
|
-
entries =
|
|
445
|
+
entries = fs3.readdirSync(discoveryDir());
|
|
1079
446
|
} catch {
|
|
1080
447
|
return void 0;
|
|
1081
448
|
}
|
|
@@ -1083,8 +450,8 @@ function findOwnerInstance(sessionId) {
|
|
|
1083
450
|
for (const name of entries.slice(0, 256)) {
|
|
1084
451
|
if (!name.endsWith(".json")) continue;
|
|
1085
452
|
try {
|
|
1086
|
-
const parsed = JSON.parse(
|
|
1087
|
-
if (parsed.instanceId === name.slice(0, -".json".length) && parsed.sessionId === sessionId && parsed.port && typeof parsed.secret === "string" && parsed.protocol === IPC_PROTOCOL_VERSION &&
|
|
453
|
+
const parsed = JSON.parse(fs3.readFileSync(path4.join(discoveryDir(), name), "utf8"));
|
|
454
|
+
if (parsed.instanceId === name.slice(0, -".json".length) && parsed.sessionId === sessionId && parsed.port && typeof parsed.secret === "string" && parsed.protocol === IPC_PROTOCOL_VERSION && pidAlive3(parsed.pid ?? 0)) {
|
|
1088
455
|
candidates.push({ file: parsed, startedAt: typeof parsed.startedAt === "number" ? parsed.startedAt : 0 });
|
|
1089
456
|
}
|
|
1090
457
|
} catch {
|
|
@@ -1095,12 +462,12 @@ function findOwnerInstance(sessionId) {
|
|
|
1095
462
|
return candidates[0].file;
|
|
1096
463
|
}
|
|
1097
464
|
var SYNTHETIC_SENDER = (() => {
|
|
1098
|
-
const hex =
|
|
465
|
+
const hex = randomUUID2().replace(/-/g, "");
|
|
1099
466
|
return `pie-${hex.slice(0, 12)}`;
|
|
1100
467
|
})();
|
|
1101
468
|
function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
|
|
1102
469
|
return new Promise((resolve4) => {
|
|
1103
|
-
const id =
|
|
470
|
+
const id = randomUUID2();
|
|
1104
471
|
const envelope = {
|
|
1105
472
|
v: IPC_PROTOCOL_VERSION,
|
|
1106
473
|
id,
|
|
@@ -1170,16 +537,16 @@ async function dispatchEventToSession(sessionId, eventText) {
|
|
|
1170
537
|
}
|
|
1171
538
|
|
|
1172
539
|
// builtin/extensions/im-forward/session-roots.ts
|
|
1173
|
-
import * as
|
|
1174
|
-
import * as
|
|
540
|
+
import * as fs4 from "node:fs";
|
|
541
|
+
import * as path5 from "node:path";
|
|
1175
542
|
function rootsDir() {
|
|
1176
|
-
return
|
|
543
|
+
return path5.join(resolveConfigDir(), "im-forward", "roots");
|
|
1177
544
|
}
|
|
1178
545
|
function rootPath(provider, messageId) {
|
|
1179
546
|
const safe = `${provider}:${messageId}`.replace(/[^a-zA-Z0-9._:-]/g, "_");
|
|
1180
|
-
return
|
|
547
|
+
return path5.join(rootsDir(), `${safe}.json`);
|
|
1181
548
|
}
|
|
1182
|
-
function
|
|
549
|
+
function pidAlive4(pid) {
|
|
1183
550
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
1184
551
|
try {
|
|
1185
552
|
process.kill(pid, 0);
|
|
@@ -1193,17 +560,17 @@ function claimSessionRoot(provider, messageId, sessionId) {
|
|
|
1193
560
|
try {
|
|
1194
561
|
const record = { sessionId, pid: process.pid, claimedAt: Date.now() };
|
|
1195
562
|
const target = rootPath(provider, messageId);
|
|
1196
|
-
|
|
1197
|
-
|
|
563
|
+
fs4.mkdirSync(rootsDir(), { recursive: true, mode: 448 });
|
|
564
|
+
fs4.writeFileSync(target, `${JSON.stringify(record)}
|
|
1198
565
|
`);
|
|
1199
566
|
} catch {
|
|
1200
567
|
}
|
|
1201
568
|
}
|
|
1202
569
|
function sessionRootOwner(provider, messageId) {
|
|
1203
570
|
try {
|
|
1204
|
-
const parsed = JSON.parse(
|
|
571
|
+
const parsed = JSON.parse(fs4.readFileSync(rootPath(provider, messageId), "utf8"));
|
|
1205
572
|
if (typeof parsed.sessionId === "string" && parsed.sessionId && typeof parsed.pid === "number") {
|
|
1206
|
-
if (!
|
|
573
|
+
if (!pidAlive4(parsed.pid)) return void 0;
|
|
1207
574
|
return { sessionId: parsed.sessionId, pid: parsed.pid, claimedAt: parsed.claimedAt ?? 0 };
|
|
1208
575
|
}
|
|
1209
576
|
return void 0;
|
|
@@ -1213,18 +580,18 @@ function sessionRootOwner(provider, messageId) {
|
|
|
1213
580
|
}
|
|
1214
581
|
|
|
1215
582
|
// builtin/extensions/im-forward/session-anchors.ts
|
|
1216
|
-
import * as
|
|
1217
|
-
import * as
|
|
583
|
+
import * as fs5 from "node:fs";
|
|
584
|
+
import * as path6 from "node:path";
|
|
1218
585
|
function anchorsDir() {
|
|
1219
|
-
return
|
|
586
|
+
return path6.join(addressBookRoot(), "im-forward", "anchors");
|
|
1220
587
|
}
|
|
1221
588
|
function anchorPath(sessionId) {
|
|
1222
589
|
const safe = sessionId.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
1223
|
-
return
|
|
590
|
+
return path6.join(anchorsDir(), `${safe}.json`);
|
|
1224
591
|
}
|
|
1225
592
|
function loadPersistedAnchor(sessionId, identity) {
|
|
1226
593
|
try {
|
|
1227
|
-
const raw =
|
|
594
|
+
const raw = fs5.readFileSync(anchorPath(sessionId), "utf8");
|
|
1228
595
|
const parsed = JSON.parse(raw);
|
|
1229
596
|
if (typeof parsed.anchor?.messageId === "string" && parsed.anchor.messageId && typeof parsed.anchor.at === "number" && parsed.provider === identity.provider && // v2 group-home (11-12): the home is the APP'S WHOLE PRESENCE, so an
|
|
1230
597
|
// anchor may live in ANY room — a group chat id differs from the
|
|
@@ -1253,8 +620,8 @@ function savePersistedAnchor(sessionId, identity, anchor) {
|
|
|
1253
620
|
anchor
|
|
1254
621
|
};
|
|
1255
622
|
const target = anchorPath(sessionId);
|
|
1256
|
-
|
|
1257
|
-
|
|
623
|
+
fs5.mkdirSync(path6.dirname(target), { recursive: true });
|
|
624
|
+
fs5.writeFileSync(target, `${JSON.stringify(file)}
|
|
1258
625
|
`, "utf8");
|
|
1259
626
|
} catch {
|
|
1260
627
|
}
|
|
@@ -1385,6 +752,7 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
|
|
|
1385
752
|
sessionId,
|
|
1386
753
|
sentAt: restoredAt
|
|
1387
754
|
});
|
|
755
|
+
claimThreadOwnership({ provider: cfg.provider, threadId: persisted.threadId }, sessionId);
|
|
1388
756
|
}
|
|
1389
757
|
}
|
|
1390
758
|
}
|
|
@@ -1629,11 +997,13 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1629
997
|
async function forwardMessage(text, sessionId, sequence, userInput, replyTo, attribution) {
|
|
1630
998
|
pruneState();
|
|
1631
999
|
const sessionName = ctx.getSessionDisplayName?.() ?? ctx.getSessionName?.();
|
|
1000
|
+
const composeMode = resolveSessionAnchor(sessionId).threadId ? "topic-reply" : "topic-root";
|
|
1632
1001
|
const composed = composeForwardBody(
|
|
1633
1002
|
sessionId,
|
|
1634
1003
|
sessionName,
|
|
1635
1004
|
userInput,
|
|
1636
|
-
text
|
|
1005
|
+
text,
|
|
1006
|
+
composeMode
|
|
1637
1007
|
);
|
|
1638
1008
|
if (terminated || !isForwardingEnabled()) return;
|
|
1639
1009
|
const [chunks] = chunkMarkdown(composed);
|
|
@@ -1820,18 +1190,18 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1820
1190
|
const files = collectFileReferences(
|
|
1821
1191
|
text,
|
|
1822
1192
|
ctx.cwd,
|
|
1823
|
-
(
|
|
1193
|
+
(path12) => {
|
|
1824
1194
|
try {
|
|
1825
|
-
const stat =
|
|
1195
|
+
const stat = fs6.statSync(path12);
|
|
1826
1196
|
return { isFile: stat.isFile(), size: stat.size };
|
|
1827
1197
|
} catch {
|
|
1828
1198
|
return null;
|
|
1829
1199
|
}
|
|
1830
1200
|
},
|
|
1831
1201
|
{
|
|
1832
|
-
canonicalize: (
|
|
1202
|
+
canonicalize: (path12) => {
|
|
1833
1203
|
try {
|
|
1834
|
-
return
|
|
1204
|
+
return fs6.realpathSync(path12);
|
|
1835
1205
|
} catch {
|
|
1836
1206
|
return null;
|
|
1837
1207
|
}
|
|
@@ -1910,6 +1280,19 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
|
|
|
1910
1280
|
claimThread: seamClaimThread,
|
|
1911
1281
|
anchors: sentAnchors
|
|
1912
1282
|
};
|
|
1283
|
+
registerDispatchReceiver((text) => {
|
|
1284
|
+
const trimmed = text.trimStart();
|
|
1285
|
+
if (!trimmed.startsWith(DISPATCH_PREFIX)) return false;
|
|
1286
|
+
try {
|
|
1287
|
+
const parsed = JSON.parse(trimmed.slice(DISPATCH_PREFIX.length).trim());
|
|
1288
|
+
if (!parsed.event) return false;
|
|
1289
|
+
void handleInboundEvent(parsed.event);
|
|
1290
|
+
return true;
|
|
1291
|
+
} catch {
|
|
1292
|
+
ctx.log("im-forward: malformed dispatch payload dropped");
|
|
1293
|
+
return true;
|
|
1294
|
+
}
|
|
1295
|
+
});
|
|
1913
1296
|
ctx.on("session:changed", (event) => {
|
|
1914
1297
|
inputEpoch++;
|
|
1915
1298
|
currentSessionId = event.sessionId;
|
|
@@ -2336,6 +1719,30 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
2336
1719
|
return resolvedBindingKey;
|
|
2337
1720
|
}
|
|
2338
1721
|
let consumerStartupInFlight = false;
|
|
1722
|
+
function residentAliveSomewhere() {
|
|
1723
|
+
if (isConcierge) return false;
|
|
1724
|
+
try {
|
|
1725
|
+
const dir = path.join(resolveConfigDir(), "run", "ipc");
|
|
1726
|
+
const entries = fs6.readdirSync(dir);
|
|
1727
|
+
for (const name of entries) {
|
|
1728
|
+
if (!name.endsWith(".json")) continue;
|
|
1729
|
+
try {
|
|
1730
|
+
const parsed = JSON.parse(fs6.readFileSync(path.join(dir, name), "utf8"));
|
|
1731
|
+
const unattended = parsed.unattended === true;
|
|
1732
|
+
if (unattended && typeof parsed.pid === "number" && parsed.pid > 0) {
|
|
1733
|
+
try {
|
|
1734
|
+
process.kill(parsed.pid, 0);
|
|
1735
|
+
return true;
|
|
1736
|
+
} catch {
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
} catch {
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
} catch {
|
|
1743
|
+
}
|
|
1744
|
+
return false;
|
|
1745
|
+
}
|
|
2339
1746
|
function needsCanonicalResolution() {
|
|
2340
1747
|
return !resolvedBindingKey && !cfg.appId && !!cfg.profile && connection.canonicalAppId !== void 0;
|
|
2341
1748
|
}
|
|
@@ -2352,6 +1759,10 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
2352
1759
|
}
|
|
2353
1760
|
function acquireClaimedSlot(binding) {
|
|
2354
1761
|
if (consumerLock) return true;
|
|
1762
|
+
if (!isConcierge && residentAliveSomewhere()) {
|
|
1763
|
+
ctx.log("im-forward: a live resident owns the feed class; standing down (dispatch mode)");
|
|
1764
|
+
return false;
|
|
1765
|
+
}
|
|
2355
1766
|
const claim = tryClaimConsumer(binding, `pie-${currentSessionId ?? "unknown"}`, () => {
|
|
2356
1767
|
ctx.log("im-forward: event-hub slot lost to another consumer; retiring ours");
|
|
2357
1768
|
consumerLock = void 0;
|
|
@@ -2525,6 +1936,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
|
|
|
2525
1936
|
ctx.registerCleanup?.(async () => {
|
|
2526
1937
|
inputEpoch++;
|
|
2527
1938
|
terminated = true;
|
|
1939
|
+
registerDispatchReceiver(void 0);
|
|
2528
1940
|
consumerLock?.release();
|
|
2529
1941
|
consumerLock = void 0;
|
|
2530
1942
|
const resources = [...scopes];
|
|
@@ -2632,9 +2044,9 @@ Enable forwarding and start the connection? No test message will be sent. Saving
|
|
|
2632
2044
|
|
|
2633
2045
|
// builtin/extensions/im-forward/providers/feishu/index.ts
|
|
2634
2046
|
import { spawn as spawn4 } from "node:child_process";
|
|
2635
|
-
import * as
|
|
2636
|
-
import * as
|
|
2637
|
-
import * as
|
|
2047
|
+
import * as fs9 from "node:fs";
|
|
2048
|
+
import * as os2 from "node:os";
|
|
2049
|
+
import * as path11 from "node:path";
|
|
2638
2050
|
|
|
2639
2051
|
// builtin/extensions/im-forward/lark-cli.ts
|
|
2640
2052
|
import { spawn as spawn2 } from "node:child_process";
|
|
@@ -2642,33 +2054,33 @@ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
|
|
|
2642
2054
|
|
|
2643
2055
|
// builtin/extensions/im-forward/launch.ts
|
|
2644
2056
|
import { spawn } from "node:child_process";
|
|
2645
|
-
import * as
|
|
2646
|
-
import * as
|
|
2057
|
+
import * as fs7 from "node:fs";
|
|
2058
|
+
import * as path7 from "node:path";
|
|
2647
2059
|
import { StringDecoder } from "node:string_decoder";
|
|
2648
2060
|
function resolveLaunchSpec(explicit, cwd = process.cwd(), platform = process.platform, env = process.env) {
|
|
2649
2061
|
const windows = platform === "win32";
|
|
2650
|
-
const candidates = explicit ? [
|
|
2062
|
+
const candidates = explicit ? [path7.resolve(cwd, explicit)] : (env.PATH ?? "").split(windows ? ";" : ":").filter(Boolean).flatMap((dir) => (windows ? ["lark-cli.exe", "lark-cli.cmd"] : ["lark-cli"]).map((name) => path7.resolve(cwd, dir, name)));
|
|
2651
2063
|
for (const candidate of candidates) {
|
|
2652
2064
|
try {
|
|
2653
|
-
if (!
|
|
2654
|
-
const ext =
|
|
2065
|
+
if (!fs7.statSync(candidate).isFile()) continue;
|
|
2066
|
+
const ext = path7.extname(candidate).toLowerCase();
|
|
2655
2067
|
if (ext === ".js" || ext === ".mjs") return { command: process.execPath, prefix: [candidate] };
|
|
2656
2068
|
if (windows && ext === ".cmd") {
|
|
2657
|
-
const dir =
|
|
2658
|
-
for (const root of [
|
|
2069
|
+
const dir = path7.dirname(candidate);
|
|
2070
|
+
for (const root of [path7.join(dir, "node_modules", "@larksuite", "cli"), path7.resolve(dir, "..", "@larksuite", "cli")]) {
|
|
2659
2071
|
try {
|
|
2660
|
-
const pkg = JSON.parse(
|
|
2072
|
+
const pkg = JSON.parse(fs7.readFileSync(path7.join(root, "package.json"), "utf8"));
|
|
2661
2073
|
const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["lark-cli"];
|
|
2662
2074
|
if (pkg.name !== "@larksuite/cli" || typeof bin !== "string" || bin.replace(/^\.\//, "") !== "scripts/run.js") continue;
|
|
2663
|
-
const entry =
|
|
2664
|
-
if (
|
|
2075
|
+
const entry = path7.join(root, "scripts", "run.js");
|
|
2076
|
+
if (fs7.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
|
|
2665
2077
|
} catch {
|
|
2666
2078
|
}
|
|
2667
2079
|
}
|
|
2668
2080
|
continue;
|
|
2669
2081
|
}
|
|
2670
2082
|
if (windows && ext !== ".exe") continue;
|
|
2671
|
-
|
|
2083
|
+
fs7.accessSync(candidate, fs7.constants.X_OK);
|
|
2672
2084
|
return { command: candidate, prefix: [] };
|
|
2673
2085
|
} catch {
|
|
2674
2086
|
}
|
|
@@ -2724,7 +2136,7 @@ function stopOwnedTreeInner(child, signal) {
|
|
|
2724
2136
|
}, 1500);
|
|
2725
2137
|
try {
|
|
2726
2138
|
const root = process.env.SystemRoot || process.env.windir || "C:\\Windows";
|
|
2727
|
-
killer = spawn(
|
|
2139
|
+
killer = spawn(path7.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { shell: false, windowsHide: true, stdio: "ignore" });
|
|
2728
2140
|
killer.on("error", () => finish(false));
|
|
2729
2141
|
killer.on("exit", (code) => finish(code === 0));
|
|
2730
2142
|
} catch {
|
|
@@ -2969,17 +2381,17 @@ function extractImageKey(content) {
|
|
|
2969
2381
|
}
|
|
2970
2382
|
|
|
2971
2383
|
// builtin/extensions/im-forward/providers/feishu/setup.ts
|
|
2972
|
-
import * as
|
|
2973
|
-
import * as
|
|
2384
|
+
import * as fs8 from "node:fs";
|
|
2385
|
+
import * as path10 from "node:path";
|
|
2974
2386
|
|
|
2975
2387
|
// builtin/extensions/im-forward/browser.ts
|
|
2976
2388
|
import { spawn as spawn3 } from "node:child_process";
|
|
2977
|
-
import
|
|
2389
|
+
import path8 from "node:path";
|
|
2978
2390
|
var browserScript = "$ErrorActionPreference = 'Stop'; try { $reader = [System.IO.StreamReader]::new([Console]::OpenStandardInput(), [System.Text.Encoding]::UTF8); $url = $reader.ReadToEnd(); Start-Process -FilePath $url; exit 0 } catch { exit 1 }";
|
|
2979
2391
|
function browserLaunch(platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
|
|
2980
2392
|
if (platform === "win32") {
|
|
2981
2393
|
if (!/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return;
|
|
2982
|
-
return { command:
|
|
2394
|
+
return { command: path8.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(browserScript, "utf16le").toString("base64")], stdin: true };
|
|
2983
2395
|
}
|
|
2984
2396
|
if (platform === "darwin") return { command: "/usr/bin/open", args: ["--"], stdin: false };
|
|
2985
2397
|
if (platform === "linux") return { command: "/usr/bin/xdg-open", args: [], stdin: false };
|
|
@@ -3038,24 +2450,24 @@ async function openBrowser(url, signal, seam = {}) {
|
|
|
3038
2450
|
}
|
|
3039
2451
|
|
|
3040
2452
|
// builtin/extensions/im-forward/existing-app-terminal.ts
|
|
3041
|
-
import
|
|
2453
|
+
import path9 from "node:path";
|
|
3042
2454
|
var existingAppInnerScript = "$ErrorActionPreference = 'Stop'; try { $payload = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PAYLOAD__')) | ConvertFrom-Json; Set-Location -LiteralPath $payload.cwd; & $payload.command @($payload.args); $code = $LASTEXITCODE; if ($null -eq $code) { exit 1 }; exit $code } catch { Write-Host 'Official setup failed. Close this window and retry from Pie.'; exit 1 }";
|
|
3043
2455
|
var existingAppOuterTemplate = "$ErrorActionPreference = 'Stop'; try { $inner = '" + existingAppInnerScript.replaceAll("'", "''") + "'; $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($inner)); $child = Start-Process -FilePath (Join-Path $PSHOME 'powershell.exe') -WindowStyle Normal -Wait -PassThru -ArgumentList @('-NoLogo', '-NoProfile', '-EncodedCommand', $encoded); exit $child.ExitCode } catch { exit 1 }";
|
|
3044
2456
|
function existingAppTerminal(binary, cwd, platform = process.platform, root = process.env.SystemRoot || "C:\\Windows") {
|
|
3045
2457
|
if (platform !== "win32" || !/^[A-Za-z]:\\/.test(root) || /[\x00-\x1f]/.test(root)) return null;
|
|
3046
2458
|
const payload = Buffer.from(JSON.stringify({ command: binary.command, args: [...binary.prefix, "config", "init", "--brand", "feishu"], cwd }), "utf8").toString("base64");
|
|
3047
2459
|
const script = existingAppOuterTemplate.replace("__PAYLOAD__", payload);
|
|
3048
|
-
return { command:
|
|
2460
|
+
return { command: path9.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), prefix: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
|
|
3049
2461
|
}
|
|
3050
2462
|
|
|
3051
2463
|
// builtin/extensions/im-forward/providers/feishu/setup.ts
|
|
3052
2464
|
function findNpmCli() {
|
|
3053
|
-
const dirs = [
|
|
3054
|
-
for (const dir of dirs) for (const root of [
|
|
2465
|
+
const dirs = [path10.dirname(process.execPath), ...(process.env.PATH ?? "").split(path10.delimiter)];
|
|
2466
|
+
for (const dir of dirs) for (const root of [path10.join(dir, "node_modules", "npm"), path10.resolve(dir, "..", "lib", "node_modules", "npm")]) {
|
|
3055
2467
|
try {
|
|
3056
|
-
const pkg = JSON.parse(
|
|
3057
|
-
const entry =
|
|
3058
|
-
if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" &&
|
|
2468
|
+
const pkg = JSON.parse(fs8.readFileSync(path10.join(root, "package.json"), "utf8"));
|
|
2469
|
+
const entry = path10.join(root, "bin", "npm-cli.js");
|
|
2470
|
+
if (pkg.name === "npm" && pkg.bin?.npm === "bin/npm-cli.js" && fs8.statSync(entry).isFile()) return { command: process.execPath, prefix: [entry] };
|
|
3059
2471
|
} catch {
|
|
3060
2472
|
}
|
|
3061
2473
|
}
|
|
@@ -3643,19 +3055,19 @@ function connect(binary, profile, targetKind = "chat") {
|
|
|
3643
3055
|
return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
|
|
3644
3056
|
},
|
|
3645
3057
|
async downloadImage(messageId, image, index) {
|
|
3646
|
-
const directory =
|
|
3647
|
-
const cleanup = () =>
|
|
3058
|
+
const directory = fs9.mkdtempSync(path11.join(os2.tmpdir(), "pie-im-forward-"));
|
|
3059
|
+
const cleanup = () => fs9.rmSync(directory, { recursive: true, force: true });
|
|
3648
3060
|
try {
|
|
3649
3061
|
const name = `image-${index + 1}.png`;
|
|
3650
3062
|
const result = await native(binary, profile ? ["im", "+messages-resources-download", "--as", "bot", "--message-id", messageId, "--file-key", image, "--type", "image", "--output", name, "--profile", profile] : ["im", "+messages-resources-download", "--as", "bot", "--message-id", messageId, "--file-key", image, "--type", "image", "--output", name], 3e4, directory, { signal: lifetime.signal });
|
|
3651
3063
|
if (result.error || !parseLarkCliEnvelope(result.stdout).ok) throw new Error("Image download failed");
|
|
3652
|
-
let target =
|
|
3653
|
-
if (
|
|
3064
|
+
let target = path11.join(directory, name);
|
|
3065
|
+
if (fs9.statSync(target).size > 10 * 1024 * 1024) throw new Error("Image exceeds 10 MiB");
|
|
3654
3066
|
const detected = readImageFormat(target);
|
|
3655
3067
|
if (detected.ext === ".bin") throw new Error("Unsupported image format");
|
|
3656
3068
|
if (detected.ext !== ".png") {
|
|
3657
|
-
const corrected =
|
|
3658
|
-
|
|
3069
|
+
const corrected = path11.join(directory, `image-${index + 1}${detected.ext}`);
|
|
3070
|
+
fs9.renameSync(target, corrected);
|
|
3659
3071
|
target = corrected;
|
|
3660
3072
|
}
|
|
3661
3073
|
return { file: { path: target, displayName: `feishu-image-${index + 1}${detected.ext}` }, cleanup };
|