@commonlyai/cli 0.1.406 → 0.1.407

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.406",
3
+ "version": "0.1.407",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -115,6 +115,19 @@ import {
115
115
  readPodFocus,
116
116
  } from '../lib/pod-focus.js';
117
117
  import { formatPodConventionsFrame } from '../lib/pod-conventions.js';
118
+ import {
119
+ ACCOUNT_BOUND_ADAPTERS,
120
+ accountToolName,
121
+ accountUseNeedsFacts,
122
+ accountUseNoticeText,
123
+ accountUseVerdict,
124
+ factsFromFallback,
125
+ factsFromStamp,
126
+ otherRequesterOf,
127
+ podOpenToStrangers,
128
+ requesterMayBeAgent,
129
+ setupLine as accountUseSetupLine,
130
+ } from '../lib/account-use-guard.js';
118
131
  import { claimReleaseFor, ackResultFor, EMPTY_OUTPUT } from '../lib/claim-outcome.js';
119
132
  import { createClaimedWorkGate } from '../lib/claimed-work-gate.js';
120
133
  import {
@@ -1712,6 +1725,19 @@ export const performAttach = async ({
1712
1725
  client, podId, environment, adapterName, log,
1713
1726
  });
1714
1727
 
1728
+ // F662: a wrapped Claude Code or Codex agent runs on its owner's own login or
1729
+ // key, so say whose account answers here before it connects. Never a refusal:
1730
+ // the run loop refuses per turn. A pod that can't be read gets the team line.
1731
+ if (ACCOUNT_BOUND_ADAPTERS.has(adapterName) && podId) {
1732
+ let pod = null;
1733
+ try {
1734
+ pod = await client.get(`/api/pods/${podId}`);
1735
+ } catch {
1736
+ pod = null;
1737
+ }
1738
+ log(accountUseSetupLine({ tool: accountToolName(adapterName), open: podOpenToStrangers(pod) }));
1739
+ }
1740
+
1715
1741
  // Identity-bearing runtime tag from the adapter (e.g. 'codex', 'claude-
1716
1742
  // code'). Falls back to adapter.name for adapters that haven't been
1717
1743
  // updated to the two-field scheme. Paired with `host: 'byo'` below so a
@@ -2623,11 +2649,17 @@ export const performRun = ({
2623
2649
  const identity = await client.get('/api/agents/runtime/installations', {}, {
2624
2650
  signal: AbortSignal.timeout(5000),
2625
2651
  });
2626
- return { installations: Array.isArray(identity?.installations) ? identity.installations : [], readError: null };
2652
+ return {
2653
+ installations: Array.isArray(identity?.installations) ? identity.installations : [],
2654
+ ownerUserId: identity?.ownerUserId ? String(identity.ownerUserId) : null,
2655
+ readError: null,
2656
+ };
2627
2657
  } catch (err) {
2628
- return { installations: null, readError: err };
2658
+ return { installations: null, ownerUserId: null, readError: err };
2629
2659
  }
2630
2660
  };
2661
+ // Said once per process: the guard can't tell the owner from anyone else.
2662
+ let ownerMissingLogged = false;
2631
2663
  const placeTurn = async () => {
2632
2664
  await refreshSeatEnvironment();
2633
2665
  if (seatEnvironment?.sandbox?.trust !== 'workspace' && !codexUnconfined) {
@@ -2690,6 +2722,28 @@ export const performRun = ({
2690
2722
  return { outcome: 'no_action', reason: 'no-prompt' };
2691
2723
  }
2692
2724
 
2725
+ // F662, as in the batch path. An ask has nobody else to answer it, so a
2726
+ // refused one is answered with the refusal instead of waiting out its expiry.
2727
+ const [{ verdict: accountVerdict, facts: accountFacts }] = await judgeAccountUse([event], eventPodId);
2728
+ if (accountVerdict === 'refuse') {
2729
+ if (event.type === 'agent.ask' && event.payload?.requestId) {
2730
+ log(`[${event.type}] event ${event._id} was started by someone other than this agent's owner `
2731
+ + 'in a pod where it answers only its owner — acked as refused, not run');
2732
+ try {
2733
+ await client.post(
2734
+ `/api/agents/runtime/asks/${encodeURIComponent(event.payload.requestId)}/respond`,
2735
+ { content: accountUseNoticeText({ verdict: 'refuse', adapterName: adapter.name, facts: accountFacts }) },
2736
+ );
2737
+ } catch (err) {
2738
+ if (err?.status !== 409 || err?.body?.code !== 'already_responded') throw err;
2739
+ }
2740
+ } else {
2741
+ await noticeAccountUseRefused(event, accountFacts, eventPodId);
2742
+ }
2743
+ return accountUseRefusedResult();
2744
+ }
2745
+ if (accountVerdict === 'warn') await noticeAccountUseWarn(accountFacts, eventPodId);
2746
+
2693
2747
  // Snapshot the pod's recent messages so that, after the spawn, we can
2694
2748
  // tell whether the agent posted itself via commonly_post_message. If it
2695
2749
  // did, its final CLI text is a narration/log — echoing it would duplicate
@@ -3820,7 +3874,11 @@ export const performRun = ({
3820
3874
  // pull, rather than being silently consumed here.
3821
3875
  // `unreadBodiesPodId` is set only for a turn a person's mention woke (ADR-018
3822
3876
  // D9.2): the unread messages this page carried go in as marked data.
3823
- const buildInboxPrompt = (entries, inboxCount = entries.length, { pod = null, unreadBodiesPodId = null } = {}) => {
3877
+ const buildInboxPrompt = (allEntries, offeredCount = allEntries.length, { pod = null, unreadBodiesPodId = null } = {}) => {
3878
+ // F662: an item refused because it isn't the owner's never reaches the
3879
+ // model, not even as context, or the owner's account would act on it.
3880
+ const entries = allEntries.filter((entry) => !entry.accountRefused);
3881
+ const inboxCount = Math.max(entries.length, offeredCount - (allEntries.length - entries.length));
3824
3882
  const BODY_LIMIT = batchLimit;
3825
3883
  const wakeEntries = entries.filter((entry) => entry.event.deliveryMode !== 'digest' && !entry.pastCap);
3826
3884
  const digestEntries = entries.filter((entry) => entry.event.deliveryMode === 'digest' && !entry.pastCap);
@@ -3975,6 +4033,103 @@ export const performRun = ({
3975
4033
  }
3976
4034
  };
3977
4035
 
4036
+ // F662: a claude or codex seat runs every turn on its owner's own login or
4037
+ // key (lib/account-use-guard.js). Judges each event before anything spawns:
4038
+ // 'run', 'refuse', 'warn' or 'defer'. Facts come from the server's stamp; an
4039
+ // event without one costs at most one /installations read per call, made
4040
+ // only when an event needs it. A failed read defers by throwing, as the
4041
+ // placement read does, so the event stays unacked and comes back through the
4042
+ // spawn-retry backoff. Every other adapter returns 'run' with no read.
4043
+ // The guard's read is its own: placement reads the pods fresh before the
4044
+ // spawn, since the batch awaits other work in between and a pod can turn
4045
+ // public meanwhile.
4046
+ // `settled` holds events already handled here (a redelivery), which only
4047
+ // ride along as context: one that can't be judged is kept out, not deferred.
4048
+ const judgeAccountUse = async (events, eventPodId, { settled = new Set() } = {}) => {
4049
+ if (!ACCOUNT_BOUND_ADAPTERS.has(adapter.name)) return events.map(() => ({ verdict: 'run', facts: null }));
4050
+ let fallback = null;
4051
+ const judged = [];
4052
+ for (const event of events) {
4053
+ let facts = factsFromStamp(event);
4054
+ if (!facts && accountUseNeedsFacts({ event, adapterName: adapter.name })) {
4055
+ // eslint-disable-next-line no-await-in-loop
4056
+ if (!fallback) fallback = await readSeatPods();
4057
+ const podOf = event.podId || eventPodId;
4058
+ const installation = fallback.installations
4059
+ ? fallback.installations.find((row) => String(row?.podId) === String(podOf)) || null
4060
+ : null;
4061
+ facts = factsFromFallback({ event, installation, ownerUserId: fallback.ownerUserId });
4062
+ }
4063
+ if (facts && !facts.ownerUserId && facts.requesterKind !== 'kernel' && !ownerMissingLogged) {
4064
+ ownerMissingLogged = true;
4065
+ log('No owner is on record for this agent, so it treats every message as someone else\'s. '
4066
+ + `Run \`${CLI} agent attach\` again to fix it.`);
4067
+ }
4068
+ let verdict = accountUseVerdict({ event, adapterName: adapter.name, facts });
4069
+ if (verdict === 'defer' && settled.has(event)) verdict = 'refuse';
4070
+ if (verdict === 'defer') {
4071
+ const cause = fallback?.readError;
4072
+ throw Object.assign(
4073
+ new Error(`turn deferred, because whether this agent may answer here could not be read${cause ? `: ${cause.message}` : ''}`,
4074
+ cause ? { cause } : undefined),
4075
+ { status: cause?.status },
4076
+ );
4077
+ }
4078
+ judged.push({ verdict, facts });
4079
+ }
4080
+ return judged;
4081
+ };
4082
+ const accountUseRefusedResult = () => ({
4083
+ outcome: 'no_action',
4084
+ refused: { reason: 'delivery-refused' },
4085
+ reason: 'account-not-owner',
4086
+ });
4087
+ // A refused turn tells the person only when someone is waiting, once per pod
4088
+ // and requester per hour, so an ambient stranger in a public pod costs no post.
4089
+ const noticeAccountUseRefused = async (event, facts, eventPodId) => {
4090
+ log(`[${event.type}] event ${event._id} was started by someone other than this agent's owner `
4091
+ + `in a pod where it answers only its owner — acked as refused, not run`);
4092
+ // An agent told would answer, a paid turn on its own owner's account.
4093
+ if (!someoneIsWaiting(event) || requesterMayBeAgent(event, facts)) return;
4094
+ const key = `account-use-refused:${eventPodId}:${otherRequesterOf(facts)}`;
4095
+ try {
4096
+ if (!noticeDue(stateKey, key, CANT_ANSWER_NOTICE_WINDOW_MS)) return;
4097
+ const delivery = await deliverTurnNotice({
4098
+ client,
4099
+ podId: eventPodId,
4100
+ text: accountUseNoticeText({ verdict: 'refuse', adapterName: adapter.name, facts }),
4101
+ limit: chatCharLimit,
4102
+ maxChunks: maxChatChunks,
4103
+ log: (line) => log(`[${event.type}] ${line}`),
4104
+ });
4105
+ if (!delivery.skipped && !delivery.refused) recordNotice(stateKey, key);
4106
+ } catch (err) {
4107
+ log(`[${event.type}] account notice failed: ${err.message}`);
4108
+ }
4109
+ };
4110
+ // Once per pod, ever (a session reset forgets it): whose account runs here.
4111
+ // True when the line was posted this time.
4112
+ const noticeAccountUseWarn = async (facts, eventPodId) => {
4113
+ const key = `account-use-warned:${eventPodId}`;
4114
+ try {
4115
+ if (!noticeDue(stateKey, key, Infinity)) return false;
4116
+ const delivery = await deliverTurnNotice({
4117
+ client,
4118
+ podId: eventPodId,
4119
+ text: accountUseNoticeText({ verdict: 'warn', adapterName: adapter.name, facts }),
4120
+ limit: chatCharLimit,
4121
+ maxChunks: maxChatChunks,
4122
+ log: (line) => log(`[inbox.batch] ${line}`),
4123
+ });
4124
+ if (delivery.skipped || delivery.refused) return false;
4125
+ recordNotice(stateKey, key);
4126
+ return true;
4127
+ } catch (err) {
4128
+ log(`[inbox.batch] account notice failed: ${err.message}`);
4129
+ return false;
4130
+ }
4131
+ };
4132
+
3978
4133
  // The greeting is CLAIMED the moment a poll returns it: claimPage reads
3979
4134
  // `status: 'pending'` and marks each returned row `delivered`, and later
3980
4135
  // polls read only pending. Leaving it unacked therefore does NOT bring it
@@ -4351,6 +4506,32 @@ export const performRun = ({
4351
4506
  }
4352
4507
  }
4353
4508
 
4509
+ // F662: before anything spawns or claims. A refused item is acked and never
4510
+ // retried; a warned one runs after the pod hears whose account it is. A
4511
+ // redelivered item is judged too: one refused before, whose ack was lost,
4512
+ // must stay out of this turn's prompt, ids and flags as well.
4513
+ const isRedelivery = (entry) => entry.result?.reason === 'duplicate-delivery';
4514
+ const unjudged = entries.filter((entry) => !entry.result || isRedelivery(entry));
4515
+ const accountUse = await judgeAccountUse(unjudged.map((entry) => entry.event), eventPodId, {
4516
+ settled: new Set(unjudged.filter(isRedelivery).map((entry) => entry.event)),
4517
+ });
4518
+ for (const [index, entry] of unjudged.entries()) {
4519
+ const { verdict, facts } = accountUse[index];
4520
+ if (isRedelivery(entry)) {
4521
+ // Already acked or noticed once; only kept out of the turn.
4522
+ if (verdict === 'refuse') entry.accountRefused = true;
4523
+ } else if (verdict === 'refuse') {
4524
+ entry.result = accountUseRefusedResult();
4525
+ entry.accountRefused = true;
4526
+ // eslint-disable-next-line no-await-in-loop
4527
+ await noticeAccountUseRefused(entry.event, facts, eventPodId);
4528
+ } else if (verdict === 'warn') {
4529
+ // Posted once the item is sure to run (below), so a lost claim or the
4530
+ // cascade cap doesn't spend the once-per-pod line.
4531
+ entry.accountWarn = facts;
4532
+ }
4533
+ }
4534
+
4354
4535
  // Null until the server says: a failed read or an older server is unknown,
4355
4536
  // not "alone" and not "with peers".
4356
4537
  let podAttendance = null;
@@ -4367,7 +4548,9 @@ export const performRun = ({
4367
4548
  }
4368
4549
  };
4369
4550
  const preSpawn = await snapshotMessages();
4370
- const preSpawnIds = preSpawn
4551
+ // The reply-detection baseline. Retaken below if the account warning posts,
4552
+ // or the warning would read as this turn's own post and drop its answer.
4553
+ let preSpawnIds = preSpawn
4371
4554
  ? new Set(preSpawn.map((message) => String(message._id || message.id)))
4372
4555
  : null;
4373
4556
  const activeEntries = entries.filter((entry) => !entry.result);
@@ -4497,6 +4680,11 @@ export const performRun = ({
4497
4680
 
4498
4681
  const actionEntries = wakingEntries.filter((entry) => !entry.result && !entry.pastCap);
4499
4682
  if (actionEntries.length === 0) return { entries };
4683
+ const accountWarnFacts = actionEntries.find((entry) => entry.accountWarn)?.accountWarn;
4684
+ if (accountWarnFacts && await noticeAccountUseWarn(accountWarnFacts, eventPodId)) {
4685
+ const afterWarn = await snapshotMessages();
4686
+ preSpawnIds = afterWarn ? new Set(afterWarn.map((message) => String(message._id || message.id))) : null;
4687
+ }
4500
4688
  const personMentioned = actionEntries.some((entry) => isPersonMention(entry.event, entry.trigger));
4501
4689
 
4502
4690
  const claimKeepers = actionEntries
@@ -4506,6 +4694,9 @@ export const performRun = ({
4506
4694
  isLost: () => claimKeepers.some((keeper) => keeper.isLost()),
4507
4695
  getHolder: () => claimKeepers.find((keeper) => keeper.isLost())?.getHolder(),
4508
4696
  } : null;
4697
+ // What this turn carries: not past the cap, and not refused as someone
4698
+ // else's on the owner's account (F662), which the model never sees.
4699
+ const inThisTurn = (entry) => !entry.pastCap && !entry.accountRefused;
4509
4700
  const batchEvent = {
4510
4701
  ...actionEntries[0].event,
4511
4702
  _id: `batch-${actionEntries[0].event._id}`,
@@ -4513,11 +4704,11 @@ export const performRun = ({
4513
4704
  commentTarget: commentTargetOf(actionEntries[0].event),
4514
4705
  payload: {
4515
4706
  ...actionEntries[0].event.payload,
4516
- batchEventIds: entries.filter((entry) => !entry.pastCap).map((entry) => String(entry.event._id)),
4517
- hasHeartbeat: entries.some((entry) => !entry.pastCap && entry.event.type === 'heartbeat'),
4518
- onlyHeartbeat: entries.filter((entry) => !entry.pastCap)
4707
+ batchEventIds: entries.filter(inThisTurn).map((entry) => String(entry.event._id)),
4708
+ hasHeartbeat: entries.some((entry) => inThisTurn(entry) && entry.event.type === 'heartbeat'),
4709
+ onlyHeartbeat: entries.filter(inThisTurn)
4519
4710
  .every((entry) => entry.event.type === 'heartbeat'),
4520
- someoneWaiting: entries.some((entry) => !entry.pastCap && someoneIsWaiting(entry.event)),
4711
+ someoneWaiting: entries.some((entry) => inThisTurn(entry) && someoneIsWaiting(entry.event)),
4521
4712
  },
4522
4713
  };
4523
4714
  // One item, run as its own turn. Used only after the provider refused a
@@ -6386,6 +6577,10 @@ Docs:
6386
6577
  });
6387
6578
  // F262: a harness the seat's turns would refuse is named now, not on the
6388
6579
  // first mention. Fired, not awaited, like the update notice above.
6580
+ // F662: once at boot, whose account this agent's turns run on.
6581
+ if (ACCOUNT_BOUND_ADAPTERS.has(adapter.name)) {
6582
+ console.log(`${stamp()} [${name}] ${accountUseSetupLine({ tool: accountToolName(adapter.name), open: false })}`);
6583
+ }
6389
6584
  Promise.resolve(adapter.startNotice?.({ unconfined: hostUnconfined || codexUnconfined }))
6390
6585
  .then((notice) => { if (notice) console.warn(`${stamp()} [${name}] ${notice}`); })
6391
6586
  .catch(() => {});
@@ -0,0 +1,218 @@
1
+ /**
2
+ * F662: whose account a wrapped Claude Code or Codex turn runs on.
3
+ *
4
+ * Vendor terms ask each end user to use their own Claude or ChatGPT account. A
5
+ * wrapped claude or codex agent runs every turn on its owner's own login or
6
+ * key, so a turn someone else starts runs on the owner's account:
7
+ * - in a pod open to strangers (publicly readable or listed) it is refused;
8
+ * - in a direct message (agent-room, agent-dm) it is refused, unless the
9
+ * sender shares a team pod with the agent, which warns instead;
10
+ * - in any other pod it runs, and the pod is told once whose account it is.
11
+ *
12
+ * An agent sender is never the owner, the owner's other agents included, and a
13
+ * board, task or lease wake carries text people wrote, so it isn't a kernel
14
+ * wake. Who asked comes from the server's `payload.accountUse` stamp. An older server
15
+ * sends none, and the run loop reads `/installations` instead (one read per
16
+ * batch). That fallback refuses an unknown requester only where the pod is
17
+ * known open or direct, and defers (leaves the event to retry) when the pod
18
+ * can't be read. Every other adapter is untouched.
19
+ */
20
+
21
+ export const ACCOUNT_BOUND_ADAPTERS = new Set(['claude', 'codex']);
22
+
23
+ const TOOL_NAMES = { claude: 'Claude Code', codex: 'Codex' };
24
+ export const accountToolName = (adapterName) => TOOL_NAMES[adapterName] || null;
25
+
26
+ export const podOpenToStrangers = (pod) => Boolean(pod && (pod.publicRead === true || pod.communityListed === true));
27
+
28
+ export const isDirectPod = (pod) => pod?.type === 'agent-room' || pod?.type === 'agent-dm';
29
+
30
+ // Visibility the server reported, rather than fields left out: a pod that no
31
+ // longer exists comes back from /installations with none of them.
32
+ const podFactsKnown = (pod) => Boolean(pod)
33
+ && (isDirectPod(pod) || (typeof pod.publicRead === 'boolean' && typeof pod.communityListed === 'boolean'));
34
+
35
+ const KERNEL_EVENT_TYPES = new Set(['heartbeat', 'first_contact']);
36
+ // The answer to an ask this agent sent: its owner's own turn asked for it.
37
+ const OWN_ASK_ANSWER_TYPES = new Set(['agent.ask.response']);
38
+
39
+ // A board, task or lease wake carries task text people wrote, strangers
40
+ // included, so it isn't "nobody": it follows the pod's ordinary rule.
41
+ const carriesTaskText = (payload) => Boolean(payload?.assignedTaskWake || payload?.boardWake || payload?.leaseWarningTaskId);
42
+ const nobodyTriggered = (event) => KERNEL_EVENT_TYPES.has(event?.type)
43
+ || ((event?.payload?.triggerAuthor === 'kernel' || event?.triggerAuthor === 'kernel')
44
+ && !carriesTaskText(event?.payload));
45
+
46
+ const idOf = (value) => (value === null || value === undefined || value === '' ? null : String(value));
47
+
48
+ // Events whose person is named in a field of their own, not `payload.userId`.
49
+ // Only a person can make either: the server refuses a bot caller for a ruling
50
+ // (decisionRequestService.chooseDecision) and for an approval
51
+ // (approvalActionService).
52
+ const PERSON_FIELD_BY_TYPE = { 'decision.ruled': 'ruledBy', 'approval.resolved': 'approvedBy' };
53
+ const namedPersonOf = (event) => {
54
+ const field = PERSON_FIELD_BY_TYPE[event?.type];
55
+ return field ? idOf(event?.payload?.[field]?.userId) : null;
56
+ };
57
+ // True when the payload says a person sent the event.
58
+ const personSentFallback = (event) => {
59
+ const payload = event?.payload || {};
60
+ return payload.senderIsHuman === true || payload.dmKind === 'user-agent' || Boolean(namedPersonOf(event));
61
+ };
62
+
63
+ const podFrom = (pod) => (pod && typeof pod === 'object' ? {
64
+ type: pod.type ?? null,
65
+ publicRead: pod.publicRead,
66
+ communityListed: pod.communityListed,
67
+ joinPolicy: pod.joinPolicy ?? null,
68
+ } : null);
69
+
70
+ /** Facts from the server's stamp, or null when the event carries none this CLI reads. */
71
+ export const factsFromStamp = (event) => {
72
+ const stamp = event?.payload?.accountUse;
73
+ if (!stamp || typeof stamp !== 'object' || stamp.v !== 1) return null;
74
+ return {
75
+ source: 'stamp',
76
+ ownerUserId: idOf(stamp.ownerUserId),
77
+ ownerName: typeof stamp.ownerName === 'string' && stamp.ownerName ? stamp.ownerName : null,
78
+ requesterUserIds: Array.isArray(stamp.requesterUserIds) ? stamp.requesterUserIds.map(idOf).filter(Boolean) : [],
79
+ requesterKind: stamp.requesterKind || 'unknown',
80
+ requesterSharesTeamPod: typeof stamp.requesterSharesTeamPod === 'boolean' ? stamp.requesterSharesTeamPod : null,
81
+ pod: podFrom(stamp.pod),
82
+ };
83
+ };
84
+
85
+ /**
86
+ * Facts an older server's payload and this seat's `/installations` row give.
87
+ * `installation` is the row for the event's pod, or null when the read failed
88
+ * or named no such pod; `ownerUserId` is the read's top-level owner.
89
+ */
90
+ export const factsFromFallback = ({ event, installation, ownerUserId = null }) => {
91
+ const payload = event?.payload || {};
92
+ const ids = [];
93
+ let identified = false;
94
+ if (nobodyTriggered(event)) {
95
+ return {
96
+ source: 'fallback', ownerUserId: idOf(ownerUserId), ownerName: null, requesterUserIds: [], requesterKind: 'kernel', requesterSharesTeamPod: null, pod: null,
97
+ };
98
+ }
99
+ // Only a person can be the owner: an agent sender, the owner's other agents
100
+ // included, is someone else.
101
+ const named = namedPersonOf(event);
102
+ if (named) {
103
+ ids.push(named);
104
+ identified = true;
105
+ } else if ((payload.senderIsHuman === true || payload.dmKind === 'user-agent') && idOf(payload.userId)) {
106
+ ids.push(idOf(payload.userId));
107
+ identified = true;
108
+ }
109
+ // A coalesced mention carries other authors' words too. Each counts, and one
110
+ // with no id leaves the row unidentified.
111
+ if (Array.isArray(payload.coalesced)) {
112
+ for (const item of payload.coalesced) {
113
+ const id = idOf(item?.userId);
114
+ if (id) ids.push(id); else identified = false;
115
+ }
116
+ }
117
+ const pod = installation ? podFrom({
118
+ type: installation.podType ?? installation.type ?? null,
119
+ publicRead: installation.publicRead,
120
+ communityListed: installation.communityListed,
121
+ joinPolicy: installation.joinPolicy,
122
+ }) : null;
123
+ return {
124
+ source: 'fallback',
125
+ ownerUserId: idOf(ownerUserId),
126
+ ownerName: null,
127
+ requesterUserIds: [...new Set(ids)],
128
+ requesterKind: identified ? 'human' : 'unknown',
129
+ // Nothing on an older server says this, so a DM fails closed.
130
+ requesterSharesTeamPod: null,
131
+ pod,
132
+ };
133
+ };
134
+
135
+ /** True when the verdict can't be 'run' without facts, so the fallback read is worth making. */
136
+ export const accountUseNeedsFacts = ({ event, adapterName }) => ACCOUNT_BOUND_ADAPTERS.has(adapterName)
137
+ && event?.deliveryMode !== 'digest'
138
+ && !nobodyTriggered(event)
139
+ && !OWN_ASK_ANSWER_TYPES.has(event?.type);
140
+
141
+ /** 'run' | 'refuse' | 'warn' | 'defer'. */
142
+ export const accountUseVerdict = ({ event, adapterName, facts }) => {
143
+ if (!accountUseNeedsFacts({ event, adapterName })) return 'run';
144
+ if (!facts) return 'defer';
145
+ // The server says 'kernel' only for a wake nobody wrote; a board wake it
146
+ // marks 'unknown' even when its row reads triggerAuthor 'kernel'.
147
+ if (facts.requesterKind === 'kernel' && !carriesTaskText(event?.payload)) return 'run';
148
+ const owner = facts.ownerUserId;
149
+ const ids = facts.requesterUserIds || [];
150
+ if (owner && ids.length > 0 && facts.requesterKind !== 'unknown' && ids.every((id) => id === owner)) return 'run';
151
+ const { pod } = facts;
152
+ if (isDirectPod(pod)) return facts.requesterSharesTeamPod === true ? 'warn' : 'refuse';
153
+ if (podOpenToStrangers(pod)) return 'refuse';
154
+ if (!podFactsKnown(pod)) {
155
+ // The stamp sends `pod: null` for a pod it couldn't find. A DM wake still
156
+ // says it's a DM, and a DM fails closed; the stamp's owner is trusted to
157
+ // have run above, so this never refuses the owner.
158
+ const dmWake = event?.type === 'dm.message' || Boolean(event?.payload?.dmKind);
159
+ return facts.source === 'stamp' && dmWake ? 'refuse' : 'defer';
160
+ }
161
+ return 'warn';
162
+ };
163
+
164
+ /** The requester a refusal notice is keyed on: the first who isn't the owner. */
165
+ export const otherRequesterOf = (facts) => (facts?.requesterUserIds || [])
166
+ .find((id) => id !== facts.ownerUserId) || 'unknown';
167
+
168
+ /**
169
+ * True when the requester is, or may be, an agent. A refusal notice to one
170
+ * would wake it into a turn of its own, so it is refused without one.
171
+ */
172
+ export const requesterMayBeAgent = (event, facts) => {
173
+ if (facts?.requesterKind === 'agent') return true;
174
+ if (facts?.source !== 'fallback') return false;
175
+ return !personSentFallback(event);
176
+ };
177
+
178
+ const ownerLabel = (owner) => owner || 'the owner';
179
+
180
+ export const refuseText = ({ tool, owner }) => {
181
+ const who = ownerLabel(owner);
182
+ return `I run on ${who}'s own ${tool} account, and this pod is open to people outside their team, so here I only `
183
+ + `take requests from ${who}. To use ${tool} here, connect your own agent on your own login or API key.`;
184
+ };
185
+
186
+ export const refuseDmText = ({ tool, owner }) => {
187
+ const who = ownerLabel(owner);
188
+ return `I run on ${who}'s own ${tool} account, so in direct messages I only take requests from ${who} and people who `
189
+ + `share a team pod with me. To use ${tool}, connect your own agent on your own login or API key.`;
190
+ };
191
+
192
+ export const warnText = ({ tool, owner }) => {
193
+ const who = ownerLabel(owner);
194
+ return `Heads up: I run on ${who}'s own ${tool} account, so requests from others in this pod use their login. `
195
+ + `For a team, ${who} should switch me to an API key or a team plan.`;
196
+ };
197
+
198
+ export const warnDmText = ({ tool, owner }) => {
199
+ const who = ownerLabel(owner);
200
+ return `Heads up: I run on ${who}'s own ${tool} account, so your requests here use their login. `
201
+ + `For a team, ${who} should switch me to an API key or a team plan.`;
202
+ };
203
+
204
+ export const setupLine = ({ tool, open }) => (open
205
+ ? 'This pod is open to people outside your team, so this agent will answer only you here. '
206
+ + 'Others can bring their own agent on their own login or key.'
207
+ : `${tool} runs on your own login or API key, and anyone in this pod can start a turn on it. `
208
+ + 'For a team, use an API key or a team plan. In public or listed pods it answers only you.');
209
+
210
+ /** The notice for a refused or warned turn, by the pod it ran in. */
211
+ export const accountUseNoticeText = ({ verdict, adapterName, facts }) => {
212
+ const tool = accountToolName(adapterName);
213
+ const owner = facts?.ownerName || null;
214
+ const direct = isDirectPod(facts?.pod);
215
+ if (verdict === 'refuse') return direct ? refuseDmText({ tool, owner }) : refuseText({ tool, owner });
216
+ if (verdict === 'warn') return direct ? warnDmText({ tool, owner }) : warnText({ tool, owner });
217
+ return null;
218
+ };