@rivus/gateway 0.22.3 → 0.24.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 +3 -3
- package/assets/audio-transcriber/THIRD_PARTY_NOTICES.md +1 -3
- package/assets/audio-transcriber/fetch-model.mjs +29 -21
- package/assets/audio-transcriber/npm-shrinkwrap.json +5 -63
- package/assets/audio-transcriber/package.json +1 -1
- package/assets/installation-policy.json +9 -4
- package/dist/bootstrap/feishu.d.ts +42 -3
- package/dist/bootstrap/feishu.js +11964 -12401
- package/dist/bootstrap/herdr-feishu.d.ts +8 -1
- package/dist/bootstrap/herdr-feishu.js +2 -2
- package/dist/chunks/dist.js +10371 -0
- package/dist/chunks/errors.js +13 -0
- package/dist/chunks/herdr-feishu-runtime.js +128 -395
- package/dist/chunks/herdr-socket-client.js +496 -0
- package/dist/chunks/public.d.ts +93 -63
- package/dist/chunks/public2.d.ts +0 -7
- package/dist/chunks/rivus-deployment-cli-process.d.ts +136 -353
- package/dist/chunks/rivus-node-entrypoint.js +1543 -1579
- package/dist/chunks/superagent-worker-programs.js +7240 -0
- package/dist/chunks/superagent-worker-wire.js +233 -0
- package/dist/index.d.ts +12 -25
- package/dist/index.js +2 -1
- package/dist/mcp.js +109 -24
- package/dist/superagent.d.ts +301 -0
- package/dist/superagent.js +2 -0
- package/package.json +25 -11
- package/dist/chunks/automation-presentation.js +0 -263
- package/dist/chunks/feishu-receive-message.js +0 -113
- package/dist/chunks/rivus-home-deployment-env.js +0 -1916
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
import { Effect, Result, Schema, SchemaIssue } from "effect";
|
|
2
|
+
import { createConnection } from "node:net";
|
|
3
|
+
import { lstat, readdir } from "node:fs/promises";
|
|
4
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
5
|
+
import { isNodeErrorWithCode } from "@rivus/platform/filesystem";
|
|
6
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
7
|
+
//#region src/lib/schema-issue-path.ts
|
|
8
|
+
/**
|
|
9
|
+
* Format an issue path with the repository's existing semantics: a dotted key, or an indexed bracket for a numeric
|
|
10
|
+
* segment. This is the path formatter shared by Feishu entry diagnostics and Automation presentation validation; it
|
|
11
|
+
* intentionally does not use Effect's internal `Formatter.formatPath`, which wraps every segment in brackets and would
|
|
12
|
+
* change the original error texts.
|
|
13
|
+
*/
|
|
14
|
+
function formatSchemaIssuePath(issue) {
|
|
15
|
+
return (issue.path ?? []).map((segment) => {
|
|
16
|
+
const key = typeof segment === "object" ? segment.key : segment;
|
|
17
|
+
return typeof key === "number" ? `[${key}]` : `.${String(key)}`;
|
|
18
|
+
}).join("");
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/terminal-session/domain/bridge/terminal-bridge-model.ts
|
|
22
|
+
var TerminalTargetChangedError = class extends Error {
|
|
23
|
+
constructor() {
|
|
24
|
+
super("Herdr target changed; select the target again");
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/** A final target check refused before the prompt RPC was invoked. */
|
|
28
|
+
var TerminalPromptPreflightError = class extends Error {
|
|
29
|
+
constructor(text) {
|
|
30
|
+
super(text);
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
const terminalWriteRefusalText = {
|
|
34
|
+
"read-only": "Terminal input is disabled for this deployment.",
|
|
35
|
+
terminal: "目标为只读终端面板,不能接收指令。",
|
|
36
|
+
"not-ready": "目标尚未完成启动,暂不接收指令;请刷新状态。",
|
|
37
|
+
busy: "目标正在执行任务,暂不接收新指令。",
|
|
38
|
+
blocked: "目标正在等待处理(如审批或提问),不会代替你处理;未提交指令。",
|
|
39
|
+
"unknown-status": "目标状态未知,请刷新确认后再发送。"
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Shared gate for every Herdr write path (locked text, /herdr send, form submit).
|
|
43
|
+
* Herdr reports the same input-awaiting agent as `done` before it is focused and
|
|
44
|
+
* `idle` afterwards, so both statuses admit a ready agent; everything else refuses
|
|
45
|
+
* with a specific reason and no PTY input. Availability and status are evaluated
|
|
46
|
+
* before the deployment read-only flag so an offline, replaced or busy target keeps
|
|
47
|
+
* reporting its own reason instead of a generic disabled notice.
|
|
48
|
+
*/
|
|
49
|
+
function evaluateTerminalWriteInput(agent, writable) {
|
|
50
|
+
const refused = (refusal) => ({
|
|
51
|
+
allowed: false,
|
|
52
|
+
refusal,
|
|
53
|
+
text: terminalWriteRefusalText[refusal]
|
|
54
|
+
});
|
|
55
|
+
if (agent.kind !== "agent") return refused("terminal");
|
|
56
|
+
if (!agent.ready) return refused("not-ready");
|
|
57
|
+
if (agent.status === "working") return refused("busy");
|
|
58
|
+
if (agent.status === "blocked") return refused("blocked");
|
|
59
|
+
if (agent.status !== "idle" && agent.status !== "done") return refused("unknown-status");
|
|
60
|
+
if (!writable) return refused("read-only");
|
|
61
|
+
return { allowed: true };
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/feishu/lib/message/feishu-receive-message.ts
|
|
65
|
+
/** Match the durable codec's non-blank check without changing the stored identifier text. */
|
|
66
|
+
const filledText = Schema.String.check(Schema.makeFilter((value) => value.trim().length > 0));
|
|
67
|
+
const storedMessageFields = {
|
|
68
|
+
chat_id: filledText,
|
|
69
|
+
content: Schema.String,
|
|
70
|
+
message_id: filledText,
|
|
71
|
+
message_type: filledText
|
|
72
|
+
};
|
|
73
|
+
/** The four fields a stored inbound-delivery payload must have; the storage accept set is fixed and shares this. */
|
|
74
|
+
const storedFeishuReceiveMessageSchema = Schema.Struct({ event: Schema.Struct({ message: Schema.Struct(storedMessageFields) }) });
|
|
75
|
+
/**
|
|
76
|
+
* Tolerance: a declared field that is present but has the wrong type (including `null`) rejects the whole payload;
|
|
77
|
+
* undeclared wire fields stay on the returned object and are never read. The required message fields are non-blank
|
|
78
|
+
* because the durable inbound-delivery codec accepts only non-blank ids.
|
|
79
|
+
*/
|
|
80
|
+
const messageFields = {
|
|
81
|
+
...storedMessageFields,
|
|
82
|
+
chat_type: Schema.optional(Schema.String),
|
|
83
|
+
create_time: Schema.optional(Schema.String),
|
|
84
|
+
mentions: Schema.optional(Schema.Array(Schema.Struct({
|
|
85
|
+
id: Schema.optional(Schema.Struct({ open_id: Schema.optional(Schema.String) })),
|
|
86
|
+
key: Schema.optional(Schema.String),
|
|
87
|
+
name: Schema.optional(Schema.String)
|
|
88
|
+
}))),
|
|
89
|
+
parent_id: Schema.optional(Schema.String),
|
|
90
|
+
root_id: Schema.optional(Schema.String),
|
|
91
|
+
thread_id: Schema.optional(Schema.String)
|
|
92
|
+
};
|
|
93
|
+
const wireMessageSchema = Schema.Struct(messageFields);
|
|
94
|
+
const senderSchema = Schema.Struct({
|
|
95
|
+
sender_id: Schema.optional(Schema.Struct({ open_id: Schema.optional(Schema.String) })),
|
|
96
|
+
sender_type: Schema.optional(Schema.String),
|
|
97
|
+
tenant_key: Schema.optional(Schema.String)
|
|
98
|
+
});
|
|
99
|
+
/** The Lark event envelope: `header`/`event` wrapping the message. */
|
|
100
|
+
const envelopeWireSchema = Schema.Struct({
|
|
101
|
+
header: Schema.optional(Schema.Struct({ tenant_key: Schema.optional(Schema.String) })),
|
|
102
|
+
event: Schema.Struct({
|
|
103
|
+
message: wireMessageSchema,
|
|
104
|
+
sender: Schema.optional(senderSchema)
|
|
105
|
+
})
|
|
106
|
+
});
|
|
107
|
+
/** The SDK dispatcher's flat shape: `tenant_key`, `message` and `sender` at the payload root. A payload that
|
|
108
|
+
* carries an `event` key is never a flat shape, even when that value is `undefined`; it is decoded as an envelope
|
|
109
|
+
* or refused by the shared union. */
|
|
110
|
+
const sdkFlatWireSchema = Schema.Struct({
|
|
111
|
+
message: wireMessageSchema,
|
|
112
|
+
sender: Schema.optional(senderSchema),
|
|
113
|
+
tenant_key: Schema.optional(Schema.String),
|
|
114
|
+
event: Schema.optionalKey(Schema.Never)
|
|
115
|
+
});
|
|
116
|
+
const wireSchema = Schema.Union([envelopeWireSchema, sdkFlatWireSchema]);
|
|
117
|
+
/** @internal */
|
|
118
|
+
var UndecodableFeishuReceiveMessage = class extends Error {
|
|
119
|
+
reason;
|
|
120
|
+
name = "UndecodableFeishuReceiveMessage";
|
|
121
|
+
_tag = "UndecodableFeishuReceiveMessage";
|
|
122
|
+
constructor(reason) {
|
|
123
|
+
super(reason);
|
|
124
|
+
this.reason = reason;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
function describeIssue(issue) {
|
|
128
|
+
const formatted = SchemaIssue.makeFormatterStandardSchemaV1()(issue).issues[0];
|
|
129
|
+
if (formatted === void 0) return "Feishu receive-message payload does not match the envelope or SDK-flat wire shape";
|
|
130
|
+
return `Feishu receive-message payload${formatSchemaIssuePath(formatted) || " value"}: ${formatted.message}`;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Decode the inbound message event once. The Lark dispatcher hands over the envelope or its flat SDK shape; one
|
|
134
|
+
* union Schema validates both, and the decoded branch decides how the value is returned:
|
|
135
|
+
*
|
|
136
|
+
* - envelope: the original payload object, so unknown wire fields survive the durable store round-trip;
|
|
137
|
+
* - flat: `{ header?, event: { message, sender? } }` built from the original nested objects, with the tenant key
|
|
138
|
+
* moved to `header` and the remaining root wire fields dropped as the previous normalizer did.
|
|
139
|
+
*
|
|
140
|
+
* The failure reason names the field path and expected type only; it never echoes a field value.
|
|
141
|
+
*/
|
|
142
|
+
function decodeFeishuReceiveMessage(raw) {
|
|
143
|
+
const decoded = Schema.decodeUnknownResult(wireSchema)(raw);
|
|
144
|
+
if (Result.isFailure(decoded)) throw new UndecodableFeishuReceiveMessage(describeIssue(decoded.failure.issue));
|
|
145
|
+
if (!("message" in decoded.success)) return raw;
|
|
146
|
+
const flat = raw;
|
|
147
|
+
return {
|
|
148
|
+
...flat.tenant_key ? { header: { tenant_key: flat.tenant_key } } : {},
|
|
149
|
+
event: {
|
|
150
|
+
message: flat.message,
|
|
151
|
+
...flat.sender ? { sender: flat.sender } : {}
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
/** The tenant key is resolved at read time, sender first. Decoding only moves a flat shape's root `tenant_key`
|
|
156
|
+
* into `header`; it does not resolve or merge the two carriers. */
|
|
157
|
+
function readTenantKey(payload) {
|
|
158
|
+
return payload.event.sender?.tenant_key ?? payload.header?.tenant_key ?? "";
|
|
159
|
+
}
|
|
160
|
+
//#endregion
|
|
161
|
+
//#region src/herdr/lib/herdr-socket-frame.ts
|
|
162
|
+
/**
|
|
163
|
+
* Object gate for a Herdr response part, not a field reader: the callers read their
|
|
164
|
+
* fields by name with their own error texts. `Schema.Record(Schema.String, Schema.Unknown)`
|
|
165
|
+
* is deliberately used only as that gate; a hand-written `typeof … === "object"` guard is
|
|
166
|
+
* forbidden (authoring guide, Validation).
|
|
167
|
+
*/
|
|
168
|
+
const herdrResponseGate = Schema.Record(Schema.String, Schema.Unknown);
|
|
169
|
+
function object(value) {
|
|
170
|
+
if (!Schema.is(herdrResponseGate)(value)) throw new Error("Invalid Herdr response");
|
|
171
|
+
return value;
|
|
172
|
+
}
|
|
173
|
+
function string(value) {
|
|
174
|
+
if (typeof value !== "string") throw new Error("Invalid Herdr response field");
|
|
175
|
+
return value;
|
|
176
|
+
}
|
|
177
|
+
var HerdrRequestError = class extends Error {
|
|
178
|
+
code;
|
|
179
|
+
constructor(code) {
|
|
180
|
+
super(`Herdr error: ${code}`);
|
|
181
|
+
this.code = code;
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
const subscriptionAck = Schema.Struct({
|
|
185
|
+
id: Schema.String,
|
|
186
|
+
result: Schema.Struct({ type: Schema.Literal("subscription_started") })
|
|
187
|
+
});
|
|
188
|
+
const workerEvent = Schema.Struct({
|
|
189
|
+
event: Schema.Literals([
|
|
190
|
+
"pane.agent_status_changed",
|
|
191
|
+
"pane_exited",
|
|
192
|
+
"pane_closed"
|
|
193
|
+
]),
|
|
194
|
+
data: Schema.Struct({
|
|
195
|
+
pane_id: Schema.NonEmptyString,
|
|
196
|
+
agent_status: Schema.optional(Schema.Literals([
|
|
197
|
+
"working",
|
|
198
|
+
"idle",
|
|
199
|
+
"done",
|
|
200
|
+
"blocked",
|
|
201
|
+
"unknown"
|
|
202
|
+
]))
|
|
203
|
+
})
|
|
204
|
+
});
|
|
205
|
+
const decodeSubscriptionLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Union([subscriptionAck, workerEvent])));
|
|
206
|
+
//#endregion
|
|
207
|
+
//#region src/herdr/infra/adapters/herdr-socket-request.ts
|
|
208
|
+
function requestHerdrSocket(path, method, params, timeoutMs, signal) {
|
|
209
|
+
return new Promise((resolve, reject) => {
|
|
210
|
+
const id = randomUUID();
|
|
211
|
+
const socket = createConnection({ path });
|
|
212
|
+
let settled = false;
|
|
213
|
+
let bytes = 0;
|
|
214
|
+
let buffer = "";
|
|
215
|
+
function finish(error, result) {
|
|
216
|
+
if (settled) return;
|
|
217
|
+
settled = true;
|
|
218
|
+
clearTimeout(timer);
|
|
219
|
+
signal.removeEventListener("abort", abort);
|
|
220
|
+
socket.removeAllListeners("connect");
|
|
221
|
+
socket.removeAllListeners("data");
|
|
222
|
+
socket.removeAllListeners("end");
|
|
223
|
+
socket.destroy();
|
|
224
|
+
if (error) reject(error);
|
|
225
|
+
else resolve(result);
|
|
226
|
+
}
|
|
227
|
+
const onError = (error) => finish(error);
|
|
228
|
+
socket.once("close", () => socket.removeListener("error", onError));
|
|
229
|
+
const abort = () => finish(/* @__PURE__ */ new Error("Herdr request aborted; input may have been submitted"));
|
|
230
|
+
const timer = setTimeout(() => finish(/* @__PURE__ */ new Error("Herdr request timed out; input may have been submitted")), timeoutMs);
|
|
231
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
232
|
+
socket.setEncoding("utf8");
|
|
233
|
+
socket.on("connect", () => socket.write(`${JSON.stringify({
|
|
234
|
+
id,
|
|
235
|
+
method,
|
|
236
|
+
params
|
|
237
|
+
})}\n`));
|
|
238
|
+
socket.on("error", onError);
|
|
239
|
+
socket.on("end", () => finish(/* @__PURE__ */ new Error("Herdr closed without a response; outcome unknown")));
|
|
240
|
+
socket.on("data", (chunk) => {
|
|
241
|
+
bytes += Buffer.byteLength(chunk);
|
|
242
|
+
if (bytes > 1048576) return finish(/* @__PURE__ */ new Error("Herdr response exceeds one MiB"));
|
|
243
|
+
buffer += chunk;
|
|
244
|
+
const newline = buffer.indexOf("\n");
|
|
245
|
+
if (newline < 0) return;
|
|
246
|
+
try {
|
|
247
|
+
const response = object(JSON.parse(buffer.slice(0, newline)));
|
|
248
|
+
if (response.id !== id) throw new Error("Herdr response identity mismatch");
|
|
249
|
+
if (response.error) throw new HerdrRequestError(string(object(response.error).code));
|
|
250
|
+
finish(void 0, object(response.result));
|
|
251
|
+
} catch (error) {
|
|
252
|
+
finish(error);
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
if (signal.aborted) abort();
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
async function subscribeHerdrWorker(path, paneId, timeoutMs, signal, onEvent) {
|
|
259
|
+
const id = randomUUID();
|
|
260
|
+
const socket = createConnection({
|
|
261
|
+
path,
|
|
262
|
+
signal
|
|
263
|
+
});
|
|
264
|
+
socket.setEncoding("utf8");
|
|
265
|
+
socket.setTimeout(timeoutMs, () => socket.destroy(/* @__PURE__ */ new Error("Herdr subscription timed out")));
|
|
266
|
+
socket.once("connect", () => {
|
|
267
|
+
socket.write(JSON.stringify({
|
|
268
|
+
id,
|
|
269
|
+
method: "events.subscribe",
|
|
270
|
+
params: { subscriptions: [
|
|
271
|
+
{
|
|
272
|
+
type: "pane.agent_status_changed",
|
|
273
|
+
pane_id: paneId
|
|
274
|
+
},
|
|
275
|
+
{ type: "pane.exited" },
|
|
276
|
+
{ type: "pane.closed" }
|
|
277
|
+
] }
|
|
278
|
+
}) + "\n");
|
|
279
|
+
});
|
|
280
|
+
let accepted = false;
|
|
281
|
+
let buffer = "";
|
|
282
|
+
try {
|
|
283
|
+
for await (const chunk of socket) {
|
|
284
|
+
buffer += chunk;
|
|
285
|
+
let newline = buffer.indexOf("\n");
|
|
286
|
+
while (newline !== -1) {
|
|
287
|
+
if (Buffer.byteLength(buffer.slice(0, newline)) > 1048576) throw new Error("Herdr event exceeds one MiB");
|
|
288
|
+
const line = decodeSubscriptionLine(buffer.slice(0, newline));
|
|
289
|
+
buffer = buffer.slice(newline + 1);
|
|
290
|
+
newline = buffer.indexOf("\n");
|
|
291
|
+
if (!accepted) {
|
|
292
|
+
if (line._tag === "None" || !("id" in line.value) || line.value.id !== id) throw new Error("Herdr subscription was rejected");
|
|
293
|
+
accepted = true;
|
|
294
|
+
socket.setTimeout(0);
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
if (line._tag === "Some" && "event" in line.value && line.value.data.pane_id === paneId) {
|
|
298
|
+
const status = line.value.event === "pane.agent_status_changed" ? line.value.data.agent_status : "lost";
|
|
299
|
+
if (status !== void 0 && status !== "unknown") onEvent(status);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (Buffer.byteLength(buffer) > 1048576) throw new Error("Herdr event exceeds one MiB");
|
|
303
|
+
}
|
|
304
|
+
} finally {
|
|
305
|
+
socket.destroy();
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
//#endregion
|
|
309
|
+
//#region src/herdr/infra/adapters/herdr-socket-client.ts
|
|
310
|
+
const label = Schema.optional(Schema.NullOr(Schema.String));
|
|
311
|
+
const sessionSnapshot = Schema.decodeUnknownSync(Schema.Struct({ snapshot: Schema.Struct({
|
|
312
|
+
protocol: Schema.Literal(22),
|
|
313
|
+
panes: Schema.Array(Schema.Struct({
|
|
314
|
+
pane_id: Schema.String,
|
|
315
|
+
terminal_id: Schema.String,
|
|
316
|
+
workspace_id: Schema.String,
|
|
317
|
+
tab_id: Schema.String,
|
|
318
|
+
agent: Schema.optional(Schema.NullOr(Schema.String)),
|
|
319
|
+
agent_session: Schema.optional(Schema.Json),
|
|
320
|
+
agent_status: Schema.String,
|
|
321
|
+
label,
|
|
322
|
+
terminal_title_stripped: label,
|
|
323
|
+
title: label
|
|
324
|
+
})),
|
|
325
|
+
agents: Schema.Array(Schema.Struct({
|
|
326
|
+
pane_id: Schema.String,
|
|
327
|
+
terminal_id: Schema.String,
|
|
328
|
+
name: label,
|
|
329
|
+
launch_pending: Schema.optional(Schema.Unknown)
|
|
330
|
+
})),
|
|
331
|
+
workspaces: Schema.optional(Schema.Array(Schema.Struct({
|
|
332
|
+
workspace_id: Schema.String,
|
|
333
|
+
label: Schema.String
|
|
334
|
+
}))),
|
|
335
|
+
tabs: Schema.optional(Schema.Array(Schema.Struct({
|
|
336
|
+
tab_id: Schema.String,
|
|
337
|
+
label: Schema.String
|
|
338
|
+
})))
|
|
339
|
+
}) }));
|
|
340
|
+
async function discoverSessions(root) {
|
|
341
|
+
const uid = process.getuid?.();
|
|
342
|
+
const directory = await lstat(root);
|
|
343
|
+
if (!directory.isDirectory() || directory.uid !== uid || (directory.mode & 18) !== 0) throw new Error("Herdr discovery root must be an owned, non-writable directory");
|
|
344
|
+
const candidates = [{
|
|
345
|
+
name: "default",
|
|
346
|
+
socketPath: join(root, "herdr.sock")
|
|
347
|
+
}];
|
|
348
|
+
const named = join(root, "sessions");
|
|
349
|
+
const info = await lstat(named).catch((error) => {
|
|
350
|
+
if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
|
|
351
|
+
return null;
|
|
352
|
+
});
|
|
353
|
+
if (info) {
|
|
354
|
+
if (!info.isDirectory() || info.uid !== uid || (info.mode & 18) !== 0) throw new Error("Invalid Herdr sessions directory");
|
|
355
|
+
for (const entry of (await readdir(named, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) if (entry.isDirectory()) candidates.push({
|
|
356
|
+
name: entry.name,
|
|
357
|
+
socketPath: join(named, entry.name, "herdr.sock")
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
const found = [];
|
|
361
|
+
for (const candidate of candidates) if (await lstat(candidate.socketPath).catch((error) => {
|
|
362
|
+
if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
|
|
363
|
+
return null;
|
|
364
|
+
})) found.push(candidate);
|
|
365
|
+
return found;
|
|
366
|
+
}
|
|
367
|
+
function createHerdrSocketClient(sessions, timeoutMs = 5e3, discoverSessionsIn) {
|
|
368
|
+
if (!sessions.length && !discoverSessionsIn || new Set(sessions.map((s) => s.name)).size !== sessions.length) throw new Error("Herdr requires unique configured session names");
|
|
369
|
+
if (discoverSessionsIn && !isAbsolute(discoverSessionsIn)) throw new Error("Herdr discovery root must be absolute");
|
|
370
|
+
let configs = new Map(sessions.map((session) => [session.name, session]));
|
|
371
|
+
const refresh = () => Effect.tryPromise({
|
|
372
|
+
try: async () => {
|
|
373
|
+
const discovered = discoverSessionsIn ? await discoverSessions(discoverSessionsIn) : [];
|
|
374
|
+
const next = /* @__PURE__ */ new Map();
|
|
375
|
+
const paths = /* @__PURE__ */ new Set();
|
|
376
|
+
for (const config of [...sessions, ...discovered]) {
|
|
377
|
+
const path = resolve(config.socketPath);
|
|
378
|
+
if (paths.has(path)) continue;
|
|
379
|
+
if (next.has(config.name)) throw new Error("Herdr session aliases collide");
|
|
380
|
+
next.set(config.name, {
|
|
381
|
+
...config,
|
|
382
|
+
socketPath: path
|
|
383
|
+
});
|
|
384
|
+
paths.add(path);
|
|
385
|
+
}
|
|
386
|
+
configs = next;
|
|
387
|
+
return [...next.keys()];
|
|
388
|
+
},
|
|
389
|
+
catch: (error) => error
|
|
390
|
+
});
|
|
391
|
+
async function checkedSocket(session) {
|
|
392
|
+
const config = configs.get(session);
|
|
393
|
+
if (config === void 0) throw new Error("Unknown Herdr session");
|
|
394
|
+
const socket = await lstat(config.socketPath);
|
|
395
|
+
if (!socket.isSocket() || (socket.mode & 63) !== 0 || socket.uid !== process.getuid?.()) throw new Error("Herdr socket must be private and owned by the current user");
|
|
396
|
+
return {
|
|
397
|
+
path: config.socketPath,
|
|
398
|
+
generation: `${socket.dev}:${socket.ino}:${socket.birthtimeMs}`
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
const invoke = (session, method, params, deadline = timeoutMs) => Effect.tryPromise({
|
|
402
|
+
try: async (signal) => {
|
|
403
|
+
const { path, generation } = await checkedSocket(session);
|
|
404
|
+
return {
|
|
405
|
+
result: await requestHerdrSocket(path, method, params, deadline, signal),
|
|
406
|
+
generation
|
|
407
|
+
};
|
|
408
|
+
},
|
|
409
|
+
catch: (error) => error
|
|
410
|
+
});
|
|
411
|
+
const listSession = (session) => invoke(session, "session.snapshot", {}).pipe(Effect.flatMap(({ result, generation }) => Effect.try(() => {
|
|
412
|
+
const { snapshot } = sessionSnapshot(result);
|
|
413
|
+
const workspaces = new Map(snapshot.workspaces?.map((entry) => [entry.workspace_id, entry.label]));
|
|
414
|
+
const tabs = new Map(snapshot.tabs?.map((entry) => [entry.tab_id, entry.label]));
|
|
415
|
+
return snapshot.panes.map((value) => {
|
|
416
|
+
const pane = value.pane_id;
|
|
417
|
+
const terminal = value.terminal_id;
|
|
418
|
+
const agent = snapshot.agents.find((item) => item.pane_id === pane && item.terminal_id === terminal);
|
|
419
|
+
const kind = value.agent || "terminal";
|
|
420
|
+
const workspace = value.workspace_id;
|
|
421
|
+
const tab = value.tab_id;
|
|
422
|
+
const title = [
|
|
423
|
+
agent?.name,
|
|
424
|
+
value.label,
|
|
425
|
+
value.terminal_title_stripped,
|
|
426
|
+
value.title
|
|
427
|
+
].find(Boolean) ?? kind;
|
|
428
|
+
return {
|
|
429
|
+
session,
|
|
430
|
+
pane,
|
|
431
|
+
identity: createHash("sha256").update(JSON.stringify([
|
|
432
|
+
generation,
|
|
433
|
+
session,
|
|
434
|
+
pane,
|
|
435
|
+
terminal,
|
|
436
|
+
kind,
|
|
437
|
+
value.agent_session ?? null
|
|
438
|
+
])).digest("hex"),
|
|
439
|
+
kind: kind === "terminal" ? "terminal" : "agent",
|
|
440
|
+
name: `${pane} / ${workspaces.get(workspace) ?? workspace} / ${tabs.get(tab) ?? tab} / ${title}`,
|
|
441
|
+
workspace: workspaces.get(workspace) ?? workspace,
|
|
442
|
+
tab: tabs.get(tab) ?? tab,
|
|
443
|
+
title,
|
|
444
|
+
status: value.agent_status,
|
|
445
|
+
ready: kind !== "terminal" && agent !== void 0 && (agent.launch_pending === void 0 || agent.launch_pending === false)
|
|
446
|
+
};
|
|
447
|
+
});
|
|
448
|
+
})));
|
|
449
|
+
const resolve$1 = (agent) => refresh().pipe(Effect.flatMap(() => listSession(agent.session)), Effect.flatMap((agents) => {
|
|
450
|
+
const current = agents.find((item) => item.pane === agent.pane && item.identity === agent.identity);
|
|
451
|
+
return current ? Effect.succeed(current) : Effect.fail(new TerminalTargetChangedError());
|
|
452
|
+
}));
|
|
453
|
+
return {
|
|
454
|
+
subscribeWorker: (session, paneId, onEvent) => refresh().pipe(Effect.andThen(Effect.tryPromise({
|
|
455
|
+
try: async (signal) => {
|
|
456
|
+
const { path } = await checkedSocket(session);
|
|
457
|
+
return subscribeHerdrWorker(path, paneId, timeoutMs, signal, onEvent);
|
|
458
|
+
},
|
|
459
|
+
catch: (error) => error
|
|
460
|
+
}))),
|
|
461
|
+
invoke: (session, method, params, deadline) => refresh().pipe(Effect.flatMap(() => invoke(session, method, params, deadline))),
|
|
462
|
+
list: () => refresh().pipe(Effect.flatMap((names) => Effect.all(names.map((name) => listSession(name).pipe(Effect.map((agents) => ({
|
|
463
|
+
agents,
|
|
464
|
+
unavailableSessions: []
|
|
465
|
+
})), Effect.catch(() => Effect.succeed({
|
|
466
|
+
agents: [],
|
|
467
|
+
unavailableSessions: [name]
|
|
468
|
+
})))), { concurrency: 4 })), Effect.map((results) => ({
|
|
469
|
+
agents: results.flatMap((result) => result.agents),
|
|
470
|
+
unavailableSessions: results.flatMap((result) => result.unavailableSessions)
|
|
471
|
+
}))),
|
|
472
|
+
inspect: resolve$1,
|
|
473
|
+
read: (agent, visible) => resolve$1(agent).pipe(Effect.flatMap(() => invoke(agent.session, "pane.read", {
|
|
474
|
+
pane_id: agent.pane,
|
|
475
|
+
source: visible ? "visible" : "recent_unwrapped",
|
|
476
|
+
format: "text",
|
|
477
|
+
lines: visible ? 80 : 120
|
|
478
|
+
})), Effect.flatMap(({ result }) => Effect.try(() => {
|
|
479
|
+
const read = object(result.read);
|
|
480
|
+
return {
|
|
481
|
+
text: string(read.text),
|
|
482
|
+
truncated: read.truncated === true
|
|
483
|
+
};
|
|
484
|
+
}))),
|
|
485
|
+
prompt: (agent, text) => resolve$1(agent).pipe(Effect.catch((error) => Effect.fail(error instanceof TerminalTargetChangedError ? error : new TerminalPromptPreflightError("目标暂不可用;未提交指令。可 /exit 后重新选择。"))), Effect.flatMap((current) => {
|
|
486
|
+
const verdict = evaluateTerminalWriteInput(current, true);
|
|
487
|
+
return verdict.allowed ? Effect.void : Effect.fail(new TerminalPromptPreflightError(`Input rejected: ${verdict.text}`));
|
|
488
|
+
}), Effect.flatMap(() => invoke(agent.session, "agent.prompt", {
|
|
489
|
+
target: agent.pane,
|
|
490
|
+
text
|
|
491
|
+
})), Effect.asVoid)
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
//#endregion
|
|
495
|
+
export { storedFeishuReceiveMessageSchema as a, evaluateTerminalWriteInput as c, readTenantKey as i, formatSchemaIssuePath as l, HerdrRequestError as n, TerminalPromptPreflightError as o, decodeFeishuReceiveMessage as r, TerminalTargetChangedError as s, createHerdrSocketClient as t };
|
|
496
|
+
|