agl 43.7.0 → 43.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/changelog.md +33 -0
  2. package/dist_serve/bundle.js +871 -858
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/aglapi/aglapisurface.document.js +824 -6
  6. package/dist_ts/aglapi/interfaces.d.ts +43 -0
  7. package/dist_ts/aglapi/interfaces.js +11 -1
  8. package/dist_ts/classes.apnsclient.d.ts +97 -0
  9. package/dist_ts/classes.apnsclient.js +363 -0
  10. package/dist_ts/classes.authmodels.js +19 -6
  11. package/dist_ts/classes.authstore.js +15 -2
  12. package/dist_ts/classes.cli.js +8 -1
  13. package/dist_ts/classes.controller.d.ts +30 -3
  14. package/dist_ts/classes.controller.js +250 -9
  15. package/dist_ts/classes.controllerdevices.d.ts +35 -7
  16. package/dist_ts/classes.controllerdevices.js +86 -13
  17. package/dist_ts/classes.controllerpush.d.ts +111 -0
  18. package/dist_ts/classes.controllerpush.js +299 -0
  19. package/dist_ts/classes.fcmclient.d.ts +78 -0
  20. package/dist_ts/classes.fcmclient.js +278 -0
  21. package/dist_ts/classes.inbox.d.ts +10 -2
  22. package/dist_ts/classes.inbox.js +9 -2
  23. package/dist_ts/classes.mcpclient.d.ts +5 -0
  24. package/dist_ts/classes.mcpclient.js +20 -8
  25. package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -0
  26. package/dist_ts/classes.mcpcontrollerhost.js +21 -2
  27. package/dist_ts/classes.mcptools.d.ts +1 -1
  28. package/dist_ts/classes.mcptools.js +2 -1
  29. package/dist_ts/classes.mcpvalidation.js +4 -1
  30. package/dist_ts/classes.mcpworkercaller.d.ts +6 -0
  31. package/dist_ts/classes.mcpworkercaller.js +26 -4
  32. package/dist_ts/classes.pushdelivery.d.ts +115 -0
  33. package/dist_ts/classes.pushdelivery.js +311 -0
  34. package/dist_ts/classes.pushhandover.d.ts +46 -0
  35. package/dist_ts/classes.pushhandover.js +131 -0
  36. package/dist_ts/classes.pushregistrations.d.ts +96 -0
  37. package/dist_ts/classes.pushregistrations.js +263 -0
  38. package/dist_ts/classes.pushsettings.d.ts +125 -0
  39. package/dist_ts/classes.pushsettings.js +377 -0
  40. package/dist_ts/classes.ticketstore.d.ts +3 -3
  41. package/dist_ts/classes.ticketstore.js +23 -4
  42. package/dist_ts/classes.workercallers.d.ts +73 -2
  43. package/dist_ts/classes.workercallers.js +354 -43
  44. package/dist_ts/driver/classes.directreports.d.ts +5 -0
  45. package/dist_ts/driver/classes.directreports.js +3 -2
  46. package/dist_ts/fleet/classes.workerlaunches.d.ts +6 -4
  47. package/dist_ts/fleet/classes.workerlaunches.js +10 -9
  48. package/dist_ts/fleet/classes.workers.d.ts +12 -2
  49. package/dist_ts/fleet/classes.workers.js +82 -2
  50. package/dist_ts/functions.deviceapi.d.ts +23 -3
  51. package/dist_ts/functions.deviceapi.js +43 -3
  52. package/dist_ts/functions.mcptickettools.d.ts +60 -0
  53. package/dist_ts/functions.mcptickettools.js +4 -3
  54. package/dist_ts/functions.pushcli.d.ts +43 -0
  55. package/dist_ts/functions.pushcli.js +201 -0
  56. package/dist_ts/functions.pushcredentials.d.ts +53 -0
  57. package/dist_ts/functions.pushcredentials.js +111 -0
  58. package/dist_ts/functions.pushwire.d.ts +8 -0
  59. package/dist_ts/functions.pushwire.js +83 -0
  60. package/dist_ts/functions.remotecli.d.ts +2 -2
  61. package/dist_ts/functions.remotecli.js +4 -4
  62. package/dist_ts/functions.ticketcli.d.ts +4 -2
  63. package/dist_ts/functions.ticketcli.js +70 -4
  64. package/dist_ts/functions.ticketlisting.d.ts +38 -0
  65. package/dist_ts/functions.ticketlisting.js +211 -0
  66. package/dist_ts/functions.ticketvalidation.d.ts +62 -0
  67. package/dist_ts/functions.ticketvalidation.js +41 -3
  68. package/dist_ts/functions.workercallervalidation.js +3 -2
  69. package/dist_ts/functions.workerprocessproof.d.ts +12 -0
  70. package/dist_ts/functions.workerprocessproof.js +32 -1
  71. package/dist_ts/interfaces.auth.d.ts +27 -3
  72. package/dist_ts/interfaces.auth.js +9 -1
  73. package/dist_ts/interfaces.lifecycle.d.ts +7 -1
  74. package/dist_ts/interfaces.push.d.ts +69 -0
  75. package/dist_ts/interfaces.push.js +25 -0
  76. package/dist_ts/plugins.d.ts +3 -1
  77. package/dist_ts/plugins.js +4 -2
  78. package/dist_ts_interfaces/devices.d.ts +178 -2
  79. package/dist_ts_interfaces/devices.js +24 -2
  80. package/dist_ts_interfaces/index.d.ts +1 -0
  81. package/dist_ts_interfaces/index.js +2 -1
  82. package/dist_ts_interfaces/mcprequests.d.ts +3 -2
  83. package/dist_ts_interfaces/mcprequests.js +3 -1
  84. package/dist_ts_interfaces/push.d.ts +166 -0
  85. package/dist_ts_interfaces/push.js +24 -0
  86. package/dist_ts_interfaces/requests.tickets.d.ts +31 -3
  87. package/dist_ts_interfaces/requests.tickets.js +2 -2
  88. package/dist_ts_interfaces/tickets.d.ts +174 -2
  89. package/dist_ts_interfaces/tickets.js +20 -2
  90. package/dist_ts_interfaces/workercallers.d.ts +43 -3
  91. package/package.json +2 -2
  92. package/readme.md +95 -14
  93. package/ts/00_commitinfo_data.ts +1 -1
  94. package/ts/aglapi/aglapisurface.document.ts +823 -5
  95. package/ts/aglapi/interfaces.ts +10 -0
  96. package/ts/classes.apnsclient.ts +389 -0
  97. package/ts/classes.authmodels.ts +21 -5
  98. package/ts/classes.authstore.ts +14 -1
  99. package/ts/classes.cli.ts +7 -0
  100. package/ts/classes.controller.ts +273 -7
  101. package/ts/classes.controllerdevices.ts +94 -12
  102. package/ts/classes.controllerpush.ts +351 -0
  103. package/ts/classes.fcmclient.ts +292 -0
  104. package/ts/classes.inbox.ts +13 -2
  105. package/ts/classes.mcpclient.ts +22 -7
  106. package/ts/classes.mcpcontrollerhost.ts +22 -1
  107. package/ts/classes.mcptools.ts +1 -0
  108. package/ts/classes.mcpvalidation.ts +2 -0
  109. package/ts/classes.mcpworkercaller.ts +24 -2
  110. package/ts/classes.pushdelivery.ts +378 -0
  111. package/ts/classes.pushhandover.ts +98 -0
  112. package/ts/classes.pushregistrations.ts +244 -0
  113. package/ts/classes.pushsettings.ts +428 -0
  114. package/ts/classes.ticketstore.ts +21 -3
  115. package/ts/classes.workercallers.ts +329 -37
  116. package/ts/driver/classes.directreports.ts +7 -1
  117. package/ts/fleet/classes.workerlaunches.ts +9 -7
  118. package/ts/fleet/classes.workers.ts +65 -2
  119. package/ts/functions.deviceapi.ts +54 -2
  120. package/ts/functions.mcptickettools.ts +3 -2
  121. package/ts/functions.pushcli.ts +212 -0
  122. package/ts/functions.pushcredentials.ts +129 -0
  123. package/ts/functions.pushwire.ts +106 -0
  124. package/ts/functions.remotecli.ts +3 -2
  125. package/ts/functions.ticketcli.ts +70 -5
  126. package/ts/functions.ticketlisting.ts +214 -0
  127. package/ts/functions.ticketvalidation.ts +41 -2
  128. package/ts/functions.workercallervalidation.ts +2 -1
  129. package/ts/functions.workerprocessproof.ts +34 -0
  130. package/ts/interfaces.auth.ts +26 -3
  131. package/ts/interfaces.lifecycle.ts +7 -1
  132. package/ts/interfaces.push.ts +78 -0
  133. package/ts/plugins.ts +3 -1
  134. package/ts_interfaces/devices.schema.json +327 -0
  135. package/ts_interfaces/devices.ts +206 -1
  136. package/ts_interfaces/index.ts +1 -0
  137. package/ts_interfaces/mcprequests.ts +3 -0
  138. package/ts_interfaces/push.ts +162 -0
  139. package/ts_interfaces/requests.tickets.ts +32 -2
  140. package/ts_interfaces/tickets.ts +136 -3
  141. package/ts_interfaces/workercallers.ts +34 -2
  142. package/ts_web/00_commitinfo_data.ts +1 -1
  143. package/ts_web/elements.inbox.ts +50 -9
