@ctliz/agent-intercom-codex 0.11.0-connect.2

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 (52) hide show
  1. package/.codex-plugin/plugin.json +39 -0
  2. package/.mcp.json +10 -0
  3. package/COPYRIGHT +6 -0
  4. package/LICENSE +661 -0
  5. package/LICENSE_TRANSITION.md +25 -0
  6. package/README.md +572 -0
  7. package/THIRD_PARTY_NOTICES.md +17 -0
  8. package/assets/logo-generated.png +0 -0
  9. package/assets/logo.svg +22 -0
  10. package/boss-control-outbox.ts +195 -0
  11. package/broker/access-credential.ts +76 -0
  12. package/broker/access-registry.ts +464 -0
  13. package/broker/audit.ts +60 -0
  14. package/broker/authorization.ts +54 -0
  15. package/broker/boss-adapter.ts +531 -0
  16. package/broker/boss-control-ledger.ts +306 -0
  17. package/broker/broker.ts +2327 -0
  18. package/broker/client.ts +1111 -0
  19. package/broker/framing.ts +87 -0
  20. package/broker/ownership.ts +61 -0
  21. package/broker/paths.ts +161 -0
  22. package/broker/spawn.ts +453 -0
  23. package/codex/app-server-client.ts +562 -0
  24. package/codex/boss-client.ts +34 -0
  25. package/codex/bridge-config.ts +282 -0
  26. package/codex/bridge-daemon.ts +913 -0
  27. package/codex/clipboard.ts +142 -0
  28. package/codex/coi.ts +802 -0
  29. package/codex/contact.ts +54 -0
  30. package/codex/mcp-protocol.ts +248 -0
  31. package/codex/runtime.ts +488 -0
  32. package/codex/server.ts +60 -0
  33. package/codex/team.ts +249 -0
  34. package/codex/tui-input.ts +174 -0
  35. package/config.ts +195 -0
  36. package/dist/bridge-daemon.mjs +3781 -0
  37. package/dist/broker.mjs +3012 -0
  38. package/dist/build-info.json +12 -0
  39. package/dist/codex-server.mjs +2890 -0
  40. package/dist/coi.mjs +4686 -0
  41. package/durable-json.ts +25 -0
  42. package/licenses/MIT-pi-intercom.txt +21 -0
  43. package/outbound-outbox.ts +116 -0
  44. package/package.json +89 -0
  45. package/protocol-v4/contract.ts +27 -0
  46. package/provider/protected-service.ts +162 -0
  47. package/provider/provider.mjs +34 -0
  48. package/scripts/build-info.mjs +58 -0
  49. package/scripts/build.mjs +55 -0
  50. package/skills/codex-intercom/SKILL.md +104 -0
  51. package/tsconfig.json +16 -0
  52. package/types.ts +225 -0
