@commonlyai/cli 0.1.405 → 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.405",
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
@@ -6188,6 +6379,7 @@ Docs:
6188
6379
  adapterName: record.adapter,
6189
6380
  adapter: getAdapter(record.adapter),
6190
6381
  environment: record.environment,
6382
+ agentName: record.agentName,
6191
6383
  checkInstalled: !bootstrapped,
6192
6384
  });
6193
6385
  const harnessOutcome = preflightOutcome(harnessProblems, { firstRun: bootstrapped });
@@ -6385,6 +6577,10 @@ Docs:
6385
6577
  });
6386
6578
  // F262: a harness the seat's turns would refuse is named now, not on the
6387
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
+ }
6388
6584
  Promise.resolve(adapter.startNotice?.({ unconfined: hostUnconfined || codexUnconfined }))
6389
6585
  .then((notice) => { if (notice) console.warn(`${stamp()} [${name}] ${notice}`); })
6390
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
+ };
@@ -1512,6 +1512,41 @@ const resolveClaudeInstall = (env) => {
1512
1512
  }
1513
1513
  };
1514
1514
 
1515
+ /**
1516
+ * F647: how the sign-in probe (`claude auth status`) runs for a seat, so it
1517
+ * reads the login the way the seat's turn does. A seat confined by Seatbelt
1518
+ * (public or workspace trust on macOS) gets its turn's state folder as HOME,
1519
+ * its turn's stripped environment and its turn's Seatbelt profile; a login the
1520
+ * jail can't read then reports signed out at setup, not at the first mention.
1521
+ * null for every other seat, which keeps the plain probe. `_prepareState` is a
1522
+ * test seam for the state folder.
1523
+ */
1524
+ export const claudeLoginProbeLaunch = async (args, {
1525
+ environment = null,
1526
+ agentName = null,
1527
+ env = process.env,
1528
+ platform = process.platform,
1529
+ _prepareState = preparePublicClaudeState,
1530
+ } = {}) => {
1531
+ // Normalized as `spawn` does: a saved `internal` seat's turn runs as `public`,
1532
+ // so its probe must too, or it reports signed in without the jail's view.
1533
+ const sandbox = normalizeSandboxTrust(environment?.sandbox);
1534
+ if (platform !== 'darwin' || !isConfinedTrust(sandbox?.trust)
1535
+ || !PUBLIC_SANDBOX_MODES.has(resolvePublicSandboxMode(sandbox, platform))) return null;
1536
+ // The turn's own state folder, keyed on the same name, with its keychain link.
1537
+ const state = await _prepareState({ agentName });
1538
+ const claudeEnv = withClaudePath(buildClaudeEnv(env, state, {}, null, true, platform));
1539
+ const claudeBin = resolveClaudePath(claudeEnv);
1540
+ const wrapped = wrapArgvWithSeatbelt([claudeBin, ...args], {
1541
+ workspacePath: state.tmpPath,
1542
+ workspaceAccess: 'read',
1543
+ executablePath: claudeBin,
1544
+ statePath: state.statePath,
1545
+ allowClaudeRuntimeAccess: true,
1546
+ });
1547
+ return { command: wrapped[0], args: wrapped.slice(1), env: claudeEnv, cwd: state.tmpPath };
1548
+ };
1549
+
1515
1550
  // A jail that cannot carry claude would fail inside at every spawn.
