wherever-dev 0.21.1 → 0.22.1

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 (103) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/assistant-channels.d.ts +242 -0
  3. package/dist/assistant-channels.d.ts.map +1 -0
  4. package/dist/assistant-channels.js +270 -0
  5. package/dist/assistant-channels.js.map +1 -0
  6. package/dist/assistant-controller.d.ts +228 -0
  7. package/dist/assistant-controller.d.ts.map +1 -0
  8. package/dist/assistant-controller.js +314 -0
  9. package/dist/assistant-controller.js.map +1 -0
  10. package/dist/assistant-cron.d.ts +87 -0
  11. package/dist/assistant-cron.d.ts.map +1 -0
  12. package/dist/assistant-cron.js +352 -0
  13. package/dist/assistant-cron.js.map +1 -0
  14. package/dist/assistant-folder.d.ts +161 -0
  15. package/dist/assistant-folder.d.ts.map +1 -0
  16. package/dist/assistant-folder.js +333 -0
  17. package/dist/assistant-folder.js.map +1 -0
  18. package/dist/assistant-schedule.d.ts +236 -0
  19. package/dist/assistant-schedule.d.ts.map +1 -0
  20. package/dist/assistant-schedule.js +454 -0
  21. package/dist/assistant-schedule.js.map +1 -0
  22. package/dist/assistant-scheduler.d.ts +210 -0
  23. package/dist/assistant-scheduler.d.ts.map +1 -0
  24. package/dist/assistant-scheduler.js +472 -0
  25. package/dist/assistant-scheduler.js.map +1 -0
  26. package/dist/assistant-tool-text.d.ts +40 -0
  27. package/dist/assistant-tool-text.d.ts.map +1 -0
  28. package/dist/assistant-tool-text.js +102 -0
  29. package/dist/assistant-tool-text.js.map +1 -0
  30. package/dist/assistant-tools.d.ts +222 -0
  31. package/dist/assistant-tools.d.ts.map +1 -0
  32. package/dist/assistant-tools.js +411 -0
  33. package/dist/assistant-tools.js.map +1 -0
  34. package/dist/cli-requests.d.ts +90 -0
  35. package/dist/cli-requests.d.ts.map +1 -0
  36. package/dist/cli-requests.js +75 -0
  37. package/dist/cli-requests.js.map +1 -0
  38. package/dist/index.js +427 -7
  39. package/dist/index.js.map +1 -1
  40. package/dist/protocol.d.ts +43 -0
  41. package/dist/protocol.d.ts.map +1 -1
  42. package/dist/reply-routing.d.ts +106 -0
  43. package/dist/reply-routing.d.ts.map +1 -0
  44. package/dist/reply-routing.js +174 -0
  45. package/dist/reply-routing.js.map +1 -0
  46. package/dist/session-pool.d.ts +235 -4
  47. package/dist/session-pool.d.ts.map +1 -1
  48. package/dist/session-pool.js +446 -100
  49. package/dist/session-pool.js.map +1 -1
  50. package/dist/telegram-channel.d.ts +275 -0
  51. package/dist/telegram-channel.d.ts.map +1 -0
  52. package/dist/telegram-channel.js +702 -0
  53. package/dist/telegram-channel.js.map +1 -0
  54. package/dist/telegram-files.d.ts +101 -0
  55. package/dist/telegram-files.d.ts.map +1 -0
  56. package/dist/telegram-files.js +145 -0
  57. package/dist/telegram-files.js.map +1 -0
  58. package/dist/telegram-pairing.d.ts +119 -0
  59. package/dist/telegram-pairing.d.ts.map +1 -0
  60. package/dist/telegram-pairing.js +97 -0
  61. package/dist/telegram-pairing.js.map +1 -0
  62. package/dist/telegram-replies.d.ts +140 -0
  63. package/dist/telegram-replies.d.ts.map +1 -0
  64. package/dist/telegram-replies.js +474 -0
  65. package/dist/telegram-replies.js.map +1 -0
  66. package/dist/telegram-token.d.ts +55 -0
  67. package/dist/telegram-token.d.ts.map +1 -0
  68. package/dist/telegram-token.js +86 -0
  69. package/dist/telegram-token.js.map +1 -0
  70. package/dist/web-push.d.ts +167 -0
  71. package/dist/web-push.d.ts.map +1 -0
  72. package/dist/web-push.js +387 -0
  73. package/dist/web-push.js.map +1 -0
  74. package/package.json +1 -1
  75. package/public/_app/immutable/assets/0.hWfYEET-.css +1 -0
  76. package/public/_app/immutable/chunks/Cuh9gHb6.js +2 -0
  77. package/public/_app/immutable/chunks/Cuh9gHb6.js.map +1 -0
  78. package/public/_app/immutable/chunks/DEUwJYqt.js +2 -0
  79. package/public/_app/immutable/chunks/{BQ9B_G4h.js.map → DEUwJYqt.js.map} +1 -1
  80. package/public/_app/immutable/chunks/DSPDB3Gw.js +2 -0
  81. package/public/_app/immutable/chunks/{BUONgvl4.js.map → DSPDB3Gw.js.map} +1 -1
  82. package/public/_app/immutable/entry/{app.BZO7Xckk.js → app.BkV4f8p8.js} +3 -3
  83. package/public/_app/immutable/entry/{app.BZO7Xckk.js.map → app.BkV4f8p8.js.map} +1 -1
  84. package/public/_app/immutable/entry/start.D5TsAoxn.js +2 -0
  85. package/public/_app/immutable/entry/start.D5TsAoxn.js.map +1 -0
  86. package/public/_app/immutable/nodes/{0.Czz2XmZU.js → 0.DR4K9Ylw.js} +3 -3
  87. package/public/_app/immutable/nodes/{0.Czz2XmZU.js.map → 0.DR4K9Ylw.js.map} +1 -1
  88. package/public/_app/immutable/nodes/{1.DDvrriUW.js → 1.DdqkeKC4.js} +2 -2
  89. package/public/_app/immutable/nodes/{1.DDvrriUW.js.map → 1.DdqkeKC4.js.map} +1 -1
  90. package/public/_app/immutable/nodes/2.n5lfdeec.js +122 -0
  91. package/public/_app/immutable/nodes/2.n5lfdeec.js.map +1 -0
  92. package/public/_app/version.json +1 -1
  93. package/public/index.html +11 -11
  94. package/public/service-worker.js +1 -1
  95. package/public/_app/immutable/assets/0.BKJ49K71.css +0 -1
  96. package/public/_app/immutable/chunks/BQ9B_G4h.js +0 -2
  97. package/public/_app/immutable/chunks/BUONgvl4.js +0 -2
  98. package/public/_app/immutable/chunks/DauELski.js +0 -2
  99. package/public/_app/immutable/chunks/DauELski.js.map +0 -1
  100. package/public/_app/immutable/entry/start.DWD60uNu.js +0 -2
  101. package/public/_app/immutable/entry/start.DWD60uNu.js.map +0 -1
  102. package/public/_app/immutable/nodes/2.C7E8EMKX.js +0 -120
  103. package/public/_app/immutable/nodes/2.C7E8EMKX.js.map +0 -1
@@ -0,0 +1,222 @@
1
+ import type { InlineExtension, ToolDefinition } from '@earendil-works/pi-coding-agent';
2
+ import { type ScheduleJob } from './assistant-schedule.js';
3
+ import type { ScheduleListing } from './assistant-scheduler.js';
4
+ import type { ChannelNotification, NotifyOutcome } from './assistant-channels.js';
5
+ /**
6
+ * The assistant's SCHEDULE and TIMEZONE tools for server-built sessions (spec
7
+ * `assistant-session-and-channels`, ADR 0015), plus the per-turn timezone line.
8
+ *
9
+ * - `assistant_schedule_add`, `assistant_schedule_list`, `assistant_schedule_remove`,
10
+ * `assistant_set_timezone`: registered in EVERY server session (not only the
11
+ * assistant's) while `assistantFolder` is CONFIGURED, so any session's agent can
12
+ * hand a job to the assistant. Every job belongs to and runs as the assistant;
13
+ * the calling session is stamped as `originSessionId` / `originCwd` (context,
14
+ * not the execution location). Self-contained in the `say` / `attach_file`
15
+ * style: each `execute` calls the scheduler directly (its write queue and its
16
+ * timezone setter), no bridge, no side channel.
17
+ * - When configured but NOT active (another server holds the folder lock, or the
18
+ * lock could not be taken), the tools stay registered and answer a clear
19
+ * lock-state error (decision: same tool set whatever the lock says, so the
20
+ * agent learns WHY it cannot schedule instead of not seeing the tools).
21
+ * - `assistant_notify` (channel-seam-notify-and-web-push, ADR 0014): the one way
22
+ * to reach the user proactively, delivered at once to every channel through
23
+ * the dispatcher (assistant-channels.ts). Registered ONLY while the assistant
24
+ * is ACTIVE (`hooks.notify` set), so a refused server's sessions do not see it.
25
+ * - The timezone line (`User's current timezone: <tz>`) is an INLINE pi extension
26
+ * (ADR 0004's conversation-mode pattern): `before_agent_start` APPENDS it to
27
+ * the prompt the event carries, never replacing it. It is added only to a
28
+ * session whose cwd is `assistantFolder` itself or its `jobs/` (path.resolve
29
+ * equality, like the controller's pointer check), and appends nothing while no
30
+ * timezone is known (assistant not active).
31
+ *
32
+ * The ops (`scheduleAdd`, ...) are separate from the tool wrappers so
33
+ * `cli-assistant-tool-twins` can answer its `cli_request` ops with the same
34
+ * code. Text lives in `assistant-tool-text.ts` (shared with the CLI twins).
35
+ */
36
+ /** The slice of `AssistantScheduler` the tools drive (faked or a temp scheduler in tests). */
37
+ export interface AssistantScheduleBackend {
38
+ addJob(input: Omit<ScheduleJob, 'id'> & {
39
+ id?: string;
40
+ }): Promise<ScheduleJob>;
41
+ removeJob(id: string): Promise<boolean>;
42
+ list(): ScheduleListing;
43
+ getUserTimezone(): string;
44
+ setUserTimezone(timezone: string, source: string): boolean;
45
+ }
46
+ /** Whether the tools can act now: the backend while active, else the lock-state error. */
47
+ export type AssistantAccess = {
48
+ ok: true;
49
+ backend: AssistantScheduleBackend;
50
+ } | {
51
+ ok: false;
52
+ error: string;
53
+ };
54
+ /** The session calling a tool (resolved server-side, never from tool arguments). */
55
+ export interface AssistantToolCaller {
56
+ sessionId: string | null;
57
+ cwd: string;
58
+ /** The caller's session file (`assistant_notify` maps an isolated job session to its job). */
59
+ sessionFile?: string | null;
60
+ }
61
+ /** A job's origin, as recorded in `schedule.json` (context: who scheduled it). */
62
+ export interface JobOrigin {
63
+ originSessionId?: string;
64
+ originCwd?: string;
65
+ }
66
+ /** What `assistant_notify` drives: the channel dispatcher plus the scheduler's job mapping. */
67
+ export interface AssistantNotifyBackend {
68
+ notify(notification: ChannelNotification): Promise<NotifyOutcome>;
69
+ /** The origin of the job `jobId` (null when there is no such job). */
70
+ jobOrigin(jobId: string): JobOrigin | null;
71
+ /** The job an isolated job session was started for (the scheduler's job mapping), or null. */
72
+ jobForSession(sessionFile: string): string | null;
73
+ }
74
+ export type AssistantNotifyAccess = {
75
+ ok: true;
76
+ backend: AssistantNotifyBackend;
77
+ } | {
78
+ ok: false;
79
+ error: string;
80
+ };
81
+ /**
82
+ * What the pool needs to give a server session its assistant tools and, in the
83
+ * assistant folder, its timezone line. Set on the pool only while
84
+ * `assistantFolder` is configured (`SessionPool.setAssistantSessionHooks`).
85
+ */
86
+ export interface AssistantSessionHooks {
87
+ /** The configured (resolved) assistant folder. */
88
+ folder: string;
89
+ /** Read at every tool call: the scheduler while active, else the lock-state error. */
90
+ access(): AssistantAccess;
91
+ /**
92
+ * `assistant_notify`'s backend, read at every call. Set ONLY while the
93
+ * assistant is ACTIVE (configured AND this server holds the folder lock):
94
+ * without it the tool is not registered at all (decision, per the task's
95
+ * acceptance criteria: unlike the schedule tools, a refused server's sessions
96
+ * do not see `assistant_notify`, since no channel could run there).
97
+ */
98
+ notify?: () => AssistantNotifyAccess;
99
+ }
100
+ export type OpResult = {
101
+ ok: true;
102
+ text: string;
103
+ details: unknown;
104
+ } | {
105
+ ok: false;
106
+ error: string;
107
+ };
108
+ /** The `source` recorded in the timezone history for a change made by `assistant_set_timezone`. */
109
+ export declare const SET_TIMEZONE_SOURCE = "assistant_set_timezone";
110
+ /** The `source` recorded for a change reported by a web client on connect. */
111
+ export declare const WEB_TIMEZONE_SOURCE = "web";
112
+ /** The lock-state error a tool answers when the assistant is configured but not active here. */
113
+ export declare function assistantNotActiveError(lock: {
114
+ state: string;
115
+ message?: string;
116
+ } | null): string;
117
+ /**
118
+ * Add a job through the scheduler's write queue, stamping the caller as origin.
119
+ * Always `enabled: true` (decision: a disabled job is a hand edit, not a tool
120
+ * call). Refuses (nothing written) on any invalid field, and on a prompt
121
+ * starting with `!` (the scheduler would refuse it at run time anyway).
122
+ */
123
+ export declare function scheduleAdd(backend: AssistantScheduleBackend, caller: AssistantToolCaller, args: unknown): Promise<OpResult>;
124
+ /** List every job, marking the caller's, with done and invalid entries. */
125
+ export declare function scheduleList(backend: AssistantScheduleBackend, caller: AssistantToolCaller): OpResult;
126
+ export declare function scheduleRemove(backend: AssistantScheduleBackend, args: unknown): Promise<OpResult>;
127
+ export declare function setTimezone(backend: AssistantScheduleBackend, args: unknown, source?: string): OpResult;
128
+ /** How the tap target was chosen (the precedence of `resolveNotifyTarget`). */
129
+ export type NotifyTargetVia = 'navigateSessionId' | 'job' | 'caller';
130
+ export interface NotifyTarget {
131
+ /** The session the notification opens (null only for a caller without a session id). */
132
+ sessionId: string | null;
133
+ via: NotifyTargetVia;
134
+ /** The job the notification is about (given, or the caller's own isolated job), or null. */
135
+ jobId: string | null;
136
+ /** That job's origin, when the job exists. */
137
+ job: JobOrigin | null;
138
+ }
139
+ /**
140
+ * The tap target precedence of `assistant_notify` (pure): `navigateSessionId`
141
+ * when given; else, when a `jobId` is given or the caller is an isolated job
142
+ * session (the scheduler's job mapping), the job's ORIGIN session; else the
143
+ * calling session. A job that is unknown (removed) or has no origin session
144
+ * falls through to the calling session (decision: a notification is never
145
+ * refused over its tap target).
146
+ */
147
+ export declare function resolveNotifyTarget(input: {
148
+ navigateSessionId?: string;
149
+ jobId?: string;
150
+ callerSessionId: string | null;
151
+ callerJobId: string | null;
152
+ jobOrigin: (jobId: string) => JobOrigin | null;
153
+ }): NotifyTarget;
154
+ /**
155
+ * The notification's `source` (WHO notified): the origin FOLDER's name. For a
156
+ * job (given or the caller's own), the folder it was scheduled from; otherwise
157
+ * the calling session's folder. Decision: folder names, not session names
158
+ * (sessions are mostly unnamed, and the folder is what the sidebar groups by).
159
+ */
160
+ export declare function notifySource(callerCwd: string, job: JobOrigin | null): string;
161
+ /** `assistant_notify`: deliver to every channel at once, with the tap target per `resolveNotifyTarget`. */
162
+ export declare function notifyOp(backend: AssistantNotifyBackend, caller: AssistantToolCaller, args: unknown): Promise<OpResult>;
163
+ /** The text of the settings' "Send test notification" (`POST /push/test`). */
164
+ export declare const TEST_NOTIFICATION_TITLE = "Test notification";
165
+ export declare const TEST_NOTIFICATION_BODY = "Sent from the wherever settings. If you can read this, notifications reach this device.";
166
+ /**
167
+ * The settings' test notification (`POST /push/test`): the SAME delivery as
168
+ * `assistant_notify` (`backend.notify`, every channel at once), from the
169
+ * assistant folder, opening `sessionId` (the session the calling device has
170
+ * open) or, without a usable one, the main screen (an empty target). The id
171
+ * only ends up in a URL fragment (`/#<id>`), so anything but a plain id is
172
+ * dropped.
173
+ */
174
+ export declare function testNotification(backend: AssistantNotifyBackend, input: {
175
+ sessionId?: unknown;
176
+ assistantFolder: string;
177
+ }): Promise<NotifyOutcome>;
178
+ /** What a CLI twin answers while `assistantFolder` is unset on this server. */
179
+ export declare const ASSISTANT_NOT_CONFIGURED_ERROR = "the wherever assistant is not configured on this server (set assistantFolder in the wherever config and restart it)";
180
+ export type AssistantCliOp = (args: unknown, caller: AssistantToolCaller) => Promise<OpResult>;
181
+ /**
182
+ * The ops behind the CLI bridge's `assistant_*` tool twins (`cli_request`, see
183
+ * cli-requests.ts and ADR 0016), keyed by op name. Each runs the SAME op as the
184
+ * server tool it twins, behind the same gates: `hooks` undefined (assistant not
185
+ * configured) answers `ASSISTANT_NOT_CONFIGURED_ERROR`; configured but not
186
+ * active answers the lock-state error, `notify` included (a server session has
187
+ * no `assistant_notify` then, a CLI twin has nothing to hide behind, so it gets
188
+ * the same error as the schedule tools). `caller` is resolved from the bridge
189
+ * registration, never from `args`.
190
+ */
191
+ export declare function assistantCliOps(hooks: AssistantSessionHooks | undefined): Record<string, AssistantCliOp>;
192
+ /**
193
+ * The tools for one server session: the four schedule / timezone tools, plus
194
+ * `assistant_notify` while active (`hooks.notify`). `caller` is read at call
195
+ * time (a session's id is stable).
196
+ */
197
+ export declare function createAssistantTools(hooks: AssistantSessionHooks, caller: () => AssistantToolCaller): ToolDefinition[];
198
+ /** `assistant_notify` for one server session (only while active, see `AssistantSessionHooks.notify`). */
199
+ export declare function createNotifyTool(access: () => AssistantNotifyAccess, caller: () => AssistantToolCaller): ToolDefinition;
200
+ /** True when `cwd` is the assistant folder itself or its `jobs/` (where the timezone line applies). */
201
+ export declare function isAssistantFolderCwd(cwd: string, folder: string): boolean;
202
+ /** Append the timezone line to the prompt the event carries (never replacing it). */
203
+ export declare function appendTimezoneLine(systemPrompt: string, timezone: string): string;
204
+ /**
205
+ * The inline extension that appends the timezone line on EVERY turn. The zone is
206
+ * read at `before_agent_start`, so a change made mid-session shows on the next
207
+ * turn; null (not active) appends nothing.
208
+ */
209
+ export declare function createTimezoneLineExtension(getTimezone: () => string | null): InlineExtension;
210
+ /** The current timezone through `hooks`, or null while not active. */
211
+ export declare function hooksTimezone(hooks: AssistantSessionHooks): string | null;
212
+ /**
213
+ * What a server session in `cwd` gets from the assistant: the four schedule
214
+ * tools (always, while configured), `assistant_notify` (only while active) and, only in the assistant folder or `jobs/`, the timezone
215
+ * line extension. Empty with `hooks` undefined (assistant not configured), so
216
+ * the session's tools and extensions are exactly as without the feature.
217
+ */
218
+ export declare function assistantSessionParts(hooks: AssistantSessionHooks | undefined, cwd: string, caller: () => AssistantToolCaller): {
219
+ customTools: ToolDefinition[];
220
+ extensionFactories: InlineExtension[];
221
+ };
222
+ //# sourceMappingURL=assistant-tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assistant-tools.d.ts","sourceRoot":"","sources":["../src/assistant-tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAuC,eAAe,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAE5H,OAAO,EAA4D,KAAK,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACrH,OAAO,KAAK,EAAa,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,KAAK,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAWlF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,8FAA8F;AAC9F,MAAM,WAAW,wBAAwB;IACvC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,GAAG;QAAE,EAAE,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IAC/E,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACxC,IAAI,IAAI,eAAe,CAAC;IACxB,eAAe,IAAI,MAAM,CAAC;IAC1B,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;CAC5D;AAED,0FAA0F;AAC1F,MAAM,MAAM,eAAe,GAAG;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,OAAO,EAAE,wBAAwB,CAAA;CAAE,GAA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,MAAM,EAAE,MAAM,mBAAmB,GAAG,cAAc,CAoBvH;AAKD,uGAAuG;AACvG,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAIzE;AAED,qFAAqF;AACrF,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEjF;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,WAAW,EAAE,MAAM,MAAM,GAAG,IAAI,GAAG,eAAe,CAc7F;AAED,sEAAsE;AACtE,wBAAgB,aAAa,CAAC,KAAK,EAAE,qBAAqB,GAAG,MAAM,GAAG,IAAI,CAIzE;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,qBAAqB,GAAG,SAAS,EACxC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,mBAAmB,GAChC;IAAE,WAAW,EAAE,cAAc,EAAE,CAAC;IAAC,kBAAkB,EAAE,eAAe,EAAE,CAAA;CAAE,CAM1E"}
@@ -0,0 +1,411 @@
1
+ import path from 'node:path';
2
+ import { Type } from 'typebox';
3
+ import { isValidTimeZone } from './assistant-cron.js';
4
+ import { ScheduleFileError, ScheduleValidationError } from './assistant-schedule.js';
5
+ import { ASSISTANT_NOTIFY_TEXT, ASSISTANT_SCHEDULE_ADD_TEXT, ASSISTANT_SCHEDULE_LIST_TEXT, ASSISTANT_SCHEDULE_REMOVE_TEXT, ASSISTANT_SET_TIMEZONE_TEXT, timezoneLine, } from './assistant-tool-text.js';
6
+ /** The `source` recorded in the timezone history for a change made by `assistant_set_timezone`. */
7
+ export const SET_TIMEZONE_SOURCE = 'assistant_set_timezone';
8
+ /** The `source` recorded for a change reported by a web client on connect. */
9
+ export const WEB_TIMEZONE_SOURCE = 'web';
10
+ /** The lock-state error a tool answers when the assistant is configured but not active here. */
11
+ export function assistantNotActiveError(lock) {
12
+ const why = lock && lock.state !== 'held' && lock.message ? lock.message : 'the assistant is not active on this server';
13
+ return `The wherever assistant is configured but NOT active on this server (folder lock ${lock?.state ?? 'missing'}): ${why}`;
14
+ }
15
+ const str = (v) => (typeof v === 'string' ? v : undefined);
16
+ function errorOf(err) {
17
+ if (err instanceof ScheduleValidationError || err instanceof ScheduleFileError)
18
+ return err.message;
19
+ return err instanceof Error ? err.message : String(err);
20
+ }
21
+ // ---------------------------------------------------------------------------
22
+ // Ops
23
+ /**
24
+ * Add a job through the scheduler's write queue, stamping the caller as origin.
25
+ * Always `enabled: true` (decision: a disabled job is a hand edit, not a tool
26
+ * call). Refuses (nothing written) on any invalid field, and on a prompt
27
+ * starting with `!` (the scheduler would refuse it at run time anyway).
28
+ */
29
+ export async function scheduleAdd(backend, caller, args) {
30
+ const a = (args ?? {});
31
+ const prompt = str(a.prompt);
32
+ if (prompt !== undefined && prompt.trimStart().startsWith('!')) {
33
+ return { ok: false, error: 'a scheduled prompt must not start with "!" (shell commands are never run from a schedule)' };
34
+ }
35
+ const input = {
36
+ name: a.name,
37
+ ...(a.cron !== undefined ? { cron: a.cron } : {}),
38
+ ...(a.at !== undefined ? { at: a.at } : {}),
39
+ ...(a.tz !== undefined && a.tz !== '' ? { tz: a.tz } : {}),
40
+ mode: a.mode,
41
+ prompt: a.prompt,
42
+ enabled: true,
43
+ ...(caller.sessionId ? { originSessionId: caller.sessionId } : {}),
44
+ originCwd: caller.cwd,
45
+ };
46
+ let job;
47
+ try {
48
+ job = await backend.addJob(input);
49
+ }
50
+ catch (err) {
51
+ return { ok: false, error: errorOf(err) };
52
+ }
53
+ const listed = safeList(backend)?.jobs.find((j) => j.job.id === job.id);
54
+ const when = listed ? describeNext(listed) : '';
55
+ return {
56
+ ok: true,
57
+ text: `Scheduled "${job.name}" (id ${job.id}): ${describeTiming(job, listed?.timezone)}, ${job.mode}${when}. It runs as the assistant.`,
58
+ details: { job, next: listed?.next ?? null, timezone: listed?.timezone ?? null },
59
+ };
60
+ }
61
+ /** List every job, marking the caller's, with done and invalid entries. */
62
+ export function scheduleList(backend, caller) {
63
+ let listing;
64
+ try {
65
+ listing = backend.list();
66
+ }
67
+ catch (err) {
68
+ return { ok: false, error: errorOf(err) };
69
+ }
70
+ const mine = (j) => !!caller.sessionId && j.job.originSessionId === caller.sessionId;
71
+ const lines = [`User's current timezone: ${listing.timezone}`];
72
+ if (listing.fileError)
73
+ lines.push(`schedule.json cannot be read, so nothing fires until it is fixed by hand: ${listing.fileError}`);
74
+ lines.push(`Jobs (${listing.jobs.length}):`);
75
+ if (listing.jobs.length === 0)
76
+ lines.push('- (none)');
77
+ for (const j of listing.jobs) {
78
+ const last = j.last ? `, last ${j.last.outcome} ${j.last.time}` : '';
79
+ lines.push(`- ${mine(j) ? '[yours] ' : ''}${j.job.id} "${j.job.name}": ${describeTiming(j.job, j.timezone)}, ${j.job.mode}, ` +
80
+ `${j.job.enabled ? '' : 'disabled, '}${j.state}${j.next ? `, next ${j.next}` : ''}${last}` +
81
+ `${j.job.originCwd ? ` (from ${j.job.originCwd})` : ''}`);
82
+ }
83
+ if (listing.invalid.length > 0) {
84
+ lines.push(`Invalid entries, never run (${listing.invalid.length}):`);
85
+ for (const inv of listing.invalid) {
86
+ lines.push(`- entry #${inv.index}${inv.id ? ` ${inv.id}` : ''}${inv.name ? ` "${inv.name}"` : ''}: ${inv.errors.join('; ')}`);
87
+ }
88
+ }
89
+ return {
90
+ ok: true,
91
+ text: lines.join('\n'),
92
+ details: {
93
+ timezone: listing.timezone,
94
+ fileError: listing.fileError,
95
+ jobs: listing.jobs.map((j) => ({ ...j, mine: mine(j) })),
96
+ invalid: listing.invalid.map(({ raw: _raw, ...rest }) => rest),
97
+ },
98
+ };
99
+ }
100
+ export async function scheduleRemove(backend, args) {
101
+ const id = str(args?.id)?.trim();
102
+ if (!id)
103
+ return { ok: false, error: 'an "id" is required (see assistant_schedule_list)' };
104
+ let removed;
105
+ try {
106
+ removed = await backend.removeJob(id);
107
+ }
108
+ catch (err) {
109
+ return { ok: false, error: errorOf(err) };
110
+ }
111
+ if (!removed)
112
+ return { ok: false, error: `no job with id "${id}" (see assistant_schedule_list)` };
113
+ return { ok: true, text: `Removed job ${id}.`, details: { id, removed: true } };
114
+ }
115
+ export function setTimezone(backend, args, source = SET_TIMEZONE_SOURCE) {
116
+ const tz = str(args?.timezone)?.trim();
117
+ if (!tz || !isValidTimeZone(tz)) {
118
+ return { ok: false, error: `not a known IANA timezone: ${JSON.stringify(tz ?? null)} (e.g. Europe/Paris, America/New_York)` };
119
+ }
120
+ let changed;
121
+ try {
122
+ changed = backend.setUserTimezone(tz, source);
123
+ }
124
+ catch (err) {
125
+ return { ok: false, error: errorOf(err) };
126
+ }
127
+ return {
128
+ ok: true,
129
+ text: changed
130
+ ? `The user's timezone is now ${tz}; every job without its own tz follows it.`
131
+ : `The user's timezone was already ${tz}; nothing changed.`,
132
+ details: { timezone: tz, changed },
133
+ };
134
+ }
135
+ /**
136
+ * The tap target precedence of `assistant_notify` (pure): `navigateSessionId`
137
+ * when given; else, when a `jobId` is given or the caller is an isolated job
138
+ * session (the scheduler's job mapping), the job's ORIGIN session; else the
139
+ * calling session. A job that is unknown (removed) or has no origin session
140
+ * falls through to the calling session (decision: a notification is never
141
+ * refused over its tap target).
142
+ */
143
+ export function resolveNotifyTarget(input) {
144
+ const jobId = input.jobId || input.callerJobId || null;
145
+ const job = jobId ? input.jobOrigin(jobId) : null;
146
+ if (input.navigateSessionId)
147
+ return { sessionId: input.navigateSessionId, via: 'navigateSessionId', jobId, job };
148
+ if (job?.originSessionId)
149
+ return { sessionId: job.originSessionId, via: 'job', jobId, job };
150
+ return { sessionId: input.callerSessionId, via: 'caller', jobId, job };
151
+ }
152
+ /**
153
+ * The notification's `source` (WHO notified): the origin FOLDER's name. For a
154
+ * job (given or the caller's own), the folder it was scheduled from; otherwise
155
+ * the calling session's folder. Decision: folder names, not session names
156
+ * (sessions are mostly unnamed, and the folder is what the sidebar groups by).
157
+ */
158
+ export function notifySource(callerCwd, job) {
159
+ const cwd = job?.originCwd || callerCwd;
160
+ return path.basename(path.resolve(cwd)) || cwd;
161
+ }
162
+ /** `assistant_notify`: deliver to every channel at once, with the tap target per `resolveNotifyTarget`. */
163
+ export async function notifyOp(backend, caller, args) {
164
+ const a = (args ?? {});
165
+ const title = str(a.title)?.trim();
166
+ const body = str(a.body)?.trim() ?? '';
167
+ if (!title)
168
+ return { ok: false, error: 'a non-empty "title" is required' };
169
+ const navigateSessionId = str(a.navigateSessionId)?.trim() || undefined;
170
+ const jobId = str(a.jobId)?.trim() || undefined;
171
+ let callerJobId = null;
172
+ try {
173
+ callerJobId = caller.sessionFile ? backend.jobForSession(caller.sessionFile) : null;
174
+ }
175
+ catch {
176
+ callerJobId = null;
177
+ }
178
+ const target = resolveNotifyTarget({
179
+ navigateSessionId,
180
+ jobId,
181
+ callerSessionId: caller.sessionId,
182
+ callerJobId,
183
+ jobOrigin: (id) => {
184
+ try {
185
+ return backend.jobOrigin(id);
186
+ }
187
+ catch {
188
+ return null;
189
+ }
190
+ },
191
+ });
192
+ if (!target.sessionId)
193
+ return { ok: false, error: 'this session has no id yet, so there is nothing to open; pass navigateSessionId' };
194
+ const source = notifySource(caller.cwd, target.job);
195
+ const outcome = await backend.notify({ title, body, source, navigate: target.sessionId });
196
+ if (!outcome.ok)
197
+ return { ok: false, error: outcome.error };
198
+ const reached = outcome.deliveries
199
+ .filter((d) => d.result.ok)
200
+ .map((d) => `${d.channel}${d.result.ok && d.result.detail ? ` (${d.result.detail})` : ''}`);
201
+ const failed = outcome.deliveries.filter((d) => !d.result.ok).map((d) => `${d.channel}: ${d.result.ok ? '' : d.result.error}`);
202
+ const unknownJob = jobId && !target.job ? ` (no job "${jobId}" was found, so it opens this session)` : '';
203
+ return {
204
+ ok: true,
205
+ text: `Notified the user via ${reached.join(', ')}; tapping it opens session ${target.sessionId}${unknownJob}.` +
206
+ (failed.length > 0 ? ` Not delivered on: ${failed.join('; ')}.` : ''),
207
+ details: { target, source, deliveries: outcome.deliveries },
208
+ };
209
+ }
210
+ /** The text of the settings' "Send test notification" (`POST /push/test`). */
211
+ export const TEST_NOTIFICATION_TITLE = 'Test notification';
212
+ export const TEST_NOTIFICATION_BODY = 'Sent from the wherever settings. If you can read this, notifications reach this device.';
213
+ /**
214
+ * The settings' test notification (`POST /push/test`): the SAME delivery as
215
+ * `assistant_notify` (`backend.notify`, every channel at once), from the
216
+ * assistant folder, opening `sessionId` (the session the calling device has
217
+ * open) or, without a usable one, the main screen (an empty target). The id
218
+ * only ends up in a URL fragment (`/#<id>`), so anything but a plain id is
219
+ * dropped.
220
+ */
221
+ export async function testNotification(backend, input) {
222
+ const raw = typeof input.sessionId === 'string' ? input.sessionId.trim() : '';
223
+ const navigate = /^[A-Za-z0-9_.:-]{1,200}$/.test(raw) && !raw.includes('..') ? raw : '';
224
+ return backend.notify({
225
+ title: TEST_NOTIFICATION_TITLE,
226
+ body: TEST_NOTIFICATION_BODY,
227
+ source: notifySource(input.assistantFolder, null),
228
+ navigate,
229
+ });
230
+ }
231
+ /** What a CLI twin answers while `assistantFolder` is unset on this server. */
232
+ export const ASSISTANT_NOT_CONFIGURED_ERROR = 'the wherever assistant is not configured on this server (set assistantFolder in the wherever config and restart it)';
233
+ /**
234
+ * The ops behind the CLI bridge's `assistant_*` tool twins (`cli_request`, see
235
+ * cli-requests.ts and ADR 0016), keyed by op name. Each runs the SAME op as the
236
+ * server tool it twins, behind the same gates: `hooks` undefined (assistant not
237
+ * configured) answers `ASSISTANT_NOT_CONFIGURED_ERROR`; configured but not
238
+ * active answers the lock-state error, `notify` included (a server session has
239
+ * no `assistant_notify` then, a CLI twin has nothing to hide behind, so it gets
240
+ * the same error as the schedule tools). `caller` is resolved from the bridge
241
+ * registration, never from `args`.
242
+ */
243
+ export function assistantCliOps(hooks) {
244
+ const withBackend = (run) => async (args, caller) => {
245
+ if (!hooks)
246
+ return { ok: false, error: ASSISTANT_NOT_CONFIGURED_ERROR };
247
+ const access = hooks.access();
248
+ if (!access.ok)
249
+ return { ok: false, error: access.error };
250
+ return run(access.backend, args, caller);
251
+ };
252
+ return {
253
+ schedule_add: withBackend((backend, args, caller) => scheduleAdd(backend, caller, args)),
254
+ schedule_list: withBackend((backend, _args, caller) => scheduleList(backend, caller)),
255
+ schedule_remove: withBackend((backend, args) => scheduleRemove(backend, args)),
256
+ set_timezone: withBackend((backend, args) => setTimezone(backend, args)),
257
+ notify: async (args, caller) => {
258
+ if (!hooks)
259
+ return { ok: false, error: ASSISTANT_NOT_CONFIGURED_ERROR };
260
+ if (!hooks.notify) {
261
+ const access = hooks.access();
262
+ return { ok: false, error: access.ok ? 'assistant_notify is not available on this server' : access.error };
263
+ }
264
+ const a = hooks.notify();
265
+ if (!a.ok)
266
+ return { ok: false, error: a.error };
267
+ return notifyOp(a.backend, caller, args);
268
+ },
269
+ };
270
+ }
271
+ function safeList(backend) {
272
+ try {
273
+ return backend.list();
274
+ }
275
+ catch {
276
+ return null;
277
+ }
278
+ }
279
+ function describeTiming(job, effectiveTz) {
280
+ const when = job.cron !== undefined ? `cron "${job.cron}"` : `at "${job.at}"`;
281
+ const tz = job.tz ? `pinned to ${job.tz}` : `follows the user${effectiveTz ? `: ${effectiveTz}` : ''}`;
282
+ return `${when} (${tz})`;
283
+ }
284
+ function describeNext(j) {
285
+ return j.next ? `, next run ${j.next}` : `, ${j.state}`;
286
+ }
287
+ function toResult(name, r) {
288
+ if (r.ok)
289
+ return { content: [{ type: 'text', text: r.text }], details: r.details };
290
+ return { content: [{ type: 'text', text: `${name}: ${r.error}` }], details: undefined, isError: true };
291
+ }
292
+ function tool(text, parameters, hooks, run) {
293
+ return {
294
+ name: text.name,
295
+ label: text.label,
296
+ description: text.description,
297
+ promptSnippet: text.promptSnippet,
298
+ promptGuidelines: [...text.promptGuidelines],
299
+ parameters,
300
+ async execute(_toolCallId, params) {
301
+ const access = hooks.access();
302
+ if (!access.ok)
303
+ return toResult(text.name, { ok: false, error: access.error });
304
+ return toResult(text.name, await run(access.backend, params));
305
+ },
306
+ };
307
+ }
308
+ /**
309
+ * The tools for one server session: the four schedule / timezone tools, plus
310
+ * `assistant_notify` while active (`hooks.notify`). `caller` is read at call
311
+ * time (a session's id is stable).
312
+ */
313
+ export function createAssistantTools(hooks, caller) {
314
+ return [
315
+ tool(ASSISTANT_SCHEDULE_ADD_TEXT, Type.Object({
316
+ name: Type.String({ description: 'Short human name for the job (shown in listings and in the scheduled turn).' }),
317
+ prompt: Type.String({
318
+ description: 'What the assistant should do when the job fires, written to make sense on its own. A prompt starting with "/" runs that command or skill.',
319
+ }),
320
+ mode: Type.Union([Type.Literal('inline'), Type.Literal('isolated')], {
321
+ description: '"inline": into the current assistant conversation once it is idle. "isolated": at once, in a fresh side session.',
322
+ }),
323
+ cron: Type.Optional(Type.String({ description: '5-field cron for a recurring job, e.g. "0 8 * * *" (every day at 08:00). Exactly one of cron / at.' })),
324
+ at: Type.Optional(Type.String({ description: 'One-shot time: ISO 8601 date-time (e.g. "2026-11-06T17:30"), or "now". Exactly one of cron / at.' })),
325
+ tz: Type.Optional(Type.String({ description: "IANA timezone to PIN the job to. Omit to follow the user's current timezone (the usual case)." })),
326
+ }), hooks, (backend, params) => scheduleAdd(backend, caller(), params)),
327
+ tool(ASSISTANT_SCHEDULE_LIST_TEXT, Type.Object({}), hooks, (backend) => scheduleList(backend, caller())),
328
+ tool(ASSISTANT_SCHEDULE_REMOVE_TEXT, Type.Object({ id: Type.String({ description: 'The id of the job to remove (from assistant_schedule_list).' }) }), hooks, (backend, params) => scheduleRemove(backend, params)),
329
+ tool(ASSISTANT_SET_TIMEZONE_TEXT, Type.Object({ timezone: Type.String({ description: 'IANA timezone name, e.g. "Europe/Paris" or "America/New_York".' }) }), hooks, (backend, params) => setTimezone(backend, params)),
330
+ ...(hooks.notify ? [createNotifyTool(hooks.notify, caller)] : []),
331
+ ];
332
+ }
333
+ /** `assistant_notify` for one server session (only while active, see `AssistantSessionHooks.notify`). */
334
+ export function createNotifyTool(access, caller) {
335
+ const text = ASSISTANT_NOTIFY_TEXT;
336
+ return {
337
+ name: text.name,
338
+ label: text.label,
339
+ description: text.description,
340
+ promptSnippet: text.promptSnippet,
341
+ promptGuidelines: [...text.promptGuidelines],
342
+ parameters: Type.Object({
343
+ title: Type.String({ description: 'Short headline, e.g. "Deploy finished" or "CI is red".' }),
344
+ body: Type.String({ description: 'The message itself: one or two sentences the user can act on.' }),
345
+ navigateSessionId: Type.Optional(Type.String({ description: 'The session id a tap should open (default: see the description).' })),
346
+ jobId: Type.Optional(Type.String({ description: 'The scheduled job this is about; a tap then opens the session that scheduled it.' })),
347
+ }),
348
+ async execute(_toolCallId, params) {
349
+ const a = access();
350
+ if (!a.ok)
351
+ return toResult(text.name, { ok: false, error: a.error });
352
+ return toResult(text.name, await notifyOp(a.backend, caller(), params));
353
+ },
354
+ };
355
+ }
356
+ // ---------------------------------------------------------------------------
357
+ // The timezone line
358
+ /** True when `cwd` is the assistant folder itself or its `jobs/` (where the timezone line applies). */
359
+ export function isAssistantFolderCwd(cwd, folder) {
360
+ const c = path.resolve(cwd);
361
+ const f = path.resolve(folder);
362
+ return c === f || c === path.join(f, 'jobs');
363
+ }
364
+ /** Append the timezone line to the prompt the event carries (never replacing it). */
365
+ export function appendTimezoneLine(systemPrompt, timezone) {
366
+ return `${systemPrompt}\n\n${timezoneLine(timezone)}`;
367
+ }
368
+ /**
369
+ * The inline extension that appends the timezone line on EVERY turn. The zone is
370
+ * read at `before_agent_start`, so a change made mid-session shows on the next
371
+ * turn; null (not active) appends nothing.
372
+ */
373
+ export function createTimezoneLineExtension(getTimezone) {
374
+ const factory = (pi) => {
375
+ pi.on('before_agent_start', (event) => {
376
+ let tz = null;
377
+ try {
378
+ tz = getTimezone();
379
+ }
380
+ catch {
381
+ tz = null;
382
+ }
383
+ if (!tz)
384
+ return;
385
+ return { systemPrompt: appendTimezoneLine(event.systemPrompt, tz) };
386
+ });
387
+ };
388
+ return { name: 'wherever-assistant-timezone', factory };
389
+ }
390
+ /** The current timezone through `hooks`, or null while not active. */
391
+ export function hooksTimezone(hooks) {
392
+ const access = hooks.access();
393
+ if (!access.ok)
394
+ return null;
395
+ return access.backend.getUserTimezone();
396
+ }
397
+ /**
398
+ * What a server session in `cwd` gets from the assistant: the four schedule
399
+ * tools (always, while configured), `assistant_notify` (only while active) and, only in the assistant folder or `jobs/`, the timezone
400
+ * line extension. Empty with `hooks` undefined (assistant not configured), so
401
+ * the session's tools and extensions are exactly as without the feature.
402
+ */
403
+ export function assistantSessionParts(hooks, cwd, caller) {
404
+ if (!hooks)
405
+ return { customTools: [], extensionFactories: [] };
406
+ return {
407
+ customTools: createAssistantTools(hooks, caller),
408
+ extensionFactories: isAssistantFolderCwd(cwd, hooks.folder) ? [createTimezoneLineExtension(() => hooksTimezone(hooks))] : [],
409
+ };
410
+ }
411
+ //# sourceMappingURL=assistant-tools.js.map