@agimon-ai/po-session 0.0.0-alpha.21 → 0.0.0-alpha.210

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 (38) hide show
  1. package/LICENSE +21 -149
  2. package/README.md +47 -1
  3. package/dist/apiContracts.cjs +34 -2
  4. package/dist/apiContracts.cjs.map +1 -1
  5. package/dist/apiContracts.d.mts +2 -2
  6. package/dist/apiContracts.d.mts.map +1 -1
  7. package/dist/apiContracts.mjs +35 -2
  8. package/dist/apiContracts.mjs.map +1 -1
  9. package/dist/extensions/native.mjs +410 -0
  10. package/dist/extensions/native.mjs.map +1 -0
  11. package/dist/extensions/server.cjs +1661 -113
  12. package/dist/extensions/server.cjs.map +1 -1
  13. package/dist/extensions/server.d.mts.map +1 -1
  14. package/dist/extensions/server.mjs +1657 -109
  15. package/dist/extensions/server.mjs.map +1 -1
  16. package/dist/extensions/web.mjs +361 -0
  17. package/dist/extensions/web.mjs.map +1 -0
  18. package/dist/index.cjs +410 -25
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.mts +599 -82
  21. package/dist/index.d.mts.map +1 -1
  22. package/dist/index.mjs +358 -1
  23. package/dist/index.mjs.map +1 -0
  24. package/dist/po-runtime-identity.json +1 -0
  25. package/dist/type-BlbiS10p.mjs +2622 -0
  26. package/dist/type-BlbiS10p.mjs.map +1 -0
  27. package/dist/type-DZtqhE4a.cjs +3083 -0
  28. package/dist/type-DZtqhE4a.cjs.map +1 -0
  29. package/llms.txt +4 -1
  30. package/locales/vi.json +29 -0
  31. package/locales/zh-CN.json +29 -0
  32. package/package.json +96 -11
  33. package/src/prompts/codemode-how-to-network/SKILL.md +49 -0
  34. package/src/prompts/codemode-how-to-session/SKILL.md +25 -0
  35. package/dist/sessionDelivery-4svjzWUW.mjs +0 -1028
  36. package/dist/sessionDelivery-4svjzWUW.mjs.map +0 -1
  37. package/dist/sessionDelivery-CGWuQyLV.cjs +0 -1219
  38. package/dist/sessionDelivery-CGWuQyLV.cjs.map +0 -1
@@ -2,13 +2,920 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
- const require_sessionDelivery = require("../sessionDelivery-CGWuQyLV.cjs");
6
- let node_path = require("node:path");
7
- node_path = require_sessionDelivery.__toESM(node_path, 1);
5
+ const require_type = require("../type-DZtqhE4a.cjs");
6
+ let _agimon_ai_po_core_backgroundWork = require("@agimon-ai/po-core/backgroundWork");
7
+ let typebox = require("typebox");
8
+ let _agimon_ai_po_core_hubChannel = require("@agimon-ai/po-core/hubChannel");
9
+ let _agimon_ai_po_core_codemode = require("@agimon-ai/po-core/codemode");
10
+ let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
8
11
  let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
12
+ let node_path = require("node:path");
13
+ node_path = require_type.__toESM(node_path, 1);
9
14
  let _agimon_ai_po_core_piSettings = require("@agimon-ai/po-core/piSettings");
10
15
  let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