1516
1551
  const claudeInstallRefusal = (claudeBin) => new Error(
1517
1552
  'Claude agents on Linux need Claude Code on PATH, so the sandbox can carry its install; '
@@ -15,7 +15,7 @@ import { readFileSync } from 'fs';
15
15
  import { checkNode, FAIL } from './doctor.js';
16
16
  import { loginState } from './adapter-login.js';
17
17
  import { missingHarnessHint } from './missing-harness.js';
18
- import { withClaudePath } from './adapters/claude.js';
18
+ import { claudeLoginProbeLaunch, withClaudePath } from './adapters/claude.js';
19
19
  import { resolveWindowsCommandWithReason } from './windows-command.js';
20
20
 
21
21
  // The reason codes the instance accepts (POST /api/agents/runtime/listen-blocked).
@@ -66,33 +66,57 @@ export const nodeFinding = ({ nodeVersion = process.versions.node, enginesRange
66
66
  * on Windows a name cmd can't find exits 1, which is the signed-out code, and
67
67
  * would stop a run that is signed in. null when the command can't be resolved
68
68
  * or the probe can't run or times out (no verdict).
69
+ *
70
+ * F647: given the seat's `environment` and name, a Claude seat confined by
71
+ * Seatbelt is probed inside its own sandbox (the turn's profile, HOME and
72
+ * environment), so a login the jail can't read is not reported signed in. A
73
+ * sandboxed probe that can't be prepared is no verdict, as any other.
69
74
  */
70
- export const runHarnessLoginStatus = (name, args, {
75
+ const plainProbeLaunch = (name, args, { env, platform, resolve }) => {
76
+ const childEnv = name === 'claude' ? withClaudePath(env) : env;
77
+ const located = resolve(name, { env: childEnv, platform });
78
+ if (!located?.command) return null;
79
+ return { command: located.command, args: [...(located.args || []), ...args], env: childEnv };
80
+ };
81
+
82
+ export const runHarnessLoginStatus = async (name, args, {
71
83
  env = process.env,
72
84
  platform = process.platform,
73
85
  resolve = resolveWindowsCommandWithReason,
74
86
  spawnFn = spawn,
75
87
  timeoutMs = 10_000,
76
- } = {}) => new Promise((done) => {
77
- const childEnv = name === 'claude' ? withClaudePath(env) : env;
78
- const located = resolve(name, { env: childEnv, platform });
79
- if (!located?.command) {
80
- done(null);
81
- return;
82
- }
83
- let child;
88
+ environment = null,
89
+ agentName = null,
90
+ _prepareClaudeState,
91
+ } = {}) => {
92
+ let launch = null;
84
93
  try {
85
- child = spawnFn(located.command, [...(located.args || []), ...args], {
86
- stdio: 'ignore', windowsHide: true, env: childEnv, shell: false,
87
- });
94
+ if (name === 'claude' && environment) {
95
+ launch = await claudeLoginProbeLaunch(args, {
96
+ environment, agentName, env, platform,
97
+ ...(_prepareClaudeState ? { _prepareState: _prepareClaudeState } : {}),
98
+ });
99
+ }
88
100
  } catch {
89
- done(null);
90
- return;
101
+ return null;
91
102
  }
92
- const timer = setTimeout(() => { child.kill(); done(null); }, timeoutMs);
93
- child.on('error', () => { clearTimeout(timer); done(null); });
94
- child.on('exit', (code) => { clearTimeout(timer); done(typeof code === 'number' ? code : null); });
95
- });
103
+ launch = launch || plainProbeLaunch(name, args, { env, platform, resolve });
104
+ if (!launch) return null;
105
+ return new Promise((done) => {
106
+ let child;
107
+ try {
108
+ child = spawnFn(launch.command, launch.args, {
109
+ stdio: 'ignore', windowsHide: true, env: launch.env, shell: false, ...(launch.cwd ? { cwd: launch.cwd } : {}),
110
+ });
111
+ } catch {
112
+ done(null);
113
+ return;
114
+ }
115
+ const timer = setTimeout(() => { child.kill(); done(null); }, timeoutMs);
116
+ child.on('error', () => { clearTimeout(timer); done(null); });
117
+ child.on('exit', (code) => { clearTimeout(timer); done(typeof code === 'number' ? code : null); });
118
+ });
119
+ };
96
120
 
97
121
  /**
98
122
  * The harness findings for one adapter: not installed, or installed and not
@@ -105,9 +129,11 @@ export const harnessFindings = async ({
105
129
  adapterName,
106
130
  adapter,
107
131
  environment = null,
132
+ // The seat's name, which keys its sandbox state folder (F647).
133
+ agentName = null,
108
134
  checkInstalled = true,
109
135
  env = process.env,
110
- runStatus = (name, args) => runHarnessLoginStatus(name, args, { env }),
136
+ runStatus = (name, args) => runHarnessLoginStatus(name, args, { env, environment, agentName }),
111
137
  }) => {
112
138
  if (!adapter || !adapterName) return [];
113
139
  if (checkInstalled) {
@@ -431,6 +431,30 @@ const isSymlink = (path) => {
431
431
  }
432
432
  };
433
433
 
434
+ // F647: a confined Claude seat's HOME is its own state folder, whose
435
+ // Library/Keychains is a link to the person's real one (preparePublicClaudeState
436
+ // in adapters/claude.js). Seatbelt checks the path a link resolves to, so the
437
+ // login keychain is admitted at that resolved path too, resolved once here. It
438
+ // is admitted only when it is the login keychain directly inside the person's
439
+ // own Library/Keychains: a link the seat's folder holds to anywhere else adds
440
+ // nothing, and never a folder.
441
+ const LOGIN_KEYCHAIN = 'login.keychain-db';
442
+ const linkedLoginKeychain = (seatHome, personHome) => {
443
+ const seatKeychains = join(seatHome, 'Library', 'Keychains');
444
+ const seatLogin = join(seatKeychains, LOGIN_KEYCHAIN);
445
+ if (!isSymlink(seatKeychains) && !isSymlink(seatLogin)) return null;
446
+ let resolved;
447
+ try {
448
+ resolved = realpathSync(seatLogin);
449
+ } catch {
450
+ return null;
451
+ }
452
+ const personKeychains = join(personHome, 'Library', 'Keychains');
453
+ const allowedFolders = new Set([personKeychains, realpathOrSelf(personKeychains)]);
454
+ if (basename(resolved) !== LOGIN_KEYCHAIN || !allowedFolders.has(dirname(resolved))) return null;
455
+ return resolved;
456
+ };
457
+
434
458
  // The two xcode-select links. The xcrun shim reads developer_dir; both name
435
459
  // the same folder on a normal install, and a turn admits each target.
436
460
  const XCODE_SELECT_LINKS = Object.freeze(['/private/var/select/developer_dir', '/private/var/db/xcode_select_link']);
@@ -664,6 +688,9 @@ export const buildSeatbeltProfile = ({
664
688
  hostReadDirectories = [],
665
689
  // The home folder those rules are judged against. Tests pass a temp one.
666
690
  hostReadHome = homedir(),
691
+ // The person whose login keychain a Claude seat reads (F647). Tests pass a
692
+ // temp one.
693
+ keychainHome = homedir(),
667
694
  loopbackNetworkPorts = [],
668
695
  allowClaudeRuntimeAccess = false,
669
696
  // 'open' (the default) or 'loopback': only the listed loopback ports.
@@ -826,11 +853,16 @@ export const buildSeatbeltProfile = ({
826
853
  // temp files on the machine, so it is not admitted.
827
854
  // Claude's security helper needs the encrypted login-keychain database and
828
855
  // this non-secret locale file: that one file, not the Keychains folder.
829
- const loginKeychain = join(homedir(), 'Library', 'Keychains', 'login.keychain-db');
830
- const textEncoding = join(homedir(), '.CFUserTextEncoding');
856
+ const loginKeychain = join(keychainHome, 'Library', 'Keychains', LOGIN_KEYCHAIN);
857
+ const textEncoding = join(keychainHome, '.CFUserTextEncoding');
858
+ const linked = linkedLoginKeychain(resolvedState, keychainHome);
831
859
  return [
832
860
  `(allow file-read* file-test-existence ${literal(loginKeychain)} ${literal(textEncoding)})`,
833
861
  `(allow file-read-metadata file-test-existence (path-ancestors "${escapeSbplString(loginKeychain)}"))`,
862
+ ...(linked && linked !== loginKeychain ? [
863
+ `(allow file-read* file-test-existence ${literal(linked)})`,
864
+ `(allow file-read-metadata file-test-existence (path-ancestors "${escapeSbplString(linked)}"))`,
865
+ ] : []),
834
866
  ];
835
867
  })() : [];
836
868