@fitchmultz/pi-subagents 0.46.2 → 0.48.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.
Files changed (71) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +1 -1
  3. package/dist/extension/build-info.js +1 -1
  4. package/dist/pi-intercom/bridge-broadcast.js +60 -0
  5. package/dist/pi-intercom/bridge-catalog.js +372 -0
  6. package/dist/pi-intercom/bridge-config.js +47 -26
  7. package/dist/pi-intercom/bridge-control.js +104 -0
  8. package/dist/pi-intercom/bridge-files.js +47 -0
  9. package/dist/pi-intercom/bridge-groups.js +135 -0
  10. package/dist/pi-intercom/bridge-http.js +8 -1
  11. package/dist/pi-intercom/bridge-launch-journal.js +84 -0
  12. package/dist/pi-intercom/bridge-launch-policy.js +71 -5
  13. package/dist/pi-intercom/bridge-launch.js +186 -76
  14. package/dist/pi-intercom/bridge-mailbox.js +324 -0
  15. package/dist/pi-intercom/bridge-operations.js +127 -0
  16. package/dist/pi-intercom/bridge-presence.js +100 -0
  17. package/dist/pi-intercom/bridge-protocol.js +7 -0
  18. package/dist/pi-intercom/bridge-routes.js +190 -17
  19. package/dist/pi-intercom/bridge-rpc-process.js +43 -15
  20. package/dist/pi-intercom/bridge-session.js +83 -85
  21. package/dist/pi-intercom/bridge-target.js +22 -0
  22. package/dist/pi-intercom/bridge-wake.js +158 -0
  23. package/dist/pi-intercom/bridge.js +84 -44
  24. package/dist/pi-intercom/broker/client.js +1 -0
  25. package/dist/pi-intercom/connection.js +2 -3
  26. package/dist/pi-intercom/inbound.js +2 -4
  27. package/dist/pi-intercom/index.js +7 -1
  28. package/dist/pi-intercom/native-control-auth.js +80 -0
  29. package/dist/pi-intercom/native-control-protocol.js +111 -0
  30. package/dist/pi-intercom/native-control.js +130 -0
  31. package/dist/pi-intercom/saved-transcript.js +135 -0
  32. package/dist/pi-intercom/session-targets.js +3 -0
  33. package/dist/pi-intercom/transcript.js +175 -0
  34. package/docs/intercom-bridge.md +293 -161
  35. package/docs/intercom.md +1 -1
  36. package/docs/reference.md +1 -1
  37. package/package.json +1 -1
  38. package/scripts/intercom-bridge-credentials.mjs +54 -12
  39. package/scripts/intercom-remote.mjs +196 -31
  40. package/scripts/package-smoke.mjs +1 -1
  41. package/src/pi-intercom/bridge-broadcast.ts +70 -0
  42. package/src/pi-intercom/bridge-catalog.ts +489 -0
  43. package/src/pi-intercom/bridge-config.ts +64 -37
  44. package/src/pi-intercom/bridge-control.ts +179 -0
  45. package/src/pi-intercom/bridge-files.ts +59 -0
  46. package/src/pi-intercom/bridge-groups.ts +169 -0
  47. package/src/pi-intercom/bridge-http.ts +15 -1
  48. package/src/pi-intercom/bridge-launch-journal.ts +122 -0
  49. package/src/pi-intercom/bridge-launch-policy.ts +88 -7
  50. package/src/pi-intercom/bridge-launch.ts +296 -107
  51. package/src/pi-intercom/bridge-mailbox.ts +395 -0
  52. package/src/pi-intercom/bridge-operations.ts +169 -0
  53. package/src/pi-intercom/bridge-presence.ts +128 -0
  54. package/src/pi-intercom/bridge-protocol.ts +8 -0
  55. package/src/pi-intercom/bridge-routes.ts +281 -32
  56. package/src/pi-intercom/bridge-rpc-process.ts +53 -16
  57. package/src/pi-intercom/bridge-session.ts +106 -105
  58. package/src/pi-intercom/bridge-target.ts +35 -0
  59. package/src/pi-intercom/bridge-wake.ts +188 -0
  60. package/src/pi-intercom/bridge.ts +88 -54
  61. package/src/pi-intercom/broker/client.ts +3 -0
  62. package/src/pi-intercom/connection.ts +2 -3
  63. package/src/pi-intercom/inbound.ts +2 -4
  64. package/src/pi-intercom/index.ts +7 -1
  65. package/src/pi-intercom/native-control-auth.ts +89 -0
  66. package/src/pi-intercom/native-control-protocol.ts +180 -0
  67. package/src/pi-intercom/native-control.ts +160 -0
  68. package/src/pi-intercom/saved-transcript.ts +175 -0
  69. package/src/pi-intercom/session-targets.ts +4 -0
  70. package/src/pi-intercom/transcript.ts +226 -0
  71. package/src/pi-intercom/types.ts +2 -0