11
- let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
16
+ let _agimon_ai_po_approval = require("@agimon-ai/po-approval");
17
+ let _agimon_ai_po_core_contextContributions = require("@agimon-ai/po-core/contextContributions");
18
+ let _agimon_ai_po_core_locale = require("@agimon-ai/po-core/locale");
19
+ let _agimon_ai_po_core_remoteOrigin = require("@agimon-ai/po-core/remoteOrigin");
20
+ let _agimon_ai_po_core_packageApi = require("@agimon-ai/po-core/packageApi");
21
+ let _agimon_ai_po_core_pluginProtocol = require("@agimon-ai/po-core/pluginProtocol");
22
+ //#region src/services/childReportLedger/index.ts
23
+ const SCHEMA = `
24
+ CREATE TABLE IF NOT EXISTS child_reports (
25
+ report_key TEXT PRIMARY KEY,
26
+ child_session_id TEXT,
27
+ episode INTEGER,
28
+ parent_session_id TEXT NOT NULL,
29
+ workspace_id TEXT NOT NULL,
30
+ state TEXT NOT NULL,
31
+ steers INTEGER NOT NULL DEFAULT 0,
32
+ outcome TEXT,
33
+ text TEXT,
34
+ summary TEXT,
35
+ context_json TEXT,
36
+ revived_parent INTEGER NOT NULL DEFAULT 0,
37
+ admit_failures INTEGER NOT NULL DEFAULT 0,
38
+ reported_at INTEGER,
39
+ updated_at INTEGER NOT NULL
40
+ );
41
+ CREATE INDEX IF NOT EXISTS child_reports_child ON child_reports(child_session_id, episode);
42
+ CREATE INDEX IF NOT EXISTS child_reports_parent ON child_reports(parent_session_id, state);
43
+ `;
44
+ const TEXT_MAX = 4e3;
45
+ const LINE_MAX = 300;
46
+ const ADMIT_ATTEMPTS = 3;
47
+ const OUTCOMES = /* @__PURE__ */ new Set([
48
+ "done",
49
+ "blocked",
50
+ "failed",
51
+ "cancelled",
52
+ "interrupted"
53
+ ]);
54
+ function episodeKey(childSessionId, episode) {
55
+ return `episode:${childSessionId}:${episode}`;
56
+ }
57
+ function toEpisode(row) {
58
+ return row?.episode == null ? void 0 : {
59
+ episode: Number(row.episode),
60
+ state: row.state,
61
+ steers: Number(row.steers)
62
+ };
63
+ }
64
+ /** Bounded, one-line context fields. Unknown keys are dropped so a source cannot smuggle prompts in. */
65
+ function boundContext(context) {
66
+ const bounded = {};
67
+ for (const key of [
68
+ "source",
69
+ "title",
70
+ "eventId",
71
+ "occurrenceId",
72
+ "runKey",
73
+ "runId",
74
+ "failedJob",
75
+ "errorClass",
76
+ "error"
77
+ ]) if (typeof context?.[key] === "string") {
78
+ const value = require_type.oneLine(context[key], LINE_MAX);
79
+ if (value) bounded[key] = value;
80
+ }
81
+ return bounded;
82
+ }
83
+ function readContext(row) {
84
+ try {
85
+ return row.context_json ? JSON.parse(row.context_json) : {};
86
+ } catch {
87
+ return {};
88
+ }
89
+ }
90
+ function describeContext(context) {
91
+ const parts = [
92
+ context.source && context.title ? `${context.source} "${context.title}"` : context.source ?? context.title,
93
+ context.eventId && `event ${context.eventId}`,
94
+ context.runKey && `run ${context.runKey}${context.runId ? `/${context.runId}` : ""}`,
95
+ context.failedJob && `failed job ${context.failedJob}`,
96
+ context.errorClass && `error class ${context.errorClass}`,
97
+ context.error && `error: ${context.error}`
98
+ ].filter(Boolean);
99
+ return parts.length ? parts.join(", ") : void 0;
100
+ }
101
+ /** Host-scope ledger: one terminal report per child episode, delivered once to a revived-if-needed parent. */
102
+ async function createChildReportLedger(options) {
103
+ const { database, sessions, onNotice } = options;
104
+ const now = options.now ?? Date.now;
105
+ await database.exec(SCHEMA);
106
+ const sinks = /* @__PURE__ */ new Map();
107
+ const delivering = /* @__PURE__ */ new Map();
108
+ const staleOpen = /* @__PURE__ */ new Set();
109
+ let closed = false;
110
+ const findSession = (sessionId) => sessions.scopes?.().find((entry) => entry.sessionId === sessionId) ?? sessions.dormant?.().find((entry) => entry.sessionId === sessionId);
111
+ const latestEpisode = (childSessionId) => database.get("SELECT * FROM child_reports WHERE child_session_id = ? AND episode IS NOT NULL ORDER BY episode DESC LIMIT 1", childSessionId);
112
+ const markReported = async (row, outcome, text, extra) => {
113
+ const context = {
114
+ ...readContext(row),
115
+ ...boundContext(extra)
116
+ };
117
+ await database.run("UPDATE child_reports SET state = 'reported', outcome = ?, text = ?, context_json = ?, reported_at = ?, updated_at = ? WHERE report_key = ?", extra?.errorClass && row.outcome ? row.outcome : outcome, text.trim().slice(0, TEXT_MAX), JSON.stringify(context), now(), now(), row.report_key);
118
+ };
119
+ const setState = (keys, state) => Promise.all(keys.map((key) => database.run("UPDATE child_reports SET state = ?, revived_parent = 0, updated_at = ? WHERE report_key = ?", state, now(), key)));
120
+ const render = (rows) => rows.map((row) => {
121
+ const child = row.child_session_id ? findSession(row.child_session_id) : void 0;
122
+ const lines = [`${row.child_session_id ? `Child session ${child?.name ? `"${require_type.oneLine(child.name, 80)}" ` : ""}(${row.child_session_id})` : "A run you started"} ended: ${row.outcome ?? "interrupted"}.`];
123
+ if (row.text) lines.push(`Report: ${row.text}`);
124
+ if (row.summary) lines.push(row.summary);
125
+ const context = describeContext(readContext(row));
126
+ if (context) lines.push(`Context: ${context}`);
127
+ return lines.join("\n");
128
+ }).concat("Resolve any blocker it reports, or continue the work. To give the child more work, message it with network.send.").join("\n\n");
129
+ const deliverParent = async (parentSessionId) => {
130
+ const rows = await database.all("SELECT * FROM child_reports WHERE parent_session_id = ? AND state = 'reported' ORDER BY reported_at, rowid", parentSessionId);
131
+ if (!rows.length || closed) return;
132
+ const keys = rows.map((row) => row.report_key);
133
+ const workspaceId = rows[0].workspace_id;
134
+ const parent = findSession(parentSessionId);
135
+ if (!parent || parent.workspaceId && parent.workspaceId !== workspaceId) {
136
+ if (!parent && !sessions.directoryReady?.(workspaceId)) return;
137
+ await setState(keys, "unavailable");
138
+ onNotice(`A child session report could not reach its parent session ${parentSessionId}: it no longer exists.`);
139
+ return;
140
+ }
141
+ let revived = rows.some((row) => row.revived_parent === 1);
142
+ if (!sessions.isLive(parentSessionId)) {
143
+ if (revived || !sessions.revive) return;
144
+ const result = await sessions.revive(parentSessionId, { automatic: true });
145
+ if (result === "not_found") {
146
+ await setState(keys, "unavailable");
147
+ return;
148
+ }
149
+ if (result !== "revived") return;
150
+ revived = true;
151
+ for (const key of keys) await database.run("UPDATE child_reports SET revived_parent = 1 WHERE report_key = ?", key);
152
+ }
153
+ const sink = sinks.get(parentSessionId);
154
+ if (!sink || sink.workspaceId !== workspaceId) return;
155
+ let receipt;
156
+ try {
157
+ receipt = await sink.sink.admit({
158
+ type: _agimon_ai_po_core_hubChannel.PO_CHILD_REPORT_TYPE,
159
+ text: render(rows),
160
+ display: true,
161
+ details: {
162
+ notice: require_type.oneLine(`Child report · ${rows.map((row) => {
163
+ return `${(row.child_session_id ? findSession(row.child_session_id) : void 0)?.name ?? row.child_session_id ?? "run"} ${row.outcome ?? "interrupted"}`;
164
+ }).join(", ")}`, LINE_MAX),
165
+ reports: rows.map((row) => ({
166
+ key: row.report_key,
167
+ childSessionId: row.child_session_id ?? void 0,
168
+ outcome: row.outcome ?? "interrupted",
169
+ context: readContext(row)
170
+ }))
171
+ }
172
+ }, `child-report:${[...keys].sort().join(",")}`);
173
+ } catch (error) {
174
+ for (const key of keys) await database.run("UPDATE child_reports SET admit_failures = admit_failures + 1 WHERE report_key = ?", key);
175
+ if (Math.max(...rows.map((row) => Number(row.admit_failures))) + 1 === ADMIT_ATTEMPTS) onNotice(`A child session report is waiting for parent session ${parentSessionId}: ${require_type.oneLine(String(error), LINE_MAX)}`);
176
+ return;
177
+ }
178
+ await setState(keys, "delivered");
179
+ if (!revived) return;
180
+ const release = () => sessions.release?.(parentSessionId, { onlyIfIdle: true });
181
+ (receipt?.settled ?? Promise.resolve()).catch(() => void 0).then(release).catch((error) => onNotice(`Releasing revived parent session ${parentSessionId} failed: ${require_type.oneLine(String(error), LINE_MAX)}`));
182
+ };
183
+ const schedule = (parentSessionId) => {
184
+ const next = (delivering.get(parentSessionId) ?? Promise.resolve()).then(() => deliverParent(parentSessionId)).catch((error) => onNotice(`Child report delivery failed: ${require_type.oneLine(String(error), LINE_MAX)}`)).finally(() => {
185
+ if (delivering.get(parentSessionId) === next) delivering.delete(parentSessionId);
186
+ });
187
+ delivering.set(parentSessionId, next);
188
+ return next;
189
+ };
190
+ const sweep = async () => {
191
+ if (closed) return;
192
+ const open = await database.all("SELECT * FROM child_reports WHERE state = 'open'");
193
+ for (const row of open) {
194
+ const childSessionId = row.child_session_id;
195
+ if (sessions.isLive(childSessionId) || !sessions.directoryReady?.(row.workspace_id)) {
196
+ staleOpen.delete(row.report_key);
197
+ continue;
198
+ }
199
+ if (!staleOpen.has(row.report_key)) {
200
+ staleOpen.add(row.report_key);
201
+ continue;
202
+ }
203
+ staleOpen.delete(row.report_key);
204
+ const dormant = sessions.dormant?.().some((entry) => entry.sessionId === childSessionId);
205
+ await markReported(row, dormant ? "interrupted" : "cancelled", "", { errorClass: dormant ? "host_restart" : "child_closed" });
206
+ }
207
+ const parents = await database.all("SELECT DISTINCT parent_session_id FROM child_reports WHERE state = 'reported'");
208
+ await Promise.all(parents.map((row) => schedule(row.parent_session_id)));
209
+ };
210
+ const timer = options.sweepMs === 0 ? void 0 : setInterval(() => void sweep(), options.sweepMs ?? 15e3);
211
+ timer?.unref?.();
212
+ const ledger = {
213
+ async openEpisode(childSessionId) {
214
+ const child = sessions.scopes?.().find((entry) => entry.sessionId === childSessionId);
215
+ if (!child?.parentSessionId || !child.workspaceId) return void 0;
216
+ const latest = await latestEpisode(childSessionId);
217
+ if (latest?.state === "open") return toEpisode(latest);
218
+ const episode = Number(latest?.episode ?? 0) + 1;
219
+ await database.run("INSERT OR IGNORE INTO child_reports (report_key, child_session_id, episode, parent_session_id, workspace_id, state, updated_at) VALUES (?, ?, ?, ?, ?, 'open', ?)", episodeKey(childSessionId, episode), childSessionId, episode, child.parentSessionId, child.workspaceId, now());
220
+ return toEpisode(await latestEpisode(childSessionId));
221
+ },
222
+ async currentEpisode(childSessionId) {
223
+ return toEpisode(await latestEpisode(childSessionId));
224
+ },
225
+ async recordSteer(childSessionId, episode) {
226
+ const key = episodeKey(childSessionId, episode);
227
+ await database.run("UPDATE child_reports SET steers = steers + 1, updated_at = ? WHERE report_key = ? AND state = 'open'", now(), key);
228
+ const row = await database.get("SELECT steers FROM child_reports WHERE report_key = ?", key);
229
+ return Number(row?.steers ?? 0);
230
+ },
231
+ async reportFromChild({ childSessionId, outcome, text, fallback }) {
232
+ if (!OUTCOMES.has(outcome)) throw new TypeError(`Unknown child report outcome '${String(outcome)}'.`);
233
+ let row = await latestEpisode(childSessionId);
234
+ if (!row) {
235
+ await ledger.openEpisode(childSessionId);
236
+ row = await latestEpisode(childSessionId);
237
+ }
238
+ if (row?.state !== "open") return { duplicate: true };
239
+ await markReported(row, outcome, text, fallback);
240
+ schedule(row.parent_session_id);
241
+ return { duplicate: false };
242
+ },
243
+ async reportFromHost(input) {
244
+ if (!OUTCOMES.has(input.outcome)) throw new TypeError(`Unknown child report outcome '${String(input.outcome)}'.`);
245
+ const summary = require_type.oneLine(input.summary, LINE_MAX);
246
+ let row;
247
+ if (input.childSessionId) {
248
+ if (input.awaitChild) await ledger.openEpisode(input.childSessionId);
249
+ row = await latestEpisode(input.childSessionId);
250
+ if (row?.state === "open" && row.parent_session_id === input.parentSessionId) {
251
+ await database.run("UPDATE child_reports SET outcome = ?, summary = ?, context_json = ?, updated_at = ? WHERE report_key = ?", input.outcome, summary, JSON.stringify({
252
+ ...readContext(row),
253
+ ...boundContext(input.context)
254
+ }), now(), row.report_key);
255
+ return "merged";
256
+ }
257
+ if (row?.reported_at != null && input.unlessChildReportedSince !== void 0 && Number(row.reported_at) >= input.unlessChildReportedSince) return "skipped";
258
+ }
259
+ if (await database.get("SELECT report_key FROM child_reports WHERE report_key = ?", input.key)) return "skipped";
260
+ await database.run("INSERT INTO child_reports (report_key, child_session_id, episode, parent_session_id, workspace_id, state, outcome, summary, context_json, reported_at, updated_at) VALUES (?, ?, ?, ?, ?, 'reported', ?, ?, ?, ?, ?)", input.key, input.childSessionId ?? null, input.childSessionId ? Number(row?.episode ?? 0) + 1 : null, input.parentSessionId, input.workspaceId, input.outcome, summary, JSON.stringify(boundContext(input.context)), now(), now());
261
+ schedule(input.parentSessionId);
262
+ return "accepted";
263
+ },
264
+ attachParentSink(session, sink) {
265
+ const entry = {
266
+ workspaceId: session.workspaceId,
267
+ sink
268
+ };
269
+ sinks.set(session.sessionId, entry);
270
+ schedule(session.sessionId);
271
+ return () => {
272
+ if (sinks.get(session.sessionId) === entry) sinks.delete(session.sessionId);
273
+ };
274
+ },
275
+ sweep,
276
+ async close() {
277
+ closed = true;
278
+ if (timer) clearInterval(timer);
279
+ await Promise.allSettled(delivering.values());
280
+ await database.close();
281
+ }
282
+ };
283
+ return ledger;
284
+ }
285
+ //#endregion
286
+ //#region src/extensions/(backend)/root.server.ts
287
+ var root_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineRoot)((plugin) => ({
288
+ value: void 0,
289
+ services: [async (context) => {
290
+ await context.inject([
291
+ _agimon_ai_po_core_platform.PO_FS_SERVICE,
292
+ _agimon_ai_po_core_platform.PO_SQLITE_SERVICE,
293
+ _agimon_ai_po_core_serverPlugin.PO_SERVER_SCOPE_SERVICE
294
+ ], async (scoped) => {
295
+ const homeDirectory = plugin.host.context.homeDirectory;
296
+ if (!homeDirectory) throw new Error("Host links require an explicit host home directory.");
297
+ const environment = plugin.host.context.environment ?? {};
298
+ const peers = await require_type.createSessionPeers({
299
+ fs: (0, _agimon_ai_po_core_platform.requirePoFs)(scoped),
300
+ homeDirectory,
301
+ environment
302
+ });
303
+ await peers.identity();
304
+ const directory = node_path.default.join((0, _agimon_ai_po_core_piSettings.poHomeDirectory)(homeDirectory, environment), "session");
305
+ await require_type.ensurePrivateDirectory((0, _agimon_ai_po_core_platform.requirePoFs)(scoped), directory, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT);
306
+ const database = await (0, _agimon_ai_po_core_platform.requirePoSqlite)(scoped).open(node_path.default.join(directory, "groups.sqlite"), _agimon_ai_po_core_platform.BACKGROUND_CONTEXT);
307
+ const groups = await require_type.createSessionGroupStore({ database });
308
+ await database.run("DELETE FROM session_group_members WHERE group_id IN (SELECT group_id FROM session_groups WHERE owner_authority = 'session-group-bridge')");
309
+ await database.run("DELETE FROM session_groups WHERE owner_authority = 'session-group-bridge'");
310
+ const bridge = require_type.createSessionGroupBridge({
311
+ groups,
312
+ peers,
313
+ onError: (error) => plugin.host.context.onNotice(`Group bridge failed: ${String(error)}`),
314
+ send: async (hostId, advert) => {
315
+ const config = peers.current();
316
+ const peer = config?.peers.find((entry) => entry.hostId === hostId);
317
+ if (!config || !peer) return;
318
+ await require_type.authenticatedPeerPost({
319
+ config,
320
+ peer,
321
+ path: "/api/plugins/session-peer/control",
322
+ value: {
323
+ type: "groups",
324
+ groups: advert
325
+ }
326
+ });
327
+ }
328
+ });
329
+ const scope = (0, _agimon_ai_po_core_serverPlugin.requirePoServerScope)(scoped);
330
+ const releasePeers = plugin.host.scope === "host" ? await scope.provide(require_type.PO_SESSION_PEERS_CONTRACT, peers) : scoped.provide(require_type.PO_SESSION_PEERS_SERVICE, peers);
331
+ let releaseBridge;
332
+ try {
333
+ releaseBridge = plugin.host.scope === "host" ? await scope.provide(require_type.PO_SESSION_GROUP_BRIDGE_CONTRACT, bridge) : scoped.provide(require_type.PO_SESSION_GROUP_BRIDGE_SERVICE, bridge);
334
+ } catch (error) {
335
+ await Promise.resolve(releasePeers());
336
+ await bridge.close();
337
+ throw error;
338
+ }
339
+ const sessions = plugin.host.context.sessionService;
340
+ let releaseLedger = () => void 0;
341
+ if (plugin.host.scope === "host" && sessions) try {
342
+ const ledger = await createChildReportLedger({
343
+ database: await (0, _agimon_ai_po_core_platform.requirePoSqlite)(scoped).open(node_path.default.join(directory, "child-reports.sqlite"), _agimon_ai_po_core_platform.BACKGROUND_CONTEXT),
344
+ sessions,
345
+ onNotice: (text) => plugin.host.context.onNotice(text)
346
+ });
347
+ const releaseContract = await scope.provide(_agimon_ai_po_core_hubChannel.PO_CHILD_REPORT_CONTRACT, ledger).catch(async (error) => {
348
+ await ledger.close();
349
+ throw error;
350
+ });
351
+ releaseLedger = async () => {
352
+ await Promise.resolve(releaseContract());
353
+ await ledger.close();
354
+ };
355
+ } catch (error) {
356
+ await releaseBridge();
357
+ await Promise.resolve(releasePeers());
358
+ await bridge.close();
359
+ throw error;
360
+ }
361
+ return async () => {
362
+ await releaseLedger();
363
+ await releaseBridge();
364
+ await Promise.resolve(releasePeers());
365
+ await bridge.close();
366
+ };
367
+ });
368
+ }]
369
+ }));
370
+ const MAX_AGENT_RUN_TIMEOUT_MS = 72e5;
371
+ const POLL_MS = 1e3;
372
+ const NAME_MAX = 60;
373
+ const INPUT_KEYS = /* @__PURE__ */ new Set([
374
+ "task",
375
+ "systemPrompt",
376
+ "preset",
377
+ "modes",
378
+ "profile",
379
+ "domains",
380
+ "model",
381
+ "thinking",
382
+ "cwd",
383
+ "timeoutMs"
384
+ ]);
385
+ const LAST_CONTROL_CODE = 31;
386
+ const DELETE_CODE = 127;
387
+ function hasControl(text) {
388
+ for (let index = 0; index < text.length; index += 1) {
389
+ const code = text.charCodeAt(index);
390
+ if (code <= LAST_CONTROL_CODE || code === DELETE_CODE) return true;
391
+ }
392
+ return false;
393
+ }
394
+ /** A turn ended by these never produced a reply the caller can use. */
395
+ const UNFINISHED_STOPS = /* @__PURE__ */ new Set([
396
+ "error",
397
+ "aborted",
398
+ "toolUse"
399
+ ]);
400
+ /** A value that becomes a harness flag argument on Node: no leading dash, no control characters, bounded. */
401
+ function name(field, value, list = false) {
402
+ if (typeof value !== "string") throw new TypeError(`agent: ${field} must be a string.`);
403
+ const text = value.trim();
404
+ if (text === "" || text.length > _agimon_ai_po_core_hubChannel.MAX_LAUNCH_PROFILE_NAME_LENGTH || text.startsWith("-") || hasControl(text) || list && text.includes(",")) throw new TypeError(`agent: ${field} '${value.slice(0, 40)}' is not a valid name.`);
405
+ return text;
406
+ }
407
+ function names(field, value) {
408
+ if (!Array.isArray(value)) throw new TypeError(`agent: ${field} must be an array of names.`);
409
+ return [...new Set(value.map((entry) => name(field, entry, true)))];
410
+ }
411
+ /** Validates an agent run request at the trust boundary. Throws a TypeError naming the bad field. */
412
+ function parseAgentRunInput(value) {
413
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("agent: input must be an object with a task.");
414
+ const record = value;
415
+ for (const key of Object.keys(record)) {
416
+ if (key === "majorMode" || key === "minorModes") throw new TypeError(`agent: '${key}' is retired; use modes.`);
417
+ if (!INPUT_KEYS.has(key)) throw new TypeError(`agent: unknown field '${key}'.`);
418
+ }
419
+ const { task, systemPrompt, cwd, timeoutMs, profile } = record;
420
+ if (typeof task !== "string" || task.trim() === "") throw new TypeError("agent: task must be a non-empty string.");
421
+ if (systemPrompt !== void 0 && typeof systemPrompt !== "string") throw new TypeError("agent: systemPrompt must be a string.");
422
+ if (cwd !== void 0 && (typeof cwd !== "string" || !cwd.startsWith("/") || hasControl(cwd))) throw new TypeError("agent: cwd must be an absolute path.");
423
+ if (timeoutMs !== void 0 && (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 72e5)) throw new TypeError(`agent: timeoutMs must be an integer from 1 to ${MAX_AGENT_RUN_TIMEOUT_MS}.`);
424
+ return {
425
+ task,
426
+ ...systemPrompt === void 0 || systemPrompt === "" ? {} : { systemPrompt },
427
+ ...record.preset === void 0 ? {} : { preset: name("preset", record.preset) },
428
+ ...record.modes === void 0 ? {} : { modes: names("modes", record.modes) },
429
+ ...profile === void 0 ? {} : { profile: profile === null ? null : name("profile", profile) },
430
+ ...record.domains === void 0 ? {} : { domains: names("domains", record.domains) },
431
+ ...record.model === void 0 ? {} : { model: name("model", record.model) },
432
+ ...record.thinking === void 0 ? {} : { thinking: name("thinking", record.thinking) },
433
+ ...cwd === void 0 ? {} : { cwd },
434
+ timeoutMs: timeoutMs ?? 6e5
435
+ };
436
+ }
437
+ /** Same request, same hash: the parsed input with its keys in a fixed order, so `profile: null` and unset differ. */
438
+ async function agentRunHash(input) {
439
+ const ordered = Object.fromEntries([...INPUT_KEYS].filter((key) => key in input).map((key) => [key, input[key]]));
440
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(ordered)));
441
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
442
+ }
443
+ /** Over message entries newest first, the newest assistant message decides: a finished reply, an error or abort, or nothing usable. */
444
+ function finalReply(entries) {
445
+ for (const item of entries) {
446
+ const entry = item;
447
+ const message = entry?.type === "message" ? entry.message : void 0;
448
+ if (message?.role !== "assistant") continue;
449
+ const stop = typeof message.stopReason === "string" ? message.stopReason : "";
450
+ if (stop === "error") return {
451
+ status: "failed",
452
+ error: typeof message.errorMessage === "string" ? message.errorMessage : "The agent run failed."
453
+ };
454
+ if (stop === "aborted") return {
455
+ status: "stopped",
456
+ error: "The agent run was stopped."
457
+ };
458
+ if (UNFINISHED_STOPS.has(stop)) return void 0;
459
+ const content = message.content;
460
+ const text = (typeof content === "string" ? content : Array.isArray(content) ? content.filter((part) => part?.type === "text" && typeof part.text === "string").map((part) => part.text).join("") : "").trim();
461
+ return text === "" ? void 0 : {
462
+ status: "completed",
463
+ text
464
+ };
465
+ }
466
+ }
467
+ function selectionOf(input) {
468
+ const selection = {
469
+ ...input.preset === void 0 ? {} : { preset: input.preset },
470
+ ...input.modes === void 0 ? {} : { modes: input.modes },
471
+ ...input.profile === void 0 ? {} : { profile: input.profile },
472
+ ...input.domains === void 0 ? {} : { domains: input.domains }
473
+ };
474
+ return Object.keys(selection).length === 0 ? void 0 : selection;
475
+ }
476
+ function errorText(error) {
477
+ return error instanceof Error ? error.message : String(error);
478
+ }
479
+ /** Settles with `work`, or rejects once `signal` aborts; no timer or listener outlives it. */
480
+ function until(work, signal) {
481
+ if (signal.aborted) return Promise.reject(signal.reason);
482
+ let stop = () => void 0;
483
+ const aborted = new Promise((_resolve, reject) => {
484
+ stop = () => reject(signal.reason);
485
+ signal.addEventListener("abort", stop, { once: true });
486
+ });
487
+ return Promise.race([work, aborted]).finally(() => signal.removeEventListener("abort", stop));
488
+ }
489
+ function pause(ms, signal) {
490
+ let timer;
491
+ return until(new Promise((resolve) => {
492
+ timer = setTimeout(resolve, ms);
493
+ }), signal).finally(() => clearTimeout(timer));
494
+ }
495
+ /**
496
+ * Runs tasks in unattended child sessions of one owning session. A child keeps the workflow-step provenance, so it
497
+ * stays out of the rail and reads like a step session once released.
498
+ */
499
+ function createAgentRunService(dependencies) {
500
+ const { sessionId: parentSessionId, sessions } = dependencies;
501
+ const pollMs = dependencies.pollMs ?? POLL_MS;
502
+ return { async run(raw, options = {}) {
503
+ const input = parseAgentRunInput(raw);
504
+ const hash = await agentRunHash(input);
505
+ const cwd = input.cwd ?? dependencies.cwd;
506
+ if (!sessions?.prompt || !sessions.readExecutionState || !sessions.readMessages || cwd === void 0) return {
507
+ status: "failed",
508
+ output: "",
509
+ error: "This host cannot run agent sessions."
510
+ };
511
+ const timeout = AbortSignal.timeout(input.timeoutMs);
512
+ const signal = AbortSignal.any([
513
+ dependencies.lifetime,
514
+ timeout,
515
+ ...options.signal === void 0 ? [] : [options.signal]
516
+ ]);
517
+ const owned = { parentSessionId };
518
+ let sessionId;
519
+ let result;
520
+ try {
521
+ const selection = selectionOf(input);
522
+ sessionId = (await sessions.create({
523
+ cwd,
524
+ name: `Agent: ${input.task.trim().split("\n", 1)[0].slice(0, NAME_MAX)}`,
525
+ parentSessionId,
526
+ sessionProvenance: _agimon_ai_po_core_hubChannel.WORKFLOW_STEP_SESSION_PROVENANCE,
527
+ interaction: "unattended",
528
+ ...selection === void 0 ? {} : { selection },
529
+ ...input.model === void 0 ? {} : { model: input.model },
530
+ ...input.thinking === void 0 ? {} : { thinking: input.thinking },
531
+ ...input.systemPrompt === void 0 ? {} : { appendSystemPrompt: input.systemPrompt },
532
+ signal
533
+ })).sessionId;
534
+ options.onStarted?.(sessionId, hash);
535
+ await until((await sessions.prompt(sessionId, input.task, {
536
+ ...owned,
537
+ signal
538
+ })).settled, signal);
539
+ for (;;) {
540
+ const state = await sessions.readExecutionState(sessionId, owned);
541
+ if (state.isIdle && !state.hasPendingMessages && !(state.backgroundWork?.items.some(_agimon_ai_po_core_backgroundWork.holdsSettledSession) ?? false) && ((await dependencies.approvals()?.unsettled(sessionId))?.length ?? 0) === 0) break;
542
+ await pause(pollMs, signal);
543
+ }
544
+ const reply = finalReply(await sessions.readMessages(sessionId, {
545
+ ...owned,
546
+ limit: 20
547
+ }));
548
+ result = reply === void 0 ? {
549
+ sessionId,
550
+ status: "failed",
551
+ output: "",
552
+ error: "The agent ended without a reply."
553
+ } : reply.status === "completed" ? {
554
+ sessionId,
555
+ status: "completed",
556
+ output: reply.text
557
+ } : {
558
+ sessionId,
559
+ status: reply.status,
560
+ output: "",
561
+ error: reply.error
562
+ };
563
+ } catch (error) {
564
+ result = {
565
+ ...sessionId === void 0 ? {} : { sessionId },
566
+ status: signal.aborted && !timeout.aborted ? "stopped" : "failed",
567
+ output: "",
568
+ error: timeout.aborted ? `The agent did not finish within ${input.timeoutMs}ms.` : errorText(error)
569
+ };
570
+ }
571
+ if (sessionId !== void 0) {
572
+ const child = sessionId;
573
+ const cleanup = async (step) => {
574
+ try {
575
+ await step();
576
+ } catch (error) {
577
+ dependencies.onError?.(error);
578
+ }
579
+ };
580
+ if (signal.aborted) await cleanup(() => sessions.abort?.(child, owned));
581
+ await cleanup(() => dependencies.approvals()?.abandon(child));
582
+ await cleanup(() => sessions.release?.(child, owned));
583
+ }
584
+ return result;
585
+ } };
586
+ }
587
+ const IDLE_DEBOUNCE_MS = 2e3;
588
+ const ERROR_MAX = 300;
589
+ /** The text a child gets when it idles without telling its parent how the work ended. */
590
+ function childReportSteerText(parentSessionId) {
591
+ return [
592
+ "Your parent session is waiting for the result of this work and has not heard from you.",
593
+ "If work remains, finish it first. Then report once, in code mode:",
594
+ `network.send({ to: '${parentSessionId}', terminal: true, outcome: 'done' | 'blocked' | 'failed', text: '<result, or the exact blocker and what you need>' })`
595
+ ].join("\n");
596
+ }
597
+ /** The newest assistant message's stop reason, to tell a model failure from a quiet stop. */
598
+ async function lastStop(session) {
599
+ for await (const entry of session.entriesNewestFirst({
600
+ type: "message",
601
+ limit: 20
602
+ })) {
603
+ const message = entry.message;
604
+ if (message?.role !== "assistant") continue;
605
+ return message.stopReason === "error" ? { error: require_type.oneLine(typeof message.errorMessage === "string" ? message.errorMessage : "Model error.", ERROR_MAX) } : {};
606
+ }
607
+ }
608
+ /**
609
+ * Child side of terminal reporting: holds the child live while its episode is open, and when it idles
610
+ * without reporting, reminds it (at most twice) before the host files a fallback report for it.
611
+ */
612
+ function createChildReportGate(options) {
613
+ const { sessionId, ledger } = options;
614
+ let holding = false;
615
+ let timer;
616
+ let closed = false;
617
+ const setHolding = (value) => {
618
+ if (holding === value) return;
619
+ holding = value;
620
+ options.onHoldChange();
621
+ };
622
+ const refresh = async () => {
623
+ const episode = await ledger.currentEpisode(sessionId);
624
+ if (!closed) setHolding(episode?.state === "open");
625
+ return episode;
626
+ };
627
+ const fallback = async (outcome, errorClass, text, error) => {
628
+ await ledger.reportFromChild({
629
+ childSessionId: sessionId,
630
+ outcome,
631
+ text: text ?? "",
632
+ fallback: {
633
+ errorClass,
634
+ ...error ? { error: require_type.oneLine(error, ERROR_MAX) } : {}
635
+ }
636
+ });
637
+ await refresh();
638
+ };
639
+ const check = async () => {
640
+ const session = options.session();
641
+ if (closed || !session) return;
642
+ const activity = await session.activity();
643
+ if (!activity.isIdle || activity.hasPendingMessages || options.otherWorkPending()) return;
644
+ const episode = await refresh();
645
+ if (closed || episode?.state !== "open") return;
646
+ const last = await require_type.lastAssistantText(session);
647
+ const stop = await lastStop(session);
648
+ if (stop?.error) return fallback("failed", "model_error", last, stop.error);
649
+ if (episode.steers >= 2 || !options.canSteer() || !session.admitMessage) return fallback("interrupted", "steer_cap", last);
650
+ const steer = await ledger.recordSteer(sessionId, episode.episode);
651
+ try {
652
+ await session.admitMessage({
653
+ type: _agimon_ai_po_core_hubChannel.PO_CHILD_REPORT_STEER_TYPE,
654
+ text: childReportSteerText(options.parentSessionId),
655
+ display: true,
656
+ details: {
657
+ episode: episode.episode,
658
+ steer
659
+ }
660
+ }, "followUp", `child-report-steer:${sessionId}:${episode.episode}:${steer}`);
661
+ } catch (error) {
662
+ await fallback("failed", "faulted", last, String(error));
663
+ }
664
+ };
665
+ const schedule = () => {
666
+ if (timer !== void 0) clearTimeout(timer);
667
+ timer = setTimeout(() => {
668
+ timer = void 0;
669
+ check().catch(options.onError);
670
+ }, options.delayMs ?? IDLE_DEBOUNCE_MS);
671
+ };
672
+ return {
673
+ get holding() {
674
+ return holding;
675
+ },
676
+ /** Restores the hold after a restart or reload, and checks a child that came back idle. */
677
+ async start() {
678
+ if ((await refresh())?.state === "open") schedule();
679
+ },
680
+ /** A run ended. The first one opens episode 1; an aborted run is the person's, so it is left alone. */
681
+ async settled(event) {
682
+ if (closed || event.aborted === true) return;
683
+ const episode = await ledger.currentEpisode(sessionId) ?? await ledger.openEpisode(sessionId);
684
+ if (closed) return;
685
+ setHolding(episode?.state === "open");
686
+ if (episode?.state === "open") schedule();
687
+ },
688
+ /** The child reported itself; drop the hold. */
689
+ refresh,
690
+ close() {
691
+ closed = true;
692
+ if (timer !== void 0) clearTimeout(timer);
693
+ timer = void 0;
694
+ }
695
+ };
696
+ }
697
+ //#endregion
698
+ //#region src/services/networkNamespace/index.ts
699
+ /** What a child may say about its own work. The host files `interrupted` itself. */
700
+ const CHILD_OUTCOMES = [
701
+ "done",
702
+ "blocked",
703
+ "failed",
704
+ "cancelled"
705
+ ];
706
+ /** `{ to, text, urgent?, terminal?, outcome? }`, validated at the namespace boundary. `urgent` exists only where the host has lanes. */
707
+ function parseSend(raw, lanes, terminal = false) {
708
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("Expected an object.");
709
+ const { urgent, terminal: isTerminal, outcome, ...rest } = raw;
710
+ if (urgent !== void 0 && !lanes) throw new Error("Unknown operation field.");
711
+ if (urgent !== void 0 && typeof urgent !== "boolean") throw new Error("urgent must be a boolean.");
712
+ if (!terminal && (isTerminal !== void 0 || outcome !== void 0)) throw new Error("Unknown operation field.");
713
+ if (isTerminal !== void 0 && typeof isTerminal !== "boolean") throw new Error("terminal must be a boolean.");
714
+ if (outcome !== void 0 && isTerminal !== true) throw new Error("outcome needs terminal: true.");
715
+ if (outcome !== void 0 && !CHILD_OUTCOMES.includes(outcome)) throw new Error(`outcome must be one of ${CHILD_OUTCOMES.join(", ")}.`);
716
+ const { to, text } = require_type.fields(rest, ["to", "text"]);
717
+ return {
718
+ to,
719
+ text,
720
+ urgent: urgent === true,
721
+ ...isTerminal === true ? { terminal: outcome ?? "done" } : {}
722
+ };
723
+ }
724
+ /** Records one outgoing message in the run, so a view of the exec call can show what was said and to whom. */
725
+ async function recorded(run, name, input, call) {
726
+ const started = Date.now();
727
+ const base = {
728
+ name,
729
+ tool: name,
730
+ args: typeof input === "object" && input !== null && !Array.isArray(input) ? { ...input } : {}
731
+ };
732
+ try {
733
+ const value = await call();
734
+ run.record?.({
735
+ ...base,
736
+ ok: true,
737
+ ms: Date.now() - started,
738
+ result: {
739
+ content: [{
740
+ type: "text",
741
+ text: JSON.stringify(value, null, 2) ?? ""
742
+ }],
743
+ details: value
744
+ }
745
+ });
746
+ return value;
747
+ } catch (error) {
748
+ const message = error instanceof Error ? error.message : String(error);
749
+ run.record?.({
750
+ ...base,
751
+ ok: false,
752
+ ms: Date.now() - started,
753
+ error: message,
754
+ result: { content: [{
755
+ type: "text",
756
+ text: message
757
+ }] }
758
+ });
759
+ throw error;
760
+ }
761
+ }
762
+ const OUT_OF_SCOPE = "Session is outside your communication scope.";
763
+ /** A session name long enough to recognise and short enough to fit the approval card title. */
764
+ const TITLE_NAME_MAX = 80;
765
+ const MESSAGE_PREVIEW_MAX = 300;
766
+ const TERMINAL_FIELDS = `; terminal?: boolean; outcome?: ${CHILD_OUTCOMES.map((outcome) => `'${outcome}'`).join(" | ")}`;
767
+ /**
768
+ * Asks the person before messaging a live session whose `@session:` mention expired when this session compacted.
769
+ * Every other target runs without asking: a live mention or a shared group passes, and anything else is refused.
770
+ */
771
+ function expiredMentionApproval(operations, verb, parse, t) {
772
+ return {
773
+ requirement: "human",
774
+ applies: (raw) => {
775
+ const to = raw?.to;
776
+ return typeof to === "string" && to !== "" && operations.mentionApprovalTarget?.(to) !== void 0;
777
+ },
778
+ resolve: ([raw]) => {
779
+ const { to, text, urgent } = parse(raw);
780
+ const target = operations.mentionApprovalTarget?.(to);
781
+ if (target === void 0) throw new Error(OUT_OF_SCOPE);
782
+ return [{
783
+ to: target.sessionId,
784
+ text,
785
+ ...urgent ? { urgent } : {}
786
+ }];
787
+ },
788
+ describe: (raw) => {
789
+ const { to, text } = parse(raw);
790
+ const name = operations.mentionApprovalTarget?.(to)?.name ?? to;
791
+ return {
792
+ source: t("session.approval.source", "Sessions"),
793
+ title: verb === "ask" ? t("session.approval.askAgain", "Let this session ask {name} again", { name: name.slice(0, TITLE_NAME_MAX) }) : t("session.approval.messageAgain", "Let this session message {name} again", { name: name.slice(0, TITLE_NAME_MAX) }),
794
+ summary: t("session.approval.restoreMention", "The earlier @session: mention expired when this session compacted. Approving restores access until the next compaction and delivers this message."),
795
+ details: [{
796
+ label: t("session.approval.session", "Session"),
797
+ value: name
798
+ }, {
799
+ label: t("session.approval.message", "Message"),
800
+ value: text.slice(0, MESSAGE_PREVIEW_MAX)
801
+ }]
802
+ };
803
+ }
804
+ };
805
+ }
806
+ /** Messaging between sessions on this host and linked hosts, with Team intercom's send, ask, reply and pending. */
807
+ function createNetworkNamespace(options) {
808
+ (0, _agimon_ai_po_core_codemode.assertCodemodeNamespaceName)("network");
809
+ const { operations, terminal } = options;
810
+ const t = options.translate ?? ((_key, fallback, vars) => (0, _agimon_ai_po_core_locale.formatMessage)(fallback, vars));
811
+ const parse = (raw) => parseSend(raw, operations.lanes === true, terminal !== void 0);
812
+ const parseAsk = (raw) => {
813
+ const { to, text } = require_type.fields(raw, ["to", "text"]);
814
+ return {
815
+ to,
816
+ text
817
+ };
818
+ };
819
+ return {
820
+ name: "network",
821
+ summary: "Message sessions on this host and linked hosts: send, ask with a tracked reply, answer questions, and keep a coordinator logbook.",
822
+ portable: true,
823
+ ...operations.mentionApprovalTarget === void 0 ? {} : { approval: {
824
+ send: expiredMentionApproval(operations, "message", parse, t),
825
+ ...operations.ask ? { ask: expiredMentionApproval(operations, "ask", parseAsk, t) } : {}
826
+ } },
827
+ declarations: `declare const network: {
828
+ list(): Promise<unknown>;
829
+ ${`${operations.lanes ? `/** Queued: arrives in one digest when the recipient's run ends. urgent joins its running turn. Both are budgeted per session. */
830
+ send(input: { to: string; text: string; urgent?: boolean${terminal ? TERMINAL_FIELDS : ""} }): Promise<unknown>;` : `send(input: { to: string; text: string${terminal ? TERMINAL_FIELDS : ""} }): Promise<unknown>;`}${terminal ? `\n /** terminal: true reports how your work for parent session '${terminal.parentSessionId}' ended, once per piece of work; to must be that parent. */` : ""}`}
831
+ ${operations.ask ? `/** Joins the recipient's running turn, so it spends the interrupt budget. The reply arrives later as a message. */
832
+ ask(input: { to: string; text: string }): Promise<{ requestId: string }>;` : ""}
833
+ ${operations.reply ? "reply(input: { requestId: string; text: string }): Promise<unknown>;" : ""}
834
+ ${operations.pending ? "pending(): Promise<{ requestId: string; from: string }[]>;" : ""}
835
+ ${operations.log ? `/** Append to your coordinator's logbook (hierarchy only, never a group). 'blocked' wakes it, batched; the host files your stop report itself. Empty to: no coordinator. */
836
+ log(input: { text: string; level?: 'info' | 'blocked' }): Promise<{ to: string[] }>;` : ""}
837
+ ${operations.logbook ? `/** Your own logbook as a coordinator, newest first. limit defaults to 20, at most 100. */
838
+ logbook(input?: { unread?: boolean; sessionId?: string; offset?: number; limit?: number }): Promise<{
839
+ entries: { id: string; from: string; name?: string; level: 'info' | 'blocked'; text: string; at?: string; read: boolean }[];
840
+ total: number;
841
+ nextOffset?: number;
842
+ }>;` : ""}
843
+ ${operations.markRead ? "markRead(input: { ids: string[] }): Promise<{ marked: number }>;" : ""}
844
+ };`,
845
+ bind(run) {
846
+ if (run.sessionId !== options.sessionId) throw new Error("Network namespace belongs to another session.");
847
+ const lifetime = new AbortController();
848
+ const signal = AbortSignal.any([run.signal, lifetime.signal]);
849
+ run.onDispose(() => lifetime.abort(/* @__PURE__ */ new Error("Network code-mode run is disposed.")));
850
+ const check = () => {
851
+ if (run.caller !== "main") throw new Error("Network operations require the main agent.");
852
+ signal.throwIfAborted();
853
+ options.assertAvailable();
854
+ };
855
+ const methods = Object.create(null);
856
+ methods.list = async () => {
857
+ check();
858
+ const result = await operations.list(signal);
859
+ check();
860
+ return require_type.detach(result);
861
+ };
862
+ methods.send = (raw) => recorded(run, "network.send", raw, async () => {
863
+ check();
864
+ const { to, text, urgent, terminal: outcome } = parse(raw);
865
+ if (outcome !== void 0 && terminal) {
866
+ if (to !== terminal.parentSessionId) throw new Error(`A terminal report goes to your parent session '${terminal.parentSessionId}' only.`);
867
+ const report = await terminal.report(outcome, text);
868
+ if (report) return {
869
+ to,
870
+ reported: true,
871
+ ...report.duplicate ? { duplicate: true } : {}
872
+ };
873
+ }
874
+ if (run.approvedCall !== void 0) operations.restoreMention?.(to);
875
+ const result = await (urgent ? operations.send(to, text, signal, { urgent }) : operations.send(to, text, signal));
876
+ const resolved = result?.to;
877
+ options.rearm?.(typeof resolved === "string" ? resolved : to);
878
+ return require_type.detach(result);
879
+ });
880
+ if (operations.ask) methods.ask = (raw) => recorded(run, "network.ask", raw, async () => {
881
+ check();
882
+ const { to, text } = parseAsk(raw);
883
+ if (run.approvedCall !== void 0) operations.restoreMention?.(to);
884
+ const result = await operations.ask(to, text, signal);
885
+ options.rearm?.(to);
886
+ return require_type.detach(result);
887
+ });
888
+ if (operations.reply) methods.reply = (raw) => recorded(run, "network.reply", raw, async () => {
889
+ check();
890
+ const { requestId, text } = require_type.fields(raw, ["requestId", "text"]);
891
+ return require_type.detach(await operations.reply(requestId, text, signal));
892
+ });
893
+ if (operations.pending) methods.pending = async () => {
894
+ check();
895
+ const result = await operations.pending(signal);
896
+ check();
897
+ return require_type.detach(result);
898
+ };
899
+ if (operations.log) methods.log = async (raw) => {
900
+ check();
901
+ const { text, level } = require_type.parseLogInput(raw);
902
+ return require_type.detach(await operations.log(text, level, signal));
903
+ };
904
+ if (operations.logbook) methods.logbook = async (raw) => {
905
+ check();
906
+ const result = await operations.logbook(require_type.parseLogbookQuery(raw), signal);
907
+ check();
908
+ return require_type.detach(result);
909
+ };
910
+ if (operations.markRead) methods.markRead = async (raw) => {
911
+ check();
912
+ return require_type.detach(await operations.markRead(require_type.parseMarkReadInput(raw), signal));
913
+ };
914
+ return methods;
915
+ }
916
+ };
917
+ }
918
+ //#endregion
12
919
  //#region src/services/peerInbox/index.ts