@@ -0,0 +1,531 @@
1
+ import {
2
+ BOSS_CAPABILITY_FEATURE_DIGEST,
3
+ BOSS_CONTROL_ENVELOPE_VERSION,
4
+ BOSS_POLICY_PRINCIPAL_VERSION,
5
+ BOSS_POLICY_SEMANTICS_HASH,
6
+ BOSS_RUN_FEATURE,
7
+ BOSS_RUN_FEATURE_CONTRACT,
8
+ BOSS_RUN_FEATURE_SEMANTICS_HASH,
9
+ BOSS_RUN_FEATURE_VERSION,
10
+ BOSS_RUN_PROTOCOL_FEATURE_CONTRACT_HASH,
11
+ BROKER_FEATURE_ATTESTATION_VERSION,
12
+ INTERCOM_BASE_PROTOCOL_VERSION,
13
+ authorizeFeatureAware,
14
+ brokerFeatureSetHash,
15
+ parseBossControlEnvelope,
16
+ parseBossParticipantBinding,
17
+ parseBossParticipantCredentialEnvelope,
18
+ parseBossRunFeatureContract,
19
+ parseBrokerCapabilityAdvertisement,
20
+ parseParticipantState,
21
+ parseWorkerIdentityV2,
22
+ type BossAuthorizationContext,
23
+ type BossControlEnvelope,
24
+ type BossControlKind,
25
+ type BossControlType,
26
+ type BossPolicyAction,
27
+ type BossPolicyPrincipal,
28
+ type BrokerCapabilityAdvertisement,
29
+ type FeatureAwareAuthorizationDecision,
30
+ type FeatureAwarePolicyState,
31
+ } from "@ctliz/agent-intercom-core/boss";
32
+ import {
33
+ ContractValidationError,
34
+ assertExactKeys,
35
+ assertRecord,
36
+ canonicalJson,
37
+ } from "@ctliz/agent-intercom-core/canonical";
38
+ import type { PolicyAction } from "@ctliz/agent-intercom-core/policy";
39
+ import { types as nodeUtilTypes } from "node:util";
40
+ import type {
41
+ BrokerMessage,
42
+ BossParticipantBindingMetadata,
43
+ BossParticipantRegistrationMetadata,
44
+ ClientMessage,
45
+ SessionInfo,
46
+ } from "../types.ts";
47
+
48
+ export const BOSS_ADVERTISEMENT_PREDICATES = [
49
+ "protectedProvider",
50
+ "brokerIdentity",
51
+ "credentialRegistry",
52
+ "authorityTransitions",
53
+ "participantHealth",
54
+ ] as const;
55
+
56
+ export type BossAdvertisementPredicate = (typeof BOSS_ADVERTISEMENT_PREDICATES)[number];
57
+ export type BossAdvertisementReadiness = Readonly<Record<BossAdvertisementPredicate, boolean>>;
58
+
59
+ export const DORMANT_BOSS_ADVERTISEMENT_READINESS: BossAdvertisementReadiness = Object.freeze({
60
+ protectedProvider: false,
61
+ brokerIdentity: false,
62
+ credentialRegistry: false,
63
+ authorityTransitions: false,
64
+ participantHealth: false,
65
+ });
66
+
67
+ const ORDINARY_SESSION_REGISTRATION_KEYS = [
68
+ "cwd",
69
+ "model",
70
+ "pid",
71
+ "startedAt",
72
+ "lastActivity",
73
+ ] as const;
74
+ const OPTIONAL_SESSION_REGISTRATION_KEYS = ["name", "status", "runtimeInstanceId"] as const;
75
+
76
+ /**
77
+ * Core's canonical parsers reject exotic descriptors, but a Proxy can mimic a
78
+ * plain record and Array iteration skips holes. Reject both before any Boss
79
+ * value crosses the adapter trust boundary.
80
+ */
81
+ export function assertBossCanonicalData(value: unknown, path = "$", seen = new WeakSet<object>()): void {
82
+ if (typeof value !== "object" || value === null) return;
83
+ if (nodeUtilTypes.isProxy(value)) {
84
+ throw new ContractValidationError(path, "proxies are not supported");
85
+ }
86
+ if (seen.has(value)) throw new ContractValidationError(path, "cyclic values are not supported");
87
+ seen.add(value);
88
+ if (Array.isArray(value)) {
89
+ if (Object.getPrototypeOf(value) !== Array.prototype) {
90
+ throw new ContractValidationError(path, "must use the exact Array prototype");
91
+ }
92
+ const ownKeys = Reflect.ownKeys(value);
93
+ const expectedKeys = new Set<PropertyKey>(["length"]);
94
+ for (let index = 0; index < value.length; index += 1) expectedKeys.add(String(index));
95
+ if (ownKeys.length !== expectedKeys.size || ownKeys.some((key) => !expectedKeys.has(key))) {
96
+ throw new ContractValidationError(path, "must be a dense array without symbols or extra properties");
97
+ }
98
+ for (let index = 0; index < value.length; index += 1) {
99
+ if (!Object.hasOwn(value, index)) {
100
+ throw new ContractValidationError(`${path}[${index}]`, "sparse array holes are not supported");
101
+ }
102
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
103
+ if (descriptor === undefined || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) {
104
+ throw new ContractValidationError(`${path}[${index}]`, "must be an own enumerable data property");
105
+ }
106
+ assertBossCanonicalData(descriptor.value, `${path}[${index}]`, seen);
107
+ }
108
+ return;
109
+ }
110
+ if (Object.getPrototypeOf(value) !== Object.prototype) {
111
+ throw new ContractValidationError(path, "must use the exact Object prototype");
112
+ }
113
+ for (const key of Reflect.ownKeys(value)) {
114
+ if (typeof key !== "string") throw new ContractValidationError(path, "symbol properties are not supported");
115
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
116
+ if (descriptor === undefined || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) {
117
+ throw new ContractValidationError(`${path}.${key}`, "must be an own enumerable data property");
118
+ }
119
+ assertBossCanonicalData(descriptor.value, `${path}.${key}`, seen);
120
+ }
121
+ }
122
+
123
+ function parseBossAdvertisementReadiness(value: unknown): BossAdvertisementReadiness {
124
+ assertBossCanonicalData(value, "$.readiness");
125
+ assertRecord(value);
126
+ assertExactKeys(value, BOSS_ADVERTISEMENT_PREDICATES);
127
+ const parsed = {} as Record<BossAdvertisementPredicate, boolean>;
128
+ for (const predicate of BOSS_ADVERTISEMENT_PREDICATES) {
129
+ const enabled = ownDataValue(value, predicate);
130
+ if (typeof enabled !== "boolean") {
131
+ throw new ContractValidationError(`$.readiness.${predicate}`, "must be a boolean");
132
+ }
133
+ parsed[predicate] = enabled;
134
+ }
135
+ return parsed;
136
+ }
137
+
138
+ export function missingBossAdvertisementPredicates(
139
+ readiness: BossAdvertisementReadiness = DORMANT_BOSS_ADVERTISEMENT_READINESS,
140
+ ): BossAdvertisementPredicate[] {
141
+ const parsed = parseBossAdvertisementReadiness(readiness);
142
+ return BOSS_ADVERTISEMENT_PREDICATES.filter((predicate) => parsed[predicate] !== true);
143
+ }
144
+
145
+ /**
146
+ * The Boss feature is intentionally absent until every lockstep service
147
+ * predicate exists. Merely importing Core contracts can never advertise it.
148
+ */
149
+ export function bossCapabilityAdvertisement(
150
+ readiness: BossAdvertisementReadiness = DORMANT_BOSS_ADVERTISEMENT_READINESS,
151
+ ): BrokerCapabilityAdvertisement | undefined {
152
+ if (missingBossAdvertisementPredicates(readiness).length > 0) return undefined;
153
+ const features = [{
154
+ version: BROKER_FEATURE_ATTESTATION_VERSION,
155
+ feature: BOSS_RUN_FEATURE,
156
+ featureVersion: BOSS_RUN_FEATURE_VERSION,
157
+ semanticsHash: BOSS_RUN_FEATURE_SEMANTICS_HASH,
158
+ controlEnvelopeVersion: BOSS_CONTROL_ENVELOPE_VERSION,
159
+ capabilityDigest: BOSS_CAPABILITY_FEATURE_DIGEST,
160
+ }];
161
+ return parseBrokerCapabilityAdvertisement({
162
+ baseProtocolVersion: INTERCOM_BASE_PROTOCOL_VERSION,
163
+ features,
164
+ protocolFeatureContractHash: BOSS_RUN_PROTOCOL_FEATURE_CONTRACT_HASH,
165
+ featureSetHash: brokerFeatureSetHash(features),
166
+ controlEnvelopeVersion: BOSS_CONTROL_ENVELOPE_VERSION,
167
+ capabilityDigest: BOSS_CAPABILITY_FEATURE_DIGEST,
168
+ });
169
+ }
170
+
171
+ function optionalOwnDataValue(value: unknown, key: string): unknown {
172
+ assertRecord(value);
173
+ const descriptor = Object.getOwnPropertyDescriptor(value as object, key);
174
+ if (descriptor === undefined) return undefined;
175
+ if (!descriptor.enumerable || !Object.hasOwn(descriptor, "value")) {
176
+ throw new ContractValidationError(`$.${key}`, "must be an own enumerable data property");
177
+ }
178
+ return descriptor.value;
179
+ }
180
+
181
+ function ownDataValue(value: unknown, key: string): unknown {
182
+ const result = optionalOwnDataValue(value, key);
183
+ if (result === undefined) throw new ContractValidationError(`$.${key}`, "is required");
184
+ return result;
185
+ }
186
+
187
+ export function parseBossParticipantRegistrationMetadata(
188
+ value: unknown,
189
+ ): BossParticipantRegistrationMetadata {
190
+ assertBossCanonicalData(value);
191
+ assertRecord(value);
192
+ assertExactKeys(value, ["featureContract", "credential"]);
193
+ const featureContract = parseBossRunFeatureContract(ownDataValue(value, "featureContract"));
194
+ if (
195
+ featureContract.baseProtocolVersion !== INTERCOM_BASE_PROTOCOL_VERSION
196
+ || canonicalJson(featureContract) !== canonicalJson(BOSS_RUN_FEATURE_CONTRACT)
197
+ ) {
198
+ throw new ContractValidationError("$.featureContract", "must exactly negotiate boss-run-v1 over base protocol v3");
199
+ }
200
+ const credential = parseBossParticipantCredentialEnvelope(ownDataValue(value, "credential"));
201
+ if (credential.namespace !== featureContract.feature) {
202
+ throw new ContractValidationError("$.credential.namespace", "must match the negotiated feature namespace");
203
+ }
204
+ return { featureContract, credential };
205
+ }
206
+
207
+ export function exactRegistrationKind(
208
+ session: { boss?: unknown },
209
+ value: unknown,
210
+ ): "ordinary" | "boss" {
211
+ assertBossCanonicalData(session, "$.session");
212
+ assertRecord(session);
213
+ const boss = optionalOwnDataValue(session, "boss");
214
+ if (boss === undefined) {
215
+ if (value === undefined) return "ordinary";
216
+ throw new ContractValidationError("$.registrationKind", "must be absent when Boss metadata is absent");
217
+ }
218
+ if (value !== "boss") {
219
+ throw new ContractValidationError("$.registrationKind", "must be boss when Boss metadata is present");
220
+ }
221
+ return "boss";
222
+ }
223
+
224
+ /**
225
+ * Validate the complete client registration discriminant before the broker
226
+ * projects any fields. Ordinary frames deliberately retain the pre-Boss wire
227
+ * shape: they have no registrationKind and no Boss capability/authority keys.
228
+ */
229
+ export function parseExactRegistrationFrame(value: unknown): Extract<ClientMessage, { type: "register" }> {
230
+ assertBossCanonicalData(value, "$.register");
231
+ assertRecord(value);
232
+ const session = ownDataValue(value, "session");
233
+ assertRecord(session);
234
+ const registrationKind = optionalOwnDataValue(value, "registrationKind");
235
+ const kind = exactRegistrationKind(session, registrationKind);
236
+ if (kind === "ordinary") {
237
+ assertExactKeys(value, ["type", "protocol", "version", "session"], ["sessionId", "stateId", "access", "scopeId"]);
238
+ assertExactKeys(session, ORDINARY_SESSION_REGISTRATION_KEYS, OPTIONAL_SESSION_REGISTRATION_KEYS);
239
+ } else {
240
+ assertExactKeys(value, ["type", "registrationKind", "protocol", "version", "session"], ["sessionId", "stateId", "scopeId"]);
241
+ assertExactKeys(session, [...ORDINARY_SESSION_REGISTRATION_KEYS, "boss"], OPTIONAL_SESSION_REGISTRATION_KEYS);
242
+ parseBossParticipantRegistrationMetadata(ownDataValue(session, "boss"));
243
+ }
244
+ if (ownDataValue(value, "type") !== "register") {
245
+ throw new ContractValidationError("$.register.type", "must be register");
246
+ }
247
+ return value as Extract<ClientMessage, { type: "register" }>;
248
+ }
249
+
250
+ /** Validate the exact broker response shape for the registration requested. */
251
+ export function parseExactRegisteredFrame(
252
+ value: unknown,
253
+ expected: "ordinary-local" | "ordinary-remote" | "boss",
254
+ ): Extract<BrokerMessage, { type: "registered" }> {
255
+ assertBossCanonicalData(value, "$.registered");
256
+ assertRecord(value);
257
+ if (expected === "boss") {
258
+ assertExactKeys(value, ["type", "registrationKind", "sessionId", "protocol", "version", "capabilities", "boss"]);
259
+ if (ownDataValue(value, "registrationKind") !== "boss") {
260
+ throw new ContractValidationError("$.registered.registrationKind", "must be boss");
261
+ }
262
+ const sessionId = ownDataValue(value, "sessionId");
263
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
264
+ throw new ContractValidationError("$.registered.sessionId", "must be a non-empty string");
265
+ }
266
+ const advertisement = parseBrokerCapabilityAdvertisement(ownDataValue(value, "capabilities"));
267
+ const expectedAdvertisement = bossCapabilityAdvertisement({
268
+ protectedProvider: true,
269
+ brokerIdentity: true,
270
+ credentialRegistry: true,
271
+ authorityTransitions: true,
272
+ participantHealth: true,
273
+ })!;
274
+ const bossFeature = advertisement.features.find((feature) => feature.feature === BOSS_RUN_FEATURE);
275
+ if (
276
+ bossFeature === undefined
277
+ || canonicalJson(bossFeature) !== canonicalJson(expectedAdvertisement.features[0])
278
+ || advertisement.baseProtocolVersion !== expectedAdvertisement.baseProtocolVersion
279
+ || advertisement.protocolFeatureContractHash !== expectedAdvertisement.protocolFeatureContractHash
280
+ || advertisement.controlEnvelopeVersion !== expectedAdvertisement.controlEnvelopeVersion
281
+ || advertisement.capabilityDigest !== expectedAdvertisement.capabilityDigest
282
+ ) throw new ContractValidationError("$.registered.capabilities", "must exactly echo the requested boss-run-v1 contract");
283
+ parseBossParticipantBindingMetadata(ownDataValue(value, "boss"), sessionId);
284
+ } else if (expected === "ordinary-remote") {
285
+ assertExactKeys(value, ["type", "sessionId", "protocol", "version", "remoteAccess", "access"]);
286
+ } else {
287
+ assertExactKeys(value, ["type", "sessionId", "protocol", "version"]);
288
+ }
289
+ if (ownDataValue(value, "type") !== "registered") {
290
+ throw new ContractValidationError("$.registered.type", "must be registered");
291
+ }
292
+ return value as Extract<BrokerMessage, { type: "registered" }>;
293
+ }
294
+
295
+ export function parseBossParticipantBindingMetadata(
296
+ value: unknown,
297
+ expectedSessionId?: string,
298
+ ): BossParticipantBindingMetadata {
299
+ assertBossCanonicalData(value);
300
+ assertRecord(value);
301
+ assertExactKeys(
302
+ value,
303
+ ["featureContract", "binding", "brokerIdentityVerified"],
304
+ ["assignedParticipantIds", "requestingPrincipalId", "workerIdentity", "participantState"],
305
+ );
306
+ const featureContract = parseBossRunFeatureContract(ownDataValue(value, "featureContract"));
307
+ if (
308
+ featureContract.baseProtocolVersion !== INTERCOM_BASE_PROTOCOL_VERSION
309
+ || canonicalJson(featureContract) !== canonicalJson(BOSS_RUN_FEATURE_CONTRACT)
310
+ ) {
311
+ throw new ContractValidationError("$.featureContract", "must exactly bind boss-run-v1 over base protocol v3");
312
+ }
313
+ const binding = parseBossParticipantBinding(ownDataValue(value, "binding"));
314
+ if (ownDataValue(value, "brokerIdentityVerified") !== true) {
315
+ throw new ContractValidationError("$.brokerIdentityVerified", "must be true for a broker-owned Boss binding");
316
+ }
317
+ if (expectedSessionId !== undefined && binding.sessionId !== expectedSessionId) {
318
+ throw new ContractValidationError("$.binding.sessionId", "must match the registered intercom session");
319
+ }
320
+ const rawAssignedParticipantIds = optionalOwnDataValue(value, "assignedParticipantIds");
321
+ let assignedParticipantIds: string[] | undefined;
322
+ if (rawAssignedParticipantIds !== undefined) {
323
+ if (
324
+ binding.role !== "manager"
325
+ || !Array.isArray(rawAssignedParticipantIds)
326
+ || rawAssignedParticipantIds.some((entry) => typeof entry !== "string" || entry.length === 0)
327
+ || new Set(rawAssignedParticipantIds).size !== rawAssignedParticipantIds.length
328
+ ) {
329
+ throw new ContractValidationError("$.assignedParticipantIds", "must be a unique participant list present only for a Manager");
330
+ }
331
+ assignedParticipantIds = rawAssignedParticipantIds as string[];
332
+ }
333
+ if (binding.role === "manager" && assignedParticipantIds === undefined) {
334
+ throw new ContractValidationError("$.assignedParticipantIds", "is required for a Manager policy binding");
335
+ }
336
+ const rawRequestingPrincipalId = optionalOwnDataValue(value, "requestingPrincipalId");
337
+ if ((binding.role === "council") !== (typeof rawRequestingPrincipalId === "string" && rawRequestingPrincipalId.length > 0)) {
338
+ throw new ContractValidationError("$.requestingPrincipalId", "is required exactly for a Council policy binding");
339
+ }
340
+ const requestingPrincipalId = typeof rawRequestingPrincipalId === "string" ? rawRequestingPrincipalId : undefined;
341
+ const rawWorkerIdentity = optionalOwnDataValue(value, "workerIdentity");
342
+ const rawParticipantState = optionalOwnDataValue(value, "participantState");
343
+ if ((rawWorkerIdentity === undefined) !== (rawParticipantState === undefined)) {
344
+ throw new ContractValidationError("$.workerIdentity", "workerIdentity and participantState must be supplied together");
345
+ }
346
+ const workerIdentity = rawWorkerIdentity === undefined ? undefined : parseWorkerIdentityV2(rawWorkerIdentity);
347
+ const participantState = rawParticipantState === undefined
348
+ ? undefined
349
+ : parseParticipantState(rawParticipantState, "$.participantState");
350
+ if (
351
+ workerIdentity !== undefined
352
+ && (
353
+ !("bossRunId" in workerIdentity)
354
+ || workerIdentity.bossRunId !== binding.bossRunId
355
+ || workerIdentity.participantId !== binding.participantId
356
+ || workerIdentity.bindingEpoch !== binding.bindingEpoch
357
+ )
358
+ ) throw new ContractValidationError("$.workerIdentity", "must match the broker-owned participant binding");
359
+ return {
360
+ featureContract,
361
+ binding,
362
+ brokerIdentityVerified: true,
363
+ ...(assignedParticipantIds === undefined ? {} : { assignedParticipantIds: [...assignedParticipantIds] }),
364
+ ...(requestingPrincipalId === undefined ? {} : { requestingPrincipalId }),
365
+ ...(workerIdentity === undefined ? {} : { workerIdentity, participantState: participantState! }),
366
+ };
367
+ }
368
+
369
+ function bossPrincipal(session: SessionInfo, metadata: BossParticipantBindingMetadata): BossPolicyPrincipal {
370
+ const { binding } = metadata;
371
+ return {
372
+ version: BOSS_POLICY_PRINCIPAL_VERSION,
373
+ principalId: session.id,
374
+ principalClass: "boss-private",
375
+ state: binding.state,
376
+ bossRunId: binding.bossRunId,
377
+ participantId: binding.participantId,
378
+ role: binding.role,
379
+ bindingEpoch: binding.bindingEpoch,
380
+ ...(binding.assignedManagerParticipantId === undefined
381
+ ? {}
382
+ : { assignedManagerParticipantId: binding.assignedManagerParticipantId }),
383
+ ...(metadata.assignedParticipantIds === undefined
384
+ ? {}
385
+ : { assignedParticipantIds: metadata.assignedParticipantIds }),
386
+ ...(metadata.requestingPrincipalId === undefined
387
+ ? {}
388
+ : { requestingPrincipalId: metadata.requestingPrincipalId }),
389
+ };
390
+ }
391
+
392
+ export function featurePolicyStateForSessions(sessions: Iterable<SessionInfo>): FeatureAwarePolicyState {
393
+ const legacy: FeatureAwarePolicyState["legacy"] = { principals: {} };
394
+ const boss: FeatureAwarePolicyState["boss"] = { principals: {} };
395
+ const registrations: FeatureAwarePolicyState["registrations"] = {};
396
+ for (const session of sessions) {
397
+ if (session.boss !== undefined) {
398
+ const metadata = parseBossParticipantBindingMetadata(session.boss, session.id);
399
+ boss.principals[session.id] = bossPrincipal(session, metadata);
400
+ registrations[session.id] = {
401
+ principalId: session.id,
402
+ principalClass: "boss-bound",
403
+ state: metadata.binding.state,
404
+ bossRunId: metadata.binding.bossRunId,
405
+ participantId: metadata.binding.participantId,
406
+ bindingEpoch: metadata.binding.bindingEpoch,
407
+ featureContract: metadata.featureContract,
408
+ policySemanticsHash: BOSS_POLICY_SEMANTICS_HASH,
409
+ capabilityDigest: BOSS_CAPABILITY_FEATURE_DIGEST,
410
+ brokerIdentityVerified: metadata.brokerIdentityVerified,
411
+ };
412
+ continue;
413
+ }
414
+ const principal = session.origin === "remote"
415
+ ? (() => {
416
+ if (!session.parentSessionId || !session.rootSessionId || !session.generation) {
417
+ throw new Error(`Remote session ${session.id} is missing broker-owned policy metadata`);
418
+ }
419
+ return {
420
+ id: session.id,
421
+ kind: "remote" as const,
422
+ state: "active" as const,
423
+ generation: session.generation,
424
+ policy: "remote-tree" as const,
425
+ parentSessionId: session.parentSessionId,
426
+ rootSessionId: session.rootSessionId,
427
+ };
428
+ })()
429
+ : {
430
+ id: session.id,
431
+ kind: "local" as const,
432
+ state: "active" as const,
433
+ generation: 1,
434
+ policy: "local-public" as const,
435
+ rootSessionId: session.id,
436
+ };
437
+ legacy.principals[session.id] = principal;
438
+ registrations[session.id] = { principalId: session.id, principalClass: "ordinary", state: "active" };
439
+ }
440
+ return { legacy, boss, registrations };
441
+ }
442
+
443
+ export function authorizeBossAwareSessionAction(
444
+ sessions: Iterable<SessionInfo>,
445
+ actorId: string,
446
+ action: PolicyAction | BossPolicyAction,
447
+ targetId: string,
448
+ bossContext?: BossAuthorizationContext,
449
+ ): FeatureAwareAuthorizationDecision {
450
+ const values = Array.from(sessions);
451
+ const state = featurePolicyStateForSessions(values);
452
+ const actor = state.registrations[actorId];
453
+ const target = state.registrations[targetId];
454
+ return authorizeFeatureAware(state, {
455
+ actorId,
456
+ action,
457
+ targetId,
458
+ ...(actor?.principalClass === "ordinary" && target?.principalClass === "ordinary"
459
+ ? {
460
+ legacyContext: {
461
+ actorGeneration: state.legacy.principals[actorId]?.generation,
462
+ targetGeneration: state.legacy.principals[targetId]?.generation,
463
+ },
464
+ }
465
+ : bossContext === undefined ? {} : { bossContext }),
466
+ });
467
+ }
468
+
469
+ const BOSS_CONTROL_KIND_BY_TYPE: Readonly<Record<BossControlType, BossControlKind>> = {
470
+ "boss.assignment.created": "assignment_request",
471
+ "boss.assignment.accepted": "assignment_response",
472
+ "boss.assignment.checkpoint": "assignment_response",
473
+ "boss.assignment.submitted": "assignment_response",
474
+ "boss.assignment.rejected": "assignment_response",
475
+ "boss.assignment.cancelled": "lifecycle",
476
+ "boss.staffing.requested": "staffing",
477
+ "boss.staffing.resolved": "staffing",
478
+ "boss.review.requested": "review_request",
479
+ "boss.review.submitted": "review_result",
480
+ "boss.council.requested": "review_request",
481
+ "boss.council.submitted": "review_result",
482
+ "boss.proof.submitted": "proof",
483
+ "boss.worker.health": "health",
484
+ "boss.worker.blocked": "health",
485
+ "boss.worker.failed": "health",
486
+ "boss.worker.notice": "lifecycle",
487
+ "boss.worker.notice_delivery_failed": "lifecycle",
488
+ "boss.decision.required": "decision",
489
+ };
490
+
491
+ export function bossControlKind(envelopeValue: unknown): {
492
+ envelope: BossControlEnvelope;
493
+ controlKind: BossControlKind;
494
+ } {
495
+ assertBossCanonicalData(envelopeValue);
496
+ const envelope = parseBossControlEnvelope(envelopeValue);
497
+ return { envelope, controlKind: BOSS_CONTROL_KIND_BY_TYPE[envelope.type] };
498
+ }
499
+
500
+ /** The legacy broker has no authoritative Boss causation ledger. */
501
+ export function hasAuthoritativeBossControlCorrelation(): false {
502
+ return false;
503
+ }
504
+
505
+ export function exactBossSessionTarget<T extends { info: { id: string } }>(
506
+ sessions: ReadonlyMap<string, T>,
507
+ requestedSessionId: string,
508
+ ): T | undefined {
509
+ const target = sessions.get(requestedSessionId);
510
+ return target?.info.id === requestedSessionId ? target : undefined;
511
+ }
512
+
513
+ export function assertBossControlSender(
514
+ session: SessionInfo,
515
+ envelopeValue: unknown,
516
+ ): BossControlEnvelope {
517
+ const { envelope } = bossControlKind(envelopeValue);
518
+ if (session.boss === undefined) {
519
+ throw new ContractValidationError("$.session", "ordinary sessions cannot originate Boss control envelopes");
520
+ }
521
+ const { binding } = parseBossParticipantBindingMetadata(session.boss, session.id);
522
+ if (
523
+ binding.state !== "active"
524
+ || envelope.bossRunId !== binding.bossRunId
525
+ || envelope.participantId !== binding.participantId
526
+ || envelope.bindingEpoch !== binding.bindingEpoch
527
+ ) {
528
+ throw new ContractValidationError("$.envelope", "does not match the active broker-owned participant binding");
529
+ }
530
+ return envelope;
531
+ }