@@ -0,0 +1,135 @@
1
+ import { constants, openSync, closeSync, fstatSync } from "node:fs";
2
+ import { loadNativeSession } from "../shared/native-session-loader.js";
3
+ import { scanJournal } from "../shared/journal-reader.js";
4
+ import { Fault } from "./bridge-protocol.js";
5
+ import { readLiveTranscript } from "./transcript.js";
6
+ const FILE_BYTES = 64 * 1024 * 1024;
7
+ const ENTRY_COUNT = 50000;
8
+ const TEXT_LIMIT = 131072;
9
+ const fields = new Set([
10
+ "type",
11
+ "id",
12
+ "parentId",
13
+ "timestamp",
14
+ "version",
15
+ "cwd",
16
+ "customType",
17
+ "display",
18
+ "content",
19
+ ]);
20
+ /** Only branch structure and public textual content are hydrated, never image/provider/custom data. */
21
+ const transcriptProjection = (path) => {
22
+ if (path.length === 0) {
23
+ return true;
24
+ }
25
+ if (path[0] === "message") {
26
+ return messageField(path.slice(1));
27
+ }
28
+ if (path[0] === "content") {
29
+ return contentField(path.slice(1));
30
+ }
31
+ return path.length === 1 && fields.has(String(path[0])) ? 4096 : false;
32
+ };
33
+ function messageField(path) {
34
+ if (path.length === 0) {
35
+ return true;
36
+ }
37
+ if (path[0] === "content") {
38
+ return contentField(path.slice(1));
39
+ }
40
+ return path.length === 1 && ["role", "output", "display", "truncated"].includes(String(path[0]))
41
+ ? TEXT_LIMIT
42
+ : false;
43
+ }
44
+ function contentField(path) {
45
+ return path.length < 2 || (path.length === 2 && ["type", "text"].includes(String(path[1])))
46
+ ? TEXT_LIMIT
47
+ : false;
48
+ }
49
+ function textField(path) {
50
+ if (path[0] === "message") {
51
+ return ((path.length === 2 && ["content", "output"].includes(String(path[1]))) ||
52
+ (path.length === 4 && path[1] === "content" && path[3] === "text"));
53
+ }
54
+ return path[0] === "content" && (path.length === 1 || (path.length === 3 && path[2] === "text"));
55
+ }
56
+ function savedLines(fd, size) {
57
+ const lines = [];
58
+ const cut = new Set();
59
+ const lengths = new Map();
60
+ scanJournal(fd, transcriptProjection, ({ value }) => {
61
+ if (lines.length >= ENTRY_COUNT) {
62
+ throw new Fault(413, "transcript_too_large", "Saved journal exceeds the 50000-entry budget.");
63
+ }
64
+ lines.push(JSON.stringify(value));
65
+ lengths.clear();
66
+ }, {
67
+ policy: "inspect",
68
+ requireNewline: true,
69
+ end: size,
70
+ limits: { depth: 64, nodes: 16384, arrayLength: 4096, keyLength: 512 },
71
+ malformed: (_start, _end, error) => {
72
+ if (error instanceof RangeError) {
73
+ throw new Fault(413, "transcript_too_large", "Saved record exceeds projection limits.");
74
+ }
75
+ lengths.clear();
76
+ cut.delete(lines.length);
77
+ },
78
+ stringChunk: (path, chunk) => {
79
+ if (textField(path)) {
80
+ const key = JSON.stringify(path);
81
+ const count = (lengths.get(key) ?? 0) + chunk.length;
82
+ lengths.set(key, count);
83
+ if (count > TEXT_LIMIT) {
84
+ cut.add(lines.length);
85
+ }
86
+ }
87
+ },
88
+ });
89
+ return { lines, cut };
90
+ }
91
+ /** Internal hook: caller MUST resolve a catalog-approved saved ID/name, never accept an HTTP filepath. */
92
+ export async function readSavedTranscript(packageRoot, approvedFile, options = {}) {
93
+ const sdk = await loadNativeSession(packageRoot);
94
+ const fd = openSync(approvedFile, constants.O_RDONLY | constants.O_NOFOLLOW);
95
+ try {
96
+ const before = fstatSync(fd);
97
+ if (!before.isFile() || before.size > FILE_BYTES) {
98
+ throw new Fault(413, "transcript_too_large", "Saved journal exceeds the 64 MiB read budget.");
99
+ }
100
+ const { lines, cut } = savedLines(fd, before.size);
101
+ const after = fstatSync(fd);
102
+ if (after.size !== before.size ||
103
+ after.mtimeMs !== before.mtimeMs ||
104
+ after.ctimeMs !== before.ctimeMs) {
105
+ throw new Fault(409, "session_changed", "Saved journal changed during reading; refresh the catalog.");
106
+ }
107
+ const entries = sdk.parseSessionEntries(lines.join("\n"));
108
+ return savedPage(entries, cut, options, sdk);
109
+ }
110
+ finally {
111
+ closeSync(fd);
112
+ }
113
+ }
114
+ function savedPage(entries, cut, options, sdk) {
115
+ const header = entries.find((entry) => entry.type === "session");
116
+ if (header === undefined) {
117
+ throw new Fault(409, "invalid_session", "Saved journal has no native session header.");
118
+ }
119
+ const legacy = (header.version ?? 1) < 2;
120
+ if (legacy && options.cursor !== undefined) {
121
+ throw new Fault(409, "cursor_unavailable", "Legacy journals have no stable entry IDs; request a fresh bounded recent transcript.");
122
+ }
123
+ // Native inMemory reconstructs branch state/migrations without ever opening or writing the file.
124
+ const manager = sdk.SessionManager.inMemory(header.cwd, undefined, entries);
125
+ const page = readLiveTranscript(manager, options);
126
+ const cutIds = new Set(entries.flatMap((entry, index) => entry.type !== "session" && cut.has(index) ? [entry.id] : []));
127
+ const records = page.records.map((entry) => cutIds.has(entry.id) ? { ...entry, truncated: true } : entry);
128
+ return {
129
+ ...page,
130
+ // ponytail: v1 has no persisted entry IDs; use catalog snapshot cursors if legacy pagination is needed.
131
+ cursor: legacy ? undefined : page.cursor,
132
+ records,
133
+ truncated: page.truncated || records.some((entry) => entry.truncated),
134
+ };
135
+ }
@@ -2,6 +2,9 @@ import { execFile } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
3
  import path from "node:path";