13
920
  const inboxes = /* @__PURE__ */ new Map();
14
921
  /**
@@ -28,94 +935,435 @@ async function deliverSessionPeerEnvelope(targetSessionId, sourceKey, type, payl
28
935
  }
29
936
  //#endregion
30
937
  //#region src/extensions/workspaces/sessions/(backend)/root.server.ts
938
+ /** How much of its own work a session is reminded of at the end of a peer's message. */
939
+ const WORK_ANCHOR_MAX = 800;
940
+ /** The outbox record of a session this one started, so it counts as engaged with it. */
941
+ const ENGAGE_KIND = "session-engage";
942
+ /** Admits an intercom notice into the session itself, to be read when its run ends. */
943
+ async function remindSession(agent, text, requestId, details) {
944
+ const session = agent.context.session;
945
+ if (session?.admitMessage) await session.admitMessage({
946
+ type: require_type.INTERCOM_MESSAGE_TYPE,
947
+ text,
948
+ display: true,
949
+ details
950
+ }, "followUp", requestId);
951
+ else await session?.admitPrompt?.(text, "followUp", void 0, requestId);
952
+ }
31
953
  var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)((pluginContext) => ({
32
954
  value: void 0,
33
- services: [require_sessionDelivery.provideBackgroundWorkService, async (context) => {
34
- const agent = pluginContext.agent;
35
- const session = agent?.context.session;
36
- const communication = pluginContext.host.context.sessionCommunication;
37
- const homeDirectory = pluginContext.host.context.homeDirectory;
38
- const sessionService = pluginContext.host.context.sessionService;
39
- if (!agent || !session?.admitPrompt || !communication || !homeDirectory || !sessionService?.canCommunicate) throw new Error("Session delivery requires the headless agent, authenticated session communication, host home directory, and communication policy.");
40
- const fs = (0, _agimon_ai_po_core_platform.requirePoFs)(pluginContext.context);
41
- const sqlite = (0, _agimon_ai_po_core_platform.requirePoSqlite)(pluginContext.context);
42
- const io = _agimon_ai_po_core_platform.BACKGROUND_CONTEXT;
43
- const sessionDirectory = node_path.default.join((0, _agimon_ai_po_core_piSettings.poHomeDirectory)(homeDirectory), "session");
44
- const deliveryDirectory = node_path.default.join(sessionDirectory, "delivery");
45
- await require_sessionDelivery.ensurePrivateDirectory(fs, deliveryDirectory, io);
46
- const peerConfig = await require_sessionDelivery.readSessionPeerConfigAsync(fs, homeDirectory, io);
47
- const peerCommunication = require_sessionDelivery.createPeerCommunication({
48
- local: communication,
49
- config: peerConfig
50
- });
51
- const remotePeerIsGranted = (peerKey) => {
52
- const peer = require_sessionDelivery.parseRemoteSessionReference(peerKey);
53
- return peer !== void 0 && peerConfig?.peers.some((candidate) => candidate.hostId === peer.hostId && candidate.allowedSessionIds.includes(agent.context.sessionId)) === true;
54
- };
55
- const fallbackAuthorization = (peerKey) => sessionService.canCommunicate?.(agent.context.sessionId, peerKey) === true || remotePeerIsGranted(peerKey);
56
- const groups = peerConfig ? await require_sessionDelivery.createSessionGroupStore({ database: await sqlite.open(node_path.default.join(sessionDirectory, "groups.sqlite"), io) }) : void 0;
57
- const localHostId = peerConfig?.hostId;
58
- const selfReference = localHostId ? require_sessionDelivery.peerSessionReference(localHostId, agent.context.sessionId) : void 0;
59
- const groupAuthorization = groups && selfReference && localHostId ? require_sessionDelivery.createSessionGroupDeliveryAuthorizer({
60
- selfReference,
61
- groups,
62
- peerReference: (peerKey) => require_sessionDelivery.parseRemoteSessionReference(peerKey) === void 0 ? require_sessionDelivery.peerSessionReference(localHostId, peerKey) : peerKey,
63
- fallback: fallbackAuthorization
64
- }) : void 0;
65
- let delivery;
66
- try {
67
- delivery = await require_sessionDelivery.provideSessionDeliveryService(context, {
68
- database: await sqlite.open(node_path.default.join(deliveryDirectory, `${agent.context.sessionId}.sqlite`), io),
69
- recipientKey: agent.context.sessionId,
70
- communication: peerCommunication,
71
- authorizePeer: (peerKey, metadata) => groupAuthorization ? groupAuthorization(peerKey, metadata) : fallbackAuthorization(peerKey),
72
- admitPrompt: (prompt, admission, requestId) => session.admitPrompt(prompt, admission, void 0, requestId)
955
+ services: [
956
+ require_type.provideBackgroundWorkService,
957
+ (owner) => {
958
+ const agent = pluginContext.agent;
959
+ if (!agent) return;
960
+ const options = {
961
+ sessionId: agent.context.sessionId,
962
+ provenance: () => pluginContext.host.context.sessionContext?.provenance,
963
+ coordination: () => pluginContext.host.context.coordination,
964
+ started: async (sessionId) => {
965
+ try {
966
+ await require_type.readPoSessionDelivery(owner)?.record({
967
+ recipientKey: sessionId,
968
+ kind: ENGAGE_KIND
969
+ });
970
+ } catch (error) {
971
+ pluginContext.host.context.onNotice(`Engage record failed: ${String(error)}`);
972
+ }
973
+ },
974
+ operations: require_type.readSessionOperations(owner) ?? require_type.createNodeSessionOperations(pluginContext.host, owner, agent.context.sessionId, (text, requestId, details) => remindSession(agent, text, requestId, details)),
975
+ assertAvailable: () => pluginContext.signal.throwIfAborted()
976
+ };
977
+ const tool = agent.registerTool(require_type.createStartSessionTool(options));
978
+ let session = agent.context.session;
979
+ const stop = require_type.createStopReport({
980
+ delayMs: require_type.STOP_REPORT_DELAY_MS,
981
+ activity: async () => await session?.activity() ?? {
982
+ isIdle: false,
983
+ hasPendingMessages: false
984
+ },
985
+ holding: () => (0, _agimon_ai_po_core_backgroundWork.readPoBackgroundWorkService)(owner)?.snapshot().items.some(_agimon_ai_po_core_backgroundWork.holdsSettledSession) === true,
986
+ report: async () => {
987
+ if (!session || !options.operations.log) return;
988
+ const text = await require_type.lastAssistantText(session) ?? "No reply yet.";
989
+ await options.operations.log(text, require_type.STOP_LEVEL, pluginContext.signal);
990
+ },
991
+ onError: (error) => pluginContext.host.context.onNotice(`Stop report failed: ${String(error)}`)
73
992
  });
74
- } catch (error) {
75
- await groups?.close();
76
- throw error;
77
- }
78
- const { service, close: closeDelivery } = delivery;
79
- const unprovide = [];
80
- if (groups && selfReference && peerConfig) {
81
- const directory = require_sessionDelivery.createSessionDirectory({ authorizeDiscovery: async (caller, subject) => {
82
- const reference = require_sessionDelivery.peerSessionReference(subject.hostId, subject.sessionId);
83
- return (await groups.groupsFor(caller)).some((group) => group.members.includes(reference)) ? { capabilities: ["message"] } : void 0;
84
- } });
85
- for (const peer of peerConfig.peers) for (const sessionId of peer.allowedSessionIds) directory.observe({
86
- hostId: peer.hostId,
87
- sessionId,
88
- hostIncarnation: "unknown",
89
- sessionIncarnation: "unknown",
90
- sequence: 0,
91
- observedAt: 0,
92
- staleAfterMs: 0,
93
- deliveryTarget: require_sessionDelivery.peerSessionReference(peer.hostId, sessionId),
94
- reachability: "unknown",
95
- runtime: "unknown",
96
- activity: "unknown",
97
- voice: {
98
- eligible: "unknown",
99
- readiness: "unknown"
993
+ const settled = agent.registerHook((0, _agimon_ai_po_core_extensionFile.defineHook)({
994
+ name: "session-report-sustained-stop",
995
+ description: "Update the session snapshot and schedule a coordinator report when the session stays stopped.",
996
+ event: "agent_settled",
997
+ handle: (_event, execution) => {
998
+ session = execution.session;
999
+ stop.settled();
1000
+ }
1001
+ }));
1002
+ const eligibility = options.provenance() === _agimon_ai_po_core_hubChannel.COORDINATOR_SESSION_PROVENANCE ? void 0 : agent.registerToolRestriction({ excludedTools: [require_type.START_SESSION_TOOL_NAME] });
1003
+ const notice = (label) => (error) => pluginContext.host.context.onNotice(`${label}: ${String(error)}`);
1004
+ const sessionContext = pluginContext.host.context.sessionContext;
1005
+ const parentSessionId = (0, _agimon_ai_po_core_hubChannel.reportsToParent)(sessionContext) ? sessionContext?.parentSessionId : void 0;
1006
+ let ledger;
1007
+ let gate;
1008
+ const networkOptions = {
1009
+ ...options,
1010
+ ...parentSessionId ? { terminal: {
1011
+ parentSessionId,
1012
+ report: async (outcome, text) => {
1013
+ if (!ledger) return void 0;
1014
+ const result = await ledger.reportFromChild({
1015
+ childSessionId: options.sessionId,
1016
+ outcome,
1017
+ text
1018
+ });
1019
+ await gate?.refresh();
1020
+ return result;
1021
+ }
1022
+ } } : {},
1023
+ rearm: (to) => {
1024
+ const child = pluginContext.host.context.sessionService?.scopes?.().find((scope) => scope.sessionId === to || scope.name === to);
1025
+ if (!ledger || child?.parentSessionId !== options.sessionId) return;
1026
+ ledger.openEpisode(child.sessionId).catch(notice("Child report episode failed"));
100
1027
  }
1028
+ };
1029
+ const reporting = owner.inject([_agimon_ai_po_core_serverPlugin.PO_SERVER_SCOPE_SERVICE, _agimon_ai_po_core_backgroundWork.PO_BACKGROUND_WORK_SERVICE], (context) => {
1030
+ const resolved = (0, _agimon_ai_po_core_serverPlugin.requirePoServerScope)(context).resolve(_agimon_ai_po_core_hubChannel.PO_CHILD_REPORT_CONTRACT);
1031
+ if (!resolved) return;
1032
+ ledger = resolved;
1033
+ const releases = [];
1034
+ if (sessionContext?.workspaceId) {
1035
+ const attach = () => resolved.attachParentSink({
1036
+ sessionId: options.sessionId,
1037
+ workspaceId: sessionContext.workspaceId
1038
+ }, { admit: async (message, requestId) => {
1039
+ const current = session ?? agent.context.session;
1040
+ if (!current?.admitMessage) throw new Error("The session cannot admit a child report.");
1041
+ return await current.admitMessage(message, "followUp", requestId);
1042
+ } });
1043
+ let detachSink = attach();
1044
+ const ready = agent.registerHook((0, _agimon_ai_po_core_extensionFile.defineHook)({
1045
+ name: "session-reattach-child-report-sink",
1046
+ description: "Reattach the child report sink when the session is ready to admit waiting reports.",
1047
+ event: "session_ready",
1048
+ handle: () => {
1049
+ detachSink();
1050
+ detachSink = attach();
1051
+ }
1052
+ }));
1053
+ releases.push(() => {
1054
+ ready.dispose();
1055
+ detachSink();
1056
+ });
1057
+ }
1058
+ if (parentSessionId) {
1059
+ const work = (0, _agimon_ai_po_core_backgroundWork.readPoBackgroundWorkService)(context);
1060
+ let handle;
1061
+ const childGate = createChildReportGate({
1062
+ sessionId: options.sessionId,
1063
+ parentSessionId,
1064
+ ledger: resolved,
1065
+ session: () => session ?? agent.context.session,
1066
+ otherWorkPending: () => work?.snapshot(options.sessionId).items.some((item) => item.provider !== _agimon_ai_po_core_hubChannel.PO_CHILD_REPORT_WORK_PROVIDER && (0, _agimon_ai_po_core_backgroundWork.awaitsCompletion)(item)) === true,
1067
+ canSteer: () => (0, _agimon_ai_po_core_codemode.readPoCodemode)(context) !== void 0,
1068
+ onHoldChange: () => handle?.update(),
1069
+ onError: notice("Child report check failed")
1070
+ });
1071
+ gate = childGate;
1072
+ handle = work?.register({
1073
+ provider: _agimon_ai_po_core_hubChannel.PO_CHILD_REPORT_WORK_PROVIDER,
1074
+ listActiveWork: () => childGate.holding ? [{
1075
+ id: `terminal-report:${options.sessionId}`,
1076
+ sessionId: options.sessionId,
1077
+ label: "Reporting to parent"
1078
+ }] : []
1079
+ });
1080
+ const settledGate = agent.registerHook((0, _agimon_ai_po_core_extensionFile.defineHook)({
1081
+ name: "session-check-child-terminal-report",
1082
+ description: "Update the session snapshot and check whether the child can report completion to its parent.",
1083
+ event: "agent_settled",
1084
+ handle: (event, execution) => {
1085
+ session = execution.session;
1086
+ childGate.settled(event).catch(notice("Child report check failed"));
1087
+ }
1088
+ }));
1089
+ childGate.start().catch(notice("Child report check failed"));
1090
+ releases.push(() => {
1091
+ settledGate.dispose();
1092
+ childGate.close();
1093
+ handle?.dispose();
1094
+ if (gate === childGate) gate = void 0;
1095
+ });
1096
+ }
1097
+ return () => {
1098
+ for (const release of releases.reverse()) release();
1099
+ if (ledger === resolved) ledger = void 0;
1100
+ };
101
1101
  });
102
- unprovide.push(context.provide(require_sessionDelivery.PO_SESSION_INTERCOM_SERVICE, require_sessionDelivery.createSessionIntercom({
103
- selfReference,
104
- directory,
105
- groups,
106
- delivery: service
107
- })));
1102
+ const injection = owner.inject([_agimon_ai_po_core_codemode.PO_CODEMODE_SERVICE], (context) => {
1103
+ const codemode = (0, _agimon_ai_po_core_codemode.readPoCodemode)(context);
1104
+ const registration = codemode?.register("@agimon-ai/po-session", require_type.createSessionsNamespace(options));
1105
+ const network = codemode?.register("@agimon-ai/po-session", createNetworkNamespace({
1106
+ ...networkOptions,
1107
+ translate: (key, fallback, vars) => (0, _agimon_ai_po_core_locale.readPoLang)(context)?.t((0, _agimon_ai_po_core_locale.readPoPersonLocale)(context)?.read(), key, fallback, vars) ?? (0, _agimon_ai_po_core_locale.formatMessage)(fallback, vars)
1108
+ }));
1109
+ const restriction = registration ? agent.registerToolRestriction({ excludedTools: [require_type.START_SESSION_TOOL_NAME, ...options.operations.fallbackToolName ? [options.operations.fallbackToolName] : []] }) : void 0;
1110
+ return () => {
1111
+ restriction?.dispose();
1112
+ network?.dispose();
1113
+ registration?.dispose();
1114
+ };
1115
+ });
1116
+ return async () => {
1117
+ await injection.dispose();
1118
+ await reporting.dispose();
1119
+ eligibility?.dispose();
1120
+ settled.dispose();
1121
+ stop.close();
1122
+ tool.dispose();
1123
+ };
1124
+ },
1125
+ (owner) => {
1126
+ owner.inject([
1127
+ require_type.PO_SESSION_PEERS_SERVICE,
1128
+ require_type.PO_SESSION_GROUP_BRIDGE_SERVICE,
1129
+ _agimon_ai_po_core_platform.PO_FS_SERVICE,
1130
+ _agimon_ai_po_core_platform.PO_SQLITE_SERVICE
1131
+ ], async (context) => {
1132
+ const agent = pluginContext.agent;
1133
+ const session = agent?.context.session;
1134
+ const communication = pluginContext.host.context.sessionCommunication;
1135
+ const homeDirectory = pluginContext.host.context.homeDirectory;
1136
+ const sessionService = pluginContext.host.context.sessionService;
1137
+ if (!agent || !session?.admitPrompt || !communication || !homeDirectory || !sessionService?.canCommunicate) throw new Error("Session delivery requires the headless agent, authenticated session communication, host home directory, and communication policy.");
1138
+ const fs = (0, _agimon_ai_po_core_platform.requirePoFs)(context);
1139
+ const sqlite = (0, _agimon_ai_po_core_platform.requirePoSqlite)(context);
1140
+ const io = _agimon_ai_po_core_platform.BACKGROUND_CONTEXT;
1141
+ const sessionDirectory = node_path.default.join((0, _agimon_ai_po_core_piSettings.poHomeDirectory)(homeDirectory, pluginContext.host.context.environment ?? {}), "session");
1142
+ const deliveryDirectory = node_path.default.join(sessionDirectory, "delivery");
1143
+ await require_type.ensurePrivateDirectory(fs, deliveryDirectory, io);
1144
+ const peers = require_type.requireSessionPeers(context);
1145
+ const peerConfig = peers.current();
1146
+ const peerCommunication = require_type.createPeerCommunication({
1147
+ local: communication,
1148
+ config: () => peers.current(),
1149
+ canPublish: (target, type, payload) => {
1150
+ if (type === "po/session-delivery/ack") return true;
1151
+ const metadata = payload?.metadata;
1152
+ return bridge?.peersFor(agent.context.sessionId).some((peer) => peer.sessionId === target && peer.sharedGroups.some((name) => require_type.namedSessionGroupId(name) === metadata?.groupId)) === true;
1153
+ },
1154
+ onError: (error) => pluginContext.host.context.onNotice(`Peer delivery failed: ${String(error)}`)
1155
+ });
1156
+ const remotePeerIsGranted = (peerKey) => {
1157
+ const peer = require_type.parseRemoteSessionReference(peerKey);
1158
+ return peer !== void 0 && peers.current()?.peers.some((candidate) => candidate.hostId === peer.hostId && candidate.allowedSessionIds.includes(agent.context.sessionId)) === true;
1159
+ };
1160
+ const fallbackAuthorization = (peerKey) => sessionService.canCommunicate?.(agent.context.sessionId, peerKey) === true || remotePeerIsGranted(peerKey);
1161
+ const bridge = require_type.readSessionGroupBridge(context);
1162
+ const groups = bridge?.groups;
1163
+ await bridge?.updateLocal(agent.context.sessionId, communication.sessionName ?? agent.context.sessionId, communication.groups ?? []);
1164
+ const localHostId = peerConfig?.hostId;
1165
+ const selfReference = localHostId ? require_type.peerSessionReference(localHostId, agent.context.sessionId) : void 0;
1166
+ const groupAuthorization = groups && selfReference && localHostId ? require_type.createSessionGroupDeliveryAuthorizer({
1167
+ selfReference,
1168
+ groups,
1169
+ peerReference: (peerKey) => require_type.parseRemoteSessionReference(peerKey) === void 0 ? require_type.peerSessionReference(localHostId, peerKey) : peerKey,
1170
+ fallback: fallbackAuthorization
1171
+ }) : void 0;
1172
+ const authorizePeer = (peerKey, metadata) => {
1173
+ if (metadata?.logbook !== void 0) {
1174
+ const peer = communication.describePeer?.(peerKey);
1175
+ if (peer?.coordinator !== true && peer?.coordinated !== true) return false;
1176
+ }
1177
+ const remote = require_type.parseRemoteSessionReference(peerKey);
1178
+ if (remote && !peers.current()?.peers.some((peer) => peer.hostId === remote.hostId)) return false;
1179
+ if (remote) {
1180
+ if (!bridge?.metadataFor(agent.context.sessionId, peerKey) || !metadata?.groupId || !bridge?.peersFor(agent.context.sessionId).find((peer) => peer.sessionId === peerKey)?.sharedGroups.some((name) => require_type.namedSessionGroupId(name) === metadata.groupId)) return false;
1181
+ return groupAuthorization ? groupAuthorization(peerKey, metadata) : false;
1182
+ }
1183
+ return groupAuthorization ? groupAuthorization(peerKey, metadata) : fallbackAuthorization(peerKey);
1184
+ };
1185
+ /** What this session was working on, so a peer's message ends by pointing back at it. */
1186
+ const workAnchor = () => {
1187
+ const work = ((0, _agimon_ai_po_core_contextContributions.readPoContextContributions)(context)?.snapshot().entries ?? []).map((entry) => entry.text).join("\n").slice(0, WORK_ANCHOR_MAX).trim();
1188
+ return work === "" ? "" : `\n\nBack to your work:\n${work}`;
1189
+ };
1190
+ /** How the chat shows a digest this session receives, under the name of what gathered it. */
1191
+ const digestMetadata = (name) => (prompt, deliveryId) => ({
1192
+ customType: require_type.INTERCOM_MESSAGE_TYPE,
1193
+ customDetails: JSON.stringify(require_type.intercomDetails("send", name, agent.context.sessionId, prompt, deliveryId))
1194
+ });
1195
+ let digest;
1196
+ let logbookWake;
1197
+ let delivery;
1198
+ try {
1199
+ delivery = await require_type.provideSessionDeliveryService(context, {
1200
+ database: await sqlite.open(node_path.default.join(deliveryDirectory, `${agent.context.sessionId}.sqlite`), io),
1201
+ recipientKey: agent.context.sessionId,
1202
+ communication: peerCommunication,
1203
+ authorizePeer,
1204
+ admitPrompt: async (prompt, admission, requestId, metadata) => {
1205
+ if (metadata.logbook !== void 0) {
1206
+ if (metadata.logbook === "blocked" || metadata.logbook === "settled") logbookWake?.note();
1207
+ return;
1208
+ }
1209
+ if (metadata.lane === "queue") {
1210
+ digest?.note();
1211
+ return;
1212
+ }
1213
+ if (!metadata.customType) {
1214
+ await session.admitPrompt(prompt, admission, void 0, requestId);
1215
+ return;
1216
+ }
1217
+ if (!session.admitMessage) throw new Error("The session cannot admit a custom delivery.");
1218
+ await session.admitMessage({
1219
+ type: metadata.customType,
1220
+ text: prompt + workAnchor(),
1221
+ display: true,
1222
+ details: metadata.customDetails === void 0 ? void 0 : JSON.parse(metadata.customDetails)
1223
+ }, admission === "steer" ? "steer" : "followUp", requestId);
1224
+ },
1225
+ onUndeliverable: (entry, error) => {
1226
+ pluginContext.host.context.onNotice(`Session delivery ${entry.kind} from ${entry.senderKey} was not admitted: ${error instanceof Error ? error.message : String(error)}`);
1227
+ if (entry.kind === "session-undelivered" || entry.metadata.logbook !== void 0) return;
1228
+ const group = bridge?.metadataFor(agent.context.sessionId, entry.senderKey);
1229
+ delivery.service.deliver(require_type.undeliveredNotice(entry, communication.sessionName ?? agent.context.sessionId, group?.sourceReference ?? agent.context.sessionId, group)).catch((failure) => pluginContext.host.context.onNotice(`Undelivered notice failed: ${String(failure)}`));
1230
+ },
1231
+ onError: (error) => pluginContext.host.context.onNotice(`Session delivery failed: ${String(error)}`)
1232
+ });
1233
+ } catch (error) {
1234
+ await bridge?.removeLocal(agent.context.sessionId);
1235
+ throw error;
1236
+ }
1237
+ const { service, close: closeDelivery } = delivery;
1238
+ const inbox = require_type.createInboxDigest({
1239
+ delayMs: require_type.INBOX_DIGEST_DELAY_MS,
1240
+ delivery: service,
1241
+ sessionId: agent.context.sessionId,
1242
+ idle: async () => (await session.activity()).isIdle,
1243
+ authorized: (entry) => authorizePeer(entry.senderKey, entry.metadata),
1244
+ metadata: digestMetadata("Inbox"),
1245
+ onError: (error) => pluginContext.host.context.onNotice(`Inbox digest failed: ${String(error)}`)
1246
+ });
1247
+ digest = inbox;
1248
+ const settledInbox = agent.registerHook((0, _agimon_ai_po_core_extensionFile.defineHook)({
1249
+ name: "session-schedule-inbox-digest",
1250
+ description: "Schedule an inbox digest after a settled run unless the person aborted it.",
1251
+ event: "agent_settled",
1252
+ handle: async (event) => {
1253
+ if (event.aborted !== true) await inbox.settled();
1254
+ }
1255
+ }));
1256
+ const compacted = agent.registerHook((0, _agimon_ai_po_core_extensionFile.defineHook)({
1257
+ name: "session-expire-mention-grants",
1258
+ description: "Expire session mention grants and reauthorize delivery after compaction completes.",
1259
+ event: "session_compact",
1260
+ handle: (event) => {
1261
+ if (event.status !== "completed") return;
1262
+ sessionService.mentions?.expire(agent.context.sessionId);
1263
+ service.reauthorize?.().catch((error) => pluginContext.host.context.onNotice(`Delivery reauthorization failed: ${String(error)}`));
1264
+ }
1265
+ }));
1266
+ inbox.note();
1267
+ await require_type.rearmAskReminders(service, (text, requestId, details) => remindSession(agent, text, requestId, details), (error) => pluginContext.host.context.onNotice(`Ask reminder failed: ${String(error)}`));
1268
+ logbookWake = require_type.createLogbookWake({
1269
+ delayMs: require_type.LOGBOOK_WAKE_DELAY_MS,
1270
+ delivery: service,
1271
+ sessionId: agent.context.sessionId,
1272
+ peer: (sessionId) => communication.describePeer?.(sessionId),
1273
+ metadata: digestMetadata("Logbook"),
1274
+ onError: (error) => pluginContext.host.context.onNotice(`Logbook wake failed: ${String(error)}`)
1275
+ });
1276
+ logbookWake.note();
1277
+ const unprovide = [];
1278
+ if (groups && selfReference && peerConfig) {
1279
+ const directory = require_type.createSessionDirectory({ authorizeDiscovery: (_caller, subject) => {
1280
+ const reference = require_type.peerSessionReference(subject.hostId, subject.sessionId);
1281
+ return bridge?.peersFor(agent.context.sessionId).some((peer) => peer.sessionId === reference) ? { capabilities: ["message"] } : void 0;
1282
+ } });
1283
+ const observedHosts = /* @__PURE__ */ new Set();
1284
+ let sequence = 0;
1285
+ const observeRemote = () => {
1286
+ const remotePeers = bridge?.peersFor(agent.context.sessionId) ?? [];
1287
+ for (const peer of remotePeers) observedHosts.add(require_type.parseRemoteSessionReference(peer.sessionId).hostId);
1288
+ sequence += 1;
1289
+ for (const hostId of observedHosts) directory.replaceHostSnapshot(hostId, "linked", remotePeers.flatMap((peer) => {
1290
+ const remote = require_type.parseRemoteSessionReference(peer.sessionId);
1291
+ return remote.hostId !== hostId ? [] : [{
1292
+ hostId,
1293
+ sessionId: remote.sessionId,
1294
+ label: peer.name,
1295
+ hostIncarnation: "linked",
1296
+ sessionIncarnation: "live",
1297
+ sequence,
1298
+ observedAt: Date.now(),
1299
+ staleAfterMs: 12e4,
1300
+ deliveryTarget: peer.sessionId,
1301
+ reachability: "unknown",
1302
+ runtime: "unknown",
1303
+ activity: "unknown",
1304
+ voice: {
1305
+ eligible: "unknown",
1306
+ readiness: "unknown"
1307
+ }
1308
+ }];
1309
+ }));
1310
+ };
1311
+ observeRemote();
1312
+ unprovide.push(bridge.subscribe(() => {
1313
+ observeRemote();
1314
+ service.reauthorize?.().catch((error) => pluginContext.host.context.onNotice(`Delivery reauthorization failed: ${String(error)}`));
1315
+ }));
1316
+ unprovide.push(context.provide(require_type.PO_SESSION_INTERCOM_SERVICE, require_type.createSessionIntercom({
1317
+ selfReference,
1318
+ directory,
1319
+ groups,
1320
+ delivery: service
1321
+ })));
1322
+ }
1323
+ const releaseGroups = pluginContext.host.context.directEvents?.subscribe(_agimon_ai_po_core_hubChannel.PO_SESSION_ATTENTION_EVENT, agent.context.sessionId, () => {
1324
+ bridge?.updateLocal(agent.context.sessionId, communication.sessionName ?? agent.context.sessionId, communication.groups ?? []).catch((error) => pluginContext.host.context.onNotice(`Group update failed: ${String(error)}`));
1325
+ });
1326
+ const unregister = registerSessionPeerInbox(agent.context.sessionId, (sourceKey, kind, payload) => service.receive?.(sourceKey, kind, payload));
1327
+ return async () => {
1328
+ unregister();
1329
+ settledInbox.dispose();
1330
+ compacted.dispose();
1331
+ inbox.close();
1332
+ logbookWake?.close();
1333
+ releaseGroups?.();
1334
+ await bridge?.removeLocal(agent.context.sessionId);
1335
+ for (const release of unprovide.reverse()) release();
1336
+ await closeDelivery();
1337
+ };
1338
+ });
1339
+ },
1340
+ (owner) => {
1341
+ const sessionId = pluginContext.host.context.sessionId;
1342
+ if (sessionId === void 0) return;
1343
+ const lifetime = new AbortController();
1344
+ const binding = owner.inject([_agimon_ai_po_core_serverPlugin.PO_SERVER_SCOPE_SERVICE], async (context) => {
1345
+ const scope = (0, _agimon_ai_po_core_serverPlugin.requirePoServerScope)(context);
1346
+ const service = createAgentRunService({
1347
+ sessionId,
1348
+ cwd: pluginContext.host.context.cwd,
1349
+ sessions: pluginContext.host.context.sessionService,
1350
+ approvals: () => scope.resolve(_agimon_ai_po_approval.APPROVAL_ROOT_SERVICE),
1351
+ lifetime: lifetime.signal,
1352
+ onError: (error) => pluginContext.host.context.onNotice(`Agent run cleanup failed: ${String(error)}`)
1353
+ });
1354
+ return await scope.provide(_agimon_ai_po_core_hubChannel.PO_AGENT_RUN_CONTRACT, service);
1355
+ });
1356
+ return async () => {
1357
+ lifetime.abort(/* @__PURE__ */ new Error("The session that started this agent run closed."));
1358
+ await binding.dispose();
1359
+ };
108
1360
  }
109
- const unregister = registerSessionPeerInbox(agent.context.sessionId, (sourceKey, kind, payload) => service.receive?.(sourceKey, kind, payload));
110
- return async () => {
111
- unregister();
112
- for (const release of unprovide.reverse()) release();
113
- await closeDelivery();
114
- await groups?.close();
115
- };
116
- }]
1361
+ ]
117
1362
  }));
118
1363
  //#endregion
1364
+ //#region src/extensions/workspaces/sessions/(backend)/contract/agentRun.server.ts
1365
+ var agentRun_server_default = (0, _agimon_ai_po_core_extensionFile.defineServiceContract)(_agimon_ai_po_core_hubChannel.PO_AGENT_RUN_CONTRACT.name, _agimon_ai_po_core_hubChannel.PO_AGENT_RUN_CONTRACT);
1366
+ //#endregion
119
1367
  //#region src/services/peerInboxApi/index.ts
120
1368
  const MAX_BODY_BYTES = 65536;
121
1369
  const DELIVERY_TYPES = /* @__PURE__ */ new Set(["po/session-delivery/envelope", "po/session-delivery/ack"]);
@@ -128,33 +1376,125 @@ function createPeerInboxApi(platform) {
128
1376
  basePath: "session-peer",
129
1377
  start(context) {
130
1378
  const homeDirectory = context.homeDirectory;
1379
+ const environment = context.environment ?? {};
131
1380
  let opened;
1381
+ const channels = require_type.createSealedPeerChannels();
1382
+ let link;
1383
+ let announcing = false;
1384
+ const announce = () => {
1385
+ if (!link || announcing) return;
1386
+ announcing = true;
1387
+ link.announce().catch((error) => context.onNotice(`Peer URL announcement failed: ${String(error)}`)).finally(() => {
1388
+ announcing = false;
1389
+ });
1390
+ };
1391
+ let linking = false;
1392
+ const autoLink = () => {
1393
+ if (!link || linking) return;
1394
+ linking = true;
1395
+ link.auto().catch((error) => context.onNotice(`Automatic host link failed: ${String(error)}`)).finally(() => {
1396
+ linking = false;
1397
+ });
1398
+ };
1399
+ const timer = platform.peers && platform.origin ? setInterval(() => {
1400
+ open().then(announce).catch((error) => context.onNotice(`Host links could not start: ${String(error)}`));
1401
+ }, 1e3) : void 0;
1402
+ timer?.unref?.();
1403
+ const autoTimer = platform.peers && platform.origin && platform.hosts ? setInterval(() => {
1404
+ open().then(autoLink).catch((error) => context.onNotice(`Host links could not start: ${String(error)}`));
1405
+ }, 6e4) : void 0;
1406
+ autoTimer?.unref?.();
132
1407
  const open = () => opened ??= (async () => {
133
1408
  if (homeDirectory === void 0) return {
134
1409
  config: void 0,
135
1410
  replay: void 0
136
1411
  };
137
- const config = await require_sessionDelivery.readSessionPeerConfigAsync(platform.fs, homeDirectory, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT);
138
- const file = node_path.default.join(node_path.default.dirname(require_sessionDelivery.sessionPeerConfigPath(homeDirectory)), require_sessionDelivery.PEER_REPLAY_DATABASE_FILE);
139
- await require_sessionDelivery.ensurePrivateDirectory(platform.fs, node_path.default.dirname(file), _agimon_ai_po_core_platform.BACKGROUND_CONTEXT);
1412
+ const config = platform.peers ? platform.peers.current() : await require_type.readSessionPeerConfigAsync(platform.fs, homeDirectory, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT, environment);
1413
+ const file = node_path.default.join(node_path.default.dirname(require_type.sessionPeerConfigPath(homeDirectory, environment)), require_type.PEER_REPLAY_DATABASE_FILE);
1414
+ await require_type.ensurePrivateDirectory(platform.fs, node_path.default.dirname(file), _agimon_ai_po_core_platform.BACKGROUND_CONTEXT);
1415
+ const replay = await require_type.createPeerReplayGuardAsync(await platform.sqlite.open(file, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT));
1416
+ if (platform.peers) link = require_type.createPeerLink({
1417
+ peers: platform.peers,
1418
+ network: platform.network,
1419
+ hosts: platform.hosts,
1420
+ groups: platform.groups,
1421
+ replay,
1422
+ channels,
1423
+ origin: platform.origin ?? (() => void 0),
1424
+ fetch: platform.fetch
1425
+ });
1426
+ announce();
1427
+ autoLink();
140
1428
  return {
141
1429
  config,
142
- replay: await require_sessionDelivery.createPeerReplayGuardAsync(await platform.sqlite.open(file, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT))
1430
+ replay
143
1431
  };
144
1432
  })().catch((error) => {
145
1433
  opened = void 0;
146
1434
  throw error;
147
1435
  });
1436
+ if (platform.peers) open().catch((error) => context.onNotice(`Host links could not start: ${String(error)}`));
148
1437
  return {
149
1438
  async fetch(request) {
150
- if (request.method !== "POST" || new URL(request.url).pathname !== "/inbox") return response(404, "Not found.");
151
- const { config, replay } = await open();
152
- if (!config) return response(503, "Paired Session delivery is not configured.");
1439
+ const pathname = new URL(request.url).pathname;
1440
+ const openedState = await open();
1441
+ const config = platform.peers ? platform.peers.current() : openedState.config;
1442
+ const replay = openedState.replay;
1443
+ if (request.method === "GET" && pathname === "/links" && platform.peers) {
1444
+ if (!(0, _agimon_ai_po_core_packageApi.poApiCallerFrom)(request.headers)) return response(403, "An authenticated caller is required.");
1445
+ return Response.json({
1446
+ hostId: config?.hostId,
1447
+ peers: config?.peers.map(({ hostId, url, urlGeneration }) => ({
1448
+ hostId,
1449
+ url,
1450
+ urlGeneration
1451
+ })) ?? []
1452
+ });
1453
+ }
1454
+ if (request.method !== "POST" || ![
1455
+ "/inbox",
1456
+ "/control",
1457
+ "/link/prepare",
1458
+ "/link/accept",
1459
+ "/link/unlink",
1460
+ "/link/hint"
1461
+ ].includes(pathname)) return response(404, "Not found.");
153
1462
  const length = request.headers.get("content-length");
154
1463
  if (length !== null && (!/^\d+$/u.test(length) || Number(length) > MAX_BODY_BYTES)) return response(413, "Request body is too large.");
155
1464
  const body = await request.text();
156
1465
  if (Buffer.byteLength(body) > MAX_BODY_BYTES) return response(413, "Request body is too large.");
157
- const peer = require_sessionDelivery.verifyPeerRequest(config, request, body);
1466
+ if (pathname.startsWith("/link/")) {
1467
+ const caller = (0, _agimon_ai_po_core_packageApi.poApiCallerFrom)(request.headers);
1468
+ if (!caller || caller.locality === "remote" && pathname !== "/link/hint" && caller.stepUp !== "verified") return response(403, "Linking hosts needs a fresh peer.link step-up.");
1469
+ if (!link) return response(503, "Host links are unavailable.");
1470
+ try {
1471
+ const input = body === "" ? {} : JSON.parse(body);
1472
+ if (pathname === "/link/prepare") return Response.json(await link.prepare());
1473
+ if (pathname === "/link/accept") {
1474
+ await link.accept(input.invite);
1475
+ return Response.json({ linked: true });
1476
+ }
1477
+ if (typeof input.hostId !== "string") return response(400, "A host identity is required.");
1478
+ if (pathname === "/link/unlink") {
1479
+ await link.unlink(input.hostId);
1480
+ return Response.json({ unlinked: true });
1481
+ }
1482
+ if (typeof input.url !== "string") return response(400, "A URL hint is required.");
1483
+ return Response.json({ rebound: await link.hint(input.hostId, input.url) });
1484
+ } catch (error) {
1485
+ return response(400, error instanceof Error ? error.message : "Host link failed.");
1486
+ }
1487
+ }
1488
+ if (pathname === "/control") {
1489
+ if (!link) return response(503, "Host links are unavailable.");
1490
+ try {
1491
+ return await link.control(request, body);
1492
+ } catch (error) {
1493
+ return response(400, error instanceof Error ? error.message : "Invalid peer control.");
1494
+ }
1495
+ }
1496
+ if (!config) return response(503, "Paired Session delivery is not configured.");
1497
+ const peer = require_type.verifyPeerRequest(config, request, body);
158
1498
  if (!peer) return response(401, "Paired Session request is unauthorized.");
159
1499
  if (!await replay?.admit(request)) return response(409, "Paired Session request was already received.");
160
1500
  let parsed;
@@ -163,17 +1503,42 @@ function createPeerInboxApi(platform) {
163
1503
  } catch {
164
1504
  return response(400, "Paired Session request is malformed.");
165
1505
  }
166
- const envelope = require_sessionDelivery.parseSessionPeerEnvelope(parsed);
1506
+ let peerChannel;
1507
+ if (peer.linkGeneration) {
1508
+ const sealed = parsed;
1509
+ peerChannel = typeof sealed?.epochId === "string" ? channels.take(peer, sealed.epochId) : void 0;
1510
+ const opened = peerChannel?.open(sealed?.envelope);
1511
+ if (!opened?.ok) return response(401, "A fresh sealed peer channel is required.");
1512
+ try {
1513
+ parsed = JSON.parse(Buffer.from(opened.plaintext).toString("utf8"));
1514
+ } catch {
1515
+ return response(400, "Invalid sealed peer envelope.");
1516
+ }
1517
+ }
1518
+ const envelope = require_type.parseSessionPeerEnvelope(parsed);
167
1519
  if (!envelope || !DELIVERY_TYPES.has(envelope.type)) return response(400, "Paired Session envelope is invalid.");
168
- if (!peer.allowedSessionIds.includes(envelope.targetSessionId)) return response(403, "Peer is not granted this session.");
169
- const state = await deliverSessionPeerEnvelope(envelope.targetSessionId, require_sessionDelivery.peerSessionReference(peer.hostId, envelope.sourceSessionId), envelope.type, envelope.payload);
1520
+ if (!peer.linkGeneration && !peer.allowedSessionIds.includes(envelope.targetSessionId)) return response(403, "Peer is not granted this session.");
1521
+ const state = await deliverSessionPeerEnvelope(envelope.targetSessionId, require_type.peerSessionReference(peer.hostId, envelope.sourceSessionId), envelope.type, envelope.payload);
1522
+ if (state !== void 0 && peerChannel) {
1523
+ const sealed = peerChannel.seal(Buffer.from(JSON.stringify({
1524
+ accepted: true,
1525
+ state
1526
+ })));
1527
+ if (!sealed.ok) return response(503, "Peer acknowledgement could not be sealed.");
1528
+ const text = JSON.stringify(sealed.envelope);
1529
+ return new Response(text, { headers: require_type.peerRequestHeaders(config.hostId, peer, "RESPONSE", "/inbox", text) });
1530
+ }
170
1531
  return state === void 0 ? response(404, "Target Session is unavailable.") : Response.json({
171
1532
  accepted: true,
172
1533
  state
173
1534
  }, { status: 202 });
174
1535
  },
175
1536
  async close() {
176
- await (await opened?.catch(() => void 0))?.replay?.close();
1537
+ if (timer) clearInterval(timer);
1538
+ if (autoTimer) clearInterval(autoTimer);
1539
+ const state = await opened?.catch(() => void 0);
1540
+ link?.close();
1541
+ await state?.replay?.close();
177
1542
  }
178
1543
  };
179
1544
  }
@@ -181,33 +1546,216 @@ function createPeerInboxApi(platform) {
181
1546
  }
182
1547
  //#endregion
183
1548
  //#region src/extensions/(backend)/api/session-peer/route.server.ts
184
- var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)(({ context }) => createPeerInboxApi({
185
- fs: (0, _agimon_ai_po_core_platform.requirePoFs)(context),
186
- sqlite: (0, _agimon_ai_po_core_platform.requirePoSqlite)(context)
187
- }));
1549
+ var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)(({ context }) => {
1550
+ let origin;
1551
+ let network;
1552
+ let hosts;
1553
+ context.inject(["po/host-requests"], (scoped) => {
1554
+ hosts = scoped.get("po/host-requests");
1555
+ return () => {
1556
+ hosts = void 0;
1557
+ };
1558
+ });
1559
+ context.inject([require_type.PO_ROSTER_PEER_SERVICE], (scoped) => {
1560
+ network = scoped.get(require_type.PO_ROSTER_PEER_SERVICE);
1561
+ return () => {
1562
+ network = void 0;
1563
+ };
1564
+ });
1565
+ context.inject([_agimon_ai_po_core_remoteOrigin.PO_REMOTE_ORIGIN_SERVICE], (scoped) => {
1566
+ origin = scoped.get(_agimon_ai_po_core_remoteOrigin.PO_REMOTE_ORIGIN_SERVICE);
1567
+ return () => {
1568
+ origin = void 0;
1569
+ };
1570
+ });
1571
+ const hasOrigin = origin !== void 0;
1572
+ return createPeerInboxApi({
1573
+ fs: (0, _agimon_ai_po_core_platform.requirePoFs)(context),
1574
+ sqlite: (0, _agimon_ai_po_core_platform.requirePoSqlite)(context),
1575
+ peers: require_type.requireSessionPeers(context),
1576
+ network,
1577
+ hosts: () => hosts,
1578
+ groups: () => require_type.readSessionGroupBridge(context),
1579
+ ...hasOrigin ? { origin: () => origin?.current() } : {}
1580
+ });
1581
+ });
1582
+ //#endregion
1583
+ //#region src/schemas/sendToSession.ts
1584
+ /** The person's own words, steered into another live session and shown there as "From you, via <from>". */
1585
+ const sendToSessionMethod = (0, _agimon_ai_po_core_pluginProtocol.definePoPluginMethod)({
1586
+ service: "sessions",
1587
+ method: "sendToSession",
1588
+ scope: "host",
1589
+ direction: "client-to-server",
1590
+ input: typebox.Type.Object({
1591
+ /** The session whose composer the person typed in; it names the message, nothing more. */
1592
+ from: typebox.Type.String({ minLength: 1 }),
1593
+ to: typebox.Type.String({ minLength: 1 }),
1594
+ text: typebox.Type.String({
1595
+ minLength: 1,
1596
+ maxLength: 1e5
1597
+ })
1598
+ }, { additionalProperties: false }),
1599
+ output: typebox.Type.Object({
1600
+ to: typebox.Type.String(),
1601
+ name: typebox.Type.String()
1602
+ })
1603
+ });
1604
+ //#endregion
1605
+ //#region src/extensions/(backend)/_lib/sendToSession.server.ts
1606
+ /**
1607
+ * Steers the person's text into another live session, attributed to them. Each refusal reads as the
1608
+ * reason the dialog shows, because the text stays there for another try.
1609
+ */
1610
+ async function sendToSession(service, input) {
1611
+ const text = input.text.trim();
1612
+ if (text === "") throw new Error("Write something to send.");
1613
+ if (input.to === input.from) throw new Error("That is this session. Pick another one.");
1614
+ if (!service?.steer || !service.scopes) throw new Error("This host cannot deliver to another session.");
1615
+ const scopes = service.scopes();
1616
+ const target = scopes.find((scope) => scope.sessionId === input.to);
1617
+ if (target === void 0) throw new Error("That session is not running. Open it to wake it, then send again.");
1618
+ const name = target.name?.trim() || input.to;
1619
+ const via = scopes.find((scope) => scope.sessionId === input.from)?.name?.trim() || "another session";
1620
+ try {
1621
+ await service.steer(input.to, {
1622
+ text,
1623
+ sender: {
1624
+ kind: "human",
1625
+ name: `From you, via ${via}`
1626
+ }
1627
+ });
1628
+ } catch (error) {
1629
+ throw new Error(`${name} could not take the message: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1630
+ }
1631
+ return {
1632
+ to: input.to,
1633
+ name
1634
+ };
1635
+ }
1636
+ //#endregion
1637
+ //#region src/extensions/(backend)/method/send-to-session.server.ts
1638
+ var send_to_session_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)(({ host }) => host.scope === "host" ? (0, _agimon_ai_po_core_serverPlugin.defineServerMethod)(sendToSessionMethod, (input) => sendToSession(host.context.sessionService, input)) : void 0, { cardinality: "optional" });
1639
+ //#endregion
1640
+ //#region src/extensions/workspaces/sessions/(backend)/hook/before-agent-start.server.ts
1641
+ const BOT_AUTONOMY = `You are running as a bot session. Be proactive and work autonomously toward the person's goals. Make decisions yourself from the evidence and reasonable defaults; do not stop to ask whether to continue while useful, authorized work remains. When something fails, diagnose it and try bounded, reversible fixes before escalating. Ask the person only when you are blocked, when uncertainty is high enough that proceeding could cause harm or wasted work, or when explicit approval is required. When you ask, give the evidence, what you tried, and the exact decision needed, then keep doing unrelated authorized work while you wait. Never bypass approval or safety gates, and stop when the person says stop.`;
1642
+ var before_agent_start_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)({
1643
+ name: "bot-autonomy-guidance",
1644
+ description: "In bot sessions, append guidance to work autonomously and ask the person only on blockers or high uncertainty.",
1645
+ event: "before_agent_start",
1646
+ async handle({ systemPrompt }, execution) {
1647
+ if (await execution.isBotSession?.() !== true) return;
1648
+ return { systemPrompt: `${typeof systemPrompt === "string" ? systemPrompt : ""}\n\n${BOT_AUTONOMY}` };
1649
+ }
1650
+ });
1651
+ //#endregion
1652
+ //#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-network.server.ts
1653
+ var codemode_how_to_network_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)({
1654
+ name: "codemode-how-to-network",
1655
+ description: "Message sessions on this host and on linked hosts through the network namespace: send, ask with a tracked reply, and answer questions. Use for any message to another session.",
1656
+ kind: "skill",
1657
+ pinned: true,
1658
+ path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-network/SKILL.md"),
1659
+ read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-network/SKILL.md")
1660
+ });
1661
+ //#endregion
1662
+ //#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-session.server.ts
1663
+ var codemode_how_to_session_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)({
1664
+ name: "codemode-how-to-session",
1665
+ description: "List related sessions and start briefed independent work as a coordinator through the sessions namespace. No stop or delete capability.",
1666
+ kind: "skill",
1667
+ pinned: true,
1668
+ path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-session/SKILL.md"),
1669
+ read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-session/SKILL.md")
1670
+ });
188
1671
  //#endregion
189
1672
  //#region generated/server.ts
190
1673
  const at = (value, context) => typeof value === "function" ? value(context) : value;
1674
+ /* v8 ignore next -- generated normalization branch */
1675
+ const defined = (values) => values.filter((value) => value !== void 0);
1676
+ const via = (identity, value) => {
1677
+ if (value === void 0) return void 0;
1678
+ const declaration = value;
1679
+ return {
1680
+ ...identity,
1681
+ ...declaration,
1682
+ ...declaration.relations === void 0 ? {} : { relations: declaration.relations.map((relation) => ({
1683
+ evidence: "declared",
1684
+ ...relation
1685
+ })) }
1686
+ };
1687
+ };
191
1688
  const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
192
1689
  name: "@agimon-ai/po-session",
193
- providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default),
194
- injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({ session: [root_server_default] }),
195
- global: (context) => ({ get api() {
196
- return [at(route_server_default, context)];
197
- } }),
198
- workspace: (context) => ({ get api() {
199
- return [at(route_server_default, context)];
200
- } }),
1690
+ providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default$1, root_server_default),
1691
+ provides: { session: [agentRun_server_default] },
1692
+ injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({
1693
+ host: [root_server_default$1],
1694
+ workspace: [root_server_default$1],
1695
+ session: [root_server_default$1, root_server_default]
1696
+ }),
1697
+ host: async (context) => {
1698
+ const scopeHost = await context.scopeRoot("host", root_server_default$1, context);
1699
+ const contextHost = {
1700
+ ...context,
1701
+ root: scopeHost.value
1702
+ };
1703
+ return {
1704
+ ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeHost),
1705
+ get api() {
1706
+ return [at(route_server_default, contextHost)];
1707
+ },
1708
+ get methods() {
1709
+ return defined([at(send_to_session_server_default, contextHost)]);
1710
+ },
1711
+ services: [...scopeHost.services ?? []]
1712
+ };
1713
+ },
1714
+ workspace: async (context) => {
1715
+ const scopeHost = await context.scopeRoot("host", root_server_default$1, context);
1716
+ const contextHost = {
1717
+ ...context,
1718
+ root: scopeHost.value
1719
+ };
1720
+ return {
1721
+ ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeHost),
1722
+ get api() {
1723
+ return defined([context.hosted("host") ? void 0 : at(route_server_default, contextHost)]);
1724
+ },
1725
+ get methods() {
1726
+ return defined([context.hosted("host") ? void 0 : at(send_to_session_server_default, contextHost)]);
1727
+ },
1728
+ services: [...scopeHost.services ?? []]
1729
+ };
1730
+ },
201
1731
  session: async (context) => {
202
- const scopeSession = await context.scopeRoot("session", root_server_default, context);
1732
+ const scopeHost = await context.scopeRoot("host", root_server_default$1, context);
1733
+ const contextHost = {
1734
+ ...context,
1735
+ root: scopeHost.value
1736
+ };
1737
+ const scopeSession = await context.scopeRoot("session", root_server_default, contextHost);
1738
+ const contextSession = {
1739
+ ...contextHost,
1740
+ root: scopeSession.value
1741
+ };
203
1742
  return {
204
- ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeSession),
1743
+ ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeHost, scopeSession),
205
1744
  get api() {
206
- return [at(route_server_default, context)];
1745
+ return defined([context.hosted("host") ? void 0 : at(route_server_default, contextHost)]);
1746
+ },
1747
+ get hooks() {
1748
+ return [via({ event: "before_agent_start" }, at(before_agent_start_server_default, contextSession))];
1749
+ },
1750
+ get methods() {
1751
+ return defined([context.hosted("host") ? void 0 : at(send_to_session_server_default, contextHost)]);
1752
+ },
1753
+ get resources() {
1754
+ return [at(codemode_how_to_network_server_default, contextSession), at(codemode_how_to_session_server_default, contextSession)];
207
1755
  },
208
- services: [...scopeSession.services ?? []],
1756
+ services: [...scopeHost.services ?? [], ...scopeSession.services ?? []],
209
1757
  get activities() {
210
- return [...scopeSession.activities ?? []];
1758
+ return [...scopeHost.activities ?? [], ...scopeSession.activities ?? []];
211
1759
  }
212
1760
  };
213
1761
  }