@cotal-ai/pi 0.11.3 → 0.11.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.
@@ -1 +1 @@
1
- {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAkB,KAAK,SAAS,EAAE,KAAK,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC5F,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAoEpE,mFAAmF;AACnF,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,GAAG,IAAI,CA+B/F"}
1
+ {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAeA,OAAO,EAAkB,KAAK,SAAS,EAAE,KAAK,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC5F,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAmEpE,mFAAmF;AACnF,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,GAAG,IAAI,CA+B/F"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cotal-ai/pi",
3
- "version": "0.11.3",
3
+ "version": "0.11.4",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -23,19 +23,17 @@
23
23
  "engines": {
24
24
  "node": ">=20"
25
25
  },
26
- "dependencies": {
27
- "typebox": "^1.1.0",
28
- "zod": "^4.4.3",
29
- "@cotal-ai/connector-core": "0.11.3"
30
- },
31
26
  "peerDependencies": {
32
- "@cotal-ai/core": "0.11.3"
27
+ "@cotal-ai/core": ">=0.1.0"
33
28
  },
34
29
  "devDependencies": {
35
30
  "@earendil-works/pi-ai": "0.79.10",
36
31
  "@earendil-works/pi-coding-agent": "0.79.10",
37
32
  "esbuild": "^0.28.0",
38
- "@cotal-ai/core": "0.11.3"
33
+ "typebox": "^1.1.0",
34
+ "zod": "^4.4.3",
35
+ "@cotal-ai/core": "0.11.4",
36
+ "@cotal-ai/connector-core": "0.11.4"
39
37
  },
40
38
  "files": [
41
39
  "dist"
@@ -45,7 +43,8 @@
45
43
  },
46
44
  "scripts": {
47
45
  "typecheck": "tsc -p tsconfig.json --noEmit",
48
- "build": "tsc -p tsconfig.json && esbuild src/standalone.ts --bundle --platform=node --format=esm --target=node20 --outfile=dist/standalone.js --external:@earendil-works/pi-coding-agent --external:@earendil-works/pi-tui --banner:js=\"import { createRequire as __cotalCreateRequire } from 'node:module'; const require = __cotalCreateRequire(import.meta.url);\"",
46
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json --emitDeclarationOnly && pnpm run bundle",
47
+ "bundle": "esbuild src/index.ts --bundle --platform=node --format=esm --target=node20 --outfile=dist/index.js --external:@cotal-ai/core && esbuild src/standalone.ts --bundle --platform=node --format=esm --target=node20 --outfile=dist/standalone.js --external:@earendil-works/pi-coding-agent --external:@earendil-works/pi-tui --banner:js=\"import { createRequire as __cotalCreateRequire } from 'node:module'; const require = __cotalCreateRequire(import.meta.url);\"",
49
48
  "test": "pnpm run build && tsx pi.smoke.ts && tsx pi-sdk.smoke.ts && node --input-type=module -e \"await import('./dist/standalone.js'); console.log('pi standalone smoke: import passed')\""
50
49
  }
51
50
  }
package/dist/connector.js DELETED
@@ -1,98 +0,0 @@
1
- import { mkdtempSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import { hardenPrivate, loadAgentFile, registry, writeSecretFile, } from "@cotal-ai/core";
6
- import { aclEnv, connectorLaunchOptions, controlEndpoint, launchEnv, userAuthEnv, } from "@cotal-ai/connector-core";
7
- const STANDALONE = fileURLToPath(import.meta.url.includes("/dist/") ? new URL("./standalone.js", import.meta.url) : new URL("../dist/standalone.js", import.meta.url));
8
- /** Provider environment names recognized by the pinned Pi 0.79.10 host. Kept Pi-local so adding a
9
- * provider here never expands the secret surface of sibling connectors. */
10
- const PI_PROVIDER_KEYS = [
11
- "ANTHROPIC_OAUTH_TOKEN",
12
- "ANTHROPIC_API_KEY",
13
- "OPENAI_API_KEY",
14
- "OPENROUTER_API_KEY",
15
- "OPENCODE_API_KEY",
16
- "GEMINI_API_KEY",
17
- "GOOGLE_CLOUD_API_KEY",
18
- "GROQ_API_KEY",
19
- "CEREBRAS_API_KEY",
20
- "DEEPSEEK_API_KEY",
21
- "MISTRAL_API_KEY",
22
- "XAI_API_KEY",
23
- "ZAI_API_KEY",
24
- "ZAI_CODING_CN_API_KEY",
25
- "MINIMAX_API_KEY",
26
- "MINIMAX_CN_API_KEY",
27
- "MOONSHOT_API_KEY",
28
- "FIREWORKS_API_KEY",
29
- "TOGETHER_API_KEY",
30
- "NVIDIA_API_KEY",
31
- "KIMI_API_KEY",
32
- "HF_TOKEN",
33
- "COPILOT_GITHUB_TOKEN",
34
- "AI_GATEWAY_API_KEY",
35
- "CLOUDFLARE_API_KEY",
36
- "XIAOMI_API_KEY",
37
- "XIAOMI_TOKEN_PLAN_CN_API_KEY",
38
- "XIAOMI_TOKEN_PLAN_AMS_API_KEY",
39
- "XIAOMI_TOKEN_PLAN_SGP_API_KEY",
40
- ];
41
- export const piConnector = {
42
- kind: "connector",
43
- name: "pi",
44
- requires: ["pi"],
45
- buildLaunch(opts) {
46
- if (opts.resume)
47
- throw new Error("pi connector: resuming an existing session (resume) is not implemented");
48
- if (opts.variant)
49
- throw new Error("pi connector: model variants (variant) are not implemented");
50
- if (opts.mcpServers && Object.keys(opts.mcpServers).length > 0)
51
- throw new Error("pi connector: MCP tool-sharing is not implemented");
52
- if (connectorLaunchOptions("pi", opts.launchOptions).length > 0)
53
- throw new Error("pi connector: launch options (--opt / launchOptions) are not implemented");
54
- let model = opts.model;
55
- let persona;
56
- if (opts.configPath) {
57
- const definition = loadAgentFile(opts.configPath);
58
- model ??= definition.model;
59
- persona = definition.persona;
60
- }
61
- const env = {
62
- ...launchEnv({ providerKeys: PI_PROVIDER_KEYS }),
63
- ...aclEnv(opts),
64
- ...userAuthEnv(opts),
65
- COTAL_SPACE: opts.space,
66
- COTAL_NAME: opts.name,
67
- };
68
- if (opts.role)
69
- env.COTAL_ROLE = opts.role;
70
- if (opts.id)
71
- env.COTAL_ID = opts.id;
72
- if (opts.creds)
73
- env.COTAL_CREDS = opts.creds;
74
- if (opts.servers)
75
- env.COTAL_SERVERS = opts.servers;
76
- if (opts.configPath)
77
- env.COTAL_AGENT_FILE = opts.configPath;
78
- const args = ["--extension", STANDALONE];
79
- if (persona) {
80
- const dir = mkdtempSync(join(tmpdir(), "cotal-persona-"));
81
- hardenPrivate(dir, "dir");
82
- const file = join(dir, "persona.md");
83
- writeSecretFile(file, persona);
84
- env.COTAL_PI_PERSONA_FILE = file;
85
- args.push("--append-system-prompt", file);
86
- }
87
- if (model) {
88
- env.COTAL_MODEL = model;
89
- args.push("--model", model);
90
- }
91
- const control = controlEndpoint(opts.space, opts.name);
92
- env.COTAL_CONTROL_SOCKET = control.path;
93
- env.COTAL_CONTROL_TOKEN = control.token;
94
- return { command: "pi", args, env, control };
95
- },
96
- };
97
- registry.register(piConnector);
98
- //# sourceMappingURL=connector.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"connector.js","sourceRoot":"","sources":["../src/connector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EACL,aAAa,EACb,aAAa,EACb,QAAQ,EACR,eAAe,GAIhB,MAAM,gBAAgB,CAAC;AACxB,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AO,EAAE,CAAC;YACZ,MAAM,GAAG,GAAG,WAAW,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,gBAAgB,CAAC,CAAC,CAAC;YAC1D,aAAa,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YAC1B,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC;YACrC,eAAe,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;YAC/B,GAAG,CAAC,qBAAqB,GAAG,IAAI,CAAC;YACjC,IAAI,CAAC,IAAI,CAAC,wBAAwB,EAAE,IAAI,CAAC,CAAC;QAC5C,CAAC;QACD,IAAI,KAAK,EAAE,CAAC;YACV,GAAG,CAAC,WAAW,GAAG,KAAK,CAAC;YACxB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;QAC9B,CAAC;QAED,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QACvD,GAAG,CAAC,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC;QACxC,GAAG,CAAC,mBAAmB,GAAG,OAAO,CAAC,KAAK,CAAC;QACxC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC;IAC/C,CAAC;CACF,CAAC;AAEF,QAAQ,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC"}
package/dist/driver.js DELETED
@@ -1,347 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { formatInjection } from "@cotal-ai/connector-core";
3
- import { InboxTurn } from "./inbox-turn.js";
4
- const CUSTOM_TYPE = "cotal-inbox";
5
- const BATCH_LIMIT = 32;
6
- const DEFAULT_START_TIMEOUT_MS = 5_000;
7
- function detailsOf(message) {
8
- if (!message || typeof message !== "object")
9
- return undefined;
10
- const value = message;
11
- if (value.role !== "custom" || value.customType !== CUSTOM_TYPE || !value.details || typeof value.details !== "object")
12
- return undefined;
13
- const details = value.details;
14
- if (details.version !== 1 || typeof details.batchId !== "string" || !Array.isArray(details.ids))
15
- return undefined;
16
- if (!details.ids.every((id) => typeof id === "string"))
17
- return undefined;
18
- return details;
19
- }
20
- function ownChannelEcho(mesh, item) {
21
- return item.kind === "channel" && item.fromId === mesh.id;
22
- }
23
- function wakeable(mesh, item) {
24
- if (ownChannelEcho(mesh, item))
25
- return false;
26
- if (item.kind !== "channel" || item.mentionsMe)
27
- return true;
28
- if (mesh.channelMode(item.channel) === "quiet")
29
- return false;
30
- return mesh.attention === "open";
31
- }
32
- /** Serialized Pi-owned delivery driver. No event callback calls the host send API outside this class. */
33
- export class PiDriver {
34
- mesh;
35
- startTimeoutMs;
36
- inbox;
37
- host;
38
- context;
39
- batches = [];
40
- contextBatchIds = new Set();
41
- requestBatchIds = new Set();
42
- terminalEvidenceBatchIds = new Set();
43
- nudges = [];
44
- presence = Promise.resolve();
45
- activeSignal;
46
- pendingContinuation = false;
47
- overflowRetry = false;
48
- _state = "idle";
49
- heldReason;
50
- constructor(mesh, startTimeoutMs = DEFAULT_START_TIMEOUT_MS) {
51
- this.mesh = mesh;
52
- this.startTimeoutMs = startTimeoutMs;
53
- this.inbox = new InboxTurn(mesh);
54
- }
55
- get state() {
56
- return this._state;
57
- }
58
- get reason() {
59
- return this.heldReason;
60
- }
61
- bind(host) {
62
- this.host = host;
63
- }
64
- onSessionStart(context) {
65
- this.context = context;
66
- if (this._state === "shuttingDown") {
67
- context.shutdown();
68
- return;
69
- }
70
- this.pump();
71
- }
72
- onSessionShutdown() {
73
- this.context = undefined;
74
- }
75
- onIncoming() {
76
- this.pump();
77
- }
78
- onWake() {
79
- this.pump();
80
- }
81
- onMentionWake(item) {
82
- if (this._state === "shuttingDown")
83
- return;
84
- const who = item.fromRole ? `${item.fromName}/${item.fromRole}` : item.fromName;
85
- this.nudges.push(`Cotal: you were @mentioned on #${item.channel} by ${who} while focused. ` +
86
- "The body is held; read it with cotal_inbox and reply with cotal_send if warranted.");
87
- if (this.nudges.length > BATCH_LIMIT)
88
- this.nudges.splice(0, this.nudges.length - BATCH_LIMIT);
89
- this.pump();
90
- }
91
- onAgentStart(context) {
92
- this.context = context;
93
- if (this._state === "shuttingDown") {
94
- context.shutdown();
95
- return;
96
- }
97
- this.activeSignal = context.signal;
98
- this.overflowRetry = false;
99
- if (this.pendingContinuation) {
100
- this.pendingContinuation = false;
101
- this.heldReason = undefined;
102
- this._state = this.batches.some((batch) => !batch.confirmed) ? "dispatching" : "streaming";
103
- }
104
- else if (this._state === "held" && this.batches.length === 0) {
105
- this.heldReason = undefined;
106
- this._state = "streaming";
107
- }
108
- else if (this._state !== "held") {
109
- this._state = this.batches.some((batch) => !batch.confirmed) ? "dispatching" : "streaming";
110
- }
111
- this.enqueuePresence("working", "thinking");
112
- if (this._state !== "held")
113
- this.pump(true);
114
- }
115
- onMessageStart(message) {
116
- if (this._state === "shuttingDown")
117
- return;
118
- const details = detailsOf(message);
119
- if (!details)
120
- return;
121
- const batch = this.batches.find((candidate) => candidate.id === details.batchId);
122
- if (!batch || batch.ids.length !== details.ids.length || !batch.ids.every((id, i) => id === details.ids[i]))
123
- return;
124
- batch.started = true;
125
- if (this.contextBatchIds.has(batch.id)) {
126
- this.requestBatchIds.add(batch.id);
127
- this.terminalEvidenceBatchIds.add(batch.id);
128
- }
129
- if (batch.watchdog)
130
- clearTimeout(batch.watchdog);
131
- batch.watchdog = undefined;
132
- }
133
- onContext(messages) {
134
- if (this._state === "shuttingDown")
135
- return;
136
- const visible = new Set(messages.map(detailsOf).filter((details) => Boolean(details)).map((d) => d.batchId));
137
- const candidates = this.batches.filter((batch) => !batch.confirmed && visible.has(batch.id));
138
- this.contextBatchIds = new Set(candidates.map((batch) => batch.id));
139
- this.requestBatchIds = new Set(candidates.filter((batch) => batch.started).map((batch) => batch.id));
140
- for (const id of this.requestBatchIds)
141
- this.terminalEvidenceBatchIds.add(id);
142
- }
143
- onProviderResponse(status) {
144
- if (this._state === "shuttingDown")
145
- return;
146
- if (status >= 200 && status < 300) {
147
- for (const id of this.requestBatchIds) {
148
- const batch = this.batches.find((candidate) => candidate.id === id);
149
- if (batch)
150
- batch.confirmed = true;
151
- }
152
- }
153
- else {
154
- for (const id of this.requestBatchIds)
155
- this.terminalEvidenceBatchIds.delete(id);
156
- }
157
- this.contextBatchIds.clear();
158
- this.requestBatchIds.clear();
159
- if (this._state !== "held") {
160
- this._state = "streaming";
161
- this.pump();
162
- }
163
- }
164
- onToolStart(name) {
165
- if (this._state === "shuttingDown")
166
- return;
167
- this.enqueuePresence("working", `running ${name || "tool"}`);
168
- }
169
- onToolEnd() {
170
- if (this._state === "shuttingDown")
171
- return;
172
- this.enqueuePresence("working", "thinking");
173
- }
174
- onAgentEnd(messages, context) {
175
- if (this._state === "shuttingDown")
176
- return;
177
- const lastAssistant = [...messages]
178
- .reverse()
179
- .find((message) => message && typeof message === "object" && message.role === "assistant");
180
- const aborted = this.activeSignal?.aborted === true;
181
- this.activeSignal = undefined;
182
- this.contextBatchIds.clear();
183
- this.requestBatchIds.clear();
184
- const terminal = !aborted &&
185
- (lastAssistant?.stopReason === "stop" ||
186
- lastAssistant?.stopReason === "toolUse" ||
187
- (lastAssistant?.stopReason === "length" && (lastAssistant.usage?.output ?? 0) > 0));
188
- if (!terminal) {
189
- this.terminalEvidenceBatchIds.clear();
190
- if (this.batches.length === 0) {
191
- this._state = "idle";
192
- this.publishIdleWhenSettled(context);
193
- return;
194
- }
195
- this.pendingContinuation = true;
196
- this.hold(aborted || lastAssistant?.stopReason === "aborted"
197
- ? "Pi turn was aborted; Cotal delivery is retained until a proven clean continuation completes"
198
- : `Pi turn ended with ${lastAssistant?.stopReason ?? "an unknown stop reason"}; ` +
199
- "Cotal delivery is retained until a proven clean continuation completes");
200
- return;
201
- }
202
- for (const id of this.terminalEvidenceBatchIds) {
203
- const batch = this.batches.find((candidate) => candidate.id === id);
204
- if (batch)
205
- batch.confirmed = true;
206
- }
207
- this.terminalEvidenceBatchIds.clear();
208
- this.pendingContinuation = false;
209
- this.finalizeEnd(context);
210
- }
211
- onBeforeCompact(reason, willRetry) {
212
- if (this._state === "shuttingDown")
213
- return;
214
- if (reason !== "overflow" || !willRetry)
215
- return;
216
- this.overflowRetry = true;
217
- }
218
- requestShutdown() {
219
- if (this._state === "shuttingDown")
220
- return;
221
- this._state = "shuttingDown";
222
- this.clearTimers();
223
- if (this.context)
224
- this.context.shutdown();
225
- }
226
- async quit() {
227
- this._state = "shuttingDown";
228
- this.clearTimers();
229
- await this.presence.catch(() => { });
230
- }
231
- async flushPresence() {
232
- await this.presence.catch(() => { });
233
- }
234
- pump(force = false) {
235
- if (!this.host || !this.context || this._state === "held" || this._state === "shuttingDown")
236
- return;
237
- if (this.batches.some((batch) => !batch.confirmed))
238
- return;
239
- this.inbox.discardTombstonedFront();
240
- this.inbox.discardFront((item) => ownChannelEcho(this.mesh, item));
241
- const reserved = new Set(this.batches.flatMap((batch) => batch.ids));
242
- const available = this.inbox.peek().filter((item) => !reserved.has(item.id));
243
- if (!force && this.nudges.length === 0 && !available.some((item) => wakeable(this.mesh, item))) {
244
- if (this.batches.length === 0)
245
- this.publishIdleWhenSettled(this.context);
246
- return;
247
- }
248
- let ids = [];
249
- let content;
250
- if (this.nudges.length > 0) {
251
- content = this.nudges.splice(0).join("\n");
252
- }
253
- else {
254
- const items = this.inbox.select(reserved, (item) => ownChannelEcho(this.mesh, item), BATCH_LIMIT);
255
- if (items.length === 0)
256
- return;
257
- ids = items.map((item) => item.id);
258
- content = formatInjection(items);
259
- }
260
- if (!content)
261
- return;
262
- const batch = { id: randomUUID(), ids, content, started: false, confirmed: false };
263
- this.batches.push(batch);
264
- this._state = "dispatching";
265
- try {
266
- this.host.sendMessage({
267
- customType: CUSTOM_TYPE,
268
- content,
269
- display: true,
270
- details: { version: 1, batchId: batch.id, ids: [...ids] },
271
- }, { triggerTurn: true, deliverAs: "steer" });
272
- if (!batch.started) {
273
- batch.watchdog = setTimeout(() => {
274
- if (!batch.started)
275
- this.hold(`Pi did not start dispatched Cotal batch ${batch.id}`);
276
- }, this.startTimeoutMs);
277
- batch.watchdog.unref?.();
278
- }
279
- }
280
- catch (error) {
281
- this.hold(`Pi rejected Cotal dispatch: ${error instanceof Error ? error.message : String(error)}`);
282
- }
283
- }
284
- finalizeEnd(context) {
285
- if (this._state === "shuttingDown")
286
- return;
287
- if (this.overflowRetry)
288
- return;
289
- const confirmed = this.batches.filter((batch) => batch.confirmed);
290
- const ids = confirmed.flatMap((batch) => batch.ids);
291
- const committed = this.inbox.commitConfirmed(ids);
292
- this.batches = this.batches.filter((batch) => !batch.confirmed);
293
- if (committed.error) {
294
- this.hold(committed.error);
295
- return;
296
- }
297
- if (this.batches.length > 0) {
298
- this.hold("Pi ended before confirming a queued Cotal steer");
299
- return;
300
- }
301
- this._state = "idle";
302
- this.heldReason = undefined;
303
- this.pump();
304
- if (this._state === "idle")
305
- this.publishIdleWhenSettled(context);
306
- }
307
- hold(reason) {
308
- if (this._state === "shuttingDown")
309
- return;
310
- this._state = "held";
311
- this.heldReason = reason;
312
- this.clearWatchdogs();
313
- this.enqueuePresence("waiting", reason);
314
- if (this.context?.hasUI)
315
- this.context.ui.notify(`Cotal delivery held: ${reason}`, "warning");
316
- }
317
- publishIdleWhenSettled(context) {
318
- const check = () => {
319
- if (this._state !== "idle")
320
- return;
321
- if (this.context !== context)
322
- return;
323
- if (!context.isIdle()) {
324
- setTimeout(check, 10).unref?.();
325
- return;
326
- }
327
- this.enqueuePresence("idle");
328
- };
329
- check();
330
- }
331
- enqueuePresence(status, activity) {
332
- this.presence = this.presence
333
- .then(() => this.mesh.setStatus(status, activity))
334
- .catch(() => { });
335
- }
336
- clearWatchdogs() {
337
- for (const batch of this.batches) {
338
- if (batch.watchdog)
339
- clearTimeout(batch.watchdog);
340
- batch.watchdog = undefined;
341
- }
342
- }
343
- clearTimers() {
344
- this.clearWatchdogs();
345
- }
346
- }
347
- //# sourceMappingURL=driver.js.map
@@ -1 +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AAC,OAAO,KAAK,OAAO;gBAAE,OAAO;YACrC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;gBACtB,UAAU,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;gBAChC,OAAO;YACT,CAAC;YACD,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;QAC/B,CAAC,CAAC;QACF,KAAK,EAAE,CAAC;IACV,CAAC;IAEO,eAAe,CAAC,MAAsC,EAAE,QAAiB;QAC/E,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ;aAC1B,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;aACjD,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IACrB,CAAC;IAEO,cAAc;QACpB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjC,IAAI,KAAK,CAAC,QAAQ;gBAAE,YAAY,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;YACjD,KAAK,CAAC,QAAQ,GAAG,SAAS,CAAC;QAC7B,CAAC;IACH,CAAC;IAEO,WAAW;QACjB,IAAI,CAAC,cAAc,EAAE,CAAC;IACxB,CAAC;CACF"}
package/dist/extension.js DELETED
@@ -1,135 +0,0 @@
1
- import { basename, dirname } from "node:path";
2
- import { rmSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { MeshAgent, configFromEnv, hasIdentity, startControlServer, } from "@cotal-ai/connector-core";
5
- import { PiDriver } from "./driver.js";
6
- import { registerCotalTools } from "./tools.js";
7
- const CUSTOM_TYPE = "cotal-inbox";
8
- const RUNTIMES = Symbol.for("cotal.pi.runtimes");
9
- function runtimeMap() {
10
- const root = globalThis;
11
- return (root[RUNTIMES] ??= new Map());
12
- }
13
- function runtimeKey(config) {
14
- return `${config.space}\0${config.id ?? config.name}`;
15
- }
16
- function asContext(context) {
17
- return context;
18
- }
19
- function messageText(content) {
20
- if (typeof content === "string")
21
- return content;
22
- if (!Array.isArray(content))
23
- return String(content ?? "");
24
- return content
25
- .map((part) => (part && typeof part === "object" && "text" in part ? String(part.text ?? "") : ""))
26
- .filter(Boolean)
27
- .join("\n");
28
- }
29
- function wrapped(line) {
30
- return {
31
- invalidate() { },
32
- render(width) {
33
- const size = Math.max(16, width);
34
- const out = [];
35
- for (const source of line.split("\n")) {
36
- let rest = source;
37
- while (rest.length > size) {
38
- const whitespace = rest.lastIndexOf(" ", size);
39
- const cut = whitespace > size / 2 ? whitespace : size;
40
- out.push(rest.slice(0, cut));
41
- rest = rest.slice(cut).trimStart();
42
- }
43
- out.push(rest);
44
- }
45
- return out;
46
- },
47
- };
48
- }
49
- function cleanPersonaFile(runtime) {
50
- if (runtime.personaCleaned)
51
- return;
52
- runtime.personaCleaned = true;
53
- const file = process.env.COTAL_PI_PERSONA_FILE;
54
- if (!file)
55
- return;
56
- const dir = dirname(file);
57
- if (basename(file) !== "persona.md" || !basename(dir).startsWith("cotal-persona-") || dirname(dir) !== tmpdir())
58
- return;
59
- try {
60
- rmSync(dir, { recursive: true, force: true });
61
- }
62
- catch {
63
- // A pre-start crash can leave the OS-temp file behind; normal cleanup remains best-effort.
64
- }
65
- }
66
- function createRuntime(config) {
67
- const path = process.env.COTAL_CONTROL_SOCKET?.trim();
68
- const token = process.env.COTAL_CONTROL_TOKEN?.trim();
69
- if (Boolean(path) !== Boolean(token)) {
70
- throw new Error("pi connector: COTAL_CONTROL_SOCKET and COTAL_CONTROL_TOKEN must be provided together");
71
- }
72
- const mesh = new MeshAgent(config);
73
- const driver = new PiDriver(mesh);
74
- const runtime = {
75
- config,
76
- mesh,
77
- driver,
78
- personaCleaned: false,
79
- };
80
- mesh.on("incoming", () => driver.onIncoming());
81
- mesh.on("wake", () => driver.onWake());
82
- mesh.on("mention-wake", (item) => driver.onMentionWake(item));
83
- mesh.start();
84
- if (path && token) {
85
- runtime.controlServer = startControlServer(mesh, { path, token }, async () => ({ ok: false, error: "pi uses in-process lifecycle events; only shutdown is supported" }), { fatalBind: true, onShutdown: () => driver.requestShutdown() });
86
- }
87
- return runtime;
88
- }
89
- /** Load Cotal into the operator's Pi. With no mesh identity this extension is completely inert. */
90
- export default async function cotalMesh(pi) {
91
- if (!hasIdentity())
92
- return;
93
- if (typeof pi.sendMessage !== "function" || typeof pi.registerMessageRenderer !== "function" || typeof pi.on !== "function") {
94
- throw new Error("pi connector: this Pi version lacks the required custom-message lifecycle API (requires Pi 0.79.10)");
95
- }
96
- const config = configFromEnv();
97
- config.connector = "pi";
98
- const key = runtimeKey(config);
99
- const runtimes = runtimeMap();
100
- let runtime = runtimes.get(key);
101
- if (!runtime) {
102
- runtime = createRuntime(config);
103
- runtimes.set(key, runtime);
104
- }
105
- runtime.driver.bind(pi);
106
- registerCotalTools(pi, runtime.mesh, runtime.config);
107
- pi.registerMessageRenderer(CUSTOM_TYPE, (message) => wrapped(messageText(message.content)));
108
- pi.on("session_start", (_event, context) => {
109
- cleanPersonaFile(runtime);
110
- runtime.driver.onSessionStart(asContext(context));
111
- });
112
- pi.on("agent_start", (_event, context) => runtime.driver.onAgentStart(asContext(context)));
113
- pi.on("message_start", (event) => runtime.driver.onMessageStart(event.message));
114
- pi.on("context", (event) => runtime.driver.onContext(event.messages));
115
- pi.on("after_provider_response", (event) => runtime.driver.onProviderResponse(event.status));
116
- pi.on("tool_execution_start", (event) => runtime.driver.onToolStart(event.toolName));
117
- pi.on("tool_execution_end", () => runtime.driver.onToolEnd());
118
- pi.on("session_before_compact", (event) => runtime.driver.onBeforeCompact(event.reason, event.willRetry));
119
- pi.on("agent_end", (event, context) => runtime.driver.onAgentEnd(event.messages, asContext(context)));
120
- pi.on("session_shutdown", async (event) => {
121
- runtime.driver.onSessionShutdown();
122
- if (event.reason !== "quit")
123
- return;
124
- await runtime.driver.quit();
125
- try {
126
- runtime.controlServer?.close();
127
- }
128
- catch {
129
- // The server may already be closing after the manager's shutdown request.
130
- }
131
- await runtime.mesh.stop().catch(() => { });
132
- runtimes.delete(key);
133
- });
134
- }
135
- //# sourceMappingURL=extension.js.map