4
4
  export const MIN_SESSION_TARGET_PREFIX_LENGTH = 8;
5
+ export function nativePeerId(sessionId) {
6
+ return `pi-${createHash("sha256").update(sessionId).digest("hex").slice(0, 32)}`;
7
+ }
5
8
  export function shortSessionId(sessionId) {
6
9
  return sessionId.slice(0, MIN_SESSION_TARGET_PREFIX_LENGTH);
7
10
  }
@@ -0,0 +1,175 @@
1
+ import { isRecord, isUnknownArray } from "../shared/unknown.js";
2
+ import { Fault, label, object } from "./bridge-protocol.js";
3
+ const SCAN_LIMIT = 1024;
4
+ export function transcriptOptions(value = {}) {
5
+ const input = object(value, ["limit", "maxBytes", "cursor"]);
6
+ const limit = integer(input.limit, 50, 1, 100);
7
+ const maxBytes = integer(input.maxBytes, 65536, 256, 131072);
8
+ const cursor = input.cursor === undefined ? undefined : label(input.cursor, "cursor", 512);
9
+ return { limit, maxBytes, cursor };
10
+ }
11
+ function integer(value, fallback, min, max) {
12
+ const result = value === undefined ? fallback : value;
13
+ if (typeof result !== "number" || !Number.isInteger(result) || result < min || result > max) {
14
+ throw new Fault(400, "invalid_input", `Transcript limit must be an integer from ${min} to ${max}.`);
15
+ }
16
+ return result;
17
+ }
18
+ function textualContent(content) {
19
+ if (typeof content === "string") {
20
+ return { text: content, truncated: false };
21
+ }
22
+ if (!isUnknownArray(content)) {
23
+ return { text: "", truncated: false };
24
+ }
25
+ const pieces = [];
26
+ let remaining = 131073;
27
+ let truncated = content.length > 4096;
28
+ for (const part of content.slice(0, 4096)) {
29
+ if (remaining <= 0) {
30
+ truncated = true;
31
+ break;
32
+ }
33
+ if (isRecord(part) && part.type === "text" && typeof part.text === "string") {
34
+ const text = part.text.slice(0, remaining);
35
+ pieces.push(text);
36
+ truncated ||= text.length < part.text.length;
37
+ remaining -= text.length + 1;
38
+ }
39
+ }
40
+ return { text: pieces.join("\n"), truncated };
41
+ }
42
+ function visible(entry) {
43
+ if (entry.type === "custom_message") {
44
+ return entry.display ? { role: "custom", ...textualContent(entry.content) } : undefined;
45
+ }
46
+ if (entry.type !== "message") {
47
+ return undefined;
48
+ }
49
+ const message = entry.message;
50
+ if (message.role === "bashExecution") {
51
+ return {
52
+ role: "toolResult",
53
+ text: message.output,
54
+ truncated: nativeTruncation(message.truncated),
55
+ };
56
+ }
57
+ if (!["user", "assistant", "toolResult", "custom"].includes(message.role)) {
58
+ return undefined;
59
+ }
60
+ if (message.role === "custom" && !message.display) {
61
+ return undefined;
62
+ }
63
+ return "content" in message
64
+ ? { role: message.role, ...textualContent(message.content) }
65
+ : undefined;
66
+ }
67
+ function nativeTruncation(value) {
68
+ // Older saved bash entries may predate the native boolean field.
69
+ return value === true;
70
+ }
71
+ function boundedText(text, budget) {
72
+ // Slice before UTF-8 encoding to avoid copying arbitrarily large live tool output.
73
+ const bytes = Buffer.from(text.slice(0, budget));
74
+ if (bytes.length <= budget) {
75
+ return bytes.toString();
76
+ }
77
+ let end = budget;
78
+ while (end > 0 && (bytes[end] & 0xc0) === 0x80) {
79
+ end -= 1;
80
+ }
81
+ return bytes.subarray(0, end).toString();
82
+ }
83
+ function startId(manager, leaf, cursor) {
84
+ if (cursor === undefined) {
85
+ return { id: leaf, scanned: 0 };
86
+ }
87
+ let raw;
88
+ try {
89
+ raw = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
90
+ }
91
+ catch {
92
+ throw new Fault(400, "invalid_cursor", "Invalid transcript cursor.");
93
+ }
94
+ const data = object(raw, ["leaf", "before"]);
95
+ if (data.leaf !== leaf) {
96
+ throw new Fault(409, "branch_changed", "Active branch changed; request a new transcript page.");
97
+ }
98
+ const before = label(data.before, "cursor entry", 128);
99
+ let id = leaf;
100
+ for (let scanned = 0; id !== null && scanned < SCAN_LIMIT; scanned += 1) {
101
+ if (id === before) {
102
+ return { id, scanned };
103
+ }
104
+ id = manager.getEntry(id)?.parentId ?? null;
105
+ }
106
+ throw new Fault(400, "invalid_cursor", "Cursor is outside the bounded active branch.");
107
+ }
108
+ /** Finalized textual output on the selected branch; never builds full history/context. */
109
+ export function readLiveTranscript(manager, input = {}) {
110
+ const options = transcriptOptions(input);
111
+ const leaf = manager.getLeafId();
112
+ const start = startId(manager, leaf, options.cursor);
113
+ let id = start.id;
114
+ let scanned = start.scanned;
115
+ const records = [];
116
+ let bytes = 0;
117
+ let textTruncated = false;
118
+ while (id !== null && scanned < SCAN_LIMIT) {
119
+ scanned += 1;
120
+ const entry = manager.getEntry(id);
121
+ if (!entry) {
122
+ textTruncated = true;
123
+ id = null;
124
+ break;
125
+ }
126
+ const record = transcriptRecord(entry, options.maxBytes - bytes);
127
+ if (record !== undefined) {
128
+ records.push(record);
129
+ bytes += Buffer.byteLength(record.text);
130
+ textTruncated ||= record.truncated;
131
+ }
132
+ id = entry.parentId;
133
+ if (records.length >= options.limit || bytes >= options.maxBytes) {
134
+ break;
135
+ }
136
+ }
137
+ return transcriptPage(manager, {
138
+ leaf,
139
+ records,
140
+ bytes,
141
+ textTruncated,
142
+ id,
143
+ scanLimitReached: scanned >= SCAN_LIMIT && id !== null,
144
+ });
145
+ }
146
+ function transcriptRecord(entry, budget) {
147
+ const output = visible(entry);
148
+ if (output === undefined || output.text.length === 0) {
149
+ return undefined;
150
+ }
151
+ const text = boundedText(output.text, budget);
152
+ return {
153
+ id: entry.id,
154
+ timestamp: entry.timestamp,
155
+ role: output.role,
156
+ text,
157
+ truncated: text !== output.text || output.truncated,
158
+ };
159
+ }
160
+ function transcriptPage(manager, state) {
161
+ const { leaf, records, bytes, textTruncated, id, scanLimitReached } = state;
162
+ return {
163
+ sessionId: manager.getSessionId(),
164
+ leafId: leaf,
165
+ records: records.reverse(),
166
+ bytes,
167
+ truncated: id !== null || textTruncated,
168
+ scanLimitReached,
169
+ ...(id !== null && !scanLimitReached
170
+ ? { cursor: Buffer.from(JSON.stringify({ leaf, before: id })).toString("base64url") }
171
+ : {}),
172
+ finalizedOnly: true,
173
+ streaming: "unavailable",
174
+ };
175
+ }