@@ -1,5 +1,6 @@
1
1
  import * as plugins from '../plugins.js';
2
- import { controllerRuntimeIdKey, type IWorkerClaudeJobRequest, type TWorkerClaudeJobObservation } from '../../ts_interfaces/index.js';
2
+ import { controllerRuntimeIdKey, type IWorkerClaudeJobRequest, type TWorkerClaudeJobObservation, type IWorkerClaudeProcessRequest,
3
+ type TWorkerClaudeProcessIdentification } from '../../ts_interfaces/index.js';
3
4
  import type { IFleetEvent, IFleetWorker, IFleetWorkerProfile, IFleetWorkerJob, IFleetNativeMessageReceipt, TFleetEventKind, TFleetWorkerAction, TFleetWorkerRequest, TFleetWorkerResponse, TFleetWorkerResponseTo, TFleetWorkerJobAction, IFleetWorkerReport, IFleetRelaunchBlocker, IFleetWorkerDispatchHolder, IFleetWorkerSummary, IFleetWorkerSummaryPage } from '../../ts_interfaces/fleetworkers.js';
4
5
  import type { IFleetConfiguration, IFleetOperation, IFleetTicketSync } from '../../ts_interfaces/fleet.js';
5
6
  import type { ITicketActor } from '../../ts_interfaces/tickets.js';
@@ -456,6 +457,63 @@ export class FleetWorkers {
456
457
  return { state: 'unproven', reason: 'the process of its Claude job could not be read' };
457
458
  }
458
459
  }
460
+ /**
461
+ * The reverse of `observeCallerJob`: which worker's Claude background job the process `request.pid` runs, for the
462
+ * controller to identify an MCP bridge that holds no launch by the process it runs under (AGL-1888). Read fresh from
463
+ * the inventories of the fleet's Claude homes (those of its Claude workers that are not archived) and the registry
464
+ * of every owner, on the same one-at-a-time chain. The controller asks only once it proved the process to run an
465
+ * installed Claude Code release.
466
+ */
467
+ public identifyCallerProcess(request: IWorkerClaudeProcessRequest): Promise<TWorkerClaudeProcessIdentification> {
468
+ const task = this.callerJobs.then(() => this.readCallerProcess(request));
469
+ this.callerJobs = task.then(() => undefined, () => undefined);
470
+ return task;
471
+ }
472
+ private async readCallerProcess(request: IWorkerClaudeProcessRequest): Promise<TWorkerClaudeProcessIdentification> {
473
+ const refused = (check: 'parent' | 'inventory' | 'worker', reason: string, forGood: boolean, named: { workerId?: string; nativeSessionId?: string } = {}): TWorkerClaudeProcessIdentification => (
474
+ { state: 'refused', check, reason, forGood, ...named });
475
+ if (this.abort.signal.aborted) return refused('inventory', 'the fleet is closing', false);
476
+ let documents: IFleetWorkerDocument[];
477
+ try { documents = await this.store.list(); }
478
+ catch (error) { return refused('worker', `the fleet registry could not be read (${this.error(error)})`, false); }
479
+ const claude = documents.filter(({ worker }) => worker.harness === 'claude');
480
+ const homes = new Map(claude.filter(({ worker }) => worker.state !== 'archived').map(({ worker }) => [worker.profile.home ?? '', worker.profile.home]));
481
+ if (homes.size === 0) return refused('worker', 'the fleet has no Claude worker', true);
482
+ const listings: Array<{ home: string; agent: IFleetNativeAgent }> = [];
483
+ for (const [key, home] of homes) {
484
+ let agents: IFleetNativeAgent[] | undefined;
485
+ try { agents = await this.backends.claude.inventory?.(home, plugins.os.homedir(), 0); }
486
+ catch (error) { return refused('inventory', `the Claude inventory could not be read (${this.error(error)})`, false); }
487
+ for (const agent of agents ?? []) listings.push({ home: key, agent });
488
+ }
489
+ const listed = listings.filter(({ agent }) => agent.pid === request.pid);
490
+ if (listed.length === 0) {
491
+ // Never an identification: only the reason a bridge one level too deep under a job's process is refused. The
492
+ // controller asks only about a process that runs an installed Claude Code release, and the inventory can still
493
+ // list the process Claude Code just replaced for a job (it retires idle jobs and continues them in a new process),
494
+ // so a process it lists for no session may be listed soon.
495
+ return listings.some(({ agent }) => agent.pid === request.parentPid && agent.kind === 'background')
496
+ ? refused('parent', 'its bridge runs under a child of its Claude job\'s process, not under the job\'s process itself', true)
497
+ : refused('inventory', 'the Claude inventory lists no session in the process its bridge runs under', false);
498
+ }
499
+ if (listed.length > 1) return refused('inventory', 'the Claude inventory lists the process its bridge runs under more than once', false);
500
+ const { home, agent } = listed[0]!;
501
+ if (agent.kind !== 'background' || !agent.id) return refused('inventory', 'the process its bridge runs under is not a Claude background job', true);
502
+ const session = { nativeSessionId: agent.sessionId };
503
+ if (listings.filter((entry) => entry.agent.sessionId === agent.sessionId).length !== 1) {
504
+ return refused('inventory', 'the Claude inventory lists its session more than once', false, session);
505
+ }
506
+ const bound = claude.filter(({ worker }) => worker.nativeId === agent.sessionId);
507
+ const current = bound.filter(({ worker }) => worker.state !== 'archived');
508
+ if (current.length === 0) return refused('worker', bound.length ? 'only an archived fleet worker binds its session' : 'no fleet worker binds its session', true, session);
509
+ if (current.length > 1) return refused('worker', 'more than one fleet worker binds its session', true, session);
510
+ const { owner, worker } = current[0]!, named = { ...session, workerId: worker.id };
511
+ if (worker.lostDispatch) return refused('worker', 'its fleet worker\'s dispatch was resolved as lost', true, named);
512
+ if (worker.pending) return refused('worker', 'its fleet worker has a dispatch in flight', false, named);
513
+ if (worker.state !== 'live') return refused('worker', `its fleet worker is ${worker.state}`, false, named);
514
+ if ((worker.profile.home ?? '') !== home) return refused('worker', 'its fleet worker\'s profile home is not the one whose inventory lists it', true, named);
515
+ return { state: 'identified', workerId: worker.id, projectId: owner, nativeSessionId: agent.sessionId, jobId: agent.id };
516
+ }
459
517
  /** The newest root threads on the host's shared Codex app-server, read at most `maxAgeMs` ago. */
