@agimon-ai/po-session 0.0.0-alpha.143 → 0.0.0-alpha.144

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.
@@ -75,6 +75,152 @@ var root_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineRoot)((pl
75
75
  }]
76
76
  }));
77
77
  //#endregion
78
+ //#region src/services/logbook/index.ts
79
+ /** The delivery kind of a logbook entry. Admission stores it and never prompts the coordinator. */
80
+ const LOGBOOK_KIND = "session-log";
81
+ /** ponytail: one fixed batch window; make it a setting only when a coordinator needs faster or slower wakes. */
82
+ const LOGBOOK_WAKE_DELAY_MS = 3e4;
83
+ const LEVELS = ["info", "blocked"];
84
+ const TEXT_MAX = 2e3;
85
+ const PAGE_MAX = 100;
86
+ const PAGE_DEFAULT = 20;
87
+ /** A settle entry is a glance at the outcome, not the whole answer. */
88
+ const SETTLE_EXCERPT_MAX = 300;
89
+ const WAKE_EXCERPT_MAX = 120;
90
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]+/gu;
91
+ function isRecord(value) {
92
+ return typeof value === "object" && value !== null && !Array.isArray(value);
93
+ }
94
+ function oneLine(text, max) {
95
+ return text.replace(CONTROL_CHARACTERS, " ").replace(/\s+/gu, " ").trim().slice(0, max).trim();
96
+ }
97
+ /** Validates `network.log` input at the namespace boundary. */
98
+ function parseLogInput(raw) {
99
+ if (!isRecord(raw)) throw new Error("Expected an object.");
100
+ if (Object.keys(raw).some((key) => key !== "text" && key !== "level")) throw new Error("Unknown operation field.");
101
+ if (typeof raw.text !== "string" || !raw.text.trim()) throw new Error("text must be non-empty text.");
102
+ if (raw.text.length > TEXT_MAX) throw new Error(`text must be at most ${TEXT_MAX} characters.`);
103
+ const level = raw.level ?? "info";
104
+ if (!LEVELS.includes(level)) throw new Error("level must be 'info' or 'blocked'.");
105
+ return {
106
+ text: raw.text.trim(),
107
+ level
108
+ };
109
+ }
110
+ /** Validates `network.logbook` input at the namespace boundary. */
111
+ function parseLogbookQuery(raw) {
112
+ if (raw === void 0) return {};
113
+ if (!isRecord(raw)) throw new Error("Expected an object.");
114
+ const known = [
115
+ "unread",
116
+ "sessionId",
117
+ "offset",
118
+ "limit"
119
+ ];
120
+ if (Object.keys(raw).some((key) => !known.includes(key))) throw new Error("Unknown operation field.");
121
+ if (raw.unread !== void 0 && typeof raw.unread !== "boolean") throw new Error("unread must be a boolean.");
122
+ if (raw.sessionId !== void 0 && (typeof raw.sessionId !== "string" || !raw.sessionId.trim())) throw new Error("sessionId must be non-empty text.");
123
+ for (const key of ["offset", "limit"]) if (raw[key] !== void 0 && (!Number.isSafeInteger(raw[key]) || raw[key] < 0)) throw new Error(`${key} must be a whole number of at least 0.`);
124
+ return {
125
+ ...raw.unread === void 0 ? {} : { unread: raw.unread },
126
+ ...raw.sessionId === void 0 ? {} : { sessionId: raw.sessionId.trim() },
127
+ ...raw.offset === void 0 ? {} : { offset: raw.offset },
128
+ ...raw.limit === void 0 ? {} : { limit: raw.limit }
129
+ };
130
+ }
131
+ /** Validates `network.markRead` input at the namespace boundary. */
132
+ function parseMarkReadInput(raw) {
133
+ if (!isRecord(raw) || Object.keys(raw).some((key) => key !== "ids")) throw new Error("Expected { ids }.");
134
+ if (!Array.isArray(raw.ids) || raw.ids.length > PAGE_MAX || raw.ids.some((id) => typeof id !== "string" || !id)) throw new Error(`ids must be at most ${PAGE_MAX} entry ids.`);
135
+ return raw.ids;
136
+ }
137
+ function entryOf(entry) {
138
+ return {
139
+ id: entry.deliveryId,
140
+ from: entry.senderKey,
141
+ ...entry.metadata.fromName === void 0 ? {} : { name: entry.metadata.fromName },
142
+ level: entry.metadata.logbook === "blocked" ? "blocked" : "info",
143
+ text: entry.prompt,
144
+ ...entry.metadata.at === void 0 ? {} : { at: entry.metadata.at },
145
+ read: entry.consumed
146
+ };
147
+ }
148
+ /** This session's logbook, newest first, one page at a time. */
149
+ async function readLogbook(delivery, query) {
150
+ const matching = (await delivery.inbox({
151
+ kind: LOGBOOK_KIND,
152
+ ...query.unread ? { consumed: false } : {}
153
+ })).filter((entry) => query.sessionId === void 0 || entry.senderKey === query.sessionId).reverse();
154
+ const offset = query.offset ?? 0;
155
+ const limit = Math.min(query.limit ?? PAGE_DEFAULT, PAGE_MAX);
156
+ return {
157
+ entries: matching.slice(offset, offset + limit).map(entryOf),
158
+ total: matching.length,
159
+ ...offset + limit < matching.length ? { nextOffset: offset + limit } : {}
160
+ };
161
+ }
162
+ /** Marks entries read. Returns how many were unread and now are. */
163
+ async function markLogbookRead(delivery, ids) {
164
+ const own = new Set((await delivery.inbox({
165
+ kind: LOGBOOK_KIND,
166
+ consumed: false
167
+ })).map((entry) => entry.deliveryId));
168
+ let marked = 0;
169
+ for (const id of ids) if (own.has(id) && await delivery.consume(id)) marked += 1;
170
+ return marked;
171
+ }
172
+ /** Unread blocked entries, oldest first, for the wake. */
173
+ async function unreadBlocked(delivery) {
174
+ return (await delivery.inbox({
175
+ kind: LOGBOOK_KIND,
176
+ consumed: false,
177
+ metadata: { logbook: "blocked" }
178
+ })).map(entryOf);
179
+ }
180
+ /**
181
+ * Gathers blocked entries for `delayMs`, then wakes the coordinator once for every one it has not
182
+ * been told about. Entries read in the meantime no longer wake it.
183
+ */
184
+ function createLogbookWake(options) {
185
+ const announced = /* @__PURE__ */ new Set();
186
+ let timer;
187
+ let closed = false;
188
+ const fire = async () => {
189
+ timer = void 0;
190
+ const fresh = (await options.unreadBlocked()).filter((entry) => !announced.has(entry.id));
191
+ if (closed || fresh.length === 0) return;
192
+ for (const entry of fresh) announced.add(entry.id);
193
+ const lines = fresh.map((entry) => `- ${JSON.stringify(entry.name ?? entry.from)} (${entry.from}): ${oneLine(entry.text, WAKE_EXCERPT_MAX)}`);
194
+ await options.wake(`Logbook: ${fresh.length} new blocked ${fresh.length === 1 ? "entry" : "entries"}.\n${lines.join("\n")}\nRead them with network.logbook({ unread: true }), act, then network.markRead({ ids }).`);
195
+ };
196
+ return {
197
+ note() {
198
+ if (closed || timer !== void 0) return;
199
+ timer = setTimeout(() => void fire().catch(options.onError), options.delayMs);
200
+ timer.unref?.();
201
+ },
202
+ close() {
203
+ closed = true;
204
+ if (timer !== void 0) clearTimeout(timer);
205
+ timer = void 0;
206
+ }
207
+ };
208
+ }
209
+ function messageText(content) {
210
+ if (typeof content === "string") return content;
211
+ if (!Array.isArray(content)) return "";
212
+ return content.map((part) => part?.type === "text" && typeof part.text === "string" ? part.text : "").join(" ");
213
+ }
214
+ /** The newest assistant text as one short line, for the automatic settle entry. */
215
+ async function lastAssistantText(session) {
216
+ for await (const entry of session.entriesNewestFirst({ type: "message" })) {
217
+ const message = entry.message;
218
+ if (message?.role !== "assistant") continue;
219
+ const text = oneLine(messageText(message.content), SETTLE_EXCERPT_MAX);
220
+ if (text !== "") return text;
221
+ }
222
+ }
223
+ //#endregion
78
224
  //#region src/services/networkNamespace/index.ts
79
225
  /** Messaging between sessions on this host and linked hosts, with Team intercom's send, ask, reply and pending. */
80
226
  function createNetworkNamespace(options) {
@@ -82,7 +228,7 @@ function createNetworkNamespace(options) {
82
228
  const { operations } = options;
83
229
  return {
84
230
  name: "network",
85
- summary: "Message sessions on this host and linked hosts: send, ask with a tracked reply, and answer questions.",
231
+ summary: "Message sessions on this host and linked hosts: send, ask with a tracked reply, answer questions, and keep a coordinator logbook.",
86
232
  portable: true,
87
233
  declarations: `declare const network: {
88
234
  list(): Promise<unknown>;
@@ -90,6 +236,15 @@ function createNetworkNamespace(options) {
90
236
  ${operations.ask ? "ask(input: { to: string; text: string }): Promise<{ requestId: string }>;" : ""}
91
237
  ${operations.reply ? "reply(input: { requestId: string; text: string }): Promise<unknown>;" : ""}
92
238
  ${operations.pending ? "pending(): Promise<{ requestId: string; from: string }[]>;" : ""}
239
+ ${operations.log ? `/** Append to your coordinator's logbook (hierarchy only, never a group). Only 'blocked' wakes it, batched. Empty to: no coordinator. */
240
+ log(input: { text: string; level?: 'info' | 'blocked' }): Promise<{ to: string[] }>;` : ""}
241
+ ${operations.logbook ? `/** Your own logbook as a coordinator, newest first. limit defaults to 20, at most 100. */
242
+ logbook(input?: { unread?: boolean; sessionId?: string; offset?: number; limit?: number }): Promise<{
243
+ entries: { id: string; from: string; name?: string; level: 'info' | 'blocked'; text: string; at?: string; read: boolean }[];
244
+ total: number;
245
+ nextOffset?: number;
246
+ }>;` : ""}
247
+ ${operations.markRead ? "markRead(input: { ids: string[] }): Promise<{ marked: number }>;" : ""}
93
248
  };`,
94
249
  bind(run) {
95
250
  if (run.sessionId !== options.sessionId) throw new Error("Network namespace belongs to another session.");
@@ -129,6 +284,21 @@ function createNetworkNamespace(options) {
129
284
  check();
130
285
  return require_type.detach(result);
131
286
  };
287
+ if (operations.log) methods.log = async (raw) => {
288
+ check();
289
+ const { text, level } = parseLogInput(raw);
290
+ return require_type.detach(await operations.log(text, level, signal));
291
+ };
292
+ if (operations.logbook) methods.logbook = async (raw) => {
293
+ check();
294
+ const result = await operations.logbook(parseLogbookQuery(raw), signal);
295
+ check();
296
+ return require_type.detach(result);
297
+ };
298
+ if (operations.markRead) methods.markRead = async (raw) => {
299
+ check();
300
+ return require_type.detach(await operations.markRead(parseMarkReadInput(raw), signal));
301
+ };
132
302
  return methods;
133
303
  }
134
304
  };
@@ -203,6 +373,11 @@ function createNodeSessionOperations(host, context, sessionId, remind) {
203
373
  self
204
374
  };
205
375
  };
376
+ const requireDelivery = () => {
377
+ const delivery = require_type.readPoSessionDelivery(context);
378
+ if (!delivery) throw new Error("Session delivery is unavailable.");
379
+ return delivery;
380
+ };
206
381
  return {
207
382
  async list(signal) {
208
383
  signal.throwIfAborted();
@@ -278,6 +453,34 @@ function createNodeSessionOperations(host, context, sessionId, remind) {
278
453
  from: entry.senderKey
279
454
  });
280
455
  return open;
456
+ },
457
+ async log(text, level, signal) {
458
+ signal.throwIfAborted();
459
+ const to = (host.context.sessionCommunication?.listPeers?.() ?? []).filter((peer) => peer.coordinator === true).map((peer) => peer.sessionId);
460
+ if (to.length === 0) return { to };
461
+ const delivery = requireDelivery();
462
+ const metadata = {
463
+ logbook: level,
464
+ fromName: name(),
465
+ at: (/* @__PURE__ */ new Date()).toISOString()
466
+ };
467
+ for (const recipient of to) await delivery.deliver({
468
+ deliveryId: `log:${sessionId}:${crypto.randomUUID()}`,
469
+ recipientKey: recipient,
470
+ kind: LOGBOOK_KIND,
471
+ prompt: text,
472
+ delivery: "followUp",
473
+ metadata
474
+ });
475
+ return { to };
476
+ },
477
+ async logbook(query, signal) {
478
+ signal.throwIfAborted();
479
+ return readLogbook(requireDelivery(), query);
480
+ },
481
+ async markRead(ids, signal) {
482
+ signal.throwIfAborted();
483
+ return { marked: await markLogbookRead(requireDelivery(), ids) };
281
484
  }
282
485
  };
283
486
  }
@@ -307,6 +510,21 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)((plug
307
510
  assertAvailable: () => pluginContext.signal.throwIfAborted()
308
511
  };
309
512
  const tool = agent.registerTool(require_type.createStartSessionTool(options));
513
+ let lastLogged;
514
+ const settled = agent.registerHook({
515
+ event: "agent_settled",
516
+ handle: async (_event, execution) => {
517
+ if (!options.operations.log) return;
518
+ try {
519
+ const text = await lastAssistantText(execution.session);
520
+ if (text === void 0 || text === lastLogged) return;
521
+ lastLogged = text;
522
+ await options.operations.log(text, "info", pluginContext.signal);
523
+ } catch (error) {
524
+ pluginContext.host.context.onNotice(`Logbook entry failed: ${String(error)}`);
525
+ }
526
+ }
527
+ });
310
528
  const eligibility = options.provenance() === _agimon_ai_po_core_hubChannel.COORDINATOR_SESSION_PROVENANCE ? void 0 : agent.registerToolRestriction({ excludedTools: [require_type.START_SESSION_TOOL_NAME] });
311
529
  const injection = owner.inject([_agimon_ai_po_core_codemode.PO_CODEMODE_SERVICE], (context) => {
312
530
  const codemode = (0, _agimon_ai_po_core_codemode.readPoCodemode)(context);
@@ -322,6 +540,7 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)((plug
322
540
  return async () => {
323
541
  await injection.dispose();
324
542
  eligibility?.dispose();
543
+ settled.dispose();
325
544
  tool.dispose();
326
545
  };
327
546
  },
@@ -373,12 +592,34 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)((plug
373
592
  fallback: fallbackAuthorization
374
593
  }) : void 0;
375
594
  let delivery;
595
+ const logbookWake = createLogbookWake({
596
+ delayMs: LOGBOOK_WAKE_DELAY_MS,
597
+ unreadBlocked: () => unreadBlocked(delivery.service),
598
+ wake: async (text) => {
599
+ const requestId = `logbook-wake:${agent.context.sessionId}:${crypto.randomUUID()}`;
600
+ if (!session.admitMessage) {
601
+ await session.admitPrompt(text, "followUp", void 0, requestId);
602
+ return;
603
+ }
604
+ await session.admitMessage({
605
+ type: INTERCOM_MESSAGE_TYPE,
606
+ text,
607
+ display: true,
608
+ details: intercomDetails("send", "Logbook", agent.context.sessionId, text, requestId)
609
+ }, "followUp", requestId);
610
+ },
611
+ onError: (error) => pluginContext.host.context.onNotice(`Logbook wake failed: ${String(error)}`)
612
+ });
376
613
  try {
377
614
  delivery = await require_type.provideSessionDeliveryService(context, {
378
615
  database: await sqlite.open(node_path.default.join(deliveryDirectory, `${agent.context.sessionId}.sqlite`), io),
379
616
  recipientKey: agent.context.sessionId,
380
617
  communication: peerCommunication,
381
618
  authorizePeer: (peerKey, metadata) => {
619
+ if (metadata?.logbook !== void 0) {
620
+ const peer = communication.describePeer?.(peerKey);
621
+ if (peer?.coordinator !== true && peer?.coordinated !== true) return false;
622
+ }
382
623
  const remote = require_type.parseRemoteSessionReference(peerKey);
383
624
  if (remote && !peers.current()?.peers.some((peer) => peer.hostId === remote.hostId)) return false;
384
625
  if (remote) {
@@ -388,6 +629,10 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)((plug
388
629
  return groupAuthorization ? groupAuthorization(peerKey, metadata) : fallbackAuthorization(peerKey);
389
630
  },
390
631
  admitPrompt: async (prompt, admission, requestId, metadata) => {
632
+ if (metadata.logbook !== void 0) {
633
+ if (metadata.logbook === "blocked") logbookWake.note();
634
+ return;
635
+ }
391
636
  if (!metadata.customType) {
392
637
  await session.admitPrompt(prompt, admission, void 0, requestId);
393
638
  return;
@@ -402,10 +647,12 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)((plug
402
647
  }
403
648
  });
404
649
  } catch (error) {
650
+ logbookWake.close();
405
651
  await bridge?.removeLocal(agent.context.sessionId);
406
652
  throw error;
407
653
  }
408
654
  const { service, close: closeDelivery } = delivery;
655
+ if ((await unreadBlocked(service)).length > 0) logbookWake.note();
409
656
  const unprovide = [];
410
657
  if (groups && selfReference && peerConfig) {
411
658
  const directory = require_type.createSessionDirectory({ authorizeDiscovery: (_caller, subject) => {
@@ -458,6 +705,7 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)((plug
458
705
  const unregister = registerSessionPeerInbox(agent.context.sessionId, (sourceKey, kind, payload) => service.receive?.(sourceKey, kind, payload));
459
706
  return async () => {
460
707
  unregister();
708
+ logbookWake.close();
461
709
  releaseGroups?.();
462
710
  await bridge?.removeLocal(agent.context.sessionId);
463
711
  for (const release of unprovide.reverse()) release();