@agimon-ai/po-notification 0.0.0-alpha.198 → 0.0.0-alpha.199
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/dist/index.cjs +84 -50
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +27 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +84 -50
- package/dist/index.mjs.map +1 -1
- package/dist/po-runtime-identity.json +1 -1
- package/package.json +5 -5
package/dist/index.cjs
CHANGED
|
@@ -475,6 +475,45 @@ function createNativePushSender(options) {
|
|
|
475
475
|
oauthPending = void 0;
|
|
476
476
|
}
|
|
477
477
|
}
|
|
478
|
+
async function apnsRequest(token, environment, body, liveActivity = false) {
|
|
479
|
+
const credentials = options.apns;
|
|
480
|
+
if (!apnsJwt || now() >= apnsJwt.expires) apnsJwt = {
|
|
481
|
+
value: signPushJwt({
|
|
482
|
+
alg: "ES256",
|
|
483
|
+
kid: credentials.keyId
|
|
484
|
+
}, {
|
|
485
|
+
iss: credentials.teamId,
|
|
486
|
+
iat: Math.floor(now() / 1e3)
|
|
487
|
+
}, credentials.key, "ES256"),
|
|
488
|
+
expires: now() + 3e6
|
|
489
|
+
};
|
|
490
|
+
return request({
|
|
491
|
+
url: `https://${environment === "development" ? "api.sandbox.push.apple.com" : "api.push.apple.com"}/3/device/${encodeURIComponent(token)}`,
|
|
492
|
+
http2: true,
|
|
493
|
+
timeoutMs,
|
|
494
|
+
headers: {
|
|
495
|
+
authorization: `bearer ${apnsJwt.value}`,
|
|
496
|
+
"apns-topic": liveActivity ? `${APNS_TOPIC}.push-type.liveactivity` : APNS_TOPIC,
|
|
497
|
+
"apns-push-type": liveActivity ? "liveactivity" : "alert",
|
|
498
|
+
"apns-priority": "10",
|
|
499
|
+
"apns-expiration": "0",
|
|
500
|
+
"content-type": "application/json"
|
|
501
|
+
},
|
|
502
|
+
body
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
function apnsOutcome(response) {
|
|
506
|
+
const value = parse(response.body).reason;
|
|
507
|
+
const reason = typeof value === "string" && APNS_REASONS.has(value) ? value : void 0;
|
|
508
|
+
const invalid = response.status === 410 && reason === "Unregistered" || response.status === 400 && reason === "BadDeviceToken";
|
|
509
|
+
if (invalid || response.status < 200 || response.status >= 300) options.diagnostic?.({
|
|
510
|
+
provider: "apns",
|
|
511
|
+
outcome: invalid ? "invalid" : "failed",
|
|
512
|
+
status: response.status,
|
|
513
|
+
...reason ? { reason } : {}
|
|
514
|
+
});
|
|
515
|
+
return { invalid };
|
|
516
|
+
}
|
|
478
517
|
return {
|
|
479
518
|
async send(registration, notification, sessionId) {
|
|
480
519
|
const provider = registration.platform === "ios" ? "apns" : "fcm";
|
|
@@ -491,52 +530,15 @@ function createNativePushSender(options) {
|
|
|
491
530
|
...sessionId ? { sessionId } : {}
|
|
492
531
|
};
|
|
493
532
|
let response;
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
iat: Math.floor(now() / 1e3)
|
|
504
|
-
}, credentials.key, "ES256"),
|
|
505
|
-
expires: now() + 3e6
|
|
506
|
-
};
|
|
507
|
-
response = await request({
|
|
508
|
-
url: `https://${registration.environment === "development" ? "api.sandbox.push.apple.com" : "api.push.apple.com"}/3/device/${encodeURIComponent(registration.token)}`,
|
|
509
|
-
http2: true,
|
|
510
|
-
timeoutMs,
|
|
511
|
-
headers: {
|
|
512
|
-
authorization: `bearer ${apnsJwt.value}`,
|
|
513
|
-
"apns-topic": APNS_TOPIC,
|
|
514
|
-
"apns-push-type": "alert",
|
|
515
|
-
"apns-priority": "10",
|
|
516
|
-
"apns-expiration": "0",
|
|
517
|
-
"content-type": "application/json"
|
|
518
|
-
},
|
|
519
|
-
body: payload(notification, (text) => ({
|
|
520
|
-
aps: {
|
|
521
|
-
alert: text,
|
|
522
|
-
sound: "default"
|
|
523
|
-
},
|
|
524
|
-
data,
|
|
525
|
-
body: data
|
|
526
|
-
}))
|
|
527
|
-
});
|
|
528
|
-
const value = parse(response.body).reason;
|
|
529
|
-
if (typeof value === "string" && APNS_REASONS.has(value)) reason = value;
|
|
530
|
-
if (response.status === 410 && reason === "Unregistered" || response.status === 400 && reason === "BadDeviceToken") {
|
|
531
|
-
options.diagnostic?.({
|
|
532
|
-
provider,
|
|
533
|
-
outcome: "invalid",
|
|
534
|
-
status: response.status,
|
|
535
|
-
...reason ? { reason } : {}
|
|
536
|
-
});
|
|
537
|
-
return { invalid: true };
|
|
538
|
-
}
|
|
539
|
-
} else {
|
|
533
|
+
if (registration.platform === "ios") return apnsOutcome(await apnsRequest(registration.token, registration.environment, payload(notification, (text) => ({
|
|
534
|
+
aps: {
|
|
535
|
+
alert: text,
|
|
536
|
+
sound: "default"
|
|
537
|
+
},
|
|
538
|
+
data,
|
|
539
|
+
body: data
|
|
540
|
+
}))));
|
|
541
|
+
else {
|
|
540
542
|
const body = payload(notification, (text) => ({ message: {
|
|
541
543
|
token: registration.token,
|
|
542
544
|
data,
|
|
@@ -566,8 +568,7 @@ function createNativePushSender(options) {
|
|
|
566
568
|
options.diagnostic?.({
|
|
567
569
|
provider,
|
|
568
570
|
outcome: "invalid",
|
|
569
|
-
status: response.status
|
|
570
|
-
...reason ? { reason } : {}
|
|
571
|
+
status: response.status
|
|
571
572
|
});
|
|
572
573
|
return { invalid: true };
|
|
573
574
|
}
|
|
@@ -575,8 +576,7 @@ function createNativePushSender(options) {
|
|
|
575
576
|
if (response.status < 200 || response.status >= 300) options.diagnostic?.({
|
|
576
577
|
provider,
|
|
577
578
|
outcome: "failed",
|
|
578
|
-
status: response.status
|
|
579
|
-
...reason ? { reason } : {}
|
|
579
|
+
status: response.status
|
|
580
580
|
});
|
|
581
581
|
} catch {
|
|
582
582
|
options.diagnostic?.({
|
|
@@ -586,6 +586,40 @@ function createNativePushSender(options) {
|
|
|
586
586
|
}
|
|
587
587
|
return { invalid: false };
|
|
588
588
|
},
|
|
589
|
+
async sendLiveActivity(registration, update) {
|
|
590
|
+
if (closed || !options.apns) {
|
|
591
|
+
options.diagnostic?.({
|
|
592
|
+
provider: "apns",
|
|
593
|
+
outcome: "unavailable"
|
|
594
|
+
});
|
|
595
|
+
return { invalid: false };
|
|
596
|
+
}
|
|
597
|
+
try {
|
|
598
|
+
for (const time of [
|
|
599
|
+
update.timestamp,
|
|
600
|
+
update.staleDate,
|
|
601
|
+
update.dismissalDate
|
|
602
|
+
]) if (time !== void 0 && (!Number.isSafeInteger(time) || time < 0)) throw new Error("Invalid APNs timestamp");
|
|
603
|
+
const body = JSON.stringify({ aps: {
|
|
604
|
+
timestamp: update.timestamp,
|
|
605
|
+
event: update.event,
|
|
606
|
+
"content-state": {
|
|
607
|
+
name: update.contentState.name,
|
|
608
|
+
props: JSON.stringify(update.contentState.props)
|
|
609
|
+
},
|
|
610
|
+
...update.staleDate === void 0 ? {} : { "stale-date": update.staleDate },
|
|
611
|
+
...update.dismissalDate === void 0 ? {} : { "dismissal-date": update.dismissalDate }
|
|
612
|
+
} });
|
|
613
|
+
if (encoder.encode(body).length > MAX_PAYLOAD_BYTES) throw new Error("Push payload too large");
|
|
614
|
+
return apnsOutcome(await apnsRequest(registration.activityToken, registration.environment, body, true));
|
|
615
|
+
} catch {
|
|
616
|
+
options.diagnostic?.({
|
|
617
|
+
provider: "apns",
|
|
618
|
+
outcome: "failed"
|
|
619
|
+
});
|
|
620
|
+
return { invalid: false };
|
|
621
|
+
}
|
|
622
|
+
},
|
|
589
623
|
close() {
|
|
590
624
|
closed = true;
|
|
591
625
|
apnsJwt = void 0;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["Worker","path","formatMessage","sign","connect","request","DEFAULT_AUTO_STOP_DELAYS","BACKGROUND_RUNNER_DEADLINE_MS","holdsSettledSessionAfterRunnerDeadline","holdsSettledSession","BACKGROUND_WORK_HOLDING_PROVIDERS","decideOnRecheck","AUTO_STOP_ACTION"],"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/completion/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 { createWriteStream } = require('node:fs');\nconst output = createWriteStream('', { fd: 1, autoClose: false });\nconst { parentPort, workerData } = require('node:worker_threads');\nlet frameIndex = 0;\nlet timer;\nconst writeTitle = (title) => output.write('\\\\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') output.end(() => 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 { formatMessage } from '@agimon-ai/po-core/locale';\n\nimport type { DesktopNotification } from '../../types/notifications';\n\nconst ELLIPSIS = '…';\nconst MAX_BODY_LENGTH = 240;\nconst MAX_PROMPT_TITLE_LENGTH = 36;\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/** Renders one message: a language pack's text for `key`, or the English `fallback`. */\nexport type NotificationTranslate = (\n key: string,\n fallback: string,\n vars?: Readonly<Record<string, string | number>>,\n) => string;\n\nconst english: NotificationTranslate = (_key, fallback, vars) => formatMessage(fallback, vars);\n\n/** Sent while the agent holds the turn and something is blocking on the user. */\nexport function attentionNotification(body: string, t: NotificationTranslate = english): DesktopNotification {\n return {\n title: t('notification.attention.title', 'Po needs your input'),\n subtitle: t('notification.attention.subtitle', 'Approval or feedback required'),\n body,\n };\n}\n\n/**\n * Sent once a run has stopped. The title carries the session name so it shows even where a\n * platform hides subtitles; an unnamed session (the hub sends `''`) falls back to the repository.\n */\nexport function settledNotification(\n { cwd, sessionName }: { cwd: string; sessionName?: string },\n t: NotificationTranslate = english,\n): DesktopNotification {\n const repository = path.basename(cwd);\n const name = sessionName?.trim();\n return {\n title: t('notification.settled.title', 'Po finished: {name}', { name: name || repository }),\n subtitle: name ? repository : '',\n body: t('notification.settled.body', 'The agent finished its work and is waiting for you.'),\n };\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';\n// Only documented provider codes may enter diagnostics, never arbitrary response text.\nconst APNS_REASONS = new Set([\n 'BadCollapseId',\n 'BadDeviceToken',\n 'BadExpirationDate',\n 'BadMessageId',\n 'BadPriority',\n 'BadTopic',\n 'DeviceTokenNotForTopic',\n 'DuplicateHeaders',\n 'IdleTimeout',\n 'InvalidPushType',\n 'MissingDeviceToken',\n 'MissingTopic',\n 'PayloadEmpty',\n 'TopicDisallowed',\n 'BadCertificate',\n 'BadCertificateEnvironment',\n 'ExpiredProviderToken',\n 'Forbidden',\n 'InvalidProviderToken',\n 'MissingProviderToken',\n 'BadPath',\n 'MethodNotAllowed',\n 'Unregistered',\n 'PayloadTooLarge',\n 'TooManyProviderTokenUpdates',\n 'TooManyRequests',\n 'InternalServerError',\n 'ServiceUnavailable',\n 'Shutdown',\n]);\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, sessionId) {\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 const data = {\n ...(registration.hostRef ? { hostRef: registration.hostRef } : {}),\n ...(sessionId ? { sessionId } : {}),\n };\n let response;\n let reason: string | undefined;\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 // Expo iOS reads custom remote data from userInfo.body. Keep data as the provider-neutral payload.\n body: payload(notification, (text) => ({ aps: { alert: text, sound: 'default' }, data, body: data })),\n });\n const value = parse(response.body).reason;\n if (typeof value === 'string' && APNS_REASONS.has(value)) reason = value;\n if (\n (response.status === 410 && reason === 'Unregistered') ||\n (response.status === 400 && reason === 'BadDeviceToken')\n ) {\n options.diagnostic?.({\n provider,\n outcome: 'invalid',\n status: response.status,\n ...(reason ? { reason } : {}),\n });\n return { invalid: true };\n }\n } else {\n const body = payload(notification, (text) => ({\n message: {\n token: registration.token,\n data,\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 options.diagnostic?.({\n provider,\n outcome: 'invalid',\n status: response.status,\n ...(reason ? { reason } : {}),\n });\n return { invalid: true };\n }\n }\n if (response.status < 200 || response.status >= 300)\n options.diagnostic?.({ provider, outcome: 'failed', status: response.status, ...(reason ? { reason } : {}) });\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","import { AUTO_STOP_ACTION, DEFAULT_AUTO_STOP_DELAYS, decideOnRecheck } from '@agimon-ai/po-autostop';\nimport {\n BACKGROUND_RUNNER_DEADLINE_MS,\n BACKGROUND_WORK_HOLDING_PROVIDERS,\n holdsSettledSession,\n holdsSettledSessionAfterRunnerDeadline,\n} from '@agimon-ai/po-core/backgroundWork';\nimport type { PoHubSessionExecutionState } from '@agimon-ai/po-core/hubChannel';\n\nimport type { SessionFinishedDecision } from './type';\n\nexport const SESSION_FINISHED_COOLDOWN_MS = DEFAULT_AUTO_STOP_DELAYS.cooldownMs;\n\n/** The completion test shared by spoken notices and native push, after the initial cooldown. */\nexport function decideSessionFinished(\n state: PoHubSessionExecutionState | undefined,\n holdingSince: number | undefined,\n now: number,\n): SessionFinishedDecision {\n // Unknown background work cannot prove the run finished.\n if (!state?.backgroundWork) return { action: 'unavailable' };\n const expired = holdingSince !== undefined && now - holdingSince >= BACKGROUND_RUNNER_DEADLINE_MS;\n const holds = expired ? holdsSettledSessionAfterRunnerDeadline : holdsSettledSession;\n const { items, errors } = state.backgroundWork;\n if (items.some(holds) || errors.some((error) => BACKGROUND_WORK_HOLDING_PROVIDERS.includes(error.provider)))\n return {\n action: 'hold',\n delayMs: SESSION_FINISHED_COOLDOWN_MS,\n holdingSince: holdingSince ?? now,\n };\n const decision = decideOnRecheck(state, DEFAULT_AUTO_STOP_DELAYS);\n if (decision.action === AUTO_STOP_ACTION.recheck) return { action: 'recheck', delayMs: decision.delayMs };\n return { action: decision.action === AUTO_STOP_ACTION.shutdown ? 'finished' : 'stand-down' };\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiC5B,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,IAAIA,oBAAAA,OAAO,qBAAqB;GAClD,MAAM;GACN,YAAY;IAAE,QAAQ;IAAgB,YAAA;GAAoC;EAC5E,CAAC;EACD,YAAY,MAAM;EAClB,YAAY,KAA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,MAAM;EAClB;CACF;AACF;;;AC/OA,MAAa,+BAA+BC,uBAAAA,yBAAyB;;AAGrE,SAAgB,sBACd,OACA,cACA,KACyB;CAEzB,IAAI,CAAC,OAAO,gBAAgB,OAAO,EAAE,QAAQ,cAAc;CAE3D,MAAM,QADU,iBAAiB,KAAA,KAAa,MAAM,gBAAgBC,kCAAAA,gCAC5CC,kCAAAA,yCAAyCC,kCAAAA;CACjE,MAAM,EAAE,OAAO,WAAW,MAAM;CAChC,IAAI,MAAM,KAAK,KAAK,KAAK,OAAO,MAAM,UAAUC,kCAAAA,kCAAkC,SAAS,MAAM,QAAQ,CAAC,GACxG,OAAO;EACL,QAAQ;EACR,SAAS;EACT,cAAc,gBAAgB;CAChC;CACF,MAAM,YAAA,GAAWC,uBAAAA,gBAAAA,CAAgB,OAAOL,uBAAAA,wBAAwB;CAChE,IAAI,SAAS,WAAWM,uBAAAA,iBAAiB,SAAS,OAAO;EAAE,QAAQ;EAAW,SAAS,SAAS;CAAQ;CACxG,OAAO,EAAE,QAAQ,SAAS,WAAWA,uBAAAA,iBAAiB,WAAW,aAAa,aAAa;AAC7F;;;ACjCA,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.cjs","names":["Worker","path","formatMessage","sign","connect","request","DEFAULT_AUTO_STOP_DELAYS","BACKGROUND_RUNNER_DEADLINE_MS","holdsSettledSessionAfterRunnerDeadline","holdsSettledSession","BACKGROUND_WORK_HOLDING_PROVIDERS","decideOnRecheck","AUTO_STOP_ACTION"],"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/completion/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 { createWriteStream } = require('node:fs');\nconst output = createWriteStream('', { fd: 1, autoClose: false });\nconst { parentPort, workerData } = require('node:worker_threads');\nlet frameIndex = 0;\nlet timer;\nconst writeTitle = (title) => output.write('\\\\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') output.end(() => 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 { formatMessage } from '@agimon-ai/po-core/locale';\n\nimport type { DesktopNotification } from '../../types/notifications';\n\nconst ELLIPSIS = '…';\nconst MAX_BODY_LENGTH = 240;\nconst MAX_PROMPT_TITLE_LENGTH = 36;\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/** Renders one message: a language pack's text for `key`, or the English `fallback`. */\nexport type NotificationTranslate = (\n key: string,\n fallback: string,\n vars?: Readonly<Record<string, string | number>>,\n) => string;\n\nconst english: NotificationTranslate = (_key, fallback, vars) => formatMessage(fallback, vars);\n\n/** Sent while the agent holds the turn and something is blocking on the user. */\nexport function attentionNotification(body: string, t: NotificationTranslate = english): DesktopNotification {\n return {\n title: t('notification.attention.title', 'Po needs your input'),\n subtitle: t('notification.attention.subtitle', 'Approval or feedback required'),\n body,\n };\n}\n\n/**\n * Sent once a run has stopped. The title carries the session name so it shows even where a\n * platform hides subtitles; an unnamed session (the hub sends `''`) falls back to the repository.\n */\nexport function settledNotification(\n { cwd, sessionName }: { cwd: string; sessionName?: string },\n t: NotificationTranslate = english,\n): DesktopNotification {\n const repository = path.basename(cwd);\n const name = sessionName?.trim();\n return {\n title: t('notification.settled.title', 'Po finished: {name}', { name: name || repository }),\n subtitle: name ? repository : '',\n body: t('notification.settled.body', 'The agent finished its work and is waiting for you.'),\n };\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';\n// Only documented provider codes may enter diagnostics, never arbitrary response text.\nconst APNS_REASONS = new Set([\n 'BadCollapseId',\n 'BadDeviceToken',\n 'BadExpirationDate',\n 'BadMessageId',\n 'BadPriority',\n 'BadTopic',\n 'DeviceTokenNotForTopic',\n 'DuplicateHeaders',\n 'IdleTimeout',\n 'InvalidPushType',\n 'MissingDeviceToken',\n 'MissingTopic',\n 'PayloadEmpty',\n 'TopicDisallowed',\n 'BadCertificate',\n 'BadCertificateEnvironment',\n 'ExpiredProviderToken',\n 'Forbidden',\n 'InvalidProviderToken',\n 'MissingProviderToken',\n 'BadPath',\n 'MethodNotAllowed',\n 'Unregistered',\n 'PayloadTooLarge',\n 'TooManyProviderTokenUpdates',\n 'TooManyRequests',\n 'InternalServerError',\n 'ServiceUnavailable',\n 'Shutdown',\n]);\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 async function apnsRequest(\n token: string,\n environment: 'development' | 'production',\n body: string,\n liveActivity = false,\n ) {\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 return request({\n url: `https://${environment === 'development' ? 'api.sandbox.push.apple.com' : 'api.push.apple.com'}/3/device/${encodeURIComponent(token)}`,\n http2: true,\n timeoutMs,\n headers: {\n authorization: `bearer ${apnsJwt.value}`,\n 'apns-topic': liveActivity ? `${APNS_TOPIC}.push-type.liveactivity` : APNS_TOPIC,\n 'apns-push-type': liveActivity ? 'liveactivity' : 'alert',\n 'apns-priority': '10',\n 'apns-expiration': '0',\n 'content-type': 'application/json',\n },\n body,\n });\n }\n\n function apnsOutcome(response: { status: number; body: string }): { invalid: boolean } {\n const value = parse(response.body).reason;\n const reason = typeof value === 'string' && APNS_REASONS.has(value) ? value : undefined;\n const invalid =\n (response.status === 410 && reason === 'Unregistered') ||\n (response.status === 400 && reason === 'BadDeviceToken');\n if (invalid || response.status < 200 || response.status >= 300)\n options.diagnostic?.({\n provider: 'apns',\n outcome: invalid ? 'invalid' : 'failed',\n status: response.status,\n ...(reason ? { reason } : {}),\n });\n return { invalid };\n }\n\n return {\n async send(registration, notification, sessionId) {\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 const data = {\n ...(registration.hostRef ? { hostRef: registration.hostRef } : {}),\n ...(sessionId ? { sessionId } : {}),\n };\n let response;\n if (registration.platform === 'ios') {\n // Expo iOS reads custom remote data from userInfo.body.\n return apnsOutcome(\n await apnsRequest(\n registration.token,\n registration.environment,\n payload(notification, (text) => ({ aps: { alert: text, sound: 'default' }, data, body: data })),\n ),\n );\n } else {\n const body = payload(notification, (text) => ({\n message: {\n token: registration.token,\n data,\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 options.diagnostic?.({\n provider,\n outcome: 'invalid',\n status: response.status,\n });\n return { invalid: true };\n }\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 async sendLiveActivity(registration, update) {\n if (closed || !options.apns) {\n options.diagnostic?.({ provider: 'apns', outcome: 'unavailable' });\n return { invalid: false };\n }\n try {\n for (const time of [update.timestamp, update.staleDate, update.dismissalDate]) {\n if (time !== undefined && (!Number.isSafeInteger(time) || time < 0))\n throw new Error('Invalid APNs timestamp');\n }\n const body = JSON.stringify({\n aps: {\n timestamp: update.timestamp,\n event: update.event,\n 'content-state': { name: update.contentState.name, props: JSON.stringify(update.contentState.props) },\n ...(update.staleDate === undefined ? {} : { 'stale-date': update.staleDate }),\n ...(update.dismissalDate === undefined ? {} : { 'dismissal-date': update.dismissalDate }),\n },\n });\n // Activity state must stay intact. Measure the complete escaped UTF-8 envelope.\n if (encoder.encode(body).length > MAX_PAYLOAD_BYTES) throw new Error('Push payload too large');\n return apnsOutcome(await apnsRequest(registration.activityToken, registration.environment, body, true));\n } catch {\n // Same safe diagnostics as alerts, including signing, transport and cancellation failures.\n options.diagnostic?.({ provider: 'apns', outcome: 'failed' });\n return { invalid: false };\n }\n },\n close() {\n closed = true;\n apnsJwt = undefined;\n oauth = undefined;\n transport.close();\n },\n };\n}\n","import { AUTO_STOP_ACTION, DEFAULT_AUTO_STOP_DELAYS, decideOnRecheck } from '@agimon-ai/po-autostop';\nimport {\n BACKGROUND_RUNNER_DEADLINE_MS,\n BACKGROUND_WORK_HOLDING_PROVIDERS,\n holdsSettledSession,\n holdsSettledSessionAfterRunnerDeadline,\n} from '@agimon-ai/po-core/backgroundWork';\nimport type { PoHubSessionExecutionState } from '@agimon-ai/po-core/hubChannel';\n\nimport type { SessionFinishedDecision } from './type';\n\nexport const SESSION_FINISHED_COOLDOWN_MS = DEFAULT_AUTO_STOP_DELAYS.cooldownMs;\n\n/** The completion test shared by spoken notices and native push, after the initial cooldown. */\nexport function decideSessionFinished(\n state: PoHubSessionExecutionState | undefined,\n holdingSince: number | undefined,\n now: number,\n): SessionFinishedDecision {\n // Unknown background work cannot prove the run finished.\n if (!state?.backgroundWork) return { action: 'unavailable' };\n const expired = holdingSince !== undefined && now - holdingSince >= BACKGROUND_RUNNER_DEADLINE_MS;\n const holds = expired ? holdsSettledSessionAfterRunnerDeadline : holdsSettledSession;\n const { items, errors } = state.backgroundWork;\n if (items.some(holds) || errors.some((error) => BACKGROUND_WORK_HOLDING_PROVIDERS.includes(error.provider)))\n return {\n action: 'hold',\n delayMs: SESSION_FINISHED_COOLDOWN_MS,\n holdingSince: holdingSince ?? now,\n };\n const decision = decideOnRecheck(state, DEFAULT_AUTO_STOP_DELAYS);\n if (decision.action === AUTO_STOP_ACTION.recheck) return { action: 'recheck', delayMs: decision.delayMs };\n return { action: decision.action === AUTO_STOP_ACTION.shutdown ? 'finished' : 'stand-down' };\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,KAA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AAWA,uBAAAA,iBAAiB,WAAW,aAAa,aAAa;AAC7F;;;ACjCA,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"}
|
package/dist/index.d.mts
CHANGED
|
@@ -76,6 +76,30 @@ type NativePushRegistration = {
|
|
|
76
76
|
token: string;
|
|
77
77
|
hostRef?: string;
|
|
78
78
|
};
|
|
79
|
+
interface NativeLiveActivityRegistration {
|
|
80
|
+
/** ActivityKit update token, never the ordinary notification device token. */
|
|
81
|
+
activityToken: string;
|
|
82
|
+
environment: 'development' | 'production';
|
|
83
|
+
}
|
|
84
|
+
type NativeLiveActivityJson = null | boolean | number | string | NativeLiveActivityJson[] | {
|
|
85
|
+
[key: string]: NativeLiveActivityJson;
|
|
86
|
+
};
|
|
87
|
+
type NativeLiveActivityPayload = {
|
|
88
|
+
/** APNs times are Unix seconds, not JavaScript milliseconds. */
|
|
89
|
+
timestamp: number;
|
|
90
|
+
contentState: {
|
|
91
|
+
name: string;
|
|
92
|
+
props: Record<string, NativeLiveActivityJson>;
|
|
93
|
+
};
|
|
94
|
+
} & ({
|
|
95
|
+
event: 'update';
|
|
96
|
+
staleDate?: number;
|
|
97
|
+
dismissalDate?: never;
|
|
98
|
+
} | {
|
|
99
|
+
event: 'end';
|
|
100
|
+
staleDate?: never;
|
|
101
|
+
dismissalDate?: number;
|
|
102
|
+
});
|
|
79
103
|
interface NativePushRequest {
|
|
80
104
|
url: string;
|
|
81
105
|
headers: Record<string, string>;
|
|
@@ -112,6 +136,9 @@ interface NativePushSender {
|
|
|
112
136
|
send(registration: NativePushRegistration, notification: PoNotificationEntryData, sessionId?: string): Promise<{
|
|
113
137
|
invalid: boolean;
|
|
114
138
|
}>;
|
|
139
|
+
sendLiveActivity(registration: NativeLiveActivityRegistration, payload: NativeLiveActivityPayload): Promise<{
|
|
140
|
+
invalid: boolean;
|
|
141
|
+
}>;
|
|
115
142
|
close(): void;
|
|
116
143
|
}
|
|
117
144
|
//#endregion
|
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/nativePushSender/type.ts","../src/services/nativePushSender/index.ts","../src/services/completion/type.ts","../src/services/completion/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;;;;;;;;wBCuCnC,+BAA+B;;;;;;;;;;wBClBzB,uBACpB,IAAI,sBACJ,cAAc,qBACd,oBACC;;;KC7BS;EACN;EAAiB;EAAe;EAAkB;;EAClD;EAAqB;EAAe;;UAEzB;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;IACZ;IACA;IACA;IACA;;;UAGa;EACf,KACE,cAAc,wBACd,cAAc,yBACd,qBACC;IAAU;;EACb;;;;
|
|
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/completion/type.ts","../src/services/completion/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;;;;;;;;wBCuCnC,+BAA+B;;;;;;;;;;wBClBzB,uBACpB,IAAI,sBACJ,cAAc,qBACd,oBACC;;;KC7BS;EACN;EAAiB;EAAe;EAAkB;;EAClD;EAAqB;EAAe;;UAEzB;;EAEf;EACA;;KAGU,4DAKR;GACG,cAAc;;KAET;;EAEV;EACA;IAAgB;IAAc,OAAO,eAAe;;;EAEhD;EAAiB;EAAoB;;EACrC;EAAc;EAAmB;;UAGtB;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;IACZ;IACA;IACA;IACA;;;UAGa;EACf,KACE,cAAc,wBACd,cAAc,yBACd,qBACC;IAAU;;EACb,iBACE,cAAc,gCACd,SAAS,4BACR;IAAU;;EACb;;;;wBCcc,uBAAuB,SAAS,0BAA0B;;;KC7E9D;WACG;;WACA;WAA4B;;WAC5B;WAAyB;WAA0B;;WACnD;;WACA;;;;qBCMF;;wBAGG,sBACd,OAAO,wCACP,kCACA,cACC;;;UCfc;EACf;EACA;;UAGe;EACf;EACA;;;;;;;;;wBAUc,gCAAgC,cAAc,kBAAkB;;wBAKhE,4BAA4B;;wBAK5B,qBAAqB,OAAO,QAAQ;;wBAKpC,kBAAkB;EAAsB;;;;;wBCdxC,YAAY;UAKX;EACf;EACA;EACA;;;;;;;;wBASc,gBAAgB,KAAK,aAAa,UAAU;;wBAS5C,iBAAiB;;KAKrB,yBACV,aACA,kBACA,OAAO,SAAS;;wBAMF,sBAAsB,cAAc,IAAG,wBAAkC;;;;;wBAYzE,sBACZ,KAAK;EAAiB;EAAa;GACrC,IAAG,wBACF"}
|
package/dist/index.mjs
CHANGED
|
@@ -451,6 +451,45 @@ function createNativePushSender(options) {
|
|
|
451
451
|
oauthPending = void 0;
|
|
452
452
|
}
|
|
453
453
|
}
|
|
454
|
+
async function apnsRequest(token, environment, body, liveActivity = false) {
|
|
455
|
+
const credentials = options.apns;
|
|
456
|
+
if (!apnsJwt || now() >= apnsJwt.expires) apnsJwt = {
|
|
457
|
+
value: signPushJwt({
|
|
458
|
+
alg: "ES256",
|
|
459
|
+
kid: credentials.keyId
|
|
460
|
+
}, {
|
|
461
|
+
iss: credentials.teamId,
|
|
462
|
+
iat: Math.floor(now() / 1e3)
|
|
463
|
+
}, credentials.key, "ES256"),
|
|
464
|
+
expires: now() + 3e6
|
|
465
|
+
};
|
|
466
|
+
return request({
|
|
467
|
+
url: `https://${environment === "development" ? "api.sandbox.push.apple.com" : "api.push.apple.com"}/3/device/${encodeURIComponent(token)}`,
|
|
468
|
+
http2: true,
|
|
469
|
+
timeoutMs,
|
|
470
|
+
headers: {
|
|
471
|
+
authorization: `bearer ${apnsJwt.value}`,
|
|
472
|
+
"apns-topic": liveActivity ? `${APNS_TOPIC}.push-type.liveactivity` : APNS_TOPIC,
|
|
473
|
+
"apns-push-type": liveActivity ? "liveactivity" : "alert",
|
|
474
|
+
"apns-priority": "10",
|
|
475
|
+
"apns-expiration": "0",
|
|
476
|
+
"content-type": "application/json"
|
|
477
|
+
},
|
|
478
|
+
body
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
function apnsOutcome(response) {
|
|
482
|
+
const value = parse(response.body).reason;
|
|
483
|
+
const reason = typeof value === "string" && APNS_REASONS.has(value) ? value : void 0;
|
|
484
|
+
const invalid = response.status === 410 && reason === "Unregistered" || response.status === 400 && reason === "BadDeviceToken";
|
|
485
|
+
if (invalid || response.status < 200 || response.status >= 300) options.diagnostic?.({
|
|
486
|
+
provider: "apns",
|
|
487
|
+
outcome: invalid ? "invalid" : "failed",
|
|
488
|
+
status: response.status,
|
|
489
|
+
...reason ? { reason } : {}
|
|
490
|
+
});
|
|
491
|
+
return { invalid };
|
|
492
|
+
}
|
|
454
493
|
return {
|
|
455
494
|
async send(registration, notification, sessionId) {
|
|
456
495
|
const provider = registration.platform === "ios" ? "apns" : "fcm";
|
|
@@ -467,52 +506,15 @@ function createNativePushSender(options) {
|
|
|
467
506
|
...sessionId ? { sessionId } : {}
|
|
468
507
|
};
|
|
469
508
|
let response;
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
iat: Math.floor(now() / 1e3)
|
|
480
|
-
}, credentials.key, "ES256"),
|
|
481
|
-
expires: now() + 3e6
|
|
482
|
-
};
|
|
483
|
-
response = await request({
|
|
484
|
-
url: `https://${registration.environment === "development" ? "api.sandbox.push.apple.com" : "api.push.apple.com"}/3/device/${encodeURIComponent(registration.token)}`,
|
|
485
|
-
http2: true,
|
|
486
|
-
timeoutMs,
|
|
487
|
-
headers: {
|
|
488
|
-
authorization: `bearer ${apnsJwt.value}`,
|
|
489
|
-
"apns-topic": APNS_TOPIC,
|
|
490
|
-
"apns-push-type": "alert",
|
|
491
|
-
"apns-priority": "10",
|
|
492
|
-
"apns-expiration": "0",
|
|
493
|
-
"content-type": "application/json"
|
|
494
|
-
},
|
|
495
|
-
body: payload(notification, (text) => ({
|
|
496
|
-
aps: {
|
|
497
|
-
alert: text,
|
|
498
|
-
sound: "default"
|
|
499
|
-
},
|
|
500
|
-
data,
|
|
501
|
-
body: data
|
|
502
|
-
}))
|
|
503
|
-
});
|
|
504
|
-
const value = parse(response.body).reason;
|
|
505
|
-
if (typeof value === "string" && APNS_REASONS.has(value)) reason = value;
|
|
506
|
-
if (response.status === 410 && reason === "Unregistered" || response.status === 400 && reason === "BadDeviceToken") {
|
|
507
|
-
options.diagnostic?.({
|
|
508
|
-
provider,
|
|
509
|
-
outcome: "invalid",
|
|
510
|
-
status: response.status,
|
|
511
|
-
...reason ? { reason } : {}
|
|
512
|
-
});
|
|
513
|
-
return { invalid: true };
|
|
514
|
-
}
|
|
515
|
-
} else {
|
|
509
|
+
if (registration.platform === "ios") return apnsOutcome(await apnsRequest(registration.token, registration.environment, payload(notification, (text) => ({
|
|
510
|
+
aps: {
|
|
511
|
+
alert: text,
|
|
512
|
+
sound: "default"
|
|
513
|
+
},
|
|
514
|
+
data,
|
|
515
|
+
body: data
|
|
516
|
+
}))));
|
|
517
|
+
else {
|
|
516
518
|
const body = payload(notification, (text) => ({ message: {
|
|
517
519
|
token: registration.token,
|
|
518
520
|
data,
|
|
@@ -542,8 +544,7 @@ function createNativePushSender(options) {
|
|
|
542
544
|
options.diagnostic?.({
|
|
543
545
|
provider,
|
|
544
546
|
outcome: "invalid",
|
|
545
|
-
status: response.status
|
|
546
|
-
...reason ? { reason } : {}
|
|
547
|
+
status: response.status
|
|
547
548
|
});
|
|
548
549
|
return { invalid: true };
|
|
549
550
|
}
|
|
@@ -551,8 +552,7 @@ function createNativePushSender(options) {
|
|
|
551
552
|
if (response.status < 200 || response.status >= 300) options.diagnostic?.({
|
|
552
553
|
provider,
|
|
553
554
|
outcome: "failed",
|
|
554
|
-
status: response.status
|
|
555
|
-
...reason ? { reason } : {}
|
|
555
|
+
status: response.status
|
|
556
556
|
});
|
|
557
557
|
} catch {
|
|
558
558
|
options.diagnostic?.({
|
|
@@ -562,6 +562,40 @@ function createNativePushSender(options) {
|
|
|
562
562
|
}
|
|
563
563
|
return { invalid: false };
|
|
564
564
|
},
|
|
565
|
+
async sendLiveActivity(registration, update) {
|
|
566
|
+
if (closed || !options.apns) {
|
|
567
|
+
options.diagnostic?.({
|
|
568
|
+
provider: "apns",
|
|
569
|
+
outcome: "unavailable"
|
|
570
|
+
});
|
|
571
|
+
return { invalid: false };
|
|
572
|
+
}
|
|
573
|
+
try {
|
|
574
|
+
for (const time of [
|
|
575
|
+
update.timestamp,
|
|
576
|
+
update.staleDate,
|
|
577
|
+
update.dismissalDate
|
|
578
|
+
]) if (time !== void 0 && (!Number.isSafeInteger(time) || time < 0)) throw new Error("Invalid APNs timestamp");
|
|
579
|
+
const body = JSON.stringify({ aps: {
|
|
580
|
+
timestamp: update.timestamp,
|
|
581
|
+
event: update.event,
|
|
582
|
+
"content-state": {
|
|
583
|
+
name: update.contentState.name,
|
|
584
|
+
props: JSON.stringify(update.contentState.props)
|
|
585
|
+
},
|
|
586
|
+
...update.staleDate === void 0 ? {} : { "stale-date": update.staleDate },
|
|
587
|
+
...update.dismissalDate === void 0 ? {} : { "dismissal-date": update.dismissalDate }
|
|
588
|
+
} });
|
|
589
|
+
if (encoder.encode(body).length > MAX_PAYLOAD_BYTES) throw new Error("Push payload too large");
|
|
590
|
+
return apnsOutcome(await apnsRequest(registration.activityToken, registration.environment, body, true));
|
|
591
|
+
} catch {
|
|
592
|
+
options.diagnostic?.({
|
|
593
|
+
provider: "apns",
|
|
594
|
+
outcome: "failed"
|
|
595
|
+
});
|
|
596
|
+
return { invalid: false };
|
|
597
|
+
}
|
|
598
|
+
},
|
|
565
599
|
close() {
|
|
566
600
|
closed = true;
|
|
567
601
|
apnsJwt = void 0;
|
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/nativePushSender/sync.ts","../src/services/nativePushSender/index.ts","../src/services/completion/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 { createWriteStream } = require('node:fs');\nconst output = createWriteStream('', { fd: 1, autoClose: false });\nconst { parentPort, workerData } = require('node:worker_threads');\nlet frameIndex = 0;\nlet timer;\nconst writeTitle = (title) => output.write('\\\\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') output.end(() => 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 { formatMessage } from '@agimon-ai/po-core/locale';\n\nimport type { DesktopNotification } from '../../types/notifications';\n\nconst ELLIPSIS = '…';\nconst MAX_BODY_LENGTH = 240;\nconst MAX_PROMPT_TITLE_LENGTH = 36;\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/** Renders one message: a language pack's text for `key`, or the English `fallback`. */\nexport type NotificationTranslate = (\n key: string,\n fallback: string,\n vars?: Readonly<Record<string, string | number>>,\n) => string;\n\nconst english: NotificationTranslate = (_key, fallback, vars) => formatMessage(fallback, vars);\n\n/** Sent while the agent holds the turn and something is blocking on the user. */\nexport function attentionNotification(body: string, t: NotificationTranslate = english): DesktopNotification {\n return {\n title: t('notification.attention.title', 'Po needs your input'),\n subtitle: t('notification.attention.subtitle', 'Approval or feedback required'),\n body,\n };\n}\n\n/**\n * Sent once a run has stopped. The title carries the session name so it shows even where a\n * platform hides subtitles; an unnamed session (the hub sends `''`) falls back to the repository.\n */\nexport function settledNotification(\n { cwd, sessionName }: { cwd: string; sessionName?: string },\n t: NotificationTranslate = english,\n): DesktopNotification {\n const repository = path.basename(cwd);\n const name = sessionName?.trim();\n return {\n title: t('notification.settled.title', 'Po finished: {name}', { name: name || repository }),\n subtitle: name ? repository : '',\n body: t('notification.settled.body', 'The agent finished its work and is waiting for you.'),\n };\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';\n// Only documented provider codes may enter diagnostics, never arbitrary response text.\nconst APNS_REASONS = new Set([\n 'BadCollapseId',\n 'BadDeviceToken',\n 'BadExpirationDate',\n 'BadMessageId',\n 'BadPriority',\n 'BadTopic',\n 'DeviceTokenNotForTopic',\n 'DuplicateHeaders',\n 'IdleTimeout',\n 'InvalidPushType',\n 'MissingDeviceToken',\n 'MissingTopic',\n 'PayloadEmpty',\n 'TopicDisallowed',\n 'BadCertificate',\n 'BadCertificateEnvironment',\n 'ExpiredProviderToken',\n 'Forbidden',\n 'InvalidProviderToken',\n 'MissingProviderToken',\n 'BadPath',\n 'MethodNotAllowed',\n 'Unregistered',\n 'PayloadTooLarge',\n 'TooManyProviderTokenUpdates',\n 'TooManyRequests',\n 'InternalServerError',\n 'ServiceUnavailable',\n 'Shutdown',\n]);\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, sessionId) {\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 const data = {\n ...(registration.hostRef ? { hostRef: registration.hostRef } : {}),\n ...(sessionId ? { sessionId } : {}),\n };\n let response;\n let reason: string | undefined;\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 // Expo iOS reads custom remote data from userInfo.body. Keep data as the provider-neutral payload.\n body: payload(notification, (text) => ({ aps: { alert: text, sound: 'default' }, data, body: data })),\n });\n const value = parse(response.body).reason;\n if (typeof value === 'string' && APNS_REASONS.has(value)) reason = value;\n if (\n (response.status === 410 && reason === 'Unregistered') ||\n (response.status === 400 && reason === 'BadDeviceToken')\n ) {\n options.diagnostic?.({\n provider,\n outcome: 'invalid',\n status: response.status,\n ...(reason ? { reason } : {}),\n });\n return { invalid: true };\n }\n } else {\n const body = payload(notification, (text) => ({\n message: {\n token: registration.token,\n data,\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 options.diagnostic?.({\n provider,\n outcome: 'invalid',\n status: response.status,\n ...(reason ? { reason } : {}),\n });\n return { invalid: true };\n }\n }\n if (response.status < 200 || response.status >= 300)\n options.diagnostic?.({ provider, outcome: 'failed', status: response.status, ...(reason ? { reason } : {}) });\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","import { AUTO_STOP_ACTION, DEFAULT_AUTO_STOP_DELAYS, decideOnRecheck } from '@agimon-ai/po-autostop';\nimport {\n BACKGROUND_RUNNER_DEADLINE_MS,\n BACKGROUND_WORK_HOLDING_PROVIDERS,\n holdsSettledSession,\n holdsSettledSessionAfterRunnerDeadline,\n} from '@agimon-ai/po-core/backgroundWork';\nimport type { PoHubSessionExecutionState } from '@agimon-ai/po-core/hubChannel';\n\nimport type { SessionFinishedDecision } from './type';\n\nexport const SESSION_FINISHED_COOLDOWN_MS = DEFAULT_AUTO_STOP_DELAYS.cooldownMs;\n\n/** The completion test shared by spoken notices and native push, after the initial cooldown. */\nexport function decideSessionFinished(\n state: PoHubSessionExecutionState | undefined,\n holdingSince: number | undefined,\n now: number,\n): SessionFinishedDecision {\n // Unknown background work cannot prove the run finished.\n if (!state?.backgroundWork) return { action: 'unavailable' };\n const expired = holdingSince !== undefined && now - holdingSince >= BACKGROUND_RUNNER_DEADLINE_MS;\n const holds = expired ? holdsSettledSessionAfterRunnerDeadline : holdsSettledSession;\n const { items, errors } = state.backgroundWork;\n if (items.some(holds) || errors.some((error) => BACKGROUND_WORK_HOLDING_PROVIDERS.includes(error.provider)))\n return {\n action: 'hold',\n delayMs: SESSION_FINISHED_COOLDOWN_MS,\n holdingSince: holdingSince ?? now,\n };\n const decision = decideOnRecheck(state, DEFAULT_AUTO_STOP_DELAYS);\n if (decision.action === AUTO_STOP_ACTION.recheck) return { action: 'recheck', delayMs: decision.delayMs };\n return { action: decision.action === AUTO_STOP_ACTION.shutdown ? 'finished' : 'stand-down' };\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiC5B,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,IAAI,OAAO,qBAAqB;GAClD,MAAM;GACN,YAAY;IAAE,QAAQ;IAAgB,YAAA;GAAoC;EAC5E,CAAC;EACD,YAAY,MAAM;EAClB,YAAY,KAAK,SAAS,QAAQ;EAClC,YAAY,KAAK,SAAS,SAAS;GACjC,IAAI,SAAS,KAAK,WAAW,aAAa,SA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a,MAAM,gBAAgB,gCAC5C,yCAAyC;CACjE,MAAM,EAAE,OAAO,WAAW,MAAM;CAChC,IAAI,MAAM,KAAK,KAAK,KAAK,OAAO,MAAM,UAAU,kCAAkC,SAAS,MAAM,QAAQ,CAAC,GACxG,OAAO;EACL,QAAQ;EACR,SAAS;EACT,cAAc,gBAAgB;CAChC;CACF,MAAM,WAAW,gBAAgB,OAAO,wBAAwB;CAChE,IAAI,SAAS,WAAW,iBAAiB,SAAS,OAAO;EAAE,QAAQ;EAAW,SAAS,SAAS;CAAQ;CACxG,OAAO,EAAE,QAAQ,SAAS,WAAW,iBAAiB,WAAW,aAAa,aAAa;AAC7F;;;ACjCA,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/completion/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 { createWriteStream } = require('node:fs');\nconst output = createWriteStream('', { fd: 1, autoClose: false });\nconst { parentPort, workerData } = require('node:worker_threads');\nlet frameIndex = 0;\nlet timer;\nconst writeTitle = (title) => output.write('\\\\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') output.end(() => 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 { formatMessage } from '@agimon-ai/po-core/locale';\n\nimport type { DesktopNotification } from '../../types/notifications';\n\nconst ELLIPSIS = '…';\nconst MAX_BODY_LENGTH = 240;\nconst MAX_PROMPT_TITLE_LENGTH = 36;\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/** Renders one message: a language pack's text for `key`, or the English `fallback`. */\nexport type NotificationTranslate = (\n key: string,\n fallback: string,\n vars?: Readonly<Record<string, string | number>>,\n) => string;\n\nconst english: NotificationTranslate = (_key, fallback, vars) => formatMessage(fallback, vars);\n\n/** Sent while the agent holds the turn and something is blocking on the user. */\nexport function attentionNotification(body: string, t: NotificationTranslate = english): DesktopNotification {\n return {\n title: t('notification.attention.title', 'Po needs your input'),\n subtitle: t('notification.attention.subtitle', 'Approval or feedback required'),\n body,\n };\n}\n\n/**\n * Sent once a run has stopped. The title carries the session name so it shows even where a\n * platform hides subtitles; an unnamed session (the hub sends `''`) falls back to the repository.\n */\nexport function settledNotification(\n { cwd, sessionName }: { cwd: string; sessionName?: string },\n t: NotificationTranslate = english,\n): DesktopNotification {\n const repository = path.basename(cwd);\n const name = sessionName?.trim();\n return {\n title: t('notification.settled.title', 'Po finished: {name}', { name: name || repository }),\n subtitle: name ? repository : '',\n body: t('notification.settled.body', 'The agent finished its work and is waiting for you.'),\n };\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';\n// Only documented provider codes may enter diagnostics, never arbitrary response text.\nconst APNS_REASONS = new Set([\n 'BadCollapseId',\n 'BadDeviceToken',\n 'BadExpirationDate',\n 'BadMessageId',\n 'BadPriority',\n 'BadTopic',\n 'DeviceTokenNotForTopic',\n 'DuplicateHeaders',\n 'IdleTimeout',\n 'InvalidPushType',\n 'MissingDeviceToken',\n 'MissingTopic',\n 'PayloadEmpty',\n 'TopicDisallowed',\n 'BadCertificate',\n 'BadCertificateEnvironment',\n 'ExpiredProviderToken',\n 'Forbidden',\n 'InvalidProviderToken',\n 'MissingProviderToken',\n 'BadPath',\n 'MethodNotAllowed',\n 'Unregistered',\n 'PayloadTooLarge',\n 'TooManyProviderTokenUpdates',\n 'TooManyRequests',\n 'InternalServerError',\n 'ServiceUnavailable',\n 'Shutdown',\n]);\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 async function apnsRequest(\n token: string,\n environment: 'development' | 'production',\n body: string,\n liveActivity = false,\n ) {\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 return request({\n url: `https://${environment === 'development' ? 'api.sandbox.push.apple.com' : 'api.push.apple.com'}/3/device/${encodeURIComponent(token)}`,\n http2: true,\n timeoutMs,\n headers: {\n authorization: `bearer ${apnsJwt.value}`,\n 'apns-topic': liveActivity ? `${APNS_TOPIC}.push-type.liveactivity` : APNS_TOPIC,\n 'apns-push-type': liveActivity ? 'liveactivity' : 'alert',\n 'apns-priority': '10',\n 'apns-expiration': '0',\n 'content-type': 'application/json',\n },\n body,\n });\n }\n\n function apnsOutcome(response: { status: number; body: string }): { invalid: boolean } {\n const value = parse(response.body).reason;\n const reason = typeof value === 'string' && APNS_REASONS.has(value) ? value : undefined;\n const invalid =\n (response.status === 410 && reason === 'Unregistered') ||\n (response.status === 400 && reason === 'BadDeviceToken');\n if (invalid || response.status < 200 || response.status >= 300)\n options.diagnostic?.({\n provider: 'apns',\n outcome: invalid ? 'invalid' : 'failed',\n status: response.status,\n ...(reason ? { reason } : {}),\n });\n return { invalid };\n }\n\n return {\n async send(registration, notification, sessionId) {\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 const data = {\n ...(registration.hostRef ? { hostRef: registration.hostRef } : {}),\n ...(sessionId ? { sessionId } : {}),\n };\n let response;\n if (registration.platform === 'ios') {\n // Expo iOS reads custom remote data from userInfo.body.\n return apnsOutcome(\n await apnsRequest(\n registration.token,\n registration.environment,\n payload(notification, (text) => ({ aps: { alert: text, sound: 'default' }, data, body: data })),\n ),\n );\n } else {\n const body = payload(notification, (text) => ({\n message: {\n token: registration.token,\n data,\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 options.diagnostic?.({\n provider,\n outcome: 'invalid',\n status: response.status,\n });\n return { invalid: true };\n }\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 async sendLiveActivity(registration, update) {\n if (closed || !options.apns) {\n options.diagnostic?.({ provider: 'apns', outcome: 'unavailable' });\n return { invalid: false };\n }\n try {\n for (const time of [update.timestamp, update.staleDate, update.dismissalDate]) {\n if (time !== undefined && (!Number.isSafeInteger(time) || time < 0))\n throw new Error('Invalid APNs timestamp');\n }\n const body = JSON.stringify({\n aps: {\n timestamp: update.timestamp,\n event: update.event,\n 'content-state': { name: update.contentState.name, props: JSON.stringify(update.contentState.props) },\n ...(update.staleDate === undefined ? {} : { 'stale-date': update.staleDate }),\n ...(update.dismissalDate === undefined ? {} : { 'dismissal-date': update.dismissalDate }),\n },\n });\n // Activity state must stay intact. Measure the complete escaped UTF-8 envelope.\n if (encoder.encode(body).length > MAX_PAYLOAD_BYTES) throw new Error('Push payload too large');\n return apnsOutcome(await apnsRequest(registration.activityToken, registration.environment, body, true));\n } catch {\n // Same safe diagnostics as alerts, including signing, transport and cancellation failures.\n options.diagnostic?.({ provider: 'apns', outcome: 'failed' });\n return { invalid: false };\n }\n },\n close() {\n closed = true;\n apnsJwt = undefined;\n oauth = undefined;\n transport.close();\n },\n };\n}\n","import { AUTO_STOP_ACTION, DEFAULT_AUTO_STOP_DELAYS, decideOnRecheck } from '@agimon-ai/po-autostop';\nimport {\n BACKGROUND_RUNNER_DEADLINE_MS,\n BACKGROUND_WORK_HOLDING_PROVIDERS,\n holdsSettledSession,\n holdsSettledSessionAfterRunnerDeadline,\n} from '@agimon-ai/po-core/backgroundWork';\nimport type { PoHubSessionExecutionState } from '@agimon-ai/po-core/hubChannel';\n\nimport type { SessionFinishedDecision } from './type';\n\nexport const SESSION_FINISHED_COOLDOWN_MS = DEFAULT_AUTO_STOP_DELAYS.cooldownMs;\n\n/** The completion test shared by spoken notices and native push, after the initial cooldown. */\nexport function decideSessionFinished(\n state: PoHubSessionExecutionState | undefined,\n holdingSince: number | undefined,\n now: number,\n): SessionFinishedDecision {\n // Unknown background work cannot prove the run finished.\n if (!state?.backgroundWork) return { action: 'unavailable' };\n const expired = holdingSince !== undefined && now - holdingSince >= BACKGROUND_RUNNER_DEADLINE_MS;\n const holds = expired ? holdsSettledSessionAfterRunnerDeadline : holdsSettledSession;\n const { items, errors } = state.backgroundWork;\n if (items.some(holds) || errors.some((error) => BACKGROUND_WORK_HOLDING_PROVIDERS.includes(error.provider)))\n return {\n action: 'hold',\n delayMs: SESSION_FINISHED_COOLDOWN_MS,\n holdingSince: holdingSince ?? now,\n };\n const decision = decideOnRecheck(state, DEFAULT_AUTO_STOP_DELAYS);\n if (decision.action === AUTO_STOP_ACTION.recheck) return { action: 'recheck', delayMs: decision.delayMs };\n return { action: decision.action === AUTO_STOP_ACTION.shutdown ? 'finished' : 'stand-down' };\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiC5B,SAAgB,8BAAoD;CAClE,MAAM,WAAW,gCAAgC;CACjD,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,MAAM,iBAAiB;EACrB,SAA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;;ACzRA,MAAa,+BAA+B,yBAAyB;;AAGrE,SAAgB,sBACd,OACA,cACA,KACyB;CAEzB,IAAI,CAAC,OAAO,gBAAgB,OAAO,EAAE,QAAQ,cAAc;CAE3D,MAAM,QADU,iBAAiB,KAAA,KAAa,MAAM,gBAAgB,gCAC5C,yCAAyC;CACjE,MAAM,EAAE,OAAO,WAAW,MAAM;CAChC,IAAI,MAAM,KAAK,KAAK,KAAK,OAAO,MAAM,UAAU,kCAAkC,SAAS,MAAM,QAAQ,CAAC,GACxG,OAAO;EACL,QAAQ;EACR,SAAS;EACT,cAAc,gBAAgB;CAChC;CACF,MAAM,WAAW,gBAAgB,OAAO,wBAAwB;CAChE,IAAI,SAAS,WAAW,iBAAiB,SAAS,OAAO;EAAE,QAAQ;EAAW,SAAS,SAAS;CAAQ;CACxG,OAAO,EAAE,QAAQ,SAAS,WAAW,iBAAiB,WAAW,aAAa,aAAa;AAC7F;;;ACjCA,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 +1 @@
|
|
|
1
|
-
{"version":1,"platformRequirements":{},"sourceFiles":["LICENSE","README.md","generated/server.ts","llms.txt","package.json","src/exports/apiContracts.ts","src/exports/index.ts","src/extensions/workspaces/sessions/(backend)/_lib/notificationCommand.ts","src/extensions/workspaces/sessions/(backend)/command/notify.server.ts","src/schemas/apiContracts.ts","src/services/completion/index.ts","src/services/completion/type.ts","src/services/nativePushSender/index.ts","src/services/nativePushSender/sync.ts","src/services/nativePushSender/type.ts","src/services/notificationPolicy/index.ts","src/services/notificationText/index.ts","src/services/shellTitleController/index.edge.ts","src/services/shellTitleController/index.ts","src/services/shellTitleController/mainThread.ts","src/services/systemNotification/index.ts","src/types/notifications.ts","tsdown.config.ts"],"sourceRevision":"
|
|
1
|
+
{"version":1,"platformRequirements":{},"sourceFiles":["LICENSE","README.md","generated/server.ts","llms.txt","package.json","src/exports/apiContracts.ts","src/exports/index.ts","src/extensions/workspaces/sessions/(backend)/_lib/notificationCommand.ts","src/extensions/workspaces/sessions/(backend)/command/notify.server.ts","src/schemas/apiContracts.ts","src/services/completion/index.ts","src/services/completion/type.ts","src/services/nativePushSender/index.ts","src/services/nativePushSender/sync.ts","src/services/nativePushSender/type.ts","src/services/notificationPolicy/index.ts","src/services/notificationText/index.ts","src/services/shellTitleController/index.edge.ts","src/services/shellTitleController/index.ts","src/services/shellTitleController/mainThread.ts","src/services/systemNotification/index.ts","src/types/notifications.ts","tsdown.config.ts"],"sourceRevision":"622dcd19d66f45d058d7806d5e741aa0","manifestRevision":"0c21699874399c8676d9047e352dc780","outputFiles":["LICENSE","README.md","dist/apiContracts.cjs","dist/apiContracts.mjs","dist/extensions/server.cjs","dist/extensions/server.mjs","dist/index.cjs","dist/index.mjs","llms.txt"],"outputRevision":"28ce2ce230475515ffc7a18345e8a442"}
|
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.199",
|
|
4
4
|
"description": "Desktop notifications and an animated shell-tab title for Po sessions.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -60,13 +60,13 @@
|
|
|
60
60
|
"access": "public"
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
|
-
"@agimon-ai/po-autostop": "0.0.0-alpha.
|
|
64
|
-
"@agimon-ai/po-core": "0.0.0-alpha.
|
|
63
|
+
"@agimon-ai/po-autostop": "0.0.0-alpha.199",
|
|
64
|
+
"@agimon-ai/po-core": "0.0.0-alpha.199",
|
|
65
65
|
"@deepseek-ai/cordis": "4.0.5"
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
|
-
"@agimon-ai/po-build": "0.0.0-alpha.
|
|
69
|
-
"@agimon-ai/vibe-lint-plugin-po-extension": "0.0.0-alpha.
|
|
68
|
+
"@agimon-ai/po-build": "0.0.0-alpha.199",
|
|
69
|
+
"@agimon-ai/vibe-lint-plugin-po-extension": "0.0.0-alpha.199",
|
|
70
70
|
"@earendil-works/pi-coding-agent": "1.6.1",
|
|
71
71
|
"@types/node": "26.6.5",
|
|
72
72
|
"@vitest/coverage-v8": "5.0.4",
|