460
518
  public async nativeThreads(maxAgeMs: number): Promise<IFleetNativeThread[]> {
461
519
  return await this.backends.codex.threads?.(plugins.os.homedir(), maxAgeMs) ?? [];
@@ -577,9 +635,11 @@ export class FleetWorkers {
577
635
  }
578
636
  /**
579
637
  * Repairs what follows `worker`'s session after an adoption: a binding that stays on it or was headed to it records
580
- * its error on it and fails the adoption, and a repair that succeeds clears the error an earlier adoption left.
638
+ * its error on it and fails the adoption, and a repair that succeeds clears the error an earlier adoption left. The
639
+ * controller identifies the adopted session's bridge afresh at its next call (AGL-1888).
581
640
  */
582
641
  private async adoptedSessions(owner: string, worker: IFleetWorker): Promise<void> {
642
+ this.options.callers?.adopted();
583
643
  const { stayed, revision } = await this.rebindSessions(owner, { names: [worker.name], own: worker.name,
584
644
  stayed: (failures) => failures.find((failure) => failure.workerName === worker.name) ?? failures.find((failure) => failure.nextName === worker.name) });
585
645
  await this.recordBinding(owner, worker.name, revision, stayed, (current) => {
@@ -818,6 +878,9 @@ export class FleetWorkers {
818
878
  delete current.reconfirmedDispatch; delete current.error; delete current.errorSource;
819
879
  })).worker;
820
880
  this.changed(owner, worker);
881
+ // The worker's caller record proves the bridges of the old session's process: revoked once the registry names
882
+ // the new session, so neither that record nor a process identification of the old session admits them again.
883
+ await this.options.callers?.revoke(worker, 'replacement');
821
884
  }
822
885
  job.workers = [worker];
823
886
  if (this.options.ticketEffects) {
@@ -58,6 +58,8 @@ import {
58
58
  type IDeviceHostDeploys,
59
59
  type IDeviceHostDevice,
60
60
  type IDeviceHostPools,
61
+ type IDeviceHostPush,
62
+ type IDevicePushFailure,
61
63
  type IDeviceHostUnavailable,
62
64
  type IDevicePoolMember,
63
65
  type IDeviceInboxDelta,
@@ -88,6 +90,7 @@ import {
88
90
  type IReq_DeviceHostGet,
89
91
  type IReq_DevicePair,
90
92
  type IReq_DevicePermissionReply,
93
+ type IReq_DevicePushRegister,
91
94
  type IReq_DeviceQuestionReply,
92
95
  type IReq_DeviceSessionRead,
93
96
  type IReq_DeviceSessionSend,
@@ -112,6 +115,7 @@ import { sessionFeedRowId } from './classes.sessionfeed.js';
112
115
  import { directReportReachable, directReportRuntimeId } from './driver/classes.directreports.js';
113
116
  import { DriverError, type DriverService, type IDriverNeedsInput } from './driver/classes.driverservice.js';
114
117
  import { deviceRefusal } from './classes.controllerdevices.js';
118
+ import { isDevicePushToken, type TControllerPushRegistrationState } from './classes.pushregistrations.js';
115
119
  import { controllerFailureJournal } from './classes.failurejournal.js';
116
120
  import { DeployError } from './fleet/classes.deploymonitor.js';
117
121
  import { AglProxyOutdatedError, AglProxyRefusedError, AglProxyUnavailableError } from './classes.proxycontrolclient.js';
@@ -451,6 +455,8 @@ const deviceTicketStoreRefusals: Readonly<Record<Exclude<TTicketErrorCode, keyof
451
455
  outcome_unknown: 'outcome_unknown',
452
456
  ticket_fleet_event_conflict: 'invalid_request',
453
457
  unauthorized: 'invalid_request',
458
+ ticket_cursor_invalid: 'invalid_request',
459
+ ticket_cursor_mismatch: 'invalid_request',
454
460
  };
455
461
 
456
462
  const deviceTicketCodes: ReadonlySet<string> = new Set(deviceTicketRefusalCodes);
@@ -546,12 +552,34 @@ export const deviceHostAgl = (aglArg: {
546
552
  : { kind: 'gateway', state: deviceGatewayStates[aglArg.gateway.state] },
547
553
  });
548
554
 
549
- /** A device's own record as it reads it: no id, key or fingerprint, and nothing it could change. */
550
- export const deviceHostDevice = (deviceArg: IControllerDevice): IDeviceHostDevice => ({
555
+ /**
556
+ * A device's own record as it reads it: no id, key or fingerprint, and nothing it could change; with its push
557
+ * registration while it holds one.
558
+ */
559
+ export const deviceHostDevice = (deviceArg: IControllerDevice, pushArg?: IDeviceHostPush): IDeviceHostDevice => ({
551
560
  name: deviceArg.name,
552
561
  model: deviceArg.model,
553
562
  pairedAt: deviceArg.pairedAt,
554
563
  ...(deviceArg.lastSeenAt === undefined ? {} : { lastSeenAt: deviceArg.lastSeenAt }),
564
+ ...(pushArg === undefined ? {} : { push: pushArg }),
565
+ });
566
+
567
+ /** What the host can send a device on its platform now (AGL-1639). */
568
+ export interface IDevicePushDelivery {
569
+ /** The host's previews setting, one for every device. */
570
+ previews: boolean;
571
+ /** Whether the host holds a credential for the platform that Apple or Google did not refuse. */
572
+ available: boolean;
573
+ /** The device's last notification that did not go out, while none went out after it. */
574
+ lastFailure?: IDevicePushFailure;
575
+ }
576
+
577
+ /** A device's push registration as it reads it: its choice and what the host can send, never its token or salt. */
578
+ export const deviceHostPush = (registrationArg: TControllerPushRegistrationState, deliveryArg: IDevicePushDelivery): IDeviceHostPush => ({
579
+ reports: registrationArg.reports,
580
+ previews: deliveryArg.previews,
581
+ available: deliveryArg.available,
582
+ ...(deliveryArg.lastFailure === undefined ? {} : { lastFailure: { at: deliveryArg.lastFailure.at, reason: deliveryArg.lastFailure.reason } }),
555
583
  });
556
584
 
557
585
  /**
@@ -1413,6 +1441,30 @@ export const assertDeviceDirectReportMessageRequest = (valueArg: unknown): IReq_
1413
1441
  return { name, text };
1414
1442
  };
1415
1443
 
1444
+ /**
1445
+ * A device's push registration, in shape: the platform's token, the APNs environment exactly for an APNs token, and
1446
+ * the choice of reports. No refusal repeats the token.
1447
+ */
1448
+ export const assertDevicePushRegisterRequest = (valueArg: unknown): IReq_DevicePushRegister['request'] => {
1449
+ const value = assertObject(valueArg, 'device push register request');
1450
+ assertKeys(value, ['platform', 'token', 'reports'], ['environment']);
1451
+ if (value.platform !== 'apns' && value.platform !== 'fcm') throw new Error('platform must be apns or fcm.');
1452
+ if (!isDevicePushToken(value.platform, value.token)) {
1453
+ throw new Error(value.platform === 'apns'
1454
+ ? 'token must be an APNs device token: lowercase hex of 32 to 100 bytes.'
1455
+ : 'token must be an FCM registration token: 1 to 1024 characters of letters, digits, _, - and :.');
1456
+ }
1457
+ if (typeof value.reports !== 'boolean') throw new Error('reports must be true or false.');
1458
+ if (value.platform === 'fcm') {
1459
+ if (value.environment !== undefined) throw new Error('environment is for an APNs token only.');
1460
+ return { platform: 'fcm', token: value.token, reports: value.reports };
1461
+ }
1462
+ if (value.environment !== 'sandbox' && value.environment !== 'production') {
1463
+ throw new Error('environment must be sandbox or production for an APNs token.');
1464
+ }
1465
+ return { platform: 'apns', token: value.token, environment: value.environment, reports: value.reports };
1466
+ };
1467
+
1416
1468
  /** A direct child's OpenCode session id, as the Inbox names it. */
1417
1469
  const assertChildSessionId = (valueArg: unknown): string => {
1418
1470
  const id = assertText(valueArg, 'childSessionId', 512);
@@ -3,7 +3,8 @@ import type { TTicketOperation } from '../ts_interfaces/tickets.js';
3
3
 
4
4
  const workflow = ' Caller identity comes from AGL, never a supplied name. Unidentified callers may list/get tickets with empty mine; every mutation requires a verified caller. Workers create in backlog and may update/move only their assigned tickets within ready, in_progress, needs_input and review. Link a branch with a full sha before Review. Only the driver or owner assigns, lands, releases or closes tickets.';
5
5
  export const ticketToolDefinitions = [
6
- { name: 'tickets_list', operation: 'list', description: 'Read the shared board across all projects. Filter by mine, project, status, label or text. mine uses your verified session. label also matches AutoLabels, which AGL computes and nobody sets: openQuestion marks a ticket with an unanswered question, planned a ticket that is not done and plans a release, a deploy or a maintenance window, undeployed a ticket released in a version some deploy target of its repository does not run yet.' },
6
+ { name: 'board_overview', operation: 'overview', description: 'Read the whole board at a glance in one bounded answer, without any ticket\'s texts; start here. Counts by column, by priority (open tickets), by AutoLabel, by project and by assignee, each open epic\'s progress over its direct children (children, done, columns), and under attention the tickets that need someone: urgent, needsInput, openQuestions, review, unassignedReady and stale (in_progress, needs_input or review work without a change for staleDays, default 3, oldest first). recent holds the tickets changed last. Every list holds at most limit tickets (default 5, at most 50) as summaries and its total counts all of them; projects, assignees and epics list at most 50 beside projectsTotal, assigneesTotal and epicsTotal. project narrows to one project, mine to your verified session. Continue with tickets_list for a whole list and ticket_get for one ticket.' },
7
+ { name: 'tickets_list', operation: 'page', description: 'List the shared board across all projects in pages of limit tickets (1-200, default 50; a page also ends at 256 KiB). Tickets are summaries: key, revision, project, kind, title, columnId, priority, updatedAt, and where present assignee, parentId, labels, autoLabels, links (a count per kind), releasePlan, deployPlan, maintenanceWindow and openQuestions; view full returns whole tickets with description and source words, ticket_get one ticket with its history. total and columns (a count per column) describe everything the filters match, on every page, so a page never hides how much there is. Filter by mine (your verified session), project, status or statuses (several columns), open (true leaves out released and closed, false keeps only those), kind, priorities, parent (a ticket\'s direct children, such as an epic\'s tasks), assignee (a person id or a session id as a ticket shows it, never a name), unassigned, keys (up to 200 tickets by key in one call), updatedSince (an ISO 8601 instant), label or text (in key, title, description or source words). label also matches AutoLabels, which AGL computes and nobody sets: openQuestion marks a ticket with an unanswered question, planned a ticket that is not done and plans a release, a deploy or a maintenance window, undeployed a ticket released in a version some deploy target of its repository does not run yet. sort is board (default: by column, then position), updated or created (newest first) or priority (urgent first). Continue with nextCursor and the same filters, sort and view; a cursor of other ones is refused. moved tells that the board changed since the first page: a ticket that changed its place meanwhile may be missing or shown twice, so list again when the reading must be exact.' },
7
8
  { name: 'ticket_get', operation: 'get', description: 'Read a ticket by its AGL-<n> key: source, links, all its questions and their answers, and the newest page of its history, oldest first: up to limit entries (default 50, at most 500), fewer when the entries and their comments would pass 256 KiB. activity is the page; comments are the markdown comments it names, and a commented entry names its comment by id. historyBefore is present while older history exists: pass it as before for the next older page. commentId instead reads the one comment an activity entry or fleet event names (without before or limit).' },
8
9
  { name: 'ticket_create', operation: 'create', description: 'Capture discussed work as a ticket. Include project, title, description and sourceText (the original words); optional attachments are named URLs. Worker-created tickets start in backlog for driver triage. The driver or owner may give it a releasePlan (repo as org/name of a fleet repository, optional version such as 41.0.0; without a version it means the next release), a deployPlan (a deploy target and the release version it should run: AGL asks the owner on the ticket whether to deploy it now, in the next maintenance window, or to hold) or a maintenanceWindow (from and to as ISO 8601 instants, at most 7 days, and the deploy targets it is for); one the driver plans asks the owner and counts once the owner approves it, the owner\'s own counts at once.' },
9
10
  { name: 'ticket_update', operation: 'update', description: 'Update the title, markdown description, priority, labels, project or parent of your assigned ticket. Supply expectedRevision from the ticket you read; stale edits return TICKET_REVISION_CONFLICT with currentRevision. Reload before editing again. Status is changed only with ticket_move; assignment is driver/owner-only. releasePlan (driver/owner only) plans a release: repo as org/name of a fleet repository and an optional version; null clears it. A hotfix is a release plan on an urgent ticket, without a version. fleet_release for the ticket refuses another repository and stops when gitzone plans another version. deployPlan (driver/owner only) plans a deploy and asks the owner its question; once asked it keeps its target and version (setting the same plan again asks anew once the owner answered; closing the ticket drops it; a deploy ticket holds no code or release: a ticket that does, or that is done, plans none, and one with a plan takes no branch, commit or release link), and AGL closes the ticket once the target runs the release. maintenanceWindow (driver/owner only) plans or moves a window; null removes it, and closing the ticket cancels it. A window the driver plans or moves asks the owner and counts once approved; while that question is open it does not change.' },
@@ -14,4 +15,4 @@ export const ticketToolDefinitions = [
14
15
  { name: 'ticket_question_ask', operation: 'ask', description: 'Ask the owner a question on your assigned ticket. question is markdown; options are up to 20 choices (label, optional description), multiSelect allows several, allowCustom (default true) allows a free-text answer. The ticket shows the openQuestion AutoLabel until the owner or driver answers; the answer arrives in your session as a ticket notice. Keep working on what the question does not block.' },
15
16
  ].map((definitionArg) => ({ ...definitionArg, operation: definitionArg.operation as TTicketOperation,
16
17
  description: definitionArg.description + workflow, inputSchema: ticketInputSchemas[definitionArg.operation as TTicketOperation],
17
- readOnly: definitionArg.operation === 'list' || definitionArg.operation === 'get' }));
18
+ readOnly: definitionArg.operation === 'page' || definitionArg.operation === 'overview' || definitionArg.operation === 'get' }));
@@ -0,0 +1,212 @@
1
+ import { ControllerMcpClient } from './classes.mcpclient.js';
2
+ import { withCliDiagnostics } from './functions.clidiagnostics.js';
3
+ import { withLocalConfigurationOwner } from './functions.configurationowner.js';
4
+ import { readStandardInputSecret } from './functions.remotecli.js';
5
+ import { defaultControllerPort } from './classes.config.js';
6
+ import { pushClockSkewText, pushTestAnswerWaitMs, type IPushChange, type IPushFailureStatus, type IPushStatus, type IPushTestResult, type TPushOperation } from '../ts_interfaces/push.js';
7
+
8
+ export const pushCliHelp = `Usage: agl push status [--json]
9
+ agl push apns set --key-id KEY_ID --team-id TEAM_ID [--topic BUNDLE_ID] < AuthKey_KEY_ID.p8
10
+ agl push apns unset
11
+ agl push fcm set < SERVICE_ACCOUNT.json
12
+ agl push fcm unset
13
+ agl push previews on|off
14
+ agl push test [--device DEVICE_ID] [--json]
15
+ Notifications of what waits in the Inbox go from this host straight to Apple's (APNs) and Google's (FCM) push
16
+ services, to the paired devices that registered for them. Every command accepts --port PORT (default 4097), runs
17
+ against the running controller as the local owner, and every change is audited.
18
+ apns set reads the AuthKey .p8 file Apple issued for the team (a key with Apple Push Notifications service) from
19
+ standard input, never from a terminal. --key-id is the key's 10-character id, --team-id the team's; the
20
+ topic is the app's bundle id, com.modelprofile.harness unless --topic names another.
21
+ fcm set reads the JSON key file of the Firebase project's service account (Project settings, Service accounts,
22
+ Generate new private key) from standard input, never from a terminal. Its token_uri is ignored: the host
23
+ asks Google's own endpoints only.
24
+ Both keys are sealed with the TPM and never printed. Set one again to replace it, also after Apple or Google
25
+ refused it: nothing is sent on a refused credential.
26
+ unset removes the platform's credential: nothing is sent on it until it is set again; the devices stay registered.
27
+ previews on: a notification also says where an item lives, what it asks and its id, which Apple or Google can read.
28
+ off (the default): it says one fixed sentence per kind of item.
29
+ status previews, and for each platform: whether its credential is set and usable, what it is for (key id, team id
30
+ and topic; project and service account), when it was set, the registered devices, why Apple or Google
31
+ refused it, and the last send that failed since the controller started (with how far the host's clock is off
32
+ when Google refused for it). --json prints the answer as JSON.
33
+ test sends the test notification ("Push from AGL works.") to every registered device, or to the one --device
34
+ names (its id, as Settings -> Devices shows it), and prints what Apple or Google answered for each: delivered,
35
+ or why not. A device whose token the push service no longer knows loses its registration; the app registers
36
+ again on its next connect. --json prints the answer as JSON.
37
+ `;
38
+
39
+ export type TPushCliArguments = { port: number; json: boolean } & (
40
+ | { operation: 'status' }
41
+ | { operation: 'apns.set'; keyId: string; teamId: string; topic?: string }
42
+ | { operation: 'apns.unset' }
43
+ | { operation: 'fcm.set' }
44
+ | { operation: 'fcm.unset' }
45
+ | { operation: 'previews'; previews: boolean }
46
+ | { operation: 'test'; deviceId?: string }
47
+ );
48
+
49
+ /** `agl push …`: the operation and its options; a usage error names the option, never a value it does not know. */
50
+ export const parsePushCliArguments = (argsArg: readonly string[]): TPushCliArguments => {
51
+ const rest = [...argsArg];
52
+ const first = rest.shift();
53
+ let operation: TPushOperation | undefined;
54
+ let previews: boolean | undefined;
55
+ if (first === 'status' || first === 'test') operation = first;
56
+ else if ((first === 'apns' || first === 'fcm') && (rest[0] === 'set' || rest[0] === 'unset')) operation = `${first}.${rest.shift() as 'set' | 'unset'}`;
57
+ else if (first === 'previews' && (rest[0] === 'on' || rest[0] === 'off')) {
58
+ operation = 'previews';
59
+ previews = rest.shift() === 'on';
60
+ }
61
+ if (!operation) throw new Error(pushCliHelp);
62
+ const allowed = new Set(['--port', ...(operation === 'status' || operation === 'test' ? ['--json'] : []),
63
+ ...(operation === 'apns.set' ? ['--key-id', '--team-id', '--topic'] : []), ...(operation === 'test' ? ['--device'] : [])]);
64
+ const options = new Map<string, string>();
65
+ for (let index = 0; index < rest.length; index++) {
66
+ const token = rest[index]!;
67
+ const equals = token.startsWith('--') ? token.indexOf('=') : -1;
68
+ const flag = equals > 0 ? token.slice(0, equals) : token;
69
+ if (!flag.startsWith('--')) throw new Error(`Unexpected argument for agl push: ${flag.slice(0, 64)}`);
70
+ if (!allowed.has(flag)) throw new Error(`Unknown push option: ${flag.slice(0, 64)}.`);
71
+ if (options.has(flag)) throw new Error(`Duplicate push option: ${flag}.`);
72
+ if (flag === '--json') {
73
+ if (equals > 0) throw new Error('--json takes no value.');
74
+ options.set(flag, 'true');
75
+ continue;
76
+ }
77
+ const value = equals > 0 ? token.slice(equals + 1) : rest[++index];
78
+ if (value === undefined || value === '' || (equals < 0 && value.startsWith('--'))) throw new Error(`${flag} requires a value.`);
79
+ options.set(flag, value);
80
+ }
81
+ const port = options.has('--port') ? Number(options.get('--port')) : defaultControllerPort;
82
+ if (!/^[1-9][0-9]{0,4}$/u.test(String(port)) || port > 65_535) throw new Error('--port must be an integer between 1 and 65535.');
83
+ const base = { port, json: options.has('--json') };
84
+ if (operation === 'apns.set') {
85
+ const keyId = options.get('--key-id');
86
+ const teamId = options.get('--team-id');
87
+ if (keyId === undefined) throw new Error('agl push apns set requires --key-id.');
88
+ if (teamId === undefined) throw new Error('agl push apns set requires --team-id.');
89
+ const topic = options.get('--topic');
90
+ return { ...base, operation, keyId, teamId, ...(topic === undefined ? {} : { topic }) };
91
+ }
92
+ if (operation === 'previews') return { ...base, operation, previews: previews! };
93
+ if (operation === 'test') {
94
+ const deviceId = options.get('--device');
95
+ return { ...base, operation, ...(deviceId === undefined ? {} : { deviceId }) };
96
+ }
97
+ return { ...base, operation };
98
+ };
99
+
100
+ const platformName = { apns: 'APNs', fcm: 'FCM' } as const;
101
+
102
+ const time = (valueArg: number): string => new Date(valueArg).toISOString();
103
+
104
+ const failureLine = (failureArg: IPushFailureStatus): string => (
105
+ `${failureArg.reason}${failureArg.vendorReason === undefined ? '' : ` (${failureArg.vendorReason})`} at ${time(failureArg.at)}`
106
+ + (failureArg.clockSkewMs === undefined ? ''
107
+ : `; the push service's clock and the host's were ${pushClockSkewText(failureArg.clockSkewMs)}: set the host's clock right (NTP)`)
108
+ );
109
+
110
+ const devices = (countArg: number): string => `${countArg} registered device${countArg === 1 ? '' : 's'}`;
111
+
112
+ /** One device's answer to `agl push test`, as a line: never its token. */
113
+ export const pushTestLine = (resultArg: IPushTestResult): string => {
114
+ const where = `${resultArg.name} (${resultArg.deviceId}, ${platformName[resultArg.platform]}${resultArg.environment === undefined ? '' : ` ${resultArg.environment}`})`;
115
+ const vendor = resultArg.vendorReason === undefined ? '' : ` (${resultArg.vendorReason})`;
116
+ if (resultArg.outcome === 'delivered') return `${where}: delivered`;
117
+ if (resultArg.outcome === 'unregistered') {
118
+ return `${where}: the push service no longer knows its token${vendor}; its registration was removed, and the app registers again on its next connect`;
119
+ }
120
+ if (resultArg.outcome === 'unavailable') return `${where}: not sent: the host holds no usable ${platformName[resultArg.platform]} credential`;
121
+ if (resultArg.outcome === 'no_answer') return `${where}: no answer in time: ${platformName[resultArg.platform]} did not answer within ${pushTestAnswerWaitMs / 1000} s; the notification may still arrive`;
122
+ return `${where}: not delivered: ${resultArg.outcome}${vendor}`;
123
+ };
124
+
125
+ /** `agl push status` as lines: previews, then each platform. */
126
+ export const pushStatusLines = (statusArg: IPushStatus): string[] => {
127
+ const lines = [`Previews: ${statusArg.previews ? 'on' : 'off'}`];
128
+ const { apns, fcm } = statusArg;
129
+ const states = {
130
+ unset: 'not set',
131
+ ready: 'ready',
132
+ refused: 'refused: nothing is sent until it is set again',
133
+ unreadable: 'unreadable on this machine: nothing is sent until it is set again',
134
+ } as const;
135
+ lines.push(`APNs: ${states[apns.state]}${apns.keyId === undefined ? '' : `, key id ${apns.keyId}, team ${apns.teamId}, topic ${apns.topic}`}`
136
+ + `${apns.setAt === undefined ? '' : `, set ${time(apns.setAt)}`}; ${devices(apns.registrations)}`);
137
+ if (apns.refused) lines.push(` refused ${failureLine(apns.refused)}`);
138
+ if (apns.lastFailure) lines.push(` last failed send: ${failureLine(apns.lastFailure)}`);
139
+ lines.push(`FCM: ${states[fcm.state]}${fcm.projectId === undefined ? '' : `, project ${fcm.projectId}, service account ${fcm.clientEmail}`}`
140
+ + `${fcm.setAt === undefined ? '' : `, set ${time(fcm.setAt)}`}; ${devices(fcm.registrations)}`);
141
+ if (fcm.refused) lines.push(` refused ${failureLine(fcm.refused)}`);
142
+ if (fcm.lastFailure) lines.push(` last failed send: ${failureLine(fcm.lastFailure)}`);
143
+ return lines;
144
+ };
145
+
146
+ /** What a change did, as one line. */
147
+ const changeLine = (parsedArg: TPushCliArguments, changeArg: IPushChange): string => {
148
+ if (parsedArg.operation === 'apns.set') {
149
+ const { keyId, teamId, topic } = changeArg.status.apns;
150
+ return `Set the APNs credential: key id ${keyId}, team ${teamId}, topic ${topic}. The key is sealed with the TPM and never printed.`;
151
+ }
152
+ if (parsedArg.operation === 'fcm.set') {
153
+ const { projectId, clientEmail } = changeArg.status.fcm;
154
+ return `Set the FCM credential: project ${projectId}, service account ${clientEmail}. The key is sealed with the TPM and never printed.`;
155
+ }
156
+ if (parsedArg.operation === 'apns.unset' || parsedArg.operation === 'fcm.unset') {
157
+ const name = platformName[parsedArg.operation === 'apns.unset' ? 'apns' : 'fcm'];
158
+ return changeArg.changed ? `Removed the ${name} credential: nothing is sent on ${name} until it is set again.`
159
+ : `No ${name} credential was set; nothing changed.`;
160
+ }
161
+ const previews = (parsedArg as { previews: boolean }).previews ? 'on' : 'off';
162
+ return changeArg.changed ? `Previews are ${previews} now.` : `Previews were ${previews} already; nothing changed.`;
163
+ };
164
+
165
+ export interface IPushCliOptions {
166
+ /** Where `apns set` and `fcm set` read their key; this process's standard input when absent. */
167
+ input?: NodeJS.ReadableStream & { isTTY?: boolean };
168
+ /** Where the outcome is written; standard output when absent. */
169
+ write?: (textArg: string) => void;
170
+ /** Runs an operation with the local owner capability; `withLocalConfigurationOwner` when absent. For tests. */
171
+ withOwner?: <T>(clientArg: ControllerMcpClient, portArg: number, operationArg: (ownerTokenArg: string) => Promise<T>) => Promise<T>;
172
+ }
173
+
174
+ /** The key a `set` reads, refused from a terminal; nothing of it is printed. */
175
+ const readKey = (parsedArg: TPushCliArguments, inputArg: NodeJS.ReadableStream & { isTTY?: boolean }): Promise<string> => (
176
+ parsedArg.operation === 'apns.set'
177
+ ? readStandardInputSecret(inputArg, 'agl push apns set reads the AuthKey .p8 file from a pipe or a file, never from a '
178
+ + 'terminal: run it as `agl push apns set --key-id KEY_ID --team-id TEAM_ID < AuthKey_KEY_ID.p8`.', 'an APNs signing key')
179
+ : readStandardInputSecret(inputArg, 'agl push fcm set reads the service account key file from a pipe or a file, never '
180
+ + 'from a terminal: run it as `agl push fcm set < SERVICE_ACCOUNT.json`.', 'a service account key file', 16 * 1024)
181
+ );
182
+
183
+ export const runPushCli = async (argsArg: string[], optionsArg: IPushCliOptions = {}): Promise<void> => {
184
+ const write = optionsArg.write ?? ((textArg: string) => { process.stdout.write(textArg); });
185
+ if (argsArg.includes('--help') || argsArg.includes('-h')) { write(pushCliHelp); return; }
186
+ const parsed = parsePushCliArguments(argsArg);
187
+ const key = parsed.operation === 'apns.set' || parsed.operation === 'fcm.set'
188
+ ? await readKey(parsed, optionsArg.input ?? process.stdin) : undefined;
189
+ const request = parsed.operation === 'apns.set'
190
+ ? { keyId: parsed.keyId, teamId: parsed.teamId, ...(parsed.topic === undefined ? {} : { topic: parsed.topic }), signingKey: key! }
191
+ : parsed.operation === 'fcm.set' ? { serviceAccount: key! }
192
+ : parsed.operation === 'previews' ? { previews: parsed.previews }
193
+ : parsed.operation === 'test' && parsed.deviceId !== undefined ? { deviceId: parsed.deviceId } : {};
194
+ const client = new ControllerMcpClient({ controllerPort: parsed.port });
195
+ const withOwner = optionsArg.withOwner ?? withLocalConfigurationOwner;
196
+ await withCliDiagnostics(async () => withOwner(client, parsed.port, async (ownerTokenArg) => {
197
+ const answer = await client.push(parsed.operation, { ...request, ownerToken: ownerTokenArg } as never);
198
+ if (parsed.operation === 'status') {
199
+ write(parsed.json ? `${JSON.stringify(answer)}\n` : pushStatusLines(answer as IPushStatus).map((lineArg) => `${lineArg}\n`).join(''));
200
+ return;
201
+ }
202
+ if (parsed.operation === 'test') {
203
+ const { results } = answer as { results: IPushTestResult[] };
204
+ write(parsed.json ? `${JSON.stringify(answer)}\n`
205
+ : results.length === 0 ? 'No paired device is registered for notifications.\n'
206
+ : results.map((resultArg) => `${pushTestLine(resultArg)}\n`).join(''));
207
+ return;
208
+ }
209
+ const change = answer as IPushChange;
210
+ write([changeLine(parsed, change), ...pushStatusLines(change.status)].map((lineArg) => `${lineArg}\n`).join(''));
211
+ }));
212
+ };
@@ -0,0 +1,129 @@
1
+ import * as plugins from './plugins.js';
2
+ import type { TPushErrorCode } from '../ts_interfaces/push.js';
3
+
4
+ /**
5
+ * The push credentials the owner gives the host (AGL-1639), checked before they are sealed: an APNs signing key
6
+ * (Apple's AuthKey .p8 file: one P-256 private key) with its key id, team id and topic, and an FCM service account key
7
+ * (Google's JSON key file: a project, the service account's address and an RSA private key). A refusal names the field
8
+ * and the rule, never what was given.
9
+ */
10
+
11
+ /** The bundle id the AGL apps ship under (iOS and Android): the APNs topic unless the owner names another. */
12
+ export const defaultApnsTopic = 'com.modelprofile.harness';
13
+
14
+ /** A refusal of an `agl push` request, with the sentence the owner reads. */
15
+ export class PushError extends Error {
16
+ constructor(public readonly code: TPushErrorCode, messageArg: string) {
17
+ super(messageArg);
18
+ this.name = 'PushError';
19
+ }
20
+ }
21
+
22
+ /** An Apple key id or team id: 10 characters of capital letters and digits. */
23
+ const appleIdPattern = /^[A-Z0-9]{10}$/u;
24
+ /** A bundle id: at least two dot-separated parts of letters, digits and hyphens, at most 155 characters. */
25
+ const bundleIdPattern = /^(?=.{3,155}$)[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/u;
26
+ /** A Google Cloud project id: 6 to 30 lowercase letters, digits and hyphens, from a letter, not ending in a hyphen. */
27
+ const projectIdPattern = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/u;
28
+ /** A service account's address: one line of printable ASCII around one `@`, at most 254 characters. */
29
+ const clientEmailPattern = /^(?=.{3,254}$)[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/u;
30
+ /** The id of a service account key, which Google names in the JWT header (`kid`). */
31
+ const privateKeyIdPattern = /^[A-Za-z0-9]{1,128}$/u;
32
+
33
+ export const isAppleId = (valueArg: unknown): valueArg is string => typeof valueArg === 'string' && appleIdPattern.test(valueArg);
34
+ export const isBundleId = (valueArg: unknown): valueArg is string => typeof valueArg === 'string' && bundleIdPattern.test(valueArg);
35
+ export const isFirebaseProjectId = (valueArg: unknown): valueArg is string => typeof valueArg === 'string' && projectIdPattern.test(valueArg);
36
+ export const isServiceAccountEmail = (valueArg: unknown): valueArg is string => typeof valueArg === 'string' && clientEmailPattern.test(valueArg);
37
+ export const isServiceAccountKeyId = (valueArg: unknown): valueArg is string => typeof valueArg === 'string' && privateKeyIdPattern.test(valueArg);
38
+
39
+ const refuse = (messageArg: string): PushError => new PushError('push_credential_invalid', messageArg);
40
+
41
+ /** A private key from PEM text; refused, without the cause (which could quote the input), when it is none. */
42
+ const readPrivateKey = (pemArg: string, refusalArg: string): plugins.crypto.KeyObject => {
43
+ try {
44
+ return plugins.crypto.createPrivateKey({ key: pemArg, format: 'pem' });
45
+ } catch {
46
+ throw refuse(refusalArg);
47
+ }
48
+ };
49
+
50
+ /** A private key as the store keeps it sealed: PKCS #8, DER. */
51
+ export const privateKeyBytes = (keyArg: plugins.crypto.KeyObject): Buffer => keyArg.export({ format: 'der', type: 'pkcs8' });
52
+
53
+ /** A sealed key read back. */
54
+ export const privateKeyFromBytes = (bytesArg: Uint8Array): plugins.crypto.KeyObject => (
55
+ plugins.crypto.createPrivateKey({ key: Buffer.from(bytesArg), format: 'der', type: 'pkcs8' })
56
+ );
57
+
58
+ export interface IApnsCredentialInput {
59
+ keyId: string;
60
+ teamId: string;
61
+ topic: string;
62
+ key: plugins.crypto.KeyObject;
63
+ }
64
+
65
+ /** Whether a key is a P-256 private key, the only kind APNs signs provider tokens with (ES256). */
66
+ export const isApnsSigningKey = (keyArg: plugins.crypto.KeyObject): boolean => (
67
+ keyArg.type === 'private' && keyArg.asymmetricKeyType === 'ec' && keyArg.asymmetricKeyDetails?.namedCurve === 'prime256v1'
68
+ );
69
+
70
+ /** Whether a key is an RSA private key of at least 2048 bits, which Google's token endpoint takes (RS256). */
71
+ export const isServiceAccountSigningKey = (keyArg: plugins.crypto.KeyObject): boolean => (
72
+ keyArg.type === 'private' && keyArg.asymmetricKeyType === 'rsa' && (keyArg.asymmetricKeyDetails?.modulusLength ?? 0) >= 2048
73
+ );
74
+
75
+ /** `agl push apns set`: the key id, team id and topic, and the .p8 file's text. */
76
+ export const parseApnsCredential = (inputArg: { keyId: unknown; teamId: unknown; topic?: unknown; signingKey: unknown }): IApnsCredentialInput => {
77
+ if (!isAppleId(inputArg.keyId)) throw refuse('--key-id must be the 10-character key id Apple shows for the key: capital letters and digits.');
78
+ if (!isAppleId(inputArg.teamId)) throw refuse('--team-id must be the 10-character Apple team id: capital letters and digits.');
79
+ const topic = inputArg.topic ?? defaultApnsTopic;
80
+ if (!isBundleId(topic)) throw refuse('--topic must be the app\'s bundle id, such as com.modelprofile.harness.');
81
+ const refusal = 'The standard input is not an APNs signing key: give the AuthKey .p8 file Apple issued, which holds one '
82
+ + 'P-256 private key (PKCS #8 PEM).';
83
+ if (typeof inputArg.signingKey !== 'string' || inputArg.signingKey.length === 0) throw refuse(refusal);
84
+ const key = readPrivateKey(inputArg.signingKey, refusal);
85
+ if (!isApnsSigningKey(key)) throw refuse(refusal);
86
+ return { keyId: inputArg.keyId, teamId: inputArg.teamId, topic, key };
87
+ };
88
+
89
+ export interface IFcmCredentialInput {
90
+ projectId: string;
91
+ clientEmail: string;
92
+ /** The key's id, when the file names one: the provider token's `kid`. */
93
+ privateKeyId?: string;
94
+ key: plugins.crypto.KeyObject;
95
+ }
96
+
97
+ /**
98
+ * `agl push fcm set`: the service account key file's JSON. Its `token_uri` and the other URLs it carries are ignored:
99
+ * the host asks Google's own token endpoint only.
100
+ */
101
+ export const parseFcmCredential = (textArg: unknown): IFcmCredentialInput => {
102
+ const file = 'The standard input is not a service account key: give the JSON key file of the Firebase project\'s service '
103
+ + 'account (Project settings, Service accounts, Generate new private key).';
104
+ if (typeof textArg !== 'string' || textArg.length === 0) throw refuse(file);
105
+ let value: unknown;
106
+ try {
107
+ value = JSON.parse(textArg);
108
+ } catch {
109
+ throw refuse(file);
110
+ }
111
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw refuse(file);
112
+ const record = value as Record<string, unknown>;
113
+ if (record.type !== 'service_account') throw refuse(`${file} Its type is not service_account.`);
114
+ if (!isFirebaseProjectId(record.project_id)) throw refuse('The service account key has no valid project_id.');
115
+ if (!isServiceAccountEmail(record.client_email)) throw refuse('The service account key has no valid client_email.');
116
+ if (record.private_key_id !== undefined && !isServiceAccountKeyId(record.private_key_id)) {
117
+ throw refuse('The service account key has an invalid private_key_id.');
118
+ }
119
+ const keyRefusal = 'The service account key\'s private_key is not an RSA private key of at least 2048 bits (PKCS #8 PEM).';
120
+ if (typeof record.private_key !== 'string' || record.private_key.length === 0) throw refuse(keyRefusal);
121
+ const key = readPrivateKey(record.private_key, keyRefusal);
122
+ if (!isServiceAccountSigningKey(key)) throw refuse(keyRefusal);
123
+ return {
124
+ projectId: record.project_id,
125
+ clientEmail: record.client_email,
126
+ ...(record.private_key_id === undefined ? {} : { privateKeyId: record.private_key_id }),
127
+ key,
128
+ };
129
+ };