@cotal-ai/core 0.164.18 → 0.165.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.
- package/dist/agent-file.d.ts +2 -2
- package/dist/agent-file.d.ts.map +1 -1
- package/dist/agent-file.js +4 -1
- package/dist/agent-file.js.map +1 -1
- package/dist/backup-config.d.ts.map +1 -1
- package/dist/backup-config.js +2 -1
- package/dist/backup-config.js.map +1 -1
- package/dist/browser-control.d.ts +3 -9
- package/dist/browser-control.d.ts.map +1 -1
- package/dist/browser-control.js +1 -2
- package/dist/browser-control.js.map +1 -1
- package/dist/browser-validators-build.d.ts +3 -3
- package/dist/browser-validators-build.d.ts.map +1 -1
- package/dist/browser-validators-build.js +10 -110
- package/dist/browser-validators-build.js.map +1 -1
- package/dist/connector.d.ts +3 -0
- package/dist/connector.d.ts.map +1 -1
- package/dist/connector.js.map +1 -1
- package/dist/contract-validator.d.ts +20 -0
- package/dist/contract-validator.d.ts.map +1 -0
- package/dist/contract-validator.js +64 -0
- package/dist/contract-validator.js.map +1 -0
- package/dist/endpoint-call.js +1 -1
- package/dist/endpoint-call.js.map +1 -1
- package/dist/endpoint-describe-observation.js.map +1 -1
- package/dist/endpoint-envelope.d.ts +3 -3
- package/dist/endpoint-envelope.d.ts.map +1 -1
- package/dist/endpoint-envelope.js +3 -6
- package/dist/endpoint-envelope.js.map +1 -1
- package/dist/endpoint-serve.js.map +1 -1
- package/dist/endpoint.d.ts +69 -8
- package/dist/endpoint.d.ts.map +1 -1
- package/dist/endpoint.js +398 -31
- package/dist/endpoint.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/permission-view.d.ts +102 -0
- package/dist/permission-view.d.ts.map +1 -0
- package/dist/permission-view.js +77 -0
- package/dist/permission-view.js.map +1 -0
- package/dist/permissions.d.ts +291 -0
- package/dist/permissions.d.ts.map +1 -0
- package/dist/permissions.js +258 -0
- package/dist/permissions.js.map +1 -0
- package/dist/provision.d.ts +4 -0
- package/dist/provision.d.ts.map +1 -1
- package/dist/provision.js +36 -3
- package/dist/provision.js.map +1 -1
- package/dist/schema-bounds.d.ts.map +1 -1
- package/dist/schema-bounds.js +4 -50
- package/dist/schema-bounds.js.map +1 -1
- package/dist/schema-profile.d.ts +8 -20
- package/dist/schema-profile.d.ts.map +1 -1
- package/dist/schema-profile.js +18 -178
- package/dist/schema-profile.js.map +1 -1
- package/dist/space-deletion-targets.js +2 -2
- package/dist/space-deletion-targets.js.map +1 -1
- package/dist/space-resource-definitions.d.ts.map +1 -1
- package/dist/space-resource-definitions.js +2 -1
- package/dist/space-resource-definitions.js.map +1 -1
- package/dist/streams.d.ts +61 -0
- package/dist/streams.d.ts.map +1 -1
- package/dist/streams.js +68 -3
- package/dist/streams.js.map +1 -1
- package/dist/subjects.d.ts +33 -0
- package/dist/subjects.d.ts.map +1 -1
- package/dist/subjects.js +52 -0
- package/dist/subjects.js.map +1 -1
- package/dist/types.d.ts +3 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +15 -5
package/dist/endpoint.js
CHANGED
|
@@ -32,7 +32,7 @@ import { assertValidKind } from "./agent-file.js";
|
|
|
32
32
|
import { assertValidName } from "./resolve.js";
|
|
33
33
|
import { EVICT_PRINCIPALS_MAX } from "./evict.js";
|
|
34
34
|
import { nextHeartbeat } from "./presence-heartbeat.js";
|
|
35
|
-
import { anycastStoreDefinition, createSpaceStreams, dmDurableConfig, dlvDurableConfig, taskDurableConfig, fanoutDurableConfig, inboxReaderConfig, MANAGER_LEASE_TTL_MS, MANAGER_LEASE_ATTEMPT_MS, TTL_RECONCILE_CANARY_KEY, PRESENCE_STORAGE } from "./streams.js";
|
|
35
|
+
import { anycastStoreDefinition, createSpaceStreams, dmDurableConfig, dlvDurableConfig, taskDurableConfig, fanoutDurableConfig, inboxReaderConfig, MANAGER_LEASE_TTL_MS, MANAGER_LEASE_ATTEMPT_MS, TTL_RECONCILE_CANARY_KEY, PRESENCE_STORAGE, PERMISSION_READER_BATCH, PERMISSION_READER_EXPIRES_MS, permissionReaderConfig } from "./streams.js";
|
|
36
36
|
import { DELIVERY_LIMIT_HEADER, HISTORY_NO_COUNT, PLANE3_MAX_MSGS_PER_SUBJECT } from "./backup-config.js";
|
|
37
37
|
import { jetstream, jetstreamManager, AckPolicy, DeliverPolicy, JetStreamApiCodes, JetStreamApiError, } from "@nats-io/jetstream";
|
|
38
38
|
import {} from "@nats-io/jetstream";
|
|
@@ -44,7 +44,9 @@ import { openDeliveryRegistry } from "./lease.js";
|
|
|
44
44
|
import { openChannelRegistry, effectiveReplay, effectiveReplayWindowMs, effectiveDeliveryClass, readChannelConfig, readChannelDefaults, decodeChannelEntry, } from "./channels.js";
|
|
45
45
|
import { isCasLoss } from "./endpoint-records.js";
|
|
46
46
|
import { ANYCAST_CANCEL_OP, ANYCAST_NOTICE_KEY, ANYCAST_RECORDS_CREDENTIAL_OUTDATED, ANYCAST_STATUS_OP, ANYCAST_TAKES_OP, AnycastRequestAuthority, isAnycastSeq, } from "./anycast-requests.js";
|
|
47
|
-
import { anycastSubject, assertValidOwnerToken, assertValidRole, CHANNEL_DEFAULTS_KEY, chatStream, chatHistDurable, chatSubject, historyReaderConsumer, calloutReaderId, HISTORY_READERS, controlServiceSubject, livenessSubject, livenessServeFilter, CONTROL_DELIVERY, CONTROL_DELIVERY_ADMIN, dmStream, dmDurable, dlvStream, dlvDurable, dlvSubject, dinboxSubject, inboxStream, parseDinboxPrincipal, FANOUT_DURABLE, INBOX_READER_DURABLE, leaseKey, managerBucket, MANAGER_LEASE_KEY, MANAGER_RENEWAL_LEASE_KEY, managerLeaseKey, assertValidChannel, channelInAllow, membershipInAllow, isConcreteChannel, isChannelFamily, familiesCovering, normalizeMentions, parseSubject, isPrincipalOwnerToken, assertInboxConnId, presenceBucket, channelBucket, isPresenceRow, assertPresenceRow, membershipBucket, MEMBERSHIP_FEED_KEY, principalKey, parsePrincipalKey, assertLifecycleToken, mintLifecycleUid, lifecycleNameKey, memberKey, DEV_OWNER, spacePrefix, spaceWildcard, subjectMatches, taskStream, taskDurable, takeServeFilter, takeSubject, parseTakeSubject, TAKE_ROUTE, token, unicastSubject, unicastRecvFilter, } from "./subjects.js";
|
|
47
|
+
import { anycastSubject, assertValidOwnerToken, assertValidRole, CHANNEL_DEFAULTS_KEY, chatStream, chatHistDurable, chatSubject, historyReaderConsumer, calloutReaderId, HISTORY_READERS, controlServiceSubject, livenessSubject, livenessServeFilter, CONTROL_DELIVERY, CONTROL_DELIVERY_ADMIN, dmStream, dmDurable, dlvStream, dlvDurable, dlvSubject, dinboxSubject, inboxStream, parseDinboxPrincipal, FANOUT_DURABLE, INBOX_READER_DURABLE, leaseKey, managerBucket, MANAGER_LEASE_KEY, MANAGER_RENEWAL_LEASE_KEY, managerLeaseKey, assertValidChannel, channelInAllow, membershipInAllow, isConcreteChannel, isChannelFamily, familiesCovering, normalizeMentions, MENTION_NOTICE_KEY, parseSubject, isPrincipalOwnerToken, assertInboxConnId, presenceBucket, channelBucket, isPresenceRow, assertPresenceRow, membershipBucket, MEMBERSHIP_FEED_KEY, principalKey, parsePrincipalKey, assertLifecycleToken, mintLifecycleUid, lifecycleNameKey, memberKey, DEV_OWNER, spacePrefix, spaceWildcard, subjectMatches, taskStream, taskDurable, takeServeFilter, takeSubject, parseTakeSubject, TAKE_ROUTE, token, unicastSubject, unicastRecvFilter, assertRuntimeToken, permissionAnswerSubject, permissionBucket, permissionReaderDurable, permissionServeFilter, } from "./subjects.js";
|
|
48
|
+
import { PERMISSION_ANSWER_TIMEOUT_MS, PERMISSION_HANDOFF_BOUND_MS, parsePermissionAnswerBody, parsePermissionAnswerReply, parsePermissionRecord, permissionAnswerOutcome, permissionKey, principalId, } from "./permissions.js";
|
|
49
|
+
import { startPermissionView, stepPermissionView, } from "./permission-view.js";
|
|
48
50
|
import { isPermissionDenied } from "./permission-denied.js";
|
|
49
51
|
export { isPermissionDenied };
|
|
50
52
|
export const DEFAULT_SERVER = "nats://127.0.0.1:4222";
|
|
@@ -102,13 +104,14 @@ export const MULTI_FILTER_READ_CONCURRENCY = 4;
|
|
|
102
104
|
const HISTORY_READER_INACTIVE_MS = 5 * 60_000;
|
|
103
105
|
/** The longest delay `setTimeout` honors, 2^31-1 ms. */
|
|
104
106
|
const MAX_TIMER_MS = 2_147_483_647;
|
|
105
|
-
/**
|
|
107
|
+
/** This endpoint's own `dm_` durable does not exist. A DM-only endpoint, and any endpoint on an
|
|
108
|
+
* authenticated mesh, binds the durable its provisioner created and never creates one. */
|
|
106
109
|
export class DmDurableMissingError extends Error {
|
|
107
110
|
stream;
|
|
108
111
|
durable;
|
|
109
112
|
code = "dm-durable-missing";
|
|
110
113
|
constructor(stream, durable) {
|
|
111
|
-
super(`dm-durable-missing: durable "${durable}" on stream "${stream}" does not exist;
|
|
114
|
+
super(`dm-durable-missing: durable "${durable}" on stream "${stream}" does not exist; this endpoint binds an existing durable and never creates one`);
|
|
112
115
|
this.stream = stream;
|
|
113
116
|
this.durable = durable;
|
|
114
117
|
this.name = "DmDurableMissingError";
|
|
@@ -391,6 +394,12 @@ export class CotalEndpoint extends EventEmitter {
|
|
|
391
394
|
* subscription on it, so a responder bound once would leave its plane to the broker's
|
|
392
395
|
* no-responders answer, which a peer grades `unbound`, while this endpoint is connected and serving. */
|
|
393
396
|
livenessResponders = new Map();
|
|
397
|
+
/** The permission holder {@link openPermissionHolder} opened: INTENT, re-bound on every (re)connect
|
|
398
|
+
* as the liveness responders are. */
|
|
399
|
+
permissionHolder;
|
|
400
|
+
/** The permission watch {@link watchPermissions} runs: told when the connection is replaced, so it
|
|
401
|
+
* opens its reader again, and when this endpoint stops. */
|
|
402
|
+
permissionWatch;
|
|
394
403
|
streamMsgs = [];
|
|
395
404
|
/** Per-channel native core subscriptions (SPEC v0.3) — the manager-free live read path for boot +
|
|
396
405
|
* runtime channels (there is no per-instance chat durable). Keyed by channel so leave unsubscribes
|
|
@@ -1601,6 +1610,8 @@ export class CotalEndpoint extends EventEmitter {
|
|
|
1601
1610
|
// the old connection and the responders with it.
|
|
1602
1611
|
for (const plane of this.livenessResponders.keys())
|
|
1603
1612
|
this.bindLiveness(plane);
|
|
1613
|
+
this.bindPermissionHolder();
|
|
1614
|
+
this.permissionWatch?.reconnected();
|
|
1604
1615
|
for (const tap of this.taps)
|
|
1605
1616
|
this.bindTap(tap);
|
|
1606
1617
|
// Bound and live — covers initial start, manual reconnect, AND background self-heal (every
|
|
@@ -2016,6 +2027,7 @@ export class CotalEndpoint extends EventEmitter {
|
|
|
2016
2027
|
this.activeGoalFollowers.clear();
|
|
2017
2028
|
this.presenceEpoch++;
|
|
2018
2029
|
this.presenceRebind = undefined;
|
|
2030
|
+
this.permissionWatch?.stopped();
|
|
2019
2031
|
// Wake a reestablishLoop sitting in backoff so it sees `stopped` and exits instead of
|
|
2020
2032
|
// sleeping out retryMs; also clears the timer so it can't fire later.
|
|
2021
2033
|
this.kickBackoff();
|
|
@@ -3994,7 +4006,7 @@ export class CotalEndpoint extends EventEmitter {
|
|
|
3994
4006
|
return { items: out.slice(-limit), complete: out.length <= limit };
|
|
3995
4007
|
}
|
|
3996
4008
|
/**
|
|
3997
|
-
* The newest `limit` chat messages across
|
|
4009
|
+
* The newest `limit` chat messages across concrete channels or one channel family, oldest-first within the page,
|
|
3998
4010
|
* each tagged with the channel the BROKER delivered it on.
|
|
3999
4011
|
*
|
|
4000
4012
|
* The CHAT stream interleaves every channel into one sequence space. Consumers take sets of
|
|
@@ -4009,21 +4021,22 @@ export class CotalEndpoint extends EventEmitter {
|
|
|
4009
4021
|
* field, and this method ignores it: the tag is derived from the subject the broker routed the
|
|
4010
4022
|
* message on, the same derivation {@link listChannels} uses to name a channel in the first place.
|
|
4011
4023
|
*
|
|
4012
|
-
*
|
|
4013
|
-
*
|
|
4014
|
-
*
|
|
4024
|
+
* A single channel family such as `events.>` uses one broker filter without enumerating its
|
|
4025
|
+
* concrete channels. Otherwise every channel must be concrete: mixing a family with other
|
|
4026
|
+
* filters, or using other wildcard patterns, is refused rather than risking overlapping filters.
|
|
4015
4027
|
*
|
|
4016
|
-
* **
|
|
4028
|
+
* **The broker enforces read authority.** A multi-filter create
|
|
4017
4029
|
* cannot encode its filter in the API subject, so it rides the bare
|
|
4018
4030
|
* `$JS.API.CONSUMER.CREATE.<CHAT>` row that only the read-only dashboard profiles hold. An agent
|
|
4019
4031
|
* credential pins the filter into the subject per channel and is denied here by the broker, which
|
|
4020
4032
|
* is the correct answer: this method reads across channels, and an agent's read ACL is per
|
|
4021
|
-
* channel.
|
|
4033
|
+
* channel. A single filter uses the filter-bearing create subject, including a channel family,
|
|
4034
|
+
* so the broker checks the credential's grant for that filter. No additional authority is minted.
|
|
4022
4035
|
*/
|
|
4023
4036
|
async multiChannelHistory(channels, opts) {
|
|
4024
4037
|
const subjects = [...new Set(channels.map((channel) => {
|
|
4025
|
-
if (!isConcreteChannel(channel))
|
|
4026
|
-
throw new Error(`multiChannelHistory: "${channel}" is a wildcard channel - one
|
|
4038
|
+
if (!isConcreteChannel(channel) && !(channels.length === 1 && isChannelFamily(channel)))
|
|
4039
|
+
throw new Error(`multiChannelHistory: "${channel}" is a wildcard channel - name one channel family alone or concrete channels without wildcards`);
|
|
4027
4040
|
// `chatSubject` builds the filter through `token()`, which REWRITES rather than refuses: it
|
|
4028
4041
|
// maps a character a subject may not carry to `_`, trims each segment, and drops empty ones.
|
|
4029
4042
|
// So "foo/bar" would filter on `foo_bar`, ".lead" on `lead`, and "team..b" on `team.b` - the
|
|
@@ -6252,6 +6265,29 @@ export class CotalEndpoint extends EventEmitter {
|
|
|
6252
6265
|
};
|
|
6253
6266
|
await this.js.publish(unicastSubject(this.space, recipient.owner, recipient.actor, this.owner, this.actor), JSON.stringify(msg), { msgID: msg.id });
|
|
6254
6267
|
}
|
|
6268
|
+
/** DM a post's sender that its mentions of `names` reached no one, because each of those agents
|
|
6269
|
+
* may not read `channel`. The id carries the post's stream seq, so a fan-out redelivered after a
|
|
6270
|
+
* crash sends the notice again under the same id and the DM stream drops the duplicate. */
|
|
6271
|
+
async sendMentionNotice(msg, channel, seq, names) {
|
|
6272
|
+
if (!this.js)
|
|
6273
|
+
throw new Error(this.notLiveMsg());
|
|
6274
|
+
const recipient = parsePrincipalKey(msg.from.id);
|
|
6275
|
+
if (!recipient)
|
|
6276
|
+
throw new Error(`mention notice: "${msg.from.id}" is not a principal`);
|
|
6277
|
+
const named = names.map((n) => `@${n}`).join(", ");
|
|
6278
|
+
const notice = {
|
|
6279
|
+
id: `mention.${seq}.${msg.id}`,
|
|
6280
|
+
ts: Date.now(),
|
|
6281
|
+
space: this.space,
|
|
6282
|
+
from: this.ref(),
|
|
6283
|
+
to: msg.from.id,
|
|
6284
|
+
parts: [
|
|
6285
|
+
{ kind: "text", text: `Your post on #${channel} mentioned ${named}, who may not read #${channel} and ${names.length === 1 ? "was" : "were"} not given it. Reach ${names.length === 1 ? "them" : "each"} another way, such as cotal_dm.` },
|
|
6286
|
+
{ kind: "data", data: { [MENTION_NOTICE_KEY]: { channel, message: msg.id, names: [...names] } } },
|
|
6287
|
+
],
|
|
6288
|
+
};
|
|
6289
|
+
await this.js.publish(unicastSubject(this.space, recipient.owner, recipient.actor, this.owner, this.actor), JSON.stringify(notice), { msgID: notice.id });
|
|
6290
|
+
}
|
|
6255
6291
|
/** Answer a sender's status or cancel for one of its own requests. The caller is the
|
|
6256
6292
|
* authenticated subject sender, checked against the request's stored subject. */
|
|
6257
6293
|
async deliveryAnycast(op, caller, args) {
|
|
@@ -6481,6 +6517,310 @@ export class CotalEndpoint extends EventEmitter {
|
|
|
6481
6517
|
// the plane, so it is graded like a refusal rather than guessed at.
|
|
6482
6518
|
return "refused";
|
|
6483
6519
|
}
|
|
6520
|
+
/**
|
|
6521
|
+
* Hold this agent's harness permission prompts (SPEC §8.2): serve the answers its owner's
|
|
6522
|
+
* principals send this process, and write its own prompt records. The broker admits only that
|
|
6523
|
+
* owner's interactive principals to ask, so every answer's `by` is one of them.
|
|
6524
|
+
*
|
|
6525
|
+
* Refused on an open mesh, where any principal could answer, and without a lifecycle UID, which
|
|
6526
|
+
* each record names so readers can tell a live holder from a gone one. It serves only the subject
|
|
6527
|
+
* of this process's runtime, which its records name, so another process of the same agent never
|
|
6528
|
+
* receives its answers. The binding is intent, re-bound on every (re)connect. A request whose reply
|
|
6529
|
+
* target is outside its own `.reply.` leaf is dropped and reported on `warning`, and a body outside
|
|
6530
|
+
* the schema is answered `bad-request`. `onAnswer` resolves `undefined` for a prompt this holder
|
|
6531
|
+
* does not hold, and then nothing is sent. Answers are handed over as they arrive, so one awaiting
|
|
6532
|
+
* its harness never delays another.
|
|
6533
|
+
*/
|
|
6534
|
+
openPermissionHolder(onAnswer) {
|
|
6535
|
+
if (!this.authed)
|
|
6536
|
+
throw new Error("permission prompts are relayed only on an authenticated mesh: on an open mesh any principal could answer them");
|
|
6537
|
+
const lifecycleUid = this.ownLifecycleUid;
|
|
6538
|
+
if (lifecycleUid === undefined)
|
|
6539
|
+
throw new Error("a permission holder needs this endpoint's lifecycleUid: its records name it so readers can tell when the holder is gone");
|
|
6540
|
+
if (this.permissionHolder)
|
|
6541
|
+
throw new Error("this endpoint already holds its permission prompts");
|
|
6542
|
+
const runtimeId = assertRuntimeToken(processRuntime(lifecycleUid).id);
|
|
6543
|
+
const held = { onAnswer, runtimeId };
|
|
6544
|
+
this.permissionHolder = held;
|
|
6545
|
+
this.bindPermissionHolder();
|
|
6546
|
+
return {
|
|
6547
|
+
agent: principalId(this.owner, this.actor),
|
|
6548
|
+
holder: { lifecycleUid, runtimeId },
|
|
6549
|
+
write: (record, step, expected) => this.writePermissionRecord(record, step, expected),
|
|
6550
|
+
close: () => {
|
|
6551
|
+
if (this.permissionHolder !== held)
|
|
6552
|
+
return;
|
|
6553
|
+
this.permissionHolder = undefined;
|
|
6554
|
+
this.dropSub(held.sub);
|
|
6555
|
+
},
|
|
6556
|
+
};
|
|
6557
|
+
}
|
|
6558
|
+
dropSub(sub) {
|
|
6559
|
+
if (!sub)
|
|
6560
|
+
return;
|
|
6561
|
+
try {
|
|
6562
|
+
sub.unsubscribe();
|
|
6563
|
+
}
|
|
6564
|
+
catch { /* dead with the old connection */ }
|
|
6565
|
+
const i = this.subs.indexOf(sub);
|
|
6566
|
+
if (i >= 0)
|
|
6567
|
+
this.subs.splice(i, 1);
|
|
6568
|
+
}
|
|
6569
|
+
bindPermissionHolder() {
|
|
6570
|
+
const held = this.permissionHolder;
|
|
6571
|
+
if (!held || !this.nc)
|
|
6572
|
+
return;
|
|
6573
|
+
this.dropSub(held.sub);
|
|
6574
|
+
const filter = permissionServeFilter(this.space, this.owner, this.actor, held.runtimeId);
|
|
6575
|
+
const sub = this.nc.subscribe(filter);
|
|
6576
|
+
held.sub = sub;
|
|
6577
|
+
this.subs.push(sub);
|
|
6578
|
+
const senders = filter.slice(0, -1);
|
|
6579
|
+
void (async () => {
|
|
6580
|
+
for await (const m of sub) {
|
|
6581
|
+
// The broker does not check a requester's embedded reply subject, and this holder may publish
|
|
6582
|
+
// beneath any `.reply.` of its rail, so a reply aimed anywhere else is not answered.
|
|
6583
|
+
if (!m.reply || !m.reply.startsWith(`${m.subject}.reply.`)) {
|
|
6584
|
+
this.emitRecoverable(new Error(`rejected permission answer on ${m.subject}: reply target "${m.reply ?? "(none)"}" is not under the sender's own reply subtree`));
|
|
6585
|
+
continue;
|
|
6586
|
+
}
|
|
6587
|
+
const actor = m.subject.slice(senders.length);
|
|
6588
|
+
let body;
|
|
6589
|
+
try {
|
|
6590
|
+
body = m.json();
|
|
6591
|
+
}
|
|
6592
|
+
catch {
|
|
6593
|
+
body = undefined;
|
|
6594
|
+
}
|
|
6595
|
+
const parsed = parsePermissionAnswerBody(body);
|
|
6596
|
+
if (!parsePrincipalKey(`${this.owner}.${actor}`) || !parsed) {
|
|
6597
|
+
try {
|
|
6598
|
+
m.respond(JSON.stringify({ v: 1, ok: false, code: "bad-request" }));
|
|
6599
|
+
}
|
|
6600
|
+
catch { /* the asker is gone */ }
|
|
6601
|
+
continue;
|
|
6602
|
+
}
|
|
6603
|
+
void held.onAnswer({ id: parsed.id, by: principalId(this.owner, actor), answer: parsed.answer })
|
|
6604
|
+
.catch(() => ({ v: 1, ok: false, code: "busy" }))
|
|
6605
|
+
.then((reply) => { if (reply)
|
|
6606
|
+
try {
|
|
6607
|
+
m.respond(JSON.stringify(reply));
|
|
6608
|
+
}
|
|
6609
|
+
catch { /* the asker is gone */ } });
|
|
6610
|
+
}
|
|
6611
|
+
})().catch((e) => this.emitRecoverable(new Error(`the permission holder stopped serving answers: ${e.message}`)));
|
|
6612
|
+
}
|
|
6613
|
+
async writePermissionRecord(record, step, expected) {
|
|
6614
|
+
const js = this.js;
|
|
6615
|
+
if (!js || !this.nc)
|
|
6616
|
+
return { kind: "unavailable" };
|
|
6617
|
+
try {
|
|
6618
|
+
// nats-server checks the expected sequence before the msg id, so a retry of a step that landed
|
|
6619
|
+
// would read as a conflict. A retry therefore carries only the msg id.
|
|
6620
|
+
const ack = await js.publish(`$KV.${permissionBucket(this.space)}.${permissionKey(record.agent, record.id)}`, JSON.stringify(record), {
|
|
6621
|
+
msgID: `${record.id}.${step}`,
|
|
6622
|
+
...(expected === "retry" ? {} : { expect: { lastSubjectSequence: expected === "absent" ? 0 : expected } }),
|
|
6623
|
+
});
|
|
6624
|
+
return { kind: "written", revision: ack.seq };
|
|
6625
|
+
}
|
|
6626
|
+
catch (e) {
|
|
6627
|
+
if (e instanceof JetStreamApiError && e.code === JetStreamApiCodes.StreamWrongLastSequence)
|
|
6628
|
+
return { kind: "conflict" };
|
|
6629
|
+
if (this.isNoResponders(e) || isPermissionDenied(e) || e instanceof JetStreamApiError)
|
|
6630
|
+
return { kind: "refused", reason: e.message };
|
|
6631
|
+
return { kind: "unavailable" };
|
|
6632
|
+
}
|
|
6633
|
+
}
|
|
6634
|
+
/**
|
|
6635
|
+
* Privileged: open one interactive lifecycle's permission reader (SPEC §8.2). Delete the consumer
|
|
6636
|
+
* that holds its name, treating not-found as absent, then create {@link permissionReaderConfig}.
|
|
6637
|
+
* The delete is the point: it is the only thing that ends a pull left parked on the old reader, and
|
|
6638
|
+
* a fresh reader's first pass is the bucket's current state. The caller must be the provisioner.
|
|
6639
|
+
*/
|
|
6640
|
+
async openPermissionReader(reader) {
|
|
6641
|
+
const jsm = await this.manager();
|
|
6642
|
+
const stream = `KV_${permissionBucket(this.space)}`;
|
|
6643
|
+
const config = permissionReaderConfig(this.space, reader);
|
|
6644
|
+
try {
|
|
6645
|
+
await jsm.consumers.delete(stream, config.durable_name);
|
|
6646
|
+
}
|
|
6647
|
+
catch (e) {
|
|
6648
|
+
if (!isJetStreamMissing(e, JetStreamApiCodes.ConsumerNotFound))
|
|
6649
|
+
throw e;
|
|
6650
|
+
}
|
|
6651
|
+
await jsm.consumers.add(stream, config);
|
|
6652
|
+
}
|
|
6653
|
+
/**
|
|
6654
|
+
* Watch every permission record of this principal's owner (SPEC §8.2) through this lifecycle's
|
|
6655
|
+
* reader, which `open` creates on the trusted side and this endpoint only binds. The watch calls
|
|
6656
|
+
* `open` before its first bind, after a reconnect, after a lost delivery, and when the reader is
|
|
6657
|
+
* missing or busy. A value that is not a record of its key is dropped and reported on `warning`.
|
|
6658
|
+
* `onChange` fires on every change after the first pass and must not throw.
|
|
6659
|
+
*
|
|
6660
|
+
* Refused on an open mesh, without a lifecycle UID, and while this endpoint already runs a watch.
|
|
6661
|
+
* A pull is never abandoned before it ends: an abandoned pull stays parked on the broker and holds
|
|
6662
|
+
* the reader's one waiting slot.
|
|
6663
|
+
*/
|
|
6664
|
+
async watchPermissions(open, onChange) {
|
|
6665
|
+
if (!this.authed)
|
|
6666
|
+
throw new Error("permission records are read only on an authenticated mesh");
|
|
6667
|
+
const reader = { owner: this.owner, actor: this.actor, lifecycleUid: this.requireLifecycleUid("watchPermissions") };
|
|
6668
|
+
if (this.permissionWatch)
|
|
6669
|
+
throw new Error("this endpoint already watches its permission records");
|
|
6670
|
+
if (!this.nc)
|
|
6671
|
+
throw new Error(this.notLiveMsg());
|
|
6672
|
+
const bucket = permissionBucket(this.space);
|
|
6673
|
+
const stream = `KV_${bucket}`, name = permissionReaderDurable(reader.owner, reader.actor, reader.lifecycleUid);
|
|
6674
|
+
let markReady;
|
|
6675
|
+
const ready = new Promise((resolve) => (markReady = resolve));
|
|
6676
|
+
let markFailed;
|
|
6677
|
+
const failed = new Promise((resolve) => (markFailed = resolve));
|
|
6678
|
+
let isReady = false;
|
|
6679
|
+
let fetching;
|
|
6680
|
+
let state;
|
|
6681
|
+
const live = (gen) => state.kind !== "failed" && state.gen === gen;
|
|
6682
|
+
const run = (next) => {
|
|
6683
|
+
state = next.state;
|
|
6684
|
+
for (const effect of next.effects) {
|
|
6685
|
+
if (effect.kind === "open")
|
|
6686
|
+
void openAndFetch(effect.gen);
|
|
6687
|
+
else if (effect.kind === "changed") {
|
|
6688
|
+
if (isReady)
|
|
6689
|
+
onChange?.();
|
|
6690
|
+
}
|
|
6691
|
+
else if (effect.kind === "ready") {
|
|
6692
|
+
isReady = true;
|
|
6693
|
+
markReady();
|
|
6694
|
+
}
|
|
6695
|
+
else {
|
|
6696
|
+
if (this.permissionWatch === intent)
|
|
6697
|
+
this.permissionWatch = undefined;
|
|
6698
|
+
fetching?.stop();
|
|
6699
|
+
markFailed(effect.failure);
|
|
6700
|
+
}
|
|
6701
|
+
}
|
|
6702
|
+
};
|
|
6703
|
+
const step = (event) => run(stepPermissionView(state, event));
|
|
6704
|
+
/** A failure of `nc`: the reader refused, the reader not ours, or a replaced connection, which the
|
|
6705
|
+
* re-arm reports as `reconnected` once the new one is bound. */
|
|
6706
|
+
const failure = (gen, nc, e) => {
|
|
6707
|
+
if (isPermissionDenied(e))
|
|
6708
|
+
step({ kind: "refused", reason: e.message });
|
|
6709
|
+
else if (!nc.isClosed() && this.nc === nc)
|
|
6710
|
+
step({ kind: "fetch-failed", gen });
|
|
6711
|
+
};
|
|
6712
|
+
const openAndFetch = async (gen) => {
|
|
6713
|
+
try {
|
|
6714
|
+
await open(reader);
|
|
6715
|
+
}
|
|
6716
|
+
catch (e) {
|
|
6717
|
+
step({ kind: "open-failed", gen, reason: e.message });
|
|
6718
|
+
return;
|
|
6719
|
+
}
|
|
6720
|
+
const nc = this.nc;
|
|
6721
|
+
if (!live(gen) || !nc || nc.isClosed())
|
|
6722
|
+
return;
|
|
6723
|
+
let consumer;
|
|
6724
|
+
let pending;
|
|
6725
|
+
try {
|
|
6726
|
+
consumer = await jetstream(nc).consumers.get(stream, name);
|
|
6727
|
+
pending = (await consumer.info(true)).num_pending;
|
|
6728
|
+
}
|
|
6729
|
+
catch (e) {
|
|
6730
|
+
failure(gen, nc, e);
|
|
6731
|
+
return;
|
|
6732
|
+
}
|
|
6733
|
+
step({ kind: "opened", gen, pending });
|
|
6734
|
+
while (live(gen)) {
|
|
6735
|
+
try {
|
|
6736
|
+
const batch = await consumer.fetch({ max_messages: PERMISSION_READER_BATCH, expires: PERMISSION_READER_EXPIRES_MS });
|
|
6737
|
+
fetching = batch;
|
|
6738
|
+
for await (const m of batch) {
|
|
6739
|
+
const key = m.subject.slice(`$KV.${bucket}.`.length);
|
|
6740
|
+
const op = m.headers?.get("KV-Operation");
|
|
6741
|
+
let change;
|
|
6742
|
+
if (op === "DEL" || op === "PURGE")
|
|
6743
|
+
change = { kind: "removed" };
|
|
6744
|
+
else {
|
|
6745
|
+
let value;
|
|
6746
|
+
try {
|
|
6747
|
+
value = m.json();
|
|
6748
|
+
}
|
|
6749
|
+
catch {
|
|
6750
|
+
value = undefined;
|
|
6751
|
+
}
|
|
6752
|
+
const record = parsePermissionRecord(value, key);
|
|
6753
|
+
if (record)
|
|
6754
|
+
change = { kind: "put", record };
|
|
6755
|
+
else {
|
|
6756
|
+
change = { kind: "dropped" };
|
|
6757
|
+
this.emitRecoverable(new Error(`dropped the value under permission key ${key}: it is not a record of that key`));
|
|
6758
|
+
}
|
|
6759
|
+
}
|
|
6760
|
+
step({ kind: "delivered", gen, dseq: m.info.deliverySequence, pending: m.info.pending, key, change });
|
|
6761
|
+
}
|
|
6762
|
+
}
|
|
6763
|
+
catch (e) {
|
|
6764
|
+
failure(gen, nc, e);
|
|
6765
|
+
return;
|
|
6766
|
+
}
|
|
6767
|
+
}
|
|
6768
|
+
};
|
|
6769
|
+
const intent = { reconnected: () => step({ kind: "reconnected" }), stopped: () => step({ kind: "stop" }) };
|
|
6770
|
+
this.permissionWatch = intent;
|
|
6771
|
+
run(startPermissionView());
|
|
6772
|
+
return {
|
|
6773
|
+
ready,
|
|
6774
|
+
failed,
|
|
6775
|
+
records: () => [...state.view.values()].sort((a, b) => a.askedAt - b.askedAt),
|
|
6776
|
+
stop: async () => { step({ kind: "stop" }); },
|
|
6777
|
+
};
|
|
6778
|
+
}
|
|
6779
|
+
/**
|
|
6780
|
+
* Answer one of an owner's agents' permission prompts as this principal (SPEC §8.2). The request
|
|
6781
|
+
* goes to the process the record names as holder, with its reply beneath the request's own
|
|
6782
|
+
* `.reply.` leaf and no muxed inbox, so a prompt no live process holds reads as the broker's
|
|
6783
|
+
* no-responders status: `gone`. The default wait outlasts the holder's handoff bound, so an
|
|
6784
|
+
* undelivered verdict reads `answered`. Throws for a shorter wait and for an answer the rail cannot
|
|
6785
|
+
* carry.
|
|
6786
|
+
*/
|
|
6787
|
+
async answerPermission(target, answer, timeoutMs = PERMISSION_ANSWER_TIMEOUT_MS) {
|
|
6788
|
+
if (!(timeoutMs >= PERMISSION_ANSWER_TIMEOUT_MS))
|
|
6789
|
+
throw new RangeError(`permission answer: a ${timeoutMs} ms wait is shorter than ${PERMISSION_ANSWER_TIMEOUT_MS} ms, the holder's ${PERMISSION_HANDOFF_BOUND_MS} ms handoff bound plus a write and the round trip, so an undelivered verdict could read as a timeout`);
|
|
6790
|
+
const agent = parsePrincipalKey(target.agent);
|
|
6791
|
+
const note = answer.decision === "deny" && answer.note !== undefined ? { note: answer.note } : {};
|
|
6792
|
+
const body = { v: 1, id: target.id, decision: answer.decision, ...note };
|
|
6793
|
+
let subject;
|
|
6794
|
+
try {
|
|
6795
|
+
if (!agent || !parsePermissionAnswerBody(body))
|
|
6796
|
+
throw new Error("not an agent, prompt id and answer");
|
|
6797
|
+
subject = permissionAnswerSubject(this.space, agent.owner, agent.actor, target.holder.runtimeId, this.owner, this.actor);
|
|
6798
|
+
}
|
|
6799
|
+
catch {
|
|
6800
|
+
throw new TypeError("permission answer: not an agent, holder, prompt id and answer the rail carries");
|
|
6801
|
+
}
|
|
6802
|
+
if (!this.nc)
|
|
6803
|
+
return { kind: "unknown", reason: "transport" };
|
|
6804
|
+
try {
|
|
6805
|
+
const m = await this.requestBoundReply(this.nc, subject, JSON.stringify(body), `${subject}.reply.${randomUUID()}`, timeoutMs);
|
|
6806
|
+
let raw;
|
|
6807
|
+
try {
|
|
6808
|
+
raw = m.json();
|
|
6809
|
+
}
|
|
6810
|
+
catch {
|
|
6811
|
+
raw = undefined;
|
|
6812
|
+
}
|
|
6813
|
+
const reply = parsePermissionAnswerReply(raw);
|
|
6814
|
+
return reply ? permissionAnswerOutcome(reply) : { kind: "unknown", reason: "malformed" };
|
|
6815
|
+
}
|
|
6816
|
+
catch (e) {
|
|
6817
|
+
if (this.isNoResponders(e))
|
|
6818
|
+
return { kind: "gone" };
|
|
6819
|
+
if (e instanceof AuthorizationError || isPermissionDenied(e))
|
|
6820
|
+
return { kind: "refused", reason: "not-permitted" };
|
|
6821
|
+
return { kind: "unknown", reason: e instanceof TimeoutError ? "timeout" : "transport" };
|
|
6822
|
+
}
|
|
6823
|
+
}
|
|
6484
6824
|
/** Serve one PRIVILEGED delivery-admin request (the D5 rail-split). The cred layer is the caller
|
|
6485
6825
|
* boundary — only the supervisor profile can publish here — and `serveControl`'s sender check +
|
|
6486
6826
|
* bounded reply still apply on top. `reloadCreds` is the class-2 renewal ADOPTION step: re-read
|
|
@@ -6722,7 +7062,9 @@ export class CotalEndpoint extends EventEmitter {
|
|
|
6722
7062
|
}
|
|
6723
7063
|
/** Route ONE chat message to eligible owners' mixed inboxes. `durable` channel → its `durable-active`
|
|
6724
7064
|
* members within interval; `live` channel → `@mention` targets authorized to read it (ACL only).
|
|
6725
|
-
*
|
|
7065
|
+
* On either class, a mention of an agent whose read ACL excludes the channel is reported to the
|
|
7066
|
+
* sender with a mention notice. Members KV is scanned FRESH per message (no cache — red-team
|
|
7067
|
+
* BLOCKER-1 catch-up correctness). */
|
|
6726
7068
|
async fanOutMessage(m) {
|
|
6727
7069
|
// FENCE, and NOT followed by an ack: this unit was dispatched before the quiesce and is resuming
|
|
6728
7070
|
// after it, so writing the fan-out now would put entries in member inboxes on behalf of a shard
|
|
@@ -6757,7 +7099,30 @@ export class CotalEndpoint extends EventEmitter {
|
|
|
6757
7099
|
// and again return without acking so the entry redelivers rather than being consumed here.
|
|
6758
7100
|
if (!this.plane3MayAct())
|
|
6759
7101
|
return;
|
|
6760
|
-
|
|
7102
|
+
const durable = (await this.deliveryClassFresh(channel)) === "durable";
|
|
7103
|
+
// Each mention is resolved once. A live channel delivers to the agents among them that may read
|
|
7104
|
+
// it, and on either class a mention of an agent that may not read the channel is reported to the
|
|
7105
|
+
// sender below, so a post never claims a reader it cannot have.
|
|
7106
|
+
const mentioned = [];
|
|
7107
|
+
for (const name of msg.mentions ?? []) {
|
|
7108
|
+
const owner = this.resolveOwnerByName(name);
|
|
7109
|
+
if (!owner || owner === msg.from.id)
|
|
7110
|
+
continue;
|
|
7111
|
+
// A mention arrives as an ALIAS (the roster names no lifecycle): resolve its single live ACL
|
|
7112
|
+
// row for BOTH the read-authorization and the lifecycle to address. Ambiguity (two live rows)
|
|
7113
|
+
// refuses THIS copy loudly rather than guessing a lifecycle.
|
|
7114
|
+
let row;
|
|
7115
|
+
try {
|
|
7116
|
+
row = await this.aclForAlias(owner);
|
|
7117
|
+
}
|
|
7118
|
+
catch (e) {
|
|
7119
|
+
this.emit("error", e);
|
|
7120
|
+
continue;
|
|
7121
|
+
}
|
|
7122
|
+
if (row)
|
|
7123
|
+
mentioned.push({ name, owner, row });
|
|
7124
|
+
}
|
|
7125
|
+
if (durable) {
|
|
6761
7126
|
// The channel's own rows and every family row above it (`review.>`). A lifecycle holding two of
|
|
6762
7127
|
// them gets two publishes and keeps one copy: the dedupe id is per message and lifecycle (#5404).
|
|
6763
7128
|
for (const rec of await listMembers(await this.membersRegistry(), { covering: channel })) {
|
|
@@ -6782,28 +7147,20 @@ export class CotalEndpoint extends EventEmitter {
|
|
|
6782
7147
|
}
|
|
6783
7148
|
}
|
|
6784
7149
|
else {
|
|
6785
|
-
for (const
|
|
6786
|
-
|
|
6787
|
-
if (!owner || owner === msg.from.id)
|
|
6788
|
-
continue;
|
|
6789
|
-
// A live-mention target arrives as an ALIAS (the roster names no lifecycle): resolve its single
|
|
6790
|
-
// live ACL row for BOTH the read-authorization and the lifecycle to address. Ambiguity (two
|
|
6791
|
-
// live rows) refuses THIS copy loudly rather than guessing a lifecycle.
|
|
6792
|
-
let row;
|
|
6793
|
-
try {
|
|
6794
|
-
row = await this.aclForAlias(owner);
|
|
6795
|
-
}
|
|
6796
|
-
catch (e) {
|
|
6797
|
-
this.emit("error", e);
|
|
6798
|
-
continue;
|
|
6799
|
-
}
|
|
6800
|
-
if (!row || !channelInAllow(row.allowSubscribe, channel))
|
|
7150
|
+
for (const { owner, row } of mentioned) {
|
|
7151
|
+
if (!channelInAllow(row.allowSubscribe, channel))
|
|
6801
7152
|
continue; // @mention can't bypass the read ACL
|
|
6802
7153
|
if (!this.plane3MayAct())
|
|
6803
7154
|
return; // same rule on the live-mention path
|
|
6804
7155
|
await this.publishDinbox(owner, row.lifecycleUid, { msg: normalizedMsg, channel, seq, reason: "live-mention", generation: 0 });
|
|
6805
7156
|
}
|
|
6806
7157
|
}
|
|
7158
|
+
const unreadable = mentioned.filter(({ row }) => !channelInAllow(row.allowSubscribe, channel)).map(({ name }) => name);
|
|
7159
|
+
if (unreadable.length) {
|
|
7160
|
+
if (!this.plane3MayAct())
|
|
7161
|
+
return;
|
|
7162
|
+
await this.sendMentionNotice(msg, channel, seq, unreadable);
|
|
7163
|
+
}
|
|
6807
7164
|
// FINAL FENCE, BEFORE THE ACK ITSELF, which is the real commit: acking tells the stream this
|
|
6808
7165
|
// shard's work is done. A daemon that stopped serving mid-fan-out must not make that claim, or
|
|
6809
7166
|
// the successor never sees the entry and the message is lost outright rather than duplicated.
|
|
@@ -7390,7 +7747,17 @@ export class CotalEndpoint extends EventEmitter {
|
|
|
7390
7747
|
inactiveThresholdMs: this.inactiveThresholdMs,
|
|
7391
7748
|
});
|
|
7392
7749
|
}
|
|
7393
|
-
|
|
7750
|
+
const dm = dmDurable(this.owner, this.actor, ownUid);
|
|
7751
|
+
try {
|
|
7752
|
+
await this.pump(dmStream(this.space), dm, { inbox: true });
|
|
7753
|
+
}
|
|
7754
|
+
catch (e) {
|
|
7755
|
+
// Auth mode cannot create the durable, so every rebind fails the same way until the session is
|
|
7756
|
+
// replaced. The typed error lets a caller name that route instead of a bare "consumer not found".
|
|
7757
|
+
if (this.authed && isConsumerNotFound(e))
|
|
7758
|
+
throw new DmDurableMissingError(dmStream(this.space), dm);
|
|
7759
|
+
throw e;
|
|
7760
|
+
}
|
|
7394
7761
|
// Plane-3 (SPEC §8): bind + pump our per-member DELIVER durable (`dlv_<id>`) — the re-authorized
|
|
7395
7762
|
// durable-backstop channel copies the trusted reader transfers to us. No-op when it isn't present
|
|
7396
7763
|
// (open mode / un-provisioned). Auth-only feature; the pump self-guards on the durable's existence.
|