@agimon-ai/po-notification 0.0.0-alpha.32 → 0.0.0-alpha.34
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.
- package/README.md +56 -5
- package/dist/index.cjs +265 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +51 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +265 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -52,11 +52,62 @@ subagent child, it does not install that wrapper and Pi's original `ui.notify` b
|
|
|
52
52
|
page receives live notification entries for every attached session, not only the focused session. Permission
|
|
53
53
|
is requested only from an explicit settings action.
|
|
54
54
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
55
|
+
Browser Web Push is not supported. Closed-app delivery uses the paired native iOS or Android app,
|
|
56
|
+
with explicit notification permission and native push enrollment. The server subscribes once to live
|
|
57
|
+
notification entries across all sessions, even with no client sockets connected. It never reads history
|
|
58
|
+
for push, and has no durable outbox or replay. Enrollment is persisted on the trusted device record;
|
|
59
|
+
revocation, token rotation and remote disable are rechecked before queued work is dispatched.
|
|
60
|
+
|
|
61
|
+
## Native push server credentials
|
|
62
|
+
|
|
63
|
+
Add these four variables to the server user's `~/.zshrc` (use absolute paths):
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
export PO_APNS_KEY_FILE="$HOME/.po-secrets/AuthKey.p8"
|
|
67
|
+
export PO_APNS_KEY_ID="ABCDEFGHIJ"
|
|
68
|
+
export PO_APNS_TEAM_ID="KLMNOPQRST"
|
|
69
|
+
export PO_FCM_SERVICE_ACCOUNT_FILE="$HOME/.po-secrets/firebase-service-account.json"
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Restrict the directory to the server user (`chmod 700`) and credential files to owner read/write
|
|
73
|
+
(`chmod 600`). Never commit, paste into logs, or distribute these files with the app. Start Po from a
|
|
74
|
+
shell that inherited these variables. GUI or service launches may not read `~/.zshrc`; configure their
|
|
75
|
+
launch environment explicitly. Restart the server after changing credentials or variables: files and
|
|
76
|
+
key material are validated once at startup. Missing or invalid credentials disable only that provider,
|
|
77
|
+
with a redacted diagnostic. No provider credentials are read from a session's environment.
|
|
78
|
+
|
|
79
|
+
For Apple, provision the company `ai.po.app` App ID with Push Notifications, sign the native app with the
|
|
80
|
+
matching entitlement and provisioning profile, and create an APNs signing key in the Apple Developer
|
|
81
|
+
team. The server topic is fixed to `ai.po.app`. The native build-only variable
|
|
82
|
+
`PO_NATIVE_APNS_ENVIRONMENT` selects `development` or `production` to match the signed entitlement;
|
|
83
|
+
it is not a server credential. At runtime the native app reads the signed APNs environment through
|
|
84
|
+
`expo-application`, and registers its token with that environment for server routing. iOS push enrollment
|
|
85
|
+
refuses a different application ID, including the previous `ai.agimon.po` development app. Rebuild and
|
|
86
|
+
pair the company iOS app with its matching profile; old iOS installs are a separate app identity.
|
|
87
|
+
|
|
88
|
+
For Firebase, register Android package `ai.agimon.po`, enable the FCM HTTP v1 API, and grant a service
|
|
89
|
+
account permission to send FCM messages. The server reads `client_email`, `private_key`, and
|
|
90
|
+
`project_id` from its service-account JSON, not from a separate project environment variable.
|
|
91
|
+
The native build-only `PO_NATIVE_ANDROID_GOOGLE_SERVICES_FILE` points to the matching Android
|
|
92
|
+
`google-services.json`. This client configuration is not the server service-account private key.
|
|
93
|
+
Rebuild and reinstall the app when changing native build configuration.
|
|
94
|
+
|
|
95
|
+
**Privacy:** native push carries the full notification title, subtitle and body, subject to provider
|
|
96
|
+
payload limits. Apple or Google and the device lock screen can receive that text, including sensitive
|
|
97
|
+
agent output. This is not generic-copy-only delivery. Do not enable it for content you cannot share
|
|
98
|
+
with those providers or display on the lock screen.
|
|
99
|
+
|
|
100
|
+
Delivery is bounded, best effort, and timeout-limited, not guaranteed. FCM uses TTL 0 and APNs uses
|
|
101
|
+
expiration 0, so providers are asked not to retain notifications for offline delivery. This is an
|
|
102
|
+
offline-retention ceiling, not a guarantee that every background or terminated app receives a notice.
|
|
103
|
+
Excess pending work is dropped. Invalid endpoints are conditionally cleared without deleting a rotated
|
|
104
|
+
token. Physical-device verification remains blocked until signed Apple/Firebase builds, credentials,
|
|
105
|
+
and paired devices are available; source tests do not establish real-device delivery.
|
|
106
|
+
|
|
107
|
+
Forgetting a paired host first requires successful remote device revocation. If the host is unreachable
|
|
108
|
+
or revocation fails, Po keeps local keys so you can reconnect and retry. A confirmed revocation is
|
|
109
|
+
checkpointed so interrupted local key deletion can finish after a restart. Revocation cannot recall
|
|
110
|
+
notifications already submitted to Apple or Google.
|
|
60
111
|
|
|
61
112
|
## The shell title
|
|
62
113
|
|
package/dist/index.cjs
CHANGED
|
@@ -24,6 +24,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
24
24
|
let node_worker_threads = require("node:worker_threads");
|
|
25
25
|
let node_path = require("node:path");
|
|
26
26
|
node_path = __toESM(node_path, 1);
|
|
27
|
+
let node_crypto = require("node:crypto");
|
|
28
|
+
let node_http2 = require("node:http2");
|
|
29
|
+
let node_https = require("node:https");
|
|
27
30
|
//#region src/services/shellTitleController/mainThread.ts
|
|
28
31
|
const BRAILLE_FRAMES = [
|
|
29
32
|
"⠋",
|
|
@@ -266,6 +269,267 @@ async function sendSystemNotification(pi, notification, platform = process.platf
|
|
|
266
269
|
]);
|
|
267
270
|
}
|
|
268
271
|
//#endregion
|
|
272
|
+
//#region src/services/nativePushSender/sync.ts
|
|
273
|
+
const MAX_RESPONSE_BYTES = 65536;
|
|
274
|
+
function signPushJwt(header, claims, key, algorithm) {
|
|
275
|
+
const input = [header, claims].map((part) => Buffer.from(JSON.stringify(part)).toString("base64url")).join(".");
|
|
276
|
+
const signature = (0, node_crypto.sign)("sha256", Buffer.from(input), {
|
|
277
|
+
key,
|
|
278
|
+
dsaEncoding: "ieee-p1363"
|
|
279
|
+
});
|
|
280
|
+
if (algorithm === "ES256" && signature.length !== 64) throw new Error("Invalid signing key");
|
|
281
|
+
return `${input}.${signature.toString("base64url")}`;
|
|
282
|
+
}
|
|
283
|
+
function createPushTransport() {
|
|
284
|
+
const pending = /* @__PURE__ */ new Set();
|
|
285
|
+
return {
|
|
286
|
+
request(input) {
|
|
287
|
+
return new Promise((resolve, reject) => {
|
|
288
|
+
const url = new URL(input.url);
|
|
289
|
+
let size = 0;
|
|
290
|
+
const chunks = [];
|
|
291
|
+
let done = false;
|
|
292
|
+
let dispose = () => {};
|
|
293
|
+
const finish = (error, status = 0) => {
|
|
294
|
+
if (done) return;
|
|
295
|
+
done = true;
|
|
296
|
+
clearTimeout(timer);
|
|
297
|
+
pending.delete(cancel);
|
|
298
|
+
dispose();
|
|
299
|
+
if (error) reject(error);
|
|
300
|
+
else resolve({
|
|
301
|
+
status,
|
|
302
|
+
body: Buffer.concat(chunks).toString("utf8")
|
|
303
|
+
});
|
|
304
|
+
};
|
|
305
|
+
const cancel = () => finish(/* @__PURE__ */ new Error("Push request cancelled"));
|
|
306
|
+
const timer = setTimeout(() => finish(/* @__PURE__ */ new Error("Push request timed out")), input.timeoutMs);
|
|
307
|
+
pending.add(cancel);
|
|
308
|
+
const data = (chunk) => {
|
|
309
|
+
size += chunk.length;
|
|
310
|
+
if (size > MAX_RESPONSE_BYTES) finish(/* @__PURE__ */ new Error("Push response too large"));
|
|
311
|
+
else chunks.push(Buffer.from(chunk));
|
|
312
|
+
};
|
|
313
|
+
if (input.http2) {
|
|
314
|
+
const session = (0, node_http2.connect)(url.origin);
|
|
315
|
+
dispose = () => session.destroy();
|
|
316
|
+
session.on("error", (error) => finish(error));
|
|
317
|
+
const stream = session.request({
|
|
318
|
+
":method": "POST",
|
|
319
|
+
":path": url.pathname,
|
|
320
|
+
...input.headers
|
|
321
|
+
});
|
|
322
|
+
let status = 0;
|
|
323
|
+
stream.on("response", (headers) => {
|
|
324
|
+
status = Number(headers[":status"]);
|
|
325
|
+
});
|
|
326
|
+
stream.on("data", data);
|
|
327
|
+
stream.on("error", (error) => finish(error));
|
|
328
|
+
stream.on("end", () => finish(void 0, status));
|
|
329
|
+
stream.end(input.body);
|
|
330
|
+
} else {
|
|
331
|
+
const req = (0, node_https.request)(url, {
|
|
332
|
+
method: "POST",
|
|
333
|
+
headers: input.headers
|
|
334
|
+
}, (response) => {
|
|
335
|
+
response.on("data", data);
|
|
336
|
+
response.on("error", (error) => finish(error));
|
|
337
|
+
response.on("end", () => finish(void 0, response.statusCode));
|
|
338
|
+
});
|
|
339
|
+
dispose = () => req.destroy();
|
|
340
|
+
req.on("error", (error) => finish(error));
|
|
341
|
+
req.end(input.body);
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
},
|
|
345
|
+
close() {
|
|
346
|
+
for (const cancel of pending) cancel();
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
//#endregion
|
|
351
|
+
//#region src/services/nativePushSender/index.ts
|
|
352
|
+
const MAX_PAYLOAD_BYTES = 4096;
|
|
353
|
+
const APNS_TOPIC = "ai.po.app";
|
|
354
|
+
const OAUTH_URL = "https://oauth2.googleapis.com/token";
|
|
355
|
+
const FCM_ERROR_TYPE = "type.googleapis.com/google.firebase.fcm.v1.FcmError";
|
|
356
|
+
const encoder = new TextEncoder();
|
|
357
|
+
function parse(body) {
|
|
358
|
+
try {
|
|
359
|
+
const value = JSON.parse(body);
|
|
360
|
+
return value && typeof value === "object" ? value : {};
|
|
361
|
+
} catch {
|
|
362
|
+
return {};
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
function payload(notification, build) {
|
|
366
|
+
const text = {
|
|
367
|
+
title: notification.title,
|
|
368
|
+
subtitle: notification.subtitle,
|
|
369
|
+
body: notification.body
|
|
370
|
+
};
|
|
371
|
+
let result = JSON.stringify(build(text));
|
|
372
|
+
for (const field of [
|
|
373
|
+
"body",
|
|
374
|
+
"subtitle",
|
|
375
|
+
"title"
|
|
376
|
+
]) {
|
|
377
|
+
if (encoder.encode(result).length <= MAX_PAYLOAD_BYTES) break;
|
|
378
|
+
const points = Array.from(text[field]);
|
|
379
|
+
let low = 0;
|
|
380
|
+
let high = points.length;
|
|
381
|
+
while (low < high) {
|
|
382
|
+
const middle = Math.ceil((low + high) / 2);
|
|
383
|
+
text[field] = points.slice(0, middle).join("");
|
|
384
|
+
if (encoder.encode(JSON.stringify(build(text))).length <= MAX_PAYLOAD_BYTES) low = middle;
|
|
385
|
+
else high = middle - 1;
|
|
386
|
+
}
|
|
387
|
+
text[field] = points.slice(0, low).join("");
|
|
388
|
+
result = JSON.stringify(build(text));
|
|
389
|
+
}
|
|
390
|
+
if (encoder.encode(result).length > MAX_PAYLOAD_BYTES) throw new Error("Push payload too large");
|
|
391
|
+
return result;
|
|
392
|
+
}
|
|
393
|
+
function createNativePushSender(options) {
|
|
394
|
+
const transport = createPushTransport();
|
|
395
|
+
const request = options.request ?? transport.request;
|
|
396
|
+
const now = options.now ?? Date.now;
|
|
397
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) ? Math.max(1, Math.min(options.timeoutMs, 3e4)) : 1e4;
|
|
398
|
+
let closed = false;
|
|
399
|
+
let apnsJwt;
|
|
400
|
+
let oauth;
|
|
401
|
+
let oauthPending;
|
|
402
|
+
async function accessToken() {
|
|
403
|
+
if (oauth && now() < oauth.expires) return oauth.value;
|
|
404
|
+
if (oauthPending) return oauthPending;
|
|
405
|
+
oauthPending = (async () => {
|
|
406
|
+
const credentials = options.fcm;
|
|
407
|
+
const issued = Math.floor(now() / 1e3);
|
|
408
|
+
const assertion = signPushJwt({
|
|
409
|
+
alg: "RS256",
|
|
410
|
+
typ: "JWT"
|
|
411
|
+
}, {
|
|
412
|
+
iss: credentials.clientEmail,
|
|
413
|
+
scope: "https://www.googleapis.com/auth/firebase.messaging",
|
|
414
|
+
aud: OAUTH_URL,
|
|
415
|
+
iat: issued,
|
|
416
|
+
exp: issued + 3600
|
|
417
|
+
}, credentials.privateKey, "RS256");
|
|
418
|
+
const response = await request({
|
|
419
|
+
url: OAUTH_URL,
|
|
420
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
421
|
+
body: new URLSearchParams({
|
|
422
|
+
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
|
423
|
+
assertion
|
|
424
|
+
}).toString(),
|
|
425
|
+
timeoutMs
|
|
426
|
+
});
|
|
427
|
+
const data = parse(response.body);
|
|
428
|
+
if (response.status !== 200 || typeof data.access_token !== "string" || !data.access_token || typeof data.expires_in !== "number" || !Number.isFinite(data.expires_in) || data.expires_in <= 0) throw new Error("OAuth failed");
|
|
429
|
+
oauth = {
|
|
430
|
+
value: data.access_token,
|
|
431
|
+
expires: now() + Math.max(0, Math.min(data.expires_in, 3600) - 60) * 1e3
|
|
432
|
+
};
|
|
433
|
+
return oauth.value;
|
|
434
|
+
})();
|
|
435
|
+
try {
|
|
436
|
+
return await oauthPending;
|
|
437
|
+
} finally {
|
|
438
|
+
oauthPending = void 0;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return {
|
|
442
|
+
async send(registration, notification) {
|
|
443
|
+
const provider = registration.platform === "ios" ? "apns" : "fcm";
|
|
444
|
+
if (closed || !options[provider]) {
|
|
445
|
+
options.diagnostic?.({
|
|
446
|
+
provider,
|
|
447
|
+
outcome: "unavailable"
|
|
448
|
+
});
|
|
449
|
+
return { invalid: false };
|
|
450
|
+
}
|
|
451
|
+
try {
|
|
452
|
+
let response;
|
|
453
|
+
if (registration.platform === "ios") {
|
|
454
|
+
const credentials = options.apns;
|
|
455
|
+
if (!apnsJwt || now() >= apnsJwt.expires) apnsJwt = {
|
|
456
|
+
value: signPushJwt({
|
|
457
|
+
alg: "ES256",
|
|
458
|
+
kid: credentials.keyId
|
|
459
|
+
}, {
|
|
460
|
+
iss: credentials.teamId,
|
|
461
|
+
iat: Math.floor(now() / 1e3)
|
|
462
|
+
}, credentials.key, "ES256"),
|
|
463
|
+
expires: now() + 3e6
|
|
464
|
+
};
|
|
465
|
+
response = await request({
|
|
466
|
+
url: `https://${registration.environment === "development" ? "api.sandbox.push.apple.com" : "api.push.apple.com"}/3/device/${encodeURIComponent(registration.token)}`,
|
|
467
|
+
http2: true,
|
|
468
|
+
timeoutMs,
|
|
469
|
+
headers: {
|
|
470
|
+
authorization: `bearer ${apnsJwt.value}`,
|
|
471
|
+
"apns-topic": APNS_TOPIC,
|
|
472
|
+
"apns-push-type": "alert",
|
|
473
|
+
"apns-priority": "10",
|
|
474
|
+
"apns-expiration": "0",
|
|
475
|
+
"content-type": "application/json"
|
|
476
|
+
},
|
|
477
|
+
body: payload(notification, (text) => ({ aps: {
|
|
478
|
+
alert: text,
|
|
479
|
+
sound: "default"
|
|
480
|
+
} }))
|
|
481
|
+
});
|
|
482
|
+
const reason = parse(response.body).reason;
|
|
483
|
+
if (response.status === 410 && reason === "Unregistered" || response.status === 400 && reason === "BadDeviceToken") return { invalid: true };
|
|
484
|
+
} else {
|
|
485
|
+
const body = payload(notification, (text) => ({ message: {
|
|
486
|
+
token: registration.token,
|
|
487
|
+
notification: {
|
|
488
|
+
title: text.title,
|
|
489
|
+
body: [text.subtitle, text.body].filter(Boolean).join("\n")
|
|
490
|
+
},
|
|
491
|
+
android: {
|
|
492
|
+
ttl: "0s",
|
|
493
|
+
priority: "HIGH",
|
|
494
|
+
notification: { channel_id: "po-notifications" }
|
|
495
|
+
}
|
|
496
|
+
} }));
|
|
497
|
+
const token = await accessToken();
|
|
498
|
+
if (closed) return { invalid: false };
|
|
499
|
+
response = await request({
|
|
500
|
+
url: `https://fcm.googleapis.com/v1/projects/${encodeURIComponent(options.fcm.projectId)}/messages:send`,
|
|
501
|
+
headers: {
|
|
502
|
+
authorization: `Bearer ${token}`,
|
|
503
|
+
"content-type": "application/json"
|
|
504
|
+
},
|
|
505
|
+
body,
|
|
506
|
+
timeoutMs
|
|
507
|
+
});
|
|
508
|
+
const error = parse(response.body).error;
|
|
509
|
+
if (response.status === 404 && error && typeof error === "object" && "details" in error && Array.isArray(error.details) && error.details.some((detail) => detail && typeof detail === "object" && "@type" in detail && detail["@type"] === FCM_ERROR_TYPE && "errorCode" in detail && detail.errorCode === "UNREGISTERED")) return { invalid: true };
|
|
510
|
+
}
|
|
511
|
+
if (response.status < 200 || response.status >= 300) options.diagnostic?.({
|
|
512
|
+
provider,
|
|
513
|
+
outcome: "failed",
|
|
514
|
+
status: response.status
|
|
515
|
+
});
|
|
516
|
+
} catch {
|
|
517
|
+
options.diagnostic?.({
|
|
518
|
+
provider,
|
|
519
|
+
outcome: "failed"
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
return { invalid: false };
|
|
523
|
+
},
|
|
524
|
+
close() {
|
|
525
|
+
closed = true;
|
|
526
|
+
apnsJwt = void 0;
|
|
527
|
+
oauth = void 0;
|
|
528
|
+
transport.close();
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
//#endregion
|
|
269
533
|
//#region src/services/notificationPolicy/index.ts
|
|
270
534
|
const DEFAULT_ASK_USER_BODY = "The agent is waiting for your feedback.";
|
|
271
535
|
const RPC_MODE = "rpc";
|
|
@@ -295,6 +559,7 @@ function askUserPromptBody(questions) {
|
|
|
295
559
|
exports.askUserPromptBody = askUserPromptBody;
|
|
296
560
|
exports.attentionNotification = attentionNotification;
|
|
297
561
|
exports.createMainThreadTitleController = createMainThreadTitleController;
|
|
562
|
+
exports.createNativePushSender = createNativePushSender;
|
|
298
563
|
exports.createWorkerTitleController = createWorkerTitleController;
|
|
299
564
|
exports.notificationBody = notificationBody;
|
|
300
565
|
exports.promptTitle = promptTitle;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["Worker","path"],"sources":["../src/services/shellTitleController/mainThread.ts","../src/services/shellTitleController/index.ts","../src/services/notificationText/index.ts","../src/services/systemNotification/index.ts","../src/services/notificationPolicy/index.ts"],"sourcesContent":["import type { ShellTitleController } from '../../types/notifications';\n\nexport const BRAILLE_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\nexport const TITLE_FRAME_INTERVAL_MS = 80;\n\n/** Animates on the main thread, for hosts where a worker could not be started. */\nexport function createMainThreadTitleController(): ShellTitleController {\n let frameIndex = 0;\n let timer: ReturnType<typeof setInterval> | undefined;\n const stopAnimation = () => {\n if (timer) clearInterval(timer);\n timer = undefined;\n frameIndex = 0;\n };\n\n return {\n set(title, write) {\n stopAnimation();\n write(title);\n },\n start(title, write) {\n stopAnimation();\n const render = () => {\n write(`${BRAILLE_FRAMES[frameIndex % BRAILLE_FRAMES.length]} ${title}`);\n frameIndex += 1;\n };\n render();\n timer = setInterval(render, TITLE_FRAME_INTERVAL_MS);\n },\n stop(title, write) {\n stopAnimation();\n write(title);\n },\n dispose(title, write) {\n stopAnimation();\n write(title);\n },\n };\n}\n","import { Worker } from 'node:worker_threads';\n\nimport type { ShellTitleCommand, ShellTitleController, WriteTitle } from '../../types/notifications';\nimport { BRAILLE_FRAMES, TITLE_FRAME_INTERVAL_MS, createMainThreadTitleController } from './mainThread';\n\nexport { createMainThreadTitleController } from './mainThread';\n/**\n * The animator runs off the main thread so a busy agent turn cannot stall the\n * spinner. It is an inline eval source rather than a shipped file because the\n * package is bundled per entry, and a separate worker module would have to be\n * located on disk at runtime.\n */\nconst TITLE_WORKER_SOURCE = `\nconst { writeSync } = require('node:fs');\nconst { parentPort, workerData } = require('node:worker_threads');\nlet frameIndex = 0;\nlet timer;\nconst writeTitle = (title) => writeSync(1, '\\\\u001b]0;' + title + '\\\\u0007');\nconst stop = () => {\n if (timer) clearInterval(timer);\n timer = undefined;\n frameIndex = 0;\n};\nparentPort.on('message', (command) => {\n stop();\n if (command.action === 'start') {\n const render = () => {\n writeTitle(workerData.frames[frameIndex % workerData.frames.length] + ' ' + command.title);\n frameIndex += 1;\n };\n render();\n timer = setInterval(render, workerData.intervalMs);\n return;\n }\n writeTitle(command.title);\n if (command.action === 'dispose') parentPort.close();\n});\n`;\n\n/**\n * Animates from a worker thread, replaying the last command on the main thread\n * if the worker never started, failed, or exited under us. The worker is\n * unreferenced so a pending frame never holds the process open.\n */\nexport function createWorkerTitleController(): ShellTitleController {\n const fallback = createMainThreadTitleController();\n let lastCommand: ShellTitleCommand | undefined;\n let lastWrite: WriteTitle | undefined;\n let worker: Worker | undefined;\n\n const fallBack = () => {\n worker = undefined;\n if (!lastCommand || !lastWrite) return;\n fallback[lastCommand.action](lastCommand.title, lastWrite);\n };\n\n try {\n const titleWorker = new Worker(TITLE_WORKER_SOURCE, {\n eval: true,\n workerData: { frames: BRAILLE_FRAMES, intervalMs: TITLE_FRAME_INTERVAL_MS },\n });\n titleWorker.unref();\n titleWorker.once('error', fallBack);\n titleWorker.once('exit', (code) => {\n if (code !== 0 && worker === titleWorker) fallBack();\n });\n worker = titleWorker;\n } catch {\n // Workers are unavailable on this host, which the main-thread animator covers.\n worker = undefined;\n }\n\n const dispatch = (command: ShellTitleCommand, write: WriteTitle) => {\n lastCommand = command;\n lastWrite = write;\n if (!worker) {\n fallback[command.action](command.title, write);\n return;\n }\n try {\n worker.postMessage(command);\n } catch {\n // The worker closed between the last frame and this command.\n fallBack();\n }\n };\n\n return {\n set: (title, write) => dispatch({ action: 'set', title }, write),\n start: (title, write) => dispatch({ action: 'start', title }, write),\n stop: (title, write) => dispatch({ action: 'stop', title }, write),\n dispose: (title, write) => dispatch({ action: 'dispose', title }, write),\n };\n}\n","import path from 'node:path';\n\nimport type { DesktopNotification } from '../../types/notifications';\n\nconst ATTENTION_SUBTITLE = 'Approval or feedback required';\nconst ATTENTION_TITLE = 'Pi needs your input';\nconst ELLIPSIS = '…';\nconst MAX_BODY_LENGTH = 240;\nconst MAX_PROMPT_TITLE_LENGTH = 36;\nconst SETTLED_BODY = 'The agent finished its work and is waiting for you.';\nconst SETTLED_TITLE = 'Pi finished';\nconst SHELL_TITLE_SEPARATOR = ' - ';\nconst SHELL_TITLE_PREFIX = 'π';\n\nfunction collapseWhitespace(value: string): string {\n return value.replace(/\\s+/g, ' ').trim();\n}\n\nfunction truncate(value: string, maxLength: number): string {\n return value.length > maxLength ? `${value.slice(0, maxLength - 1)}${ELLIPSIS}` : value;\n}\n\n/** The first user prompt, shortened to fit a shell tab. A blank prompt names nothing. */\nexport function promptTitle(prompt: string): string | undefined {\n const normalized = collapseWhitespace(prompt);\n return normalized ? truncate(normalized, MAX_PROMPT_TITLE_LENGTH) : undefined;\n}\n\nexport interface ShellTabTitleInput {\n cwd: string;\n sessionName?: string;\n prompt?: string;\n}\n\n/**\n * The idle shell-tab title: `π - <label> - <repository>`.\n *\n * The session name wins over the first prompt because the user chose it. With\n * neither, the repository alone still tells two tabs apart.\n */\nexport function shellTabTitle({ cwd, sessionName, prompt }: ShellTabTitleInput): string {\n const repository = path.basename(cwd);\n const label = sessionName ?? prompt;\n return label\n ? `${SHELL_TITLE_PREFIX}${SHELL_TITLE_SEPARATOR}${label}${SHELL_TITLE_SEPARATOR}${repository}`\n : `${SHELL_TITLE_PREFIX}${SHELL_TITLE_SEPARATOR}${repository}`;\n}\n\n/** Notification bodies are one line in a system panel, so they collapse and truncate. */\nexport function notificationBody(body: string): string {\n return truncate(collapseWhitespace(body), MAX_BODY_LENGTH);\n}\n\n/** Sent while the agent holds the turn and something is blocking on the user. */\nexport function attentionNotification(body: string): DesktopNotification {\n return { title: ATTENTION_TITLE, subtitle: ATTENTION_SUBTITLE, body };\n}\n\n/** Sent once a run has stopped, subtitled with whichever name the user recognises. */\nexport function settledNotification({ cwd, sessionName }: { cwd: string; sessionName?: string }): DesktopNotification {\n return { title: SETTLED_TITLE, subtitle: sessionName ?? path.basename(cwd), body: SETTLED_BODY };\n}\n","import type { DesktopNotification, NotificationExecutor } from '../../types/notifications';\nimport { notificationBody } from '../notificationText';\n\nconst CMUX_COMMAND = 'cmux';\nconst COMMAND_TIMEOUT_MS = 3_000;\nconst DARWIN_PLATFORM = 'darwin';\nconst OSASCRIPT_COMMAND = 'osascript';\nconst OSASCRIPT_EXPRESSION_FLAG = '-e';\n\nasync function execute(pi: NotificationExecutor, command: string, args: string[]): Promise<boolean> {\n try {\n const result = await pi.exec(command, args, { timeout: COMMAND_TIMEOUT_MS });\n return result.code === 0;\n } catch {\n // A notifier that is not installed is the ordinary case, not a fault: report\n // \"not delivered\" and let the caller decide whether another one exists.\n return false;\n }\n}\n\n/**\n * Delivers one desktop notification on a best-effort basis.\n *\n * cmux is tried first because it routes the notification to the window the\n * session actually lives in. Only macOS has a second option worth attempting,\n * and a host with neither stays silent rather than failing the turn.\n */\nexport async function sendSystemNotification(\n pi: NotificationExecutor,\n notification: DesktopNotification,\n platform: string = process.platform,\n): Promise<void> {\n const body = notificationBody(notification.body);\n const sentToCmux = await execute(pi, CMUX_COMMAND, [\n 'notify',\n '--title',\n notification.title,\n '--subtitle',\n notification.subtitle,\n '--body',\n body,\n ]);\n if (sentToCmux || platform !== DARWIN_PLATFORM) return;\n\n await execute(pi, OSASCRIPT_COMMAND, [\n OSASCRIPT_EXPRESSION_FLAG,\n 'on run argv',\n OSASCRIPT_EXPRESSION_FLAG,\n 'display notification (item 3 of argv) with title (item 1 of argv) subtitle (item 2 of argv)',\n OSASCRIPT_EXPRESSION_FLAG,\n 'end run',\n notification.title,\n notification.subtitle,\n body,\n ]);\n}\n","const DEFAULT_ASK_USER_BODY = 'The agent is waiting for your feedback.';\nconst RPC_MODE = 'rpc';\n\nexport interface AttentionState {\n agentRunning: boolean;\n askUserBlocked: boolean;\n}\n\nexport interface ShellSurface {\n hasUI: boolean;\n mode?: string;\n}\n\n/**\n * A dialog is worth interrupting the user for only while the agent holds the turn.\n *\n * Outside a run the user opened the dialog themselves and is already looking at\n * it. An ask-user prompt is announced by its own event, so the dialog it then\n * opens must stay silent or the same question notifies twice.\n */\nexport function warrantsAttentionNotification({ agentRunning, askUserBlocked }: AttentionState): boolean {\n return agentRunning && !askUserBlocked;\n}\n\n/** A queued follow-up means the agent keeps working, so the run has not stopped for the user. */\nexport function warrantsSettledNotification(hasPendingMessages: boolean): boolean {\n return !hasPendingMessages;\n}\n\n/** Terminal title escapes only mean something on an attached terminal; RPC output stays clean. */\nexport function supportsShellTitle({ hasUI, mode }: ShellSurface): boolean {\n return hasUI && mode !== RPC_MODE;\n}\n\n/** The question an ask-user prompt is blocking on, or a stand-in when it asked none. */\nexport function askUserPromptBody(questions: readonly { question: string }[]): string {\n return questions[0]?.question ?? DEFAULT_ASK_USER_BODY;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,MAAa,iBAAiB;CAAC;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;AAAG;;AAI/E,SAAgB,kCAAwD;CACtE,IAAI,aAAa;CACjB,IAAI;CACJ,MAAM,sBAAsB;EAC1B,IAAI,OAAO,cAAc,KAAK;EAC9B,QAAQ,KAAA;EACR,aAAa;CACf;CAEA,OAAO;EACL,IAAI,OAAO,OAAO;GAChB,cAAc;GACd,MAAM,KAAK;EACb;EACA,MAAM,OAAO,OAAO;GAClB,cAAc;GACd,MAAM,eAAe;IACnB,MAAM,GAAG,eAAe,aAAa,eAAe,QAAQ,GAAG,OAAO;IACtE,cAAc;GAChB;GACA,OAAO;GACP,QAAQ,YAAY,QAAA,EAA+B;EACrD;EACA,KAAK,OAAO,OAAO;GACjB,cAAc;GACd,MAAM,KAAK;EACb;EACA,QAAQ,OAAO,OAAO;GACpB,cAAc;GACd,MAAM,KAAK;EACb;CACF;AACF;;;;;;;;;AC1BA,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgC5B,SAAgB,8BAAoD;CAClE,MAAM,WAAW,gCAAgC;CACjD,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,MAAM,iBAAiB;EACrB,SAAS,KAAA;EACT,IAAI,CAAC,eAAe,CAAC,WAAW;EAChC,SAAS,YAAY,OAAO,CAAC,YAAY,OAAO,SAAS;CAC3D;CAEA,IAAI;EACF,MAAM,cAAc,IAA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BjB,SAAgB,8BAA8B,EAAE,cAAc,kBAA2C;CACvG,OAAO,gBAAgB,CAAC;AAC1B;;AAGA,SAAgB,4BAA4B,oBAAsC;CAChF,OAAO,CAAC;AACV;;AAGA,SAAgB,mBAAmB,EAAE,OAAO,QAA+B;CACzE,OAAO,SAAS,SAAS;AAC3B;;AAGA,SAAgB,kBAAkB,WAAoD;CACpF,OAAO,UAAU,EAAE,EAAE,YAAY;AACnC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["Worker","path","sign","connect","request"],"sources":["../src/services/shellTitleController/mainThread.ts","../src/services/shellTitleController/index.ts","../src/services/notificationText/index.ts","../src/services/systemNotification/index.ts","../src/services/nativePushSender/sync.ts","../src/services/nativePushSender/index.ts","../src/services/notificationPolicy/index.ts"],"sourcesContent":["import type { ShellTitleController } from '../../types/notifications';\n\nexport const BRAILLE_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\nexport const TITLE_FRAME_INTERVAL_MS = 80;\n\n/** Animates on the main thread, for hosts where a worker could not be started. */\nexport function createMainThreadTitleController(): ShellTitleController {\n let frameIndex = 0;\n let timer: ReturnType<typeof setInterval> | undefined;\n const stopAnimation = () => {\n if (timer) clearInterval(timer);\n timer = undefined;\n frameIndex = 0;\n };\n\n return {\n set(title, write) {\n stopAnimation();\n write(title);\n },\n start(title, write) {\n stopAnimation();\n const render = () => {\n write(`${BRAILLE_FRAMES[frameIndex % BRAILLE_FRAMES.length]} ${title}`);\n frameIndex += 1;\n };\n render();\n timer = setInterval(render, TITLE_FRAME_INTERVAL_MS);\n },\n stop(title, write) {\n stopAnimation();\n write(title);\n },\n dispose(title, write) {\n stopAnimation();\n write(title);\n },\n };\n}\n","import { Worker } from 'node:worker_threads';\n\nimport type { ShellTitleCommand, ShellTitleController, WriteTitle } from '../../types/notifications';\nimport { BRAILLE_FRAMES, TITLE_FRAME_INTERVAL_MS, createMainThreadTitleController } from './mainThread';\n\nexport { createMainThreadTitleController } from './mainThread';\n/**\n * The animator runs off the main thread so a busy agent turn cannot stall the\n * spinner. It is an inline eval source rather than a shipped file because the\n * package is bundled per entry, and a separate worker module would have to be\n * located on disk at runtime.\n */\nconst TITLE_WORKER_SOURCE = `\nconst { writeSync } = require('node:fs');\nconst { parentPort, workerData } = require('node:worker_threads');\nlet frameIndex = 0;\nlet timer;\nconst writeTitle = (title) => writeSync(1, '\\\\u001b]0;' + title + '\\\\u0007');\nconst stop = () => {\n if (timer) clearInterval(timer);\n timer = undefined;\n frameIndex = 0;\n};\nparentPort.on('message', (command) => {\n stop();\n if (command.action === 'start') {\n const render = () => {\n writeTitle(workerData.frames[frameIndex % workerData.frames.length] + ' ' + command.title);\n frameIndex += 1;\n };\n render();\n timer = setInterval(render, workerData.intervalMs);\n return;\n }\n writeTitle(command.title);\n if (command.action === 'dispose') parentPort.close();\n});\n`;\n\n/**\n * Animates from a worker thread, replaying the last command on the main thread\n * if the worker never started, failed, or exited under us. The worker is\n * unreferenced so a pending frame never holds the process open.\n */\nexport function createWorkerTitleController(): ShellTitleController {\n const fallback = createMainThreadTitleController();\n let lastCommand: ShellTitleCommand | undefined;\n let lastWrite: WriteTitle | undefined;\n let worker: Worker | undefined;\n\n const fallBack = () => {\n worker = undefined;\n if (!lastCommand || !lastWrite) return;\n fallback[lastCommand.action](lastCommand.title, lastWrite);\n };\n\n try {\n const titleWorker = new Worker(TITLE_WORKER_SOURCE, {\n eval: true,\n workerData: { frames: BRAILLE_FRAMES, intervalMs: TITLE_FRAME_INTERVAL_MS },\n });\n titleWorker.unref();\n titleWorker.once('error', fallBack);\n titleWorker.once('exit', (code) => {\n if (code !== 0 && worker === titleWorker) fallBack();\n });\n worker = titleWorker;\n } catch {\n // Workers are unavailable on this host, which the main-thread animator covers.\n worker = undefined;\n }\n\n const dispatch = (command: ShellTitleCommand, write: WriteTitle) => {\n lastCommand = command;\n lastWrite = write;\n if (!worker) {\n fallback[command.action](command.title, write);\n return;\n }\n try {\n worker.postMessage(command);\n } catch {\n // The worker closed between the last frame and this command.\n fallBack();\n }\n };\n\n return {\n set: (title, write) => dispatch({ action: 'set', title }, write),\n start: (title, write) => dispatch({ action: 'start', title }, write),\n stop: (title, write) => dispatch({ action: 'stop', title }, write),\n dispose: (title, write) => dispatch({ action: 'dispose', title }, write),\n };\n}\n","import path from 'node:path';\n\nimport type { DesktopNotification } from '../../types/notifications';\n\nconst ATTENTION_SUBTITLE = 'Approval or feedback required';\nconst ATTENTION_TITLE = 'Pi needs your input';\nconst ELLIPSIS = '…';\nconst MAX_BODY_LENGTH = 240;\nconst MAX_PROMPT_TITLE_LENGTH = 36;\nconst SETTLED_BODY = 'The agent finished its work and is waiting for you.';\nconst SETTLED_TITLE = 'Pi finished';\nconst SHELL_TITLE_SEPARATOR = ' - ';\nconst SHELL_TITLE_PREFIX = 'π';\n\nfunction collapseWhitespace(value: string): string {\n return value.replace(/\\s+/g, ' ').trim();\n}\n\nfunction truncate(value: string, maxLength: number): string {\n return value.length > maxLength ? `${value.slice(0, maxLength - 1)}${ELLIPSIS}` : value;\n}\n\n/** The first user prompt, shortened to fit a shell tab. A blank prompt names nothing. */\nexport function promptTitle(prompt: string): string | undefined {\n const normalized = collapseWhitespace(prompt);\n return normalized ? truncate(normalized, MAX_PROMPT_TITLE_LENGTH) : undefined;\n}\n\nexport interface ShellTabTitleInput {\n cwd: string;\n sessionName?: string;\n prompt?: string;\n}\n\n/**\n * The idle shell-tab title: `π - <label> - <repository>`.\n *\n * The session name wins over the first prompt because the user chose it. With\n * neither, the repository alone still tells two tabs apart.\n */\nexport function shellTabTitle({ cwd, sessionName, prompt }: ShellTabTitleInput): string {\n const repository = path.basename(cwd);\n const label = sessionName ?? prompt;\n return label\n ? `${SHELL_TITLE_PREFIX}${SHELL_TITLE_SEPARATOR}${label}${SHELL_TITLE_SEPARATOR}${repository}`\n : `${SHELL_TITLE_PREFIX}${SHELL_TITLE_SEPARATOR}${repository}`;\n}\n\n/** Notification bodies are one line in a system panel, so they collapse and truncate. */\nexport function notificationBody(body: string): string {\n return truncate(collapseWhitespace(body), MAX_BODY_LENGTH);\n}\n\n/** Sent while the agent holds the turn and something is blocking on the user. */\nexport function attentionNotification(body: string): DesktopNotification {\n return { title: ATTENTION_TITLE, subtitle: ATTENTION_SUBTITLE, body };\n}\n\n/** Sent once a run has stopped, subtitled with whichever name the user recognises. */\nexport function settledNotification({ cwd, sessionName }: { cwd: string; sessionName?: string }): DesktopNotification {\n return { title: SETTLED_TITLE, subtitle: sessionName ?? path.basename(cwd), body: SETTLED_BODY };\n}\n","import type { DesktopNotification, NotificationExecutor } from '../../types/notifications';\nimport { notificationBody } from '../notificationText';\n\nconst CMUX_COMMAND = 'cmux';\nconst COMMAND_TIMEOUT_MS = 3_000;\nconst DARWIN_PLATFORM = 'darwin';\nconst OSASCRIPT_COMMAND = 'osascript';\nconst OSASCRIPT_EXPRESSION_FLAG = '-e';\n\nasync function execute(pi: NotificationExecutor, command: string, args: string[]): Promise<boolean> {\n try {\n const result = await pi.exec(command, args, { timeout: COMMAND_TIMEOUT_MS });\n return result.code === 0;\n } catch {\n // A notifier that is not installed is the ordinary case, not a fault: report\n // \"not delivered\" and let the caller decide whether another one exists.\n return false;\n }\n}\n\n/**\n * Delivers one desktop notification on a best-effort basis.\n *\n * cmux is tried first because it routes the notification to the window the\n * session actually lives in. Only macOS has a second option worth attempting,\n * and a host with neither stays silent rather than failing the turn.\n */\nexport async function sendSystemNotification(\n pi: NotificationExecutor,\n notification: DesktopNotification,\n platform: string = process.platform,\n): Promise<void> {\n const body = notificationBody(notification.body);\n const sentToCmux = await execute(pi, CMUX_COMMAND, [\n 'notify',\n '--title',\n notification.title,\n '--subtitle',\n notification.subtitle,\n '--body',\n body,\n ]);\n if (sentToCmux || platform !== DARWIN_PLATFORM) return;\n\n await execute(pi, OSASCRIPT_COMMAND, [\n OSASCRIPT_EXPRESSION_FLAG,\n 'on run argv',\n OSASCRIPT_EXPRESSION_FLAG,\n 'display notification (item 3 of argv) with title (item 1 of argv) subtitle (item 2 of argv)',\n OSASCRIPT_EXPRESSION_FLAG,\n 'end run',\n notification.title,\n notification.subtitle,\n body,\n ]);\n}\n","import { sign } from 'node:crypto';\nimport { connect } from 'node:http2';\nimport { request } from 'node:https';\n\nimport type { NativePushRequest, NativePushResponse } from './type';\n\nconst MAX_RESPONSE_BYTES = 65_536;\n\nexport function signPushJwt(header: object, claims: object, key: string, algorithm: 'ES256' | 'RS256'): string {\n const input = [header, claims].map((part) => Buffer.from(JSON.stringify(part)).toString('base64url')).join('.');\n const signature = sign('sha256', Buffer.from(input), { key, dsaEncoding: 'ieee-p1363' });\n // APNs requires the raw P1363 ECDSA signature, not ASN.1 DER.\n if (algorithm === 'ES256' && signature.length !== 64) throw new Error('Invalid signing key');\n return `${input}.${signature.toString('base64url')}`;\n}\n\nexport function createPushTransport() {\n const pending = new Set<() => void>();\n return {\n request(this: void, input: NativePushRequest): Promise<NativePushResponse> {\n return new Promise((resolve, reject) => {\n const url = new URL(input.url);\n let size = 0;\n const chunks: Buffer[] = [];\n let done = false;\n let dispose = () => {};\n const finish = (error?: Error, status = 0) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n pending.delete(cancel);\n dispose();\n if (error) reject(error);\n else resolve({ status, body: Buffer.concat(chunks).toString('utf8') });\n };\n const cancel = () => finish(new Error('Push request cancelled'));\n const timer = setTimeout(() => finish(new Error('Push request timed out')), input.timeoutMs);\n pending.add(cancel);\n const data = (chunk: Buffer) => {\n size += chunk.length;\n if (size > MAX_RESPONSE_BYTES) finish(new Error('Push response too large'));\n else chunks.push(Buffer.from(chunk));\n };\n if (input.http2) {\n const session = connect(url.origin);\n dispose = () => session.destroy();\n session.on('error', (error) => finish(error));\n const stream = session.request({ ':method': 'POST', ':path': url.pathname, ...input.headers });\n let status = 0;\n stream.on('response', (headers) => {\n status = Number(headers[':status']);\n });\n stream.on('data', data);\n stream.on('error', (error) => finish(error));\n stream.on('end', () => finish(undefined, status));\n stream.end(input.body);\n } else {\n const req = request(url, { method: 'POST', headers: input.headers }, (response) => {\n response.on('data', data);\n response.on('error', (error) => finish(error));\n response.on('end', () => finish(undefined, response.statusCode));\n });\n dispose = () => req.destroy();\n req.on('error', (error) => finish(error));\n req.end(input.body);\n }\n });\n },\n close() {\n for (const cancel of pending) cancel();\n },\n };\n}\n","import type { PoNotificationEntryData } from '@agimon-ai/po-core';\n\nimport { createPushTransport, signPushJwt } from './sync';\nimport type { NativePushSender, NativePushSenderOptions } from './type';\n\nconst MAX_PAYLOAD_BYTES = 4096;\nconst APNS_TOPIC = 'ai.po.app';\nconst OAUTH_URL = 'https://oauth2.googleapis.com/token';\nconst FCM_ERROR_TYPE = 'type.googleapis.com/google.firebase.fcm.v1.FcmError';\nconst encoder = new TextEncoder();\n\nfunction parse(body: string): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(body);\n return value && typeof value === 'object' ? (value as Record<string, unknown>) : {};\n } catch {\n return {};\n } // Malformed provider responses never invalidate registrations.\n}\n\nfunction payload(\n notification: PoNotificationEntryData,\n build: (text: { title: string; subtitle: string; body: string }) => object,\n): string {\n const text = { title: notification.title, subtitle: notification.subtitle, body: notification.body };\n let result = JSON.stringify(build(text));\n // Measure the full serialized envelope, including escaped text and the FCM token.\n for (const field of ['body', 'subtitle', 'title'] as const) {\n if (encoder.encode(result).length <= MAX_PAYLOAD_BYTES) break;\n const points = Array.from(text[field]);\n let low = 0;\n let high = points.length;\n while (low < high) {\n const middle = Math.ceil((low + high) / 2);\n text[field] = points.slice(0, middle).join('');\n if (encoder.encode(JSON.stringify(build(text))).length <= MAX_PAYLOAD_BYTES) low = middle;\n else high = middle - 1;\n }\n text[field] = points.slice(0, low).join('');\n result = JSON.stringify(build(text));\n }\n if (encoder.encode(result).length > MAX_PAYLOAD_BYTES) throw new Error('Push payload too large');\n return result;\n}\n\nexport function createNativePushSender(options: NativePushSenderOptions): NativePushSender {\n const transport = createPushTransport();\n const request = options.request ?? transport.request;\n const now = options.now ?? Date.now;\n const timeoutMs = Number.isFinite(options.timeoutMs) ? Math.max(1, Math.min(options.timeoutMs!, 30_000)) : 10_000;\n let closed = false;\n let apnsJwt: { value: string; expires: number } | undefined;\n let oauth: { value: string; expires: number } | undefined;\n let oauthPending: Promise<string> | undefined;\n\n async function accessToken(): Promise<string> {\n if (oauth && now() < oauth.expires) return oauth.value;\n if (oauthPending) return oauthPending;\n oauthPending = (async () => {\n const credentials = options.fcm!;\n const issued = Math.floor(now() / 1000);\n const assertion = signPushJwt(\n { alg: 'RS256', typ: 'JWT' },\n {\n iss: credentials.clientEmail,\n scope: 'https://www.googleapis.com/auth/firebase.messaging',\n aud: OAUTH_URL,\n iat: issued,\n exp: issued + 3600,\n },\n credentials.privateKey,\n 'RS256',\n );\n const response = await request({\n url: OAUTH_URL,\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion }).toString(),\n timeoutMs,\n });\n const data = parse(response.body);\n if (\n response.status !== 200 ||\n typeof data.access_token !== 'string' ||\n !data.access_token ||\n typeof data.expires_in !== 'number' ||\n !Number.isFinite(data.expires_in) ||\n data.expires_in <= 0\n )\n throw new Error('OAuth failed');\n oauth = { value: data.access_token, expires: now() + Math.max(0, Math.min(data.expires_in, 3600) - 60) * 1000 };\n return oauth.value;\n })();\n try {\n return await oauthPending;\n } finally {\n oauthPending = undefined;\n }\n }\n\n return {\n async send(registration, notification) {\n const provider = registration.platform === 'ios' ? 'apns' : 'fcm';\n if (closed || !options[provider]) {\n options.diagnostic?.({ provider, outcome: 'unavailable' });\n return { invalid: false };\n }\n try {\n let response;\n if (registration.platform === 'ios') {\n const credentials = options.apns!;\n if (!apnsJwt || now() >= apnsJwt.expires) {\n apnsJwt = {\n value: signPushJwt(\n { alg: 'ES256', kid: credentials.keyId },\n {\n iss: credentials.teamId,\n iat: Math.floor(now() / 1000),\n },\n credentials.key,\n 'ES256',\n ),\n expires: now() + 50 * 60_000,\n };\n }\n response = await request({\n url: `https://${registration.environment === 'development' ? 'api.sandbox.push.apple.com' : 'api.push.apple.com'}/3/device/${encodeURIComponent(registration.token)}`,\n http2: true,\n timeoutMs,\n headers: {\n authorization: `bearer ${apnsJwt.value}`,\n 'apns-topic': APNS_TOPIC,\n 'apns-push-type': 'alert',\n 'apns-priority': '10',\n 'apns-expiration': '0',\n 'content-type': 'application/json',\n },\n // ponytail: live alerts only; add a durable outbox if delayed delivery becomes a requirement.\n body: payload(notification, (text) => ({ aps: { alert: text, sound: 'default' } })),\n });\n const reason = parse(response.body).reason;\n if (\n (response.status === 410 && reason === 'Unregistered') ||\n (response.status === 400 && reason === 'BadDeviceToken')\n )\n return { invalid: true };\n } else {\n const body = payload(notification, (text) => ({\n message: {\n token: registration.token,\n notification: { title: text.title, body: [text.subtitle, text.body].filter(Boolean).join('\\n') },\n // ponytail: zero TTL, no offline delivery; an outbox would own delayed sends.\n android: { ttl: '0s', priority: 'HIGH', notification: { channel_id: 'po-notifications' } },\n },\n }));\n const token = await accessToken();\n if (closed) return { invalid: false };\n response = await request({\n url: `https://fcm.googleapis.com/v1/projects/${encodeURIComponent(options.fcm!.projectId)}/messages:send`,\n headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },\n body,\n timeoutMs,\n });\n const error = parse(response.body).error;\n if (\n response.status === 404 &&\n error &&\n typeof error === 'object' &&\n 'details' in error &&\n Array.isArray(error.details) &&\n error.details.some(\n (detail: unknown) =>\n detail &&\n typeof detail === 'object' &&\n '@type' in detail &&\n detail['@type'] === FCM_ERROR_TYPE &&\n 'errorCode' in detail &&\n detail.errorCode === 'UNREGISTERED',\n )\n )\n return { invalid: true };\n }\n if (response.status < 200 || response.status >= 300)\n options.diagnostic?.({ provider, outcome: 'failed', status: response.status });\n } catch {\n // Never expose provider bodies, credentials, device tokens, or network errors.\n options.diagnostic?.({ provider, outcome: 'failed' });\n }\n return { invalid: false };\n },\n close() {\n closed = true;\n apnsJwt = undefined;\n oauth = undefined;\n transport.close();\n },\n };\n}\n","const DEFAULT_ASK_USER_BODY = 'The agent is waiting for your feedback.';\nconst RPC_MODE = 'rpc';\n\nexport interface AttentionState {\n agentRunning: boolean;\n askUserBlocked: boolean;\n}\n\nexport interface ShellSurface {\n hasUI: boolean;\n mode?: string;\n}\n\n/**\n * A dialog is worth interrupting the user for only while the agent holds the turn.\n *\n * Outside a run the user opened the dialog themselves and is already looking at\n * it. An ask-user prompt is announced by its own event, so the dialog it then\n * opens must stay silent or the same question notifies twice.\n */\nexport function warrantsAttentionNotification({ agentRunning, askUserBlocked }: AttentionState): boolean {\n return agentRunning && !askUserBlocked;\n}\n\n/** A queued follow-up means the agent keeps working, so the run has not stopped for the user. */\nexport function warrantsSettledNotification(hasPendingMessages: boolean): boolean {\n return !hasPendingMessages;\n}\n\n/** Terminal title escapes only mean something on an attached terminal; RPC output stays clean. */\nexport function supportsShellTitle({ hasUI, mode }: ShellSurface): boolean {\n return hasUI && mode !== RPC_MODE;\n}\n\n/** The question an ask-user prompt is blocking on, or a stand-in when it asked none. */\nexport function askUserPromptBody(questions: readonly { question: string }[]): string {\n return questions[0]?.question ?? DEFAULT_ASK_USER_BODY;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,MAAa,iBAAiB;CAAC;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;AAAG;;AAI/E,SAAgB,kCAAwD;CACtE,IAAI,aAAa;CACjB,IAAI;CACJ,MAAM,sBAAsB;EAC1B,IAAI,OAAO,cAAc,KAAK;EAC9B,QAAQ,KAAA;EACR,aAAa;CACf;CAEA,OAAO;EACL,IAAI,OAAO,OAAO;GAChB,cAAc;GACd,MAAM,KAAK;EACb;EACA,MAAM,OAAO,OAAO;GAClB,cAAc;GACd,MAAM,eAAe;IACnB,MAAM,GAAG,eAAe,aAAa,eAAe,QAAQ,GAAG,OAAO;IACtE,cAAc;GAChB;GACA,OAAO;GACP,QAAQ,YAAY,Q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BAAkB,WAAoD;CACpF,OAAO,UAAU,EAAE,EAAE,YAAY;AACnC"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PoNotificationEntryData } from "@agimon-ai/po-core";
|
|
1
2
|
//#region src/types/notifications.d.ts
|
|
2
3
|
interface NotificationExtensionOptions {
|
|
3
4
|
/** Replaces the worker-thread animator, which a host without worker threads cannot start. */
|
|
@@ -63,6 +64,56 @@ export declare function createWorkerTitleController(): ShellTitleController;
|
|
|
63
64
|
*/
|
|
64
65
|
export declare function sendSystemNotification(pi: NotificationExecutor, notification: DesktopNotification, platform?: string): Promise<void>;
|
|
65
66
|
//#endregion
|
|
67
|
+
//#region src/services/nativePushSender/type.d.ts
|
|
68
|
+
type NativePushRegistration = {
|
|
69
|
+
platform: 'ios';
|
|
70
|
+
token: string;
|
|
71
|
+
environment: 'development' | 'production';
|
|
72
|
+
} | {
|
|
73
|
+
platform: 'android';
|
|
74
|
+
token: string;
|
|
75
|
+
};
|
|
76
|
+
interface NativePushRequest {
|
|
77
|
+
url: string;
|
|
78
|
+
headers: Record<string, string>;
|
|
79
|
+
body: string;
|
|
80
|
+
timeoutMs: number;
|
|
81
|
+
http2?: boolean;
|
|
82
|
+
}
|
|
83
|
+
interface NativePushResponse {
|
|
84
|
+
status: number;
|
|
85
|
+
body: string;
|
|
86
|
+
}
|
|
87
|
+
interface NativePushSenderOptions {
|
|
88
|
+
apns?: {
|
|
89
|
+
key: string;
|
|
90
|
+
keyId: string;
|
|
91
|
+
teamId: string;
|
|
92
|
+
};
|
|
93
|
+
fcm?: {
|
|
94
|
+
clientEmail: string;
|
|
95
|
+
privateKey: string;
|
|
96
|
+
projectId: string;
|
|
97
|
+
};
|
|
98
|
+
now?: () => number;
|
|
99
|
+
request?: (request: NativePushRequest) => Promise<NativePushResponse>;
|
|
100
|
+
timeoutMs?: number;
|
|
101
|
+
diagnostic?: (event: {
|
|
102
|
+
provider: 'apns' | 'fcm';
|
|
103
|
+
outcome: 'failed' | 'unavailable';
|
|
104
|
+
status?: number;
|
|
105
|
+
}) => void;
|
|
106
|
+
}
|
|
107
|
+
interface NativePushSender {
|
|
108
|
+
send(registration: NativePushRegistration, notification: PoNotificationEntryData): Promise<{
|
|
109
|
+
invalid: boolean;
|
|
110
|
+
}>;
|
|
111
|
+
close(): void;
|
|
112
|
+
}
|
|
113
|
+
//#endregion
|
|
114
|
+
//#region src/services/nativePushSender/index.d.ts
|
|
115
|
+
export declare function createNativePushSender(options: NativePushSenderOptions): NativePushSender;
|
|
116
|
+
//#endregion
|
|
66
117
|
//#region src/services/notificationPolicy/index.d.ts
|
|
67
118
|
interface AttentionState {
|
|
68
119
|
agentRunning: boolean;
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types/notifications.ts","../src/services/shellTitleController/mainThread.ts","../src/services/shellTitleController/index.ts","../src/services/systemNotification/index.ts","../src/services/notificationPolicy/index.ts","../src/services/notificationText/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types/notifications.ts","../src/services/shellTitleController/mainThread.ts","../src/services/shellTitleController/index.ts","../src/services/systemNotification/index.ts","../src/services/nativePushSender/type.ts","../src/services/nativePushSender/index.ts","../src/services/notificationPolicy/index.ts","../src/services/notificationText/index.ts"],"mappings":";;UAAiB;;EAEf,kBAAkB;EAClB,cAAc,OAAO;;UAGN;EACf,KAAK,iBAAiB,gBAAgB;IAAW;MAAoB;IAAU;;;;KAIrE,cAAc;;KAGd;;UAGK;EACf,QAAQ;EACR;;;;;;;;;;UAWe;EACf,IAAI,eAAe,OAAO;EAC1B,MAAM,eAAe,OAAO;EAC5B,KAAK,eAAe,OAAO;EAC3B,QAAQ,eAAe,OAAO;;;UAIf;EACf;EACA;EACA;;;;;wBCnCc,mCAAmC;;;;;;;;wBCsCnC,+BAA+B;;;;;;;;;;wBCjBzB,uBACpB,IAAI,sBACJ,cAAc,qBACd,oBACC;;;KC7BS;EACN;EAAiB;EAAe;;EAChC;EAAqB;;UAEV;EACf;EACA,SAAS;EACT;EACA;EACA;;UAEe;EACf;EACA;;UAEe;EACf;IAAS;IAAa;IAAe;;EACrC;IAAQ;IAAqB;IAAoB;;EACjD;EACA,WAAW,SAAS,sBAAsB,QAAQ;EAClD;EACA,cAAc;IAAS;IAA0B;IAAmC;;;UAErE;EACf,KAAK,cAAc,wBAAwB,cAAc,0BAA0B;IAAU;;EAC7F;;;;wBCkBc,uBAAuB,SAAS,0BAA0B;;;UC1CzD;EACf;EACA;;UAGe;EACf;EACA;;;;;;;;;wBAUc,gCAAgC,cAAc,kBAAkB;;wBAKhE,4BAA4B;;wBAK5B,qBAAqB,OAAO,QAAQ;;wBAKpC,kBAAkB;EAAsB;;;;;wBCZxC,YAAY;UAKX;EACf;EACA;EACA;;;;;;;;wBASc,gBAAgB,KAAK,aAAa,UAAU;;wBAS5C,iBAAiB;;wBAKjB,sBAAsB,eAAe;;wBAKrC,sBAAsB,KAAK;EAAiB;EAAa;IAAyB"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { Worker } from "node:worker_threads";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { sign } from "node:crypto";
|
|
4
|
+
import { connect } from "node:http2";
|
|
5
|
+
import { request } from "node:https";
|
|
3
6
|
//#region src/services/shellTitleController/mainThread.ts
|
|
4
7
|
const BRAILLE_FRAMES = [
|
|
5
8
|
"⠋",
|
|
@@ -242,6 +245,267 @@ async function sendSystemNotification(pi, notification, platform = process.platf
|
|
|
242
245
|
]);
|
|
243
246
|
}
|
|
244
247
|
//#endregion
|
|
248
|
+
//#region src/services/nativePushSender/sync.ts
|
|
249
|
+
const MAX_RESPONSE_BYTES = 65536;
|
|
250
|
+
function signPushJwt(header, claims, key, algorithm) {
|
|
251
|
+
const input = [header, claims].map((part) => Buffer.from(JSON.stringify(part)).toString("base64url")).join(".");
|
|
252
|
+
const signature = sign("sha256", Buffer.from(input), {
|
|
253
|
+
key,
|
|
254
|
+
dsaEncoding: "ieee-p1363"
|
|
255
|
+
});
|
|
256
|
+
if (algorithm === "ES256" && signature.length !== 64) throw new Error("Invalid signing key");
|
|
257
|
+
return `${input}.${signature.toString("base64url")}`;
|
|
258
|
+
}
|
|
259
|
+
function createPushTransport() {
|
|
260
|
+
const pending = /* @__PURE__ */ new Set();
|
|
261
|
+
return {
|
|
262
|
+
request(input) {
|
|
263
|
+
return new Promise((resolve, reject) => {
|
|
264
|
+
const url = new URL(input.url);
|
|
265
|
+
let size = 0;
|
|
266
|
+
const chunks = [];
|
|
267
|
+
let done = false;
|
|
268
|
+
let dispose = () => {};
|
|
269
|
+
const finish = (error, status = 0) => {
|
|
270
|
+
if (done) return;
|
|
271
|
+
done = true;
|
|
272
|
+
clearTimeout(timer);
|
|
273
|
+
pending.delete(cancel);
|
|
274
|
+
dispose();
|
|
275
|
+
if (error) reject(error);
|
|
276
|
+
else resolve({
|
|
277
|
+
status,
|
|
278
|
+
body: Buffer.concat(chunks).toString("utf8")
|
|
279
|
+
});
|
|
280
|
+
};
|
|
281
|
+
const cancel = () => finish(/* @__PURE__ */ new Error("Push request cancelled"));
|
|
282
|
+
const timer = setTimeout(() => finish(/* @__PURE__ */ new Error("Push request timed out")), input.timeoutMs);
|
|
283
|
+
pending.add(cancel);
|
|
284
|
+
const data = (chunk) => {
|
|
285
|
+
size += chunk.length;
|
|
286
|
+
if (size > MAX_RESPONSE_BYTES) finish(/* @__PURE__ */ new Error("Push response too large"));
|
|
287
|
+
else chunks.push(Buffer.from(chunk));
|
|
288
|
+
};
|
|
289
|
+
if (input.http2) {
|
|
290
|
+
const session = connect(url.origin);
|
|
291
|
+
dispose = () => session.destroy();
|
|
292
|
+
session.on("error", (error) => finish(error));
|
|
293
|
+
const stream = session.request({
|
|
294
|
+
":method": "POST",
|
|
295
|
+
":path": url.pathname,
|
|
296
|
+
...input.headers
|
|
297
|
+
});
|
|
298
|
+
let status = 0;
|
|
299
|
+
stream.on("response", (headers) => {
|
|
300
|
+
status = Number(headers[":status"]);
|
|
301
|
+
});
|
|
302
|
+
stream.on("data", data);
|
|
303
|
+
stream.on("error", (error) => finish(error));
|
|
304
|
+
stream.on("end", () => finish(void 0, status));
|
|
305
|
+
stream.end(input.body);
|
|
306
|
+
} else {
|
|
307
|
+
const req = request(url, {
|
|
308
|
+
method: "POST",
|
|
309
|
+
headers: input.headers
|
|
310
|
+
}, (response) => {
|
|
311
|
+
response.on("data", data);
|
|
312
|
+
response.on("error", (error) => finish(error));
|
|
313
|
+
response.on("end", () => finish(void 0, response.statusCode));
|
|
314
|
+
});
|
|
315
|
+
dispose = () => req.destroy();
|
|
316
|
+
req.on("error", (error) => finish(error));
|
|
317
|
+
req.end(input.body);
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
},
|
|
321
|
+
close() {
|
|
322
|
+
for (const cancel of pending) cancel();
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
//#endregion
|
|
327
|
+
//#region src/services/nativePushSender/index.ts
|
|
328
|
+
const MAX_PAYLOAD_BYTES = 4096;
|
|
329
|
+
const APNS_TOPIC = "ai.po.app";
|
|
330
|
+
const OAUTH_URL = "https://oauth2.googleapis.com/token";
|
|
331
|
+
const FCM_ERROR_TYPE = "type.googleapis.com/google.firebase.fcm.v1.FcmError";
|
|
332
|
+
const encoder = new TextEncoder();
|
|
333
|
+
function parse(body) {
|
|
334
|
+
try {
|
|
335
|
+
const value = JSON.parse(body);
|
|
336
|
+
return value && typeof value === "object" ? value : {};
|
|
337
|
+
} catch {
|
|
338
|
+
return {};
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
function payload(notification, build) {
|
|
342
|
+
const text = {
|
|
343
|
+
title: notification.title,
|
|
344
|
+
subtitle: notification.subtitle,
|
|
345
|
+
body: notification.body
|
|
346
|
+
};
|
|
347
|
+
let result = JSON.stringify(build(text));
|
|
348
|
+
for (const field of [
|
|
349
|
+
"body",
|
|
350
|
+
"subtitle",
|
|
351
|
+
"title"
|
|
352
|
+
]) {
|
|
353
|
+
if (encoder.encode(result).length <= MAX_PAYLOAD_BYTES) break;
|
|
354
|
+
const points = Array.from(text[field]);
|
|
355
|
+
let low = 0;
|
|
356
|
+
let high = points.length;
|
|
357
|
+
while (low < high) {
|
|
358
|
+
const middle = Math.ceil((low + high) / 2);
|
|
359
|
+
text[field] = points.slice(0, middle).join("");
|
|
360
|
+
if (encoder.encode(JSON.stringify(build(text))).length <= MAX_PAYLOAD_BYTES) low = middle;
|
|
361
|
+
else high = middle - 1;
|
|
362
|
+
}
|
|
363
|
+
text[field] = points.slice(0, low).join("");
|
|
364
|
+
result = JSON.stringify(build(text));
|
|
365
|
+
}
|
|
366
|
+
if (encoder.encode(result).length > MAX_PAYLOAD_BYTES) throw new Error("Push payload too large");
|
|
367
|
+
return result;
|
|
368
|
+
}
|
|
369
|
+
function createNativePushSender(options) {
|
|
370
|
+
const transport = createPushTransport();
|
|
371
|
+
const request = options.request ?? transport.request;
|
|
372
|
+
const now = options.now ?? Date.now;
|
|
373
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) ? Math.max(1, Math.min(options.timeoutMs, 3e4)) : 1e4;
|
|
374
|
+
let closed = false;
|
|
375
|
+
let apnsJwt;
|
|
376
|
+
let oauth;
|
|
377
|
+
let oauthPending;
|
|
378
|
+
async function accessToken() {
|
|
379
|
+
if (oauth && now() < oauth.expires) return oauth.value;
|
|
380
|
+
if (oauthPending) return oauthPending;
|
|
381
|
+
oauthPending = (async () => {
|
|
382
|
+
const credentials = options.fcm;
|
|
383
|
+
const issued = Math.floor(now() / 1e3);
|
|
384
|
+
const assertion = signPushJwt({
|
|
385
|
+
alg: "RS256",
|
|
386
|
+
typ: "JWT"
|
|
387
|
+
}, {
|
|
388
|
+
iss: credentials.clientEmail,
|
|
389
|
+
scope: "https://www.googleapis.com/auth/firebase.messaging",
|
|
390
|
+
aud: OAUTH_URL,
|
|
391
|
+
iat: issued,
|
|
392
|
+
exp: issued + 3600
|
|
393
|
+
}, credentials.privateKey, "RS256");
|
|
394
|
+
const response = await request({
|
|
395
|
+
url: OAUTH_URL,
|
|
396
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
397
|
+
body: new URLSearchParams({
|
|
398
|
+
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
|
399
|
+
assertion
|
|
400
|
+
}).toString(),
|
|
401
|
+
timeoutMs
|
|
402
|
+
});
|
|
403
|
+
const data = parse(response.body);
|
|
404
|
+
if (response.status !== 200 || typeof data.access_token !== "string" || !data.access_token || typeof data.expires_in !== "number" || !Number.isFinite(data.expires_in) || data.expires_in <= 0) throw new Error("OAuth failed");
|
|
405
|
+
oauth = {
|
|
406
|
+
value: data.access_token,
|
|
407
|
+
expires: now() + Math.max(0, Math.min(data.expires_in, 3600) - 60) * 1e3
|
|
408
|
+
};
|
|
409
|
+
return oauth.value;
|
|
410
|
+
})();
|
|
411
|
+
try {
|
|
412
|
+
return await oauthPending;
|
|
413
|
+
} finally {
|
|
414
|
+
oauthPending = void 0;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return {
|
|
418
|
+
async send(registration, notification) {
|
|
419
|
+
const provider = registration.platform === "ios" ? "apns" : "fcm";
|
|
420
|
+
if (closed || !options[provider]) {
|
|
421
|
+
options.diagnostic?.({
|
|
422
|
+
provider,
|
|
423
|
+
outcome: "unavailable"
|
|
424
|
+
});
|
|
425
|
+
return { invalid: false };
|
|
426
|
+
}
|
|
427
|
+
try {
|
|
428
|
+
let response;
|
|
429
|
+
if (registration.platform === "ios") {
|
|
430
|
+
const credentials = options.apns;
|
|
431
|
+
if (!apnsJwt || now() >= apnsJwt.expires) apnsJwt = {
|
|
432
|
+
value: signPushJwt({
|
|
433
|
+
alg: "ES256",
|
|
434
|
+
kid: credentials.keyId
|
|
435
|
+
}, {
|
|
436
|
+
iss: credentials.teamId,
|
|
437
|
+
iat: Math.floor(now() / 1e3)
|
|
438
|
+
}, credentials.key, "ES256"),
|
|
439
|
+
expires: now() + 3e6
|
|
440
|
+
};
|
|
441
|
+
response = await request({
|
|
442
|
+
url: `https://${registration.environment === "development" ? "api.sandbox.push.apple.com" : "api.push.apple.com"}/3/device/${encodeURIComponent(registration.token)}`,
|
|
443
|
+
http2: true,
|
|
444
|
+
timeoutMs,
|
|
445
|
+
headers: {
|
|
446
|
+
authorization: `bearer ${apnsJwt.value}`,
|
|
447
|
+
"apns-topic": APNS_TOPIC,
|
|
448
|
+
"apns-push-type": "alert",
|
|
449
|
+
"apns-priority": "10",
|
|
450
|
+
"apns-expiration": "0",
|
|
451
|
+
"content-type": "application/json"
|
|
452
|
+
},
|
|
453
|
+
body: payload(notification, (text) => ({ aps: {
|
|
454
|
+
alert: text,
|
|
455
|
+
sound: "default"
|
|
456
|
+
} }))
|
|
457
|
+
});
|
|
458
|
+
const reason = parse(response.body).reason;
|
|
459
|
+
if (response.status === 410 && reason === "Unregistered" || response.status === 400 && reason === "BadDeviceToken") return { invalid: true };
|
|
460
|
+
} else {
|
|
461
|
+
const body = payload(notification, (text) => ({ message: {
|
|
462
|
+
token: registration.token,
|
|
463
|
+
notification: {
|
|
464
|
+
title: text.title,
|
|
465
|
+
body: [text.subtitle, text.body].filter(Boolean).join("\n")
|
|
466
|
+
},
|
|
467
|
+
android: {
|
|
468
|
+
ttl: "0s",
|
|
469
|
+
priority: "HIGH",
|
|
470
|
+
notification: { channel_id: "po-notifications" }
|
|
471
|
+
}
|
|
472
|
+
} }));
|
|
473
|
+
const token = await accessToken();
|
|
474
|
+
if (closed) return { invalid: false };
|
|
475
|
+
response = await request({
|
|
476
|
+
url: `https://fcm.googleapis.com/v1/projects/${encodeURIComponent(options.fcm.projectId)}/messages:send`,
|
|
477
|
+
headers: {
|
|
478
|
+
authorization: `Bearer ${token}`,
|
|
479
|
+
"content-type": "application/json"
|
|
480
|
+
},
|
|
481
|
+
body,
|
|
482
|
+
timeoutMs
|
|
483
|
+
});
|
|
484
|
+
const error = parse(response.body).error;
|
|
485
|
+
if (response.status === 404 && error && typeof error === "object" && "details" in error && Array.isArray(error.details) && error.details.some((detail) => detail && typeof detail === "object" && "@type" in detail && detail["@type"] === FCM_ERROR_TYPE && "errorCode" in detail && detail.errorCode === "UNREGISTERED")) return { invalid: true };
|
|
486
|
+
}
|
|
487
|
+
if (response.status < 200 || response.status >= 300) options.diagnostic?.({
|
|
488
|
+
provider,
|
|
489
|
+
outcome: "failed",
|
|
490
|
+
status: response.status
|
|
491
|
+
});
|
|
492
|
+
} catch {
|
|
493
|
+
options.diagnostic?.({
|
|
494
|
+
provider,
|
|
495
|
+
outcome: "failed"
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
return { invalid: false };
|
|
499
|
+
},
|
|
500
|
+
close() {
|
|
501
|
+
closed = true;
|
|
502
|
+
apnsJwt = void 0;
|
|
503
|
+
oauth = void 0;
|
|
504
|
+
transport.close();
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
//#endregion
|
|
245
509
|
//#region src/services/notificationPolicy/index.ts
|
|
246
510
|
const DEFAULT_ASK_USER_BODY = "The agent is waiting for your feedback.";
|
|
247
511
|
const RPC_MODE = "rpc";
|
|
@@ -268,6 +532,6 @@ function askUserPromptBody(questions) {
|
|
|
268
532
|
return questions[0]?.question ?? DEFAULT_ASK_USER_BODY;
|
|
269
533
|
}
|
|
270
534
|
//#endregion
|
|
271
|
-
export { askUserPromptBody, attentionNotification, createMainThreadTitleController, createWorkerTitleController, notificationBody, promptTitle, sendSystemNotification, settledNotification, shellTabTitle, supportsShellTitle, warrantsAttentionNotification, warrantsSettledNotification };
|
|
535
|
+
export { askUserPromptBody, attentionNotification, createMainThreadTitleController, createNativePushSender, createWorkerTitleController, notificationBody, promptTitle, sendSystemNotification, settledNotification, shellTabTitle, supportsShellTitle, warrantsAttentionNotification, warrantsSettledNotification };
|
|
272
536
|
|
|
273
537
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/services/shellTitleController/mainThread.ts","../src/services/shellTitleController/index.ts","../src/services/notificationText/index.ts","../src/services/systemNotification/index.ts","../src/services/notificationPolicy/index.ts"],"sourcesContent":["import type { ShellTitleController } from '../../types/notifications';\n\nexport const BRAILLE_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\nexport const TITLE_FRAME_INTERVAL_MS = 80;\n\n/** Animates on the main thread, for hosts where a worker could not be started. */\nexport function createMainThreadTitleController(): ShellTitleController {\n let frameIndex = 0;\n let timer: ReturnType<typeof setInterval> | undefined;\n const stopAnimation = () => {\n if (timer) clearInterval(timer);\n timer = undefined;\n frameIndex = 0;\n };\n\n return {\n set(title, write) {\n stopAnimation();\n write(title);\n },\n start(title, write) {\n stopAnimation();\n const render = () => {\n write(`${BRAILLE_FRAMES[frameIndex % BRAILLE_FRAMES.length]} ${title}`);\n frameIndex += 1;\n };\n render();\n timer = setInterval(render, TITLE_FRAME_INTERVAL_MS);\n },\n stop(title, write) {\n stopAnimation();\n write(title);\n },\n dispose(title, write) {\n stopAnimation();\n write(title);\n },\n };\n}\n","import { Worker } from 'node:worker_threads';\n\nimport type { ShellTitleCommand, ShellTitleController, WriteTitle } from '../../types/notifications';\nimport { BRAILLE_FRAMES, TITLE_FRAME_INTERVAL_MS, createMainThreadTitleController } from './mainThread';\n\nexport { createMainThreadTitleController } from './mainThread';\n/**\n * The animator runs off the main thread so a busy agent turn cannot stall the\n * spinner. It is an inline eval source rather than a shipped file because the\n * package is bundled per entry, and a separate worker module would have to be\n * located on disk at runtime.\n */\nconst TITLE_WORKER_SOURCE = `\nconst { writeSync } = require('node:fs');\nconst { parentPort, workerData } = require('node:worker_threads');\nlet frameIndex = 0;\nlet timer;\nconst writeTitle = (title) => writeSync(1, '\\\\u001b]0;' + title + '\\\\u0007');\nconst stop = () => {\n if (timer) clearInterval(timer);\n timer = undefined;\n frameIndex = 0;\n};\nparentPort.on('message', (command) => {\n stop();\n if (command.action === 'start') {\n const render = () => {\n writeTitle(workerData.frames[frameIndex % workerData.frames.length] + ' ' + command.title);\n frameIndex += 1;\n };\n render();\n timer = setInterval(render, workerData.intervalMs);\n return;\n }\n writeTitle(command.title);\n if (command.action === 'dispose') parentPort.close();\n});\n`;\n\n/**\n * Animates from a worker thread, replaying the last command on the main thread\n * if the worker never started, failed, or exited under us. The worker is\n * unreferenced so a pending frame never holds the process open.\n */\nexport function createWorkerTitleController(): ShellTitleController {\n const fallback = createMainThreadTitleController();\n let lastCommand: ShellTitleCommand | undefined;\n let lastWrite: WriteTitle | undefined;\n let worker: Worker | undefined;\n\n const fallBack = () => {\n worker = undefined;\n if (!lastCommand || !lastWrite) return;\n fallback[lastCommand.action](lastCommand.title, lastWrite);\n };\n\n try {\n const titleWorker = new Worker(TITLE_WORKER_SOURCE, {\n eval: true,\n workerData: { frames: BRAILLE_FRAMES, intervalMs: TITLE_FRAME_INTERVAL_MS },\n });\n titleWorker.unref();\n titleWorker.once('error', fallBack);\n titleWorker.once('exit', (code) => {\n if (code !== 0 && worker === titleWorker) fallBack();\n });\n worker = titleWorker;\n } catch {\n // Workers are unavailable on this host, which the main-thread animator covers.\n worker = undefined;\n }\n\n const dispatch = (command: ShellTitleCommand, write: WriteTitle) => {\n lastCommand = command;\n lastWrite = write;\n if (!worker) {\n fallback[command.action](command.title, write);\n return;\n }\n try {\n worker.postMessage(command);\n } catch {\n // The worker closed between the last frame and this command.\n fallBack();\n }\n };\n\n return {\n set: (title, write) => dispatch({ action: 'set', title }, write),\n start: (title, write) => dispatch({ action: 'start', title }, write),\n stop: (title, write) => dispatch({ action: 'stop', title }, write),\n dispose: (title, write) => dispatch({ action: 'dispose', title }, write),\n };\n}\n","import path from 'node:path';\n\nimport type { DesktopNotification } from '../../types/notifications';\n\nconst ATTENTION_SUBTITLE = 'Approval or feedback required';\nconst ATTENTION_TITLE = 'Pi needs your input';\nconst ELLIPSIS = '…';\nconst MAX_BODY_LENGTH = 240;\nconst MAX_PROMPT_TITLE_LENGTH = 36;\nconst SETTLED_BODY = 'The agent finished its work and is waiting for you.';\nconst SETTLED_TITLE = 'Pi finished';\nconst SHELL_TITLE_SEPARATOR = ' - ';\nconst SHELL_TITLE_PREFIX = 'π';\n\nfunction collapseWhitespace(value: string): string {\n return value.replace(/\\s+/g, ' ').trim();\n}\n\nfunction truncate(value: string, maxLength: number): string {\n return value.length > maxLength ? `${value.slice(0, maxLength - 1)}${ELLIPSIS}` : value;\n}\n\n/** The first user prompt, shortened to fit a shell tab. A blank prompt names nothing. */\nexport function promptTitle(prompt: string): string | undefined {\n const normalized = collapseWhitespace(prompt);\n return normalized ? truncate(normalized, MAX_PROMPT_TITLE_LENGTH) : undefined;\n}\n\nexport interface ShellTabTitleInput {\n cwd: string;\n sessionName?: string;\n prompt?: string;\n}\n\n/**\n * The idle shell-tab title: `π - <label> - <repository>`.\n *\n * The session name wins over the first prompt because the user chose it. With\n * neither, the repository alone still tells two tabs apart.\n */\nexport function shellTabTitle({ cwd, sessionName, prompt }: ShellTabTitleInput): string {\n const repository = path.basename(cwd);\n const label = sessionName ?? prompt;\n return label\n ? `${SHELL_TITLE_PREFIX}${SHELL_TITLE_SEPARATOR}${label}${SHELL_TITLE_SEPARATOR}${repository}`\n : `${SHELL_TITLE_PREFIX}${SHELL_TITLE_SEPARATOR}${repository}`;\n}\n\n/** Notification bodies are one line in a system panel, so they collapse and truncate. */\nexport function notificationBody(body: string): string {\n return truncate(collapseWhitespace(body), MAX_BODY_LENGTH);\n}\n\n/** Sent while the agent holds the turn and something is blocking on the user. */\nexport function attentionNotification(body: string): DesktopNotification {\n return { title: ATTENTION_TITLE, subtitle: ATTENTION_SUBTITLE, body };\n}\n\n/** Sent once a run has stopped, subtitled with whichever name the user recognises. */\nexport function settledNotification({ cwd, sessionName }: { cwd: string; sessionName?: string }): DesktopNotification {\n return { title: SETTLED_TITLE, subtitle: sessionName ?? path.basename(cwd), body: SETTLED_BODY };\n}\n","import type { DesktopNotification, NotificationExecutor } from '../../types/notifications';\nimport { notificationBody } from '../notificationText';\n\nconst CMUX_COMMAND = 'cmux';\nconst COMMAND_TIMEOUT_MS = 3_000;\nconst DARWIN_PLATFORM = 'darwin';\nconst OSASCRIPT_COMMAND = 'osascript';\nconst OSASCRIPT_EXPRESSION_FLAG = '-e';\n\nasync function execute(pi: NotificationExecutor, command: string, args: string[]): Promise<boolean> {\n try {\n const result = await pi.exec(command, args, { timeout: COMMAND_TIMEOUT_MS });\n return result.code === 0;\n } catch {\n // A notifier that is not installed is the ordinary case, not a fault: report\n // \"not delivered\" and let the caller decide whether another one exists.\n return false;\n }\n}\n\n/**\n * Delivers one desktop notification on a best-effort basis.\n *\n * cmux is tried first because it routes the notification to the window the\n * session actually lives in. Only macOS has a second option worth attempting,\n * and a host with neither stays silent rather than failing the turn.\n */\nexport async function sendSystemNotification(\n pi: NotificationExecutor,\n notification: DesktopNotification,\n platform: string = process.platform,\n): Promise<void> {\n const body = notificationBody(notification.body);\n const sentToCmux = await execute(pi, CMUX_COMMAND, [\n 'notify',\n '--title',\n notification.title,\n '--subtitle',\n notification.subtitle,\n '--body',\n body,\n ]);\n if (sentToCmux || platform !== DARWIN_PLATFORM) return;\n\n await execute(pi, OSASCRIPT_COMMAND, [\n OSASCRIPT_EXPRESSION_FLAG,\n 'on run argv',\n OSASCRIPT_EXPRESSION_FLAG,\n 'display notification (item 3 of argv) with title (item 1 of argv) subtitle (item 2 of argv)',\n OSASCRIPT_EXPRESSION_FLAG,\n 'end run',\n notification.title,\n notification.subtitle,\n body,\n ]);\n}\n","const DEFAULT_ASK_USER_BODY = 'The agent is waiting for your feedback.';\nconst RPC_MODE = 'rpc';\n\nexport interface AttentionState {\n agentRunning: boolean;\n askUserBlocked: boolean;\n}\n\nexport interface ShellSurface {\n hasUI: boolean;\n mode?: string;\n}\n\n/**\n * A dialog is worth interrupting the user for only while the agent holds the turn.\n *\n * Outside a run the user opened the dialog themselves and is already looking at\n * it. An ask-user prompt is announced by its own event, so the dialog it then\n * opens must stay silent or the same question notifies twice.\n */\nexport function warrantsAttentionNotification({ agentRunning, askUserBlocked }: AttentionState): boolean {\n return agentRunning && !askUserBlocked;\n}\n\n/** A queued follow-up means the agent keeps working, so the run has not stopped for the user. */\nexport function warrantsSettledNotification(hasPendingMessages: boolean): boolean {\n return !hasPendingMessages;\n}\n\n/** Terminal title escapes only mean something on an attached terminal; RPC output stays clean. */\nexport function supportsShellTitle({ hasUI, mode }: ShellSurface): boolean {\n return hasUI && mode !== RPC_MODE;\n}\n\n/** The question an ask-user prompt is blocking on, or a stand-in when it asked none. */\nexport function askUserPromptBody(questions: readonly { question: string }[]): string {\n return questions[0]?.question ?? DEFAULT_ASK_USER_BODY;\n}\n"],"mappings":";;;AAEA,MAAa,iBAAiB;CAAC;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;AAAG;;AAI/E,SAAgB,kCAAwD;CACtE,IAAI,aAAa;CACjB,IAAI;CACJ,MAAM,sBAAsB;EAC1B,IAAI,OAAO,cAAc,KAAK;EAC9B,QAAQ,KAAA;EACR,aAAa;CACf;CAEA,OAAO;EACL,IAAI,OAAO,OAAO;GAChB,cAAc;GACd,MAAM,KAAK;EACb;EACA,MAAM,OAAO,OAAO;GAClB,cAAc;GACd,MAAM,eAAe;IACnB,MAAM,GAAG,eAAe,aAAa,eAAe,QAAQ,GAAG,OAAO;IACtE,cAAc;GAChB;GACA,OAAO;GACP,QAAQ,YAAY,QAAA,EAA+B;EACrD;EACA,KAAK,OAAO,OAAO;GACjB,cAAc;GACd,MAAM,KAAK;EACb;EACA,QAAQ,OAAO,OAAO;GACpB,cAAc;GACd,MAAM,KAAK;EACb;CACF;AACF;;;;;;;;;AC1BA,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;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ACA;EACA,aAAa;EACb;EACA,aAAa;EACb;EACA;CACF,CAAC,KACiB,aAAa,iBAAiB;CAEhD,MAAM,QAAQ,IAAI,mBAAmB;EACnC;EACA;EACA;EACA;EACA;EACA;EACA,aAAa;EACb,aAAa;EACb;CACF,CAAC;AACH;;;ACvDA,MAAM,wBAAwB;AAC9B,MAAM,WAAW;;;;;;;;AAmBjB,SAAgB,8BAA8B,EAAE,cAAc,kBAA2C;CACvG,OAAO,gBAAgB,CAAC;AAC1B;;AAGA,SAAgB,4BAA4B,oBAAsC;CAChF,OAAO,CAAC;AACV;;AAGA,SAAgB,mBAAmB,EAAE,OAAO,QAA+B;CACzE,OAAO,SAAS,SAAS;AAC3B;;AAGA,SAAgB,kBAAkB,WAAoD;CACpF,OAAO,UAAU,EAAE,EAAE,YAAY;AACnC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/services/shellTitleController/mainThread.ts","../src/services/shellTitleController/index.ts","../src/services/notificationText/index.ts","../src/services/systemNotification/index.ts","../src/services/nativePushSender/sync.ts","../src/services/nativePushSender/index.ts","../src/services/notificationPolicy/index.ts"],"sourcesContent":["import type { ShellTitleController } from '../../types/notifications';\n\nexport const BRAILLE_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\nexport const TITLE_FRAME_INTERVAL_MS = 80;\n\n/** Animates on the main thread, for hosts where a worker could not be started. */\nexport function createMainThreadTitleController(): ShellTitleController {\n let frameIndex = 0;\n let timer: ReturnType<typeof setInterval> | undefined;\n const stopAnimation = () => {\n if (timer) clearInterval(timer);\n timer = undefined;\n frameIndex = 0;\n };\n\n return {\n set(title, write) {\n stopAnimation();\n write(title);\n },\n start(title, write) {\n stopAnimation();\n const render = () => {\n write(`${BRAILLE_FRAMES[frameIndex % BRAILLE_FRAMES.length]} ${title}`);\n frameIndex += 1;\n };\n render();\n timer = setInterval(render, TITLE_FRAME_INTERVAL_MS);\n },\n stop(title, write) {\n stopAnimation();\n write(title);\n },\n dispose(title, write) {\n stopAnimation();\n write(title);\n },\n };\n}\n","import { Worker } from 'node:worker_threads';\n\nimport type { ShellTitleCommand, ShellTitleController, WriteTitle } from '../../types/notifications';\nimport { BRAILLE_FRAMES, TITLE_FRAME_INTERVAL_MS, createMainThreadTitleController } from './mainThread';\n\nexport { createMainThreadTitleController } from './mainThread';\n/**\n * The animator runs off the main thread so a busy agent turn cannot stall the\n * spinner. It is an inline eval source rather than a shipped file because the\n * package is bundled per entry, and a separate worker module would have to be\n * located on disk at runtime.\n */\nconst TITLE_WORKER_SOURCE = `\nconst { writeSync } = require('node:fs');\nconst { parentPort, workerData } = require('node:worker_threads');\nlet frameIndex = 0;\nlet timer;\nconst writeTitle = (title) => writeSync(1, '\\\\u001b]0;' + title + '\\\\u0007');\nconst stop = () => {\n if (timer) clearInterval(timer);\n timer = undefined;\n frameIndex = 0;\n};\nparentPort.on('message', (command) => {\n stop();\n if (command.action === 'start') {\n const render = () => {\n writeTitle(workerData.frames[frameIndex % workerData.frames.length] + ' ' + command.title);\n frameIndex += 1;\n };\n render();\n timer = setInterval(render, workerData.intervalMs);\n return;\n }\n writeTitle(command.title);\n if (command.action === 'dispose') parentPort.close();\n});\n`;\n\n/**\n * Animates from a worker thread, replaying the last command on the main thread\n * if the worker never started, failed, or exited under us. The worker is\n * unreferenced so a pending frame never holds the process open.\n */\nexport function createWorkerTitleController(): ShellTitleController {\n const fallback = createMainThreadTitleController();\n let lastCommand: ShellTitleCommand | undefined;\n let lastWrite: WriteTitle | undefined;\n let worker: Worker | undefined;\n\n const fallBack = () => {\n worker = undefined;\n if (!lastCommand || !lastWrite) return;\n fallback[lastCommand.action](lastCommand.title, lastWrite);\n };\n\n try {\n const titleWorker = new Worker(TITLE_WORKER_SOURCE, {\n eval: true,\n workerData: { frames: BRAILLE_FRAMES, intervalMs: TITLE_FRAME_INTERVAL_MS },\n });\n titleWorker.unref();\n titleWorker.once('error', fallBack);\n titleWorker.once('exit', (code) => {\n if (code !== 0 && worker === titleWorker) fallBack();\n });\n worker = titleWorker;\n } catch {\n // Workers are unavailable on this host, which the main-thread animator covers.\n worker = undefined;\n }\n\n const dispatch = (command: ShellTitleCommand, write: WriteTitle) => {\n lastCommand = command;\n lastWrite = write;\n if (!worker) {\n fallback[command.action](command.title, write);\n return;\n }\n try {\n worker.postMessage(command);\n } catch {\n // The worker closed between the last frame and this command.\n fallBack();\n }\n };\n\n return {\n set: (title, write) => dispatch({ action: 'set', title }, write),\n start: (title, write) => dispatch({ action: 'start', title }, write),\n stop: (title, write) => dispatch({ action: 'stop', title }, write),\n dispose: (title, write) => dispatch({ action: 'dispose', title }, write),\n };\n}\n","import path from 'node:path';\n\nimport type { DesktopNotification } from '../../types/notifications';\n\nconst ATTENTION_SUBTITLE = 'Approval or feedback required';\nconst ATTENTION_TITLE = 'Pi needs your input';\nconst ELLIPSIS = '…';\nconst MAX_BODY_LENGTH = 240;\nconst MAX_PROMPT_TITLE_LENGTH = 36;\nconst SETTLED_BODY = 'The agent finished its work and is waiting for you.';\nconst SETTLED_TITLE = 'Pi finished';\nconst SHELL_TITLE_SEPARATOR = ' - ';\nconst SHELL_TITLE_PREFIX = 'π';\n\nfunction collapseWhitespace(value: string): string {\n return value.replace(/\\s+/g, ' ').trim();\n}\n\nfunction truncate(value: string, maxLength: number): string {\n return value.length > maxLength ? `${value.slice(0, maxLength - 1)}${ELLIPSIS}` : value;\n}\n\n/** The first user prompt, shortened to fit a shell tab. A blank prompt names nothing. */\nexport function promptTitle(prompt: string): string | undefined {\n const normalized = collapseWhitespace(prompt);\n return normalized ? truncate(normalized, MAX_PROMPT_TITLE_LENGTH) : undefined;\n}\n\nexport interface ShellTabTitleInput {\n cwd: string;\n sessionName?: string;\n prompt?: string;\n}\n\n/**\n * The idle shell-tab title: `π - <label> - <repository>`.\n *\n * The session name wins over the first prompt because the user chose it. With\n * neither, the repository alone still tells two tabs apart.\n */\nexport function shellTabTitle({ cwd, sessionName, prompt }: ShellTabTitleInput): string {\n const repository = path.basename(cwd);\n const label = sessionName ?? prompt;\n return label\n ? `${SHELL_TITLE_PREFIX}${SHELL_TITLE_SEPARATOR}${label}${SHELL_TITLE_SEPARATOR}${repository}`\n : `${SHELL_TITLE_PREFIX}${SHELL_TITLE_SEPARATOR}${repository}`;\n}\n\n/** Notification bodies are one line in a system panel, so they collapse and truncate. */\nexport function notificationBody(body: string): string {\n return truncate(collapseWhitespace(body), MAX_BODY_LENGTH);\n}\n\n/** Sent while the agent holds the turn and something is blocking on the user. */\nexport function attentionNotification(body: string): DesktopNotification {\n return { title: ATTENTION_TITLE, subtitle: ATTENTION_SUBTITLE, body };\n}\n\n/** Sent once a run has stopped, subtitled with whichever name the user recognises. */\nexport function settledNotification({ cwd, sessionName }: { cwd: string; sessionName?: string }): DesktopNotification {\n return { title: SETTLED_TITLE, subtitle: sessionName ?? path.basename(cwd), body: SETTLED_BODY };\n}\n","import type { DesktopNotification, NotificationExecutor } from '../../types/notifications';\nimport { notificationBody } from '../notificationText';\n\nconst CMUX_COMMAND = 'cmux';\nconst COMMAND_TIMEOUT_MS = 3_000;\nconst DARWIN_PLATFORM = 'darwin';\nconst OSASCRIPT_COMMAND = 'osascript';\nconst OSASCRIPT_EXPRESSION_FLAG = '-e';\n\nasync function execute(pi: NotificationExecutor, command: string, args: string[]): Promise<boolean> {\n try {\n const result = await pi.exec(command, args, { timeout: COMMAND_TIMEOUT_MS });\n return result.code === 0;\n } catch {\n // A notifier that is not installed is the ordinary case, not a fault: report\n // \"not delivered\" and let the caller decide whether another one exists.\n return false;\n }\n}\n\n/**\n * Delivers one desktop notification on a best-effort basis.\n *\n * cmux is tried first because it routes the notification to the window the\n * session actually lives in. Only macOS has a second option worth attempting,\n * and a host with neither stays silent rather than failing the turn.\n */\nexport async function sendSystemNotification(\n pi: NotificationExecutor,\n notification: DesktopNotification,\n platform: string = process.platform,\n): Promise<void> {\n const body = notificationBody(notification.body);\n const sentToCmux = await execute(pi, CMUX_COMMAND, [\n 'notify',\n '--title',\n notification.title,\n '--subtitle',\n notification.subtitle,\n '--body',\n body,\n ]);\n if (sentToCmux || platform !== DARWIN_PLATFORM) return;\n\n await execute(pi, OSASCRIPT_COMMAND, [\n OSASCRIPT_EXPRESSION_FLAG,\n 'on run argv',\n OSASCRIPT_EXPRESSION_FLAG,\n 'display notification (item 3 of argv) with title (item 1 of argv) subtitle (item 2 of argv)',\n OSASCRIPT_EXPRESSION_FLAG,\n 'end run',\n notification.title,\n notification.subtitle,\n body,\n ]);\n}\n","import { sign } from 'node:crypto';\nimport { connect } from 'node:http2';\nimport { request } from 'node:https';\n\nimport type { NativePushRequest, NativePushResponse } from './type';\n\nconst MAX_RESPONSE_BYTES = 65_536;\n\nexport function signPushJwt(header: object, claims: object, key: string, algorithm: 'ES256' | 'RS256'): string {\n const input = [header, claims].map((part) => Buffer.from(JSON.stringify(part)).toString('base64url')).join('.');\n const signature = sign('sha256', Buffer.from(input), { key, dsaEncoding: 'ieee-p1363' });\n // APNs requires the raw P1363 ECDSA signature, not ASN.1 DER.\n if (algorithm === 'ES256' && signature.length !== 64) throw new Error('Invalid signing key');\n return `${input}.${signature.toString('base64url')}`;\n}\n\nexport function createPushTransport() {\n const pending = new Set<() => void>();\n return {\n request(this: void, input: NativePushRequest): Promise<NativePushResponse> {\n return new Promise((resolve, reject) => {\n const url = new URL(input.url);\n let size = 0;\n const chunks: Buffer[] = [];\n let done = false;\n let dispose = () => {};\n const finish = (error?: Error, status = 0) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n pending.delete(cancel);\n dispose();\n if (error) reject(error);\n else resolve({ status, body: Buffer.concat(chunks).toString('utf8') });\n };\n const cancel = () => finish(new Error('Push request cancelled'));\n const timer = setTimeout(() => finish(new Error('Push request timed out')), input.timeoutMs);\n pending.add(cancel);\n const data = (chunk: Buffer) => {\n size += chunk.length;\n if (size > MAX_RESPONSE_BYTES) finish(new Error('Push response too large'));\n else chunks.push(Buffer.from(chunk));\n };\n if (input.http2) {\n const session = connect(url.origin);\n dispose = () => session.destroy();\n session.on('error', (error) => finish(error));\n const stream = session.request({ ':method': 'POST', ':path': url.pathname, ...input.headers });\n let status = 0;\n stream.on('response', (headers) => {\n status = Number(headers[':status']);\n });\n stream.on('data', data);\n stream.on('error', (error) => finish(error));\n stream.on('end', () => finish(undefined, status));\n stream.end(input.body);\n } else {\n const req = request(url, { method: 'POST', headers: input.headers }, (response) => {\n response.on('data', data);\n response.on('error', (error) => finish(error));\n response.on('end', () => finish(undefined, response.statusCode));\n });\n dispose = () => req.destroy();\n req.on('error', (error) => finish(error));\n req.end(input.body);\n }\n });\n },\n close() {\n for (const cancel of pending) cancel();\n },\n };\n}\n","import type { PoNotificationEntryData } from '@agimon-ai/po-core';\n\nimport { createPushTransport, signPushJwt } from './sync';\nimport type { NativePushSender, NativePushSenderOptions } from './type';\n\nconst MAX_PAYLOAD_BYTES = 4096;\nconst APNS_TOPIC = 'ai.po.app';\nconst OAUTH_URL = 'https://oauth2.googleapis.com/token';\nconst FCM_ERROR_TYPE = 'type.googleapis.com/google.firebase.fcm.v1.FcmError';\nconst encoder = new TextEncoder();\n\nfunction parse(body: string): Record<string, unknown> {\n try {\n const value: unknown = JSON.parse(body);\n return value && typeof value === 'object' ? (value as Record<string, unknown>) : {};\n } catch {\n return {};\n } // Malformed provider responses never invalidate registrations.\n}\n\nfunction payload(\n notification: PoNotificationEntryData,\n build: (text: { title: string; subtitle: string; body: string }) => object,\n): string {\n const text = { title: notification.title, subtitle: notification.subtitle, body: notification.body };\n let result = JSON.stringify(build(text));\n // Measure the full serialized envelope, including escaped text and the FCM token.\n for (const field of ['body', 'subtitle', 'title'] as const) {\n if (encoder.encode(result).length <= MAX_PAYLOAD_BYTES) break;\n const points = Array.from(text[field]);\n let low = 0;\n let high = points.length;\n while (low < high) {\n const middle = Math.ceil((low + high) / 2);\n text[field] = points.slice(0, middle).join('');\n if (encoder.encode(JSON.stringify(build(text))).length <= MAX_PAYLOAD_BYTES) low = middle;\n else high = middle - 1;\n }\n text[field] = points.slice(0, low).join('');\n result = JSON.stringify(build(text));\n }\n if (encoder.encode(result).length > MAX_PAYLOAD_BYTES) throw new Error('Push payload too large');\n return result;\n}\n\nexport function createNativePushSender(options: NativePushSenderOptions): NativePushSender {\n const transport = createPushTransport();\n const request = options.request ?? transport.request;\n const now = options.now ?? Date.now;\n const timeoutMs = Number.isFinite(options.timeoutMs) ? Math.max(1, Math.min(options.timeoutMs!, 30_000)) : 10_000;\n let closed = false;\n let apnsJwt: { value: string; expires: number } | undefined;\n let oauth: { value: string; expires: number } | undefined;\n let oauthPending: Promise<string> | undefined;\n\n async function accessToken(): Promise<string> {\n if (oauth && now() < oauth.expires) return oauth.value;\n if (oauthPending) return oauthPending;\n oauthPending = (async () => {\n const credentials = options.fcm!;\n const issued = Math.floor(now() / 1000);\n const assertion = signPushJwt(\n { alg: 'RS256', typ: 'JWT' },\n {\n iss: credentials.clientEmail,\n scope: 'https://www.googleapis.com/auth/firebase.messaging',\n aud: OAUTH_URL,\n iat: issued,\n exp: issued + 3600,\n },\n credentials.privateKey,\n 'RS256',\n );\n const response = await request({\n url: OAUTH_URL,\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion }).toString(),\n timeoutMs,\n });\n const data = parse(response.body);\n if (\n response.status !== 200 ||\n typeof data.access_token !== 'string' ||\n !data.access_token ||\n typeof data.expires_in !== 'number' ||\n !Number.isFinite(data.expires_in) ||\n data.expires_in <= 0\n )\n throw new Error('OAuth failed');\n oauth = { value: data.access_token, expires: now() + Math.max(0, Math.min(data.expires_in, 3600) - 60) * 1000 };\n return oauth.value;\n })();\n try {\n return await oauthPending;\n } finally {\n oauthPending = undefined;\n }\n }\n\n return {\n async send(registration, notification) {\n const provider = registration.platform === 'ios' ? 'apns' : 'fcm';\n if (closed || !options[provider]) {\n options.diagnostic?.({ provider, outcome: 'unavailable' });\n return { invalid: false };\n }\n try {\n let response;\n if (registration.platform === 'ios') {\n const credentials = options.apns!;\n if (!apnsJwt || now() >= apnsJwt.expires) {\n apnsJwt = {\n value: signPushJwt(\n { alg: 'ES256', kid: credentials.keyId },\n {\n iss: credentials.teamId,\n iat: Math.floor(now() / 1000),\n },\n credentials.key,\n 'ES256',\n ),\n expires: now() + 50 * 60_000,\n };\n }\n response = await request({\n url: `https://${registration.environment === 'development' ? 'api.sandbox.push.apple.com' : 'api.push.apple.com'}/3/device/${encodeURIComponent(registration.token)}`,\n http2: true,\n timeoutMs,\n headers: {\n authorization: `bearer ${apnsJwt.value}`,\n 'apns-topic': APNS_TOPIC,\n 'apns-push-type': 'alert',\n 'apns-priority': '10',\n 'apns-expiration': '0',\n 'content-type': 'application/json',\n },\n // ponytail: live alerts only; add a durable outbox if delayed delivery becomes a requirement.\n body: payload(notification, (text) => ({ aps: { alert: text, sound: 'default' } })),\n });\n const reason = parse(response.body).reason;\n if (\n (response.status === 410 && reason === 'Unregistered') ||\n (response.status === 400 && reason === 'BadDeviceToken')\n )\n return { invalid: true };\n } else {\n const body = payload(notification, (text) => ({\n message: {\n token: registration.token,\n notification: { title: text.title, body: [text.subtitle, text.body].filter(Boolean).join('\\n') },\n // ponytail: zero TTL, no offline delivery; an outbox would own delayed sends.\n android: { ttl: '0s', priority: 'HIGH', notification: { channel_id: 'po-notifications' } },\n },\n }));\n const token = await accessToken();\n if (closed) return { invalid: false };\n response = await request({\n url: `https://fcm.googleapis.com/v1/projects/${encodeURIComponent(options.fcm!.projectId)}/messages:send`,\n headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },\n body,\n timeoutMs,\n });\n const error = parse(response.body).error;\n if (\n response.status === 404 &&\n error &&\n typeof error === 'object' &&\n 'details' in error &&\n Array.isArray(error.details) &&\n error.details.some(\n (detail: unknown) =>\n detail &&\n typeof detail === 'object' &&\n '@type' in detail &&\n detail['@type'] === FCM_ERROR_TYPE &&\n 'errorCode' in detail &&\n detail.errorCode === 'UNREGISTERED',\n )\n )\n return { invalid: true };\n }\n if (response.status < 200 || response.status >= 300)\n options.diagnostic?.({ provider, outcome: 'failed', status: response.status });\n } catch {\n // Never expose provider bodies, credentials, device tokens, or network errors.\n options.diagnostic?.({ provider, outcome: 'failed' });\n }\n return { invalid: false };\n },\n close() {\n closed = true;\n apnsJwt = undefined;\n oauth = undefined;\n transport.close();\n },\n };\n}\n","const DEFAULT_ASK_USER_BODY = 'The agent is waiting for your feedback.';\nconst RPC_MODE = 'rpc';\n\nexport interface AttentionState {\n agentRunning: boolean;\n askUserBlocked: boolean;\n}\n\nexport interface ShellSurface {\n hasUI: boolean;\n mode?: string;\n}\n\n/**\n * A dialog is worth interrupting the user for only while the agent holds the turn.\n *\n * Outside a run the user opened the dialog themselves and is already looking at\n * it. An ask-user prompt is announced by its own event, so the dialog it then\n * opens must stay silent or the same question notifies twice.\n */\nexport function warrantsAttentionNotification({ agentRunning, askUserBlocked }: AttentionState): boolean {\n return agentRunning && !askUserBlocked;\n}\n\n/** A queued follow-up means the agent keeps working, so the run has not stopped for the user. */\nexport function warrantsSettledNotification(hasPendingMessages: boolean): boolean {\n return !hasPendingMessages;\n}\n\n/** Terminal title escapes only mean something on an attached terminal; RPC output stays clean. */\nexport function supportsShellTitle({ hasUI, mode }: ShellSurface): boolean {\n return hasUI && mode !== RPC_MODE;\n}\n\n/** The question an ask-user prompt is blocking on, or a stand-in when it asked none. */\nexport function askUserPromptBody(questions: readonly { question: string }[]): string {\n return questions[0]?.question ?? DEFAULT_ASK_USER_BODY;\n}\n"],"mappings":";;;;;;AAEA,MAAa,iBAAiB;CAAC;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;AAAG;;AAI/E,SAAgB,kCAAwD;CACtE,IAAI,aAAa;CACjB,IAAI;CACJ,MAAM,sBAAsB;EAC1B,IAAI,OAAO,cAAc,KAAK;EAC9B,QAAQ,KAAA;EACR,aAAa;CACf;CAEA,OAAO;EACL,IAAI,OAAO,OAAO;G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C;AACV;;AAGA,SAAgB,mBAAmB,EAAE,OAAO,QAA+B;CACzE,OAAO,SAAS,SAAS;AAC3B;;AAGA,SAAgB,kBAAkB,WAAoD;CACpF,OAAO,UAAU,EAAE,EAAE,YAAY;AACnC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agimon-ai/po-notification",
|
|
3
|
-
"version": "0.0.0-alpha.
|
|
3
|
+
"version": "0.0.0-alpha.34",
|
|
4
4
|
"description": "Desktop notifications and an animated shell-tab title for Po sessions.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -60,12 +60,12 @@
|
|
|
60
60
|
"access": "public"
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
|
-
"@agimon-ai/po-core": "0.0.0-alpha.
|
|
63
|
+
"@agimon-ai/po-core": "0.0.0-alpha.34",
|
|
64
64
|
"@deepseek-ai/cordis": "4.0.5"
|
|
65
65
|
},
|
|
66
66
|
"devDependencies": {
|
|
67
|
-
"@agimon-ai/po-build": "0.0.0-alpha.
|
|
68
|
-
"@agimon-ai/vibe-lint-plugin-po-extension": "0.0.0-alpha.
|
|
67
|
+
"@agimon-ai/po-build": "0.0.0-alpha.34",
|
|
68
|
+
"@agimon-ai/vibe-lint-plugin-po-extension": "0.0.0-alpha.34",
|
|
69
69
|
"@earendil-works/pi-coding-agent": "1.3.0",
|
|
70
70
|
"@types/node": "26.6.5",
|
|
71
71
|
"@vitest/coverage-v8": "5.0.4",
|