@agimon-ai/po-wake 0.0.1-alpha.13 → 0.0.1-alpha.15

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.
@@ -6,10 +6,13 @@ const require_wakeRecords = require("../wakeRecords-CfkvJoto.cjs");
6
6
  let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
7
7
  let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
8
8
  let _agimon_ai_po_db = require("@agimon-ai/po-db");
9
+ let _agimon_ai_po_core_codemode = require("@agimon-ai/po-core/codemode");
9
10
  let _agimon_ai_po_core_locale = require("@agimon-ai/po-core/locale");
10
11
  let _agimon_ai_po_profile = require("@agimon-ai/po-profile");
11
12
  let _agimon_ai_po_core_headless = require("@agimon-ai/po-core/headless");
12
13
  let _agimon_ai_po_core_hubChannel = require("@agimon-ai/po-core/hubChannel");
14
+ let typebox_value = require("typebox/value");
15
+ let typebox = require("typebox");
13
16
  let _agimon_ai_po_core_help = require("@agimon-ai/po-core/help");
14
17
  //#region src/services/wakeAlarm/index.ts
15
18
  async function withWakeAlarm(_context, start) {
@@ -34,7 +37,7 @@ async function withWakeAlarm(_context, start) {
34
37
  }
35
38
  //#endregion
36
39
  //#region src/services/wakeDeadlines/index.ts
37
- const SELECT = "SELECT workspace_id AS workspaceId, session_id AS sessionId, slot, at, request_id AS requestId FROM po_wake_deadlines";
40
+ const SELECT = "SELECT workspace_id AS workspaceId, session_id AS sessionId, slot, at, request_id AS requestId, prompt, origin, profile FROM po_wake_deadlines";
38
41
  const KEY = "workspace_id = ? AND session_id = ? AND slot = ?";
39
42
  const key = (owner, slot) => [
40
43
  owner.workspaceId,
@@ -49,6 +52,22 @@ async function openWakeDeadlines(db) {
49
52
  workspace_id TEXT NOT NULL, session_id TEXT NOT NULL, slot TEXT NOT NULL CHECK (slot IN ('reminder', 'routine')),
50
53
  at INTEGER NOT NULL, request_id TEXT NOT NULL, PRIMARY KEY (workspace_id, session_id, slot)
51
54
  )`, "CREATE INDEX po_wake_deadlines_at ON po_wake_deadlines (at)"]
55
+ }, {
56
+ version: 2,
57
+ statements: [
58
+ `CREATE TABLE po_wake_deadlines_v2 (
59
+ workspace_id TEXT NOT NULL, session_id TEXT NOT NULL,
60
+ slot TEXT NOT NULL CHECK (slot IN ('reminder', 'routine', 'self')),
61
+ at INTEGER NOT NULL, request_id TEXT NOT NULL,
62
+ prompt TEXT, origin TEXT CHECK (origin IN ('agent', 'model')), profile TEXT,
63
+ PRIMARY KEY (workspace_id, session_id, slot)
64
+ )`,
65
+ `INSERT INTO po_wake_deadlines_v2 (workspace_id, session_id, slot, at, request_id)
66
+ SELECT workspace_id, session_id, slot, at, request_id FROM po_wake_deadlines`,
67
+ "DROP TABLE po_wake_deadlines",
68
+ "ALTER TABLE po_wake_deadlines_v2 RENAME TO po_wake_deadlines",
69
+ "CREATE INDEX po_wake_deadlines_at ON po_wake_deadlines (at)"
70
+ ]
52
71
  }]);
53
72
  const { database } = db;
54
73
  return {
@@ -56,7 +75,22 @@ async function openWakeDeadlines(db) {
56
75
  await database.run(`INSERT INTO po_wake_deadlines (workspace_id, session_id, slot, at, request_id) VALUES (?, ?, ?, ?, ?)
57
76
  ON CONFLICT (workspace_id, session_id, slot) ${preserve ? "DO NOTHING" : "DO UPDATE SET at = excluded.at, request_id = excluded.request_id"}`, ...key(owner, slot), at, requestId());
58
77
  },
78
+ /**
79
+ * Writes the one `self` wake. The bot's own plan always replaces it; a model plan never replaces the bot's,
80
+ * and that check lives in the one statement so a late model reply cannot win a race. True when written.
81
+ */
82
+ async plan(owner, plan) {
83
+ return await database.runCounted(`INSERT INTO po_wake_deadlines (workspace_id, session_id, slot, at, request_id, prompt, origin, profile)
84
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
85
+ ON CONFLICT (workspace_id, session_id, slot) DO UPDATE SET at = excluded.at, request_id = excluded.request_id,
86
+ prompt = excluded.prompt, origin = excluded.origin, profile = excluded.profile
87
+ ${plan.origin === "model" ? "WHERE po_wake_deadlines.origin = 'model'" : ""}`, ...key(owner, "self"), plan.at, requestId(), plan.prompt, plan.origin, plan.profile) > 0;
88
+ },
89
+ planned: (owner) => database.get(`${SELECT} WHERE ${KEY}`, ...key(owner, "self")),
90
+ dropModelPlan: (owner) => database.run(`DELETE FROM po_wake_deadlines WHERE ${KEY} AND origin = 'model'`, ...key(owner, "self")),
59
91
  cancel: (owner, slot) => database.run(`DELETE FROM po_wake_deadlines WHERE ${KEY}`, ...key(owner, slot)),
92
+ /** Every armed deadline of one session, for diagnostics. */
93
+ list: (owner) => database.all(`${SELECT} WHERE workspace_id = ? AND session_id = ? ORDER BY at`, owner.workspaceId, owner.sessionId),
60
94
  due: (at) => database.all(`${SELECT} WHERE at <= ? ORDER BY at, slot`, at),
61
95
  next: async () => (await database.get(`${SELECT} ORDER BY at LIMIT 1`))?.at,
62
96
  current: async (row) => !!await database.get(`${SELECT} WHERE ${KEY} AND request_id = ?`, ...key(row, row.slot), row.requestId),
@@ -173,6 +207,13 @@ function createWakeRootValue(scopes, onError, timer) {
173
207
  await timer?.store.cancel(owner, slot);
174
208
  await rearm();
175
209
  },
210
+ planned: async (owner) => disposed ? void 0 : await timer?.store.planned(owner),
211
+ async plan(owner, plan) {
212
+ if (disposed || !timer) return false;
213
+ const written = await timer.store.plan(owner, plan);
214
+ await rearm();
215
+ return written;
216
+ },
176
217
  async start() {
177
218
  const unsubscribe = timer?.alarm.onAlarm(drain);
178
219
  const stop = () => {
@@ -251,6 +292,10 @@ const WAKE_INTENT_TYPE = "po.wake-intent";
251
292
  const WAKE_RESULT_TYPE = "po.wake-result";
252
293
  const LEGACY_WAKE_INTENT_TYPE = "po.calendar-wake-intent";
253
294
  const LEGACY_WAKE_RESULT_TYPE = "po.calendar-wake-result";
295
+ /** Bounds for a planned `self` wake, shared by the scheduler and delivery. */
296
+ const SELF_WAKE_MIN_DELAY_MS = 3e5;
297
+ const SELF_WAKE_MAX_DELAY_MS = 6048e5;
298
+ const SELF_WAKE_MAX_PROMPT = 4e3;
254
299
  //#endregion
255
300
  //#region src/services/wake/index.ts
256
301
  const WAKE_ROUTINE_TYPE = "po.wake-routine";
@@ -328,6 +373,16 @@ function createWake(options) {
328
373
  return saved.available && !saved.entry ? await session.customSnapshot(legacy) : saved;
329
374
  };
330
375
  const dueRecords = (read) => read.records.filter((entry) => entry.due);
376
+ /** The earliest moment a not-yet-due record becomes due, so a routine can wake for it. */
377
+ const nextDueAt = (read) => {
378
+ const times = read.records.filter((entry) => !entry.due && typeof entry.dueAt === "number" && entry.dueAt > now()).map((entry) => entry.dueAt);
379
+ return times.length ? Math.min(...times) : void 0;
380
+ };
381
+ /** The pending `self` wake planned under the applied profile. A plan from another profile is dropped when it fires. */
382
+ const heldPlan = async () => {
383
+ const plan = await timer.planned();
384
+ return plan && (plan.profile ?? null) === (options.profile()?.profileName ?? null) ? plan : void 0;
385
+ };
331
386
  const routineKey = (due) => JSON.stringify(due.map((entry) => [
332
387
  entry.source,
333
388
  entry.title,
@@ -352,7 +407,9 @@ function createWake(options) {
352
407
  const saved = record(last.entry?.["data"]);
353
408
  const due = dueRecords(read);
354
409
  if (!due.length) {
355
- await timer.cancel("routine");
410
+ const next = nextDueAt(read);
411
+ if (next === void 0) await timer.cancel("routine");
412
+ else await timer.schedule("routine", next, preserve);
356
413
  return false;
357
414
  }
358
415
  const key = routineKey(due);
@@ -366,17 +423,46 @@ function createWake(options) {
366
423
  });
367
424
  return true;
368
425
  };
426
+ /** The bot's planned wake: no provider read and no coverage, since the bot chose this moment itself. */
427
+ const self = async (row, current, session, bot) => {
428
+ const live = liveFor(bot, fenceOf(options.profile()));
429
+ if ((row.profile ?? null) !== (options.profile()?.profileName ?? null)) return {};
430
+ const prompt = row.prompt?.trim().slice(0, SELF_WAKE_MAX_PROMPT);
431
+ if (!prompt) return {};
432
+ if (!live() || !await current() || !live()) return { retry: true };
433
+ const receipt = await session.admitMessage({
434
+ type: WAKE_NUDGE_TYPE,
435
+ text: [
436
+ prompt,
437
+ "",
438
+ GUIDANCE[1]
439
+ ].join("\n"),
440
+ display: true,
441
+ details: { origin: row.origin }
442
+ }, "followUp", row.requestId);
443
+ if (!receipt) return { retry: true };
444
+ if (live()) await timer.schedule("reminder", now() + horizonOf(bot));
445
+ return { settled: receipt.settled };
446
+ };
369
447
  const due = async (row, current) => {
370
448
  const bot = options.bot();
371
449
  if (!bot || signal.aborted) return { retry: true };
372
450
  const session = options.session();
373
451
  if (!session?.admitMessage || !session.customSnapshot) return { retry: true };
452
+ if (row.slot === "self") return self(row, current, session, bot);
374
453
  const live = liveFor(bot, fenceOf(options.profile()));
375
454
  const horizon = horizonOf(bot);
376
455
  const read = await readWakeRecords(options.providers(), now(), horizon);
377
456
  if (!live() || read.status !== "ok" || read.records.length > MAX_RECORDS || !await current()) return { retry: true };
378
457
  const routines = dueRecords(read);
379
- if (row.slot === "routine" && !routines.length) return {};
458
+ if (row.slot === "routine" && !routines.length) {
459
+ const next = nextDueAt(read);
460
+ return next === void 0 ? {} : { nextAt: next };
461
+ }
462
+ if (row.slot === "reminder") {
463
+ const plan = await heldPlan();
464
+ if (plan) return { nextAt: Math.max(now(), plan.at) + horizon };
465
+ }
380
466
  if (read.records.some((entry) => entry.covers)) return { nextAt: now() + horizon };
381
467
  const text = row.slot === "routine" ? [
382
468
  "Your routines are due:",
@@ -447,13 +533,15 @@ function createWake(options) {
447
533
  if (settledId && !inputs.length) return "no-input";
448
534
  const nudgeOnly = inputs.length > 0 && inputs.every(isNudge);
449
535
  const passiveOnly = inputs.length > 0 && inputs.every((type) => isNudge(type) || type === "calendar-outcome");
450
- if (runId !== void 0 && !passiveOnly && live()) await timer.schedule("reminder", now() + horizon);
536
+ const plan = await heldPlan();
537
+ if (runId !== void 0 && !passiveOnly && live()) await timer.schedule("reminder", Math.max(now(), plan?.at ?? 0) + horizon);
451
538
  const read = await readWakeRecords(options.providers(), now(), horizon);
452
539
  if (read.status !== "ok") return "unavailable";
453
540
  if (read.records.length > MAX_RECORDS) return "too-many";
454
541
  const routinesCover = await routineWake(session, read, live, runId === void 0);
455
542
  if (nudgeOnly) return "nudge-only";
456
543
  if (passiveOnly) return "passive-only";
544
+ if (plan) return "planned";
457
545
  if (routinesCover || read.records.some((entry) => entry.covers)) return "covered";
458
546
  if (runId === void 0 && settledId && requestId === void 0) return "no-record";
459
547
  if (!live()) return "fenced";
@@ -501,6 +589,101 @@ function createWake(options) {
501
589
  };
502
590
  }
503
591
  //#endregion
592
+ //#region src/schemas/wakeSchedule.ts
593
+ const MINUTE_MS$1 = 6e4;
594
+ /** `wake.schedule` input. */
595
+ const WakeScheduleParametersSchema = typebox.Type.Object({
596
+ inMinutes: typebox.Type.Integer({
597
+ minimum: SELF_WAKE_MIN_DELAY_MS / MINUTE_MS$1,
598
+ maximum: SELF_WAKE_MAX_DELAY_MS / MINUTE_MS$1,
599
+ description: "Minutes from now, 5 to 10080 (7 days)."
600
+ }),
601
+ prompt: typebox.Type.String({
602
+ minLength: 1,
603
+ maxLength: SELF_WAKE_MAX_PROMPT,
604
+ description: "What to do when woken, written to your future self. Private to this session."
605
+ })
606
+ }, { additionalProperties: false });
607
+ //#endregion
608
+ //#region src/services/wakeNamespace/index.ts
609
+ const MINUTE_MS = 6e4;
610
+ /** The `wake.schedule` receipt. Replaces any earlier planned wake. */
611
+ async function scheduleSelfWake(plan, input) {
612
+ if (!(0, typebox_value.Check)(WakeScheduleParametersSchema, input)) throw new Error("Provide inMinutes (5 to 10080) and a prompt of 1 to 4000 characters.");
613
+ const prompt = input.prompt.trim();
614
+ if (!prompt) throw new Error("The prompt is blank.");
615
+ const planned = await plan(input.inMinutes * MINUTE_MS, prompt, "agent");
616
+ if (!planned) throw new Error("Only a bot session can schedule its own wake.");
617
+ const details = {
618
+ scheduled: planned.written,
619
+ at: new Date(planned.at).toISOString()
620
+ };
621
+ return {
622
+ content: [{
623
+ type: "text",
624
+ text: `Wake scheduled for ${details.at}. It replaces any earlier planned wake.`
625
+ }],
626
+ details
627
+ };
628
+ }
629
+ const DECLARATIONS = `declare const wake: {
630
+ /**
631
+ * Wake this bot session once, inMinutes from now (5 to 10080), with prompt as the message you receive.
632
+ * Replaces any earlier planned wake. at is an ISO time.
633
+ */
634
+ schedule(input: { inMinutes: number; prompt: string }): Promise<{ scheduled: boolean; at: string }>;
635
+ };`;
636
+ /** The main agent's own next nudge. */
637
+ function createWakeNamespace(options) {
638
+ return {
639
+ name: "wake",
640
+ summary: "Plan this bot session’s next wake: one durable, private nudge to your future self.",
641
+ declarations: DECLARATIONS,
642
+ bind(run) {
643
+ if (run.sessionId !== options.sessionId) throw new Error("The wake namespace belongs to another session.");
644
+ let disposed = false;
645
+ run.onDispose(() => {
646
+ disposed = true;
647
+ });
648
+ return { schedule: async (input) => {
649
+ const started = Date.now();
650
+ const base = {
651
+ name: "wake.schedule",
652
+ args: JSON.parse(JSON.stringify(input ?? {}))
653
+ };
654
+ try {
655
+ run.signal.throwIfAborted();
656
+ if (disposed) throw new Error("This exec run has ended. Nothing changed.");
657
+ if (run.caller !== "main") throw new Error("Only the main agent plans its own wake.");
658
+ const result = await scheduleSelfWake(options.plan, input);
659
+ run.record?.({
660
+ ...base,
661
+ tool: base.name,
662
+ ok: true,
663
+ ms: Date.now() - started,
664
+ result
665
+ });
666
+ return JSON.parse(JSON.stringify(result.details));
667
+ } catch (error) {
668
+ const message = error instanceof Error ? error.message : String(error);
669
+ run.record?.({
670
+ ...base,
671
+ tool: base.name,
672
+ ok: false,
673
+ ms: Date.now() - started,
674
+ error: message,
675
+ result: { content: [{
676
+ type: "text",
677
+ text: message
678
+ }] }
679
+ });
680
+ throw error instanceof Error ? error : new Error(message);
681
+ }
682
+ } };
683
+ }
684
+ };
685
+ }
686
+ //#endregion
504
687
  //#region src/services/wakeSession/index.ts
505
688
  const SESSION_DETACHED = "Wake session detached.";
506
689
  function createWakeSessionState(agent, root, owner) {
@@ -529,7 +712,9 @@ function createWakeSessionState(agent, root, owner) {
529
712
  signal: lifetime.signal,
530
713
  timer: {
531
714
  schedule: (slot, at, preserve) => root.schedule(owner, slot, at, preserve),
532
- cancel: (slot) => root.cancel(owner, slot)
715
+ cancel: (slot) => root.cancel(owner, slot),
716
+ planned: () => root.planned(owner),
717
+ plan: (plan) => root.plan(owner, plan)
533
718
  }
534
719
  });
535
720
  const check = async (operation) => {
@@ -547,12 +732,39 @@ function createWakeSessionState(agent, root, owner) {
547
732
  level: "warning"
548
733
  });
549
734
  };
735
+ const plan = async (delayMs, prompt, origin) => {
736
+ if (lifetime.signal.aborted || !root.botSession(owner)) return void 0;
737
+ const at = Date.now() + delayMs;
738
+ const profile = profileRuntime?.readSelection().profileName ?? null;
739
+ return {
740
+ at,
741
+ written: await root.plan(owner, {
742
+ at,
743
+ prompt,
744
+ origin,
745
+ profile
746
+ })
747
+ };
748
+ };
550
749
  return {
551
750
  value: {
552
751
  read: () => readWakeRecords(providers, Date.now(), wakePeriodOf(root.botSession(owner), profileRuntime?.readSelection().settings?.wake?.periodMs)),
553
- translate: t
752
+ translate: t,
753
+ plan
554
754
  },
555
755
  services: [
756
+ (context) => {
757
+ const fiber = context.inject([_agimon_ai_po_core_codemode.PO_CODEMODE_SERVICE], (bound) => {
758
+ const codemode = (0, _agimon_ai_po_core_codemode.readPoCodemode)(bound);
759
+ if (!codemode) return void 0;
760
+ const registration = codemode.register("@agimon-ai/po-wake", createWakeNamespace({
761
+ sessionId: owner.sessionId,
762
+ plan
763
+ }));
764
+ return () => registration.dispose();
765
+ });
766
+ return () => fiber.dispose();
767
+ },
556
768
  (context) => {
557
769
  const fiber = context.inject([_agimon_ai_po_core_serverPlugin.PO_SERVER_SCOPE_SERVICE], (bound) => {
558
770
  const scope = (0, _agimon_ai_po_core_serverPlugin.requirePoServerScope)(bound);
@@ -671,6 +883,16 @@ var wake_server_default = (0, _agimon_ai_po_core_extensionFile.defineCommand)((c
671
883
  }
672
884
  }));
673
885
  //#endregion
886
+ //#region src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-wake.server.ts
887
+ var codemode_how_to_wake_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)({
888
+ name: "codemode-how-to-wake",
889
+ description: "Plan this bot session's next wake, one durable private nudge to your future self, through the wake namespace.",
890
+ kind: "skill",
891
+ pinned: true,
892
+ path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-wake/SKILL.md"),
893
+ read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/codemode-how-to-wake/SKILL.md")
894
+ });
895
+ //#endregion
674
896
  //#region src/extensions/workspaces/sessions/(backend)/resource/help-how-to-wake.server.ts
675
897
  var help_how_to_wake_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)({
676
898
  name: "help-how-to-wake",
@@ -756,7 +978,7 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
756
978
  return [via({ name: "wake" }, at(wake_server_default, contextSession))];
757
979
  },
758
980
  get resources() {
759
- return [at(help_how_to_wake_server_default, contextSession)];
981
+ return [at(codemode_how_to_wake_server_default, contextSession), at(help_how_to_wake_server_default, contextSession)];
760
982
  },
761
983
  services: [
762
984
  ...scopeHost.services ?? [],