@commonlyai/cli 0.1.147 → 0.1.153

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.147",
3
+ "version": "0.1.153",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -463,7 +463,10 @@ const DEFERRABLE_SOLO_EVENT_TYPES = new Set(['first_contact']);
463
463
  // Inside one batch the person's item leads the prompt; the greeting follows it.
464
464
  const PERSON_WAITING_EVENT_TYPES = new Set(['chat.mention', 'message.posted', 'dm.message']);
465
465
 
466
- const inboxPriority = (event) => (PERSON_WAITING_EVENT_TYPES.has(event?.type) ? 0 : 1);
466
+ const inboxPriority = (event) => {
467
+ if (event?.deliveryMode === 'digest') return 2;
468
+ return PERSON_WAITING_EVENT_TYPES.has(event?.type) ? 0 : 1;
469
+ };
467
470
 
468
471
  // Consultations have a per-request private response channel, rather than a
469
472
  // pod-chat delivery. They stay on their existing single-event path; every
@@ -1506,7 +1509,7 @@ export const performRun = ({
1506
1509
  // own conversation (Sage stood down twice on Anvil's thread
1507
1510
  // replies, 2026-08-24). Interim for TASK-058.
1508
1511
  const repliesToThisSeat = event.payload?.repliesToYourMessage === true;
1509
- if (ADDRESSED_EVENT_TYPES.has(event.type) || repliesToThisSeat) {
1512
+ if (ADDRESSED_EVENT_TYPES.has(event.type) || event.payload?.addressed === true || repliesToThisSeat) {
1510
1513
  log(
1511
1514
  `[${event.type}] message ${claimMessageId} held by ${claim.holder} — `
1512
1515
  + (repliesToThisSeat
@@ -2008,10 +2011,12 @@ export const performRun = ({
2008
2011
  // pull, rather than being silently consumed here.
2009
2012
  const buildInboxPrompt = (entries, inboxCount = entries.length) => {
2010
2013
  const BODY_LIMIT = batchLimit;
2011
- const bodies = entries.slice(0, BODY_LIMIT).map((entry, index) => {
2014
+ const wakeEntries = entries.filter((entry) => entry.event.deliveryMode !== 'digest');
2015
+ const digestEntries = entries.filter((entry) => entry.event.deliveryMode === 'digest');
2016
+ const bodies = wakeEntries.slice(0, BODY_LIMIT).map((entry, index) => {
2012
2017
  const messageId = entry.event.payload?.messageId;
2013
2018
  const prefix = [
2014
- `Event ${index + 1}/${entries.length}: ${entry.event.type}`,
2019
+ `Event ${index + 1}/${wakeEntries.length}: ${entry.event.type}`,
2015
2020
  messageId ? `message ${messageId}` : null,
2016
2021
  ].filter(Boolean).join(' — ');
2017
2022
  const claimContext = entry.readOnly
@@ -2021,11 +2026,43 @@ export const performRun = ({
2021
2026
  const body = entry.prompt || '[No usable prompt was delivered for this item.]';
2022
2027
  return `${prefix}\n${claimContext}${body}`;
2023
2028
  });
2024
- const omitted = Math.max(0, inboxCount - bodies.length);
2029
+ const rollup = wakeEntries.find((entry) => entry.event.payload?.digestRollup)?.event.payload?.digestRollup;
2030
+ const conversationCounts = new Map();
2031
+ let knownOlder = 0;
2032
+ for (const conversation of Array.isArray(rollup?.conversations) ? rollup.conversations : []) {
2033
+ if (typeof conversation.label !== 'string' || !Number.isInteger(conversation.count)
2034
+ || conversation.count < 1) continue;
2035
+ conversationCounts.set(conversation.label,
2036
+ (conversationCounts.get(conversation.label) || 0) + conversation.count);
2037
+ knownOlder += conversation.count;
2038
+ }
2039
+ if (rollup?.unreadCount > knownOlder) {
2040
+ conversationCounts.set('older pod activity', rollup.unreadCount - knownOlder);
2041
+ }
2042
+ const seenDigestSources = new Set();
2043
+ for (const entry of digestEntries) {
2044
+ const { threadRootId, taskId, taskKind, messageId, content } = entry.event.payload || {};
2045
+ const sourceId = messageId != null ? `message:${messageId}`
2046
+ : (typeof taskId === 'string' ? `task:${taskId}:${taskKind || ''}:${content || ''}` : null);
2047
+ if (sourceId && seenDigestSources.has(sourceId)) continue;
2048
+ if (sourceId) seenDigestSources.add(sourceId);
2049
+ const label = Number.isInteger(Number(threadRootId)) && Number(threadRootId) > 0
2050
+ ? `thread ${threadRootId}`
2051
+ : (/^TASK-\d+$/.test(String(taskId || '')) ? taskId : 'pod conversation');
2052
+ conversationCounts.set(label, (conversationCounts.get(label) || 0) + 1);
2053
+ }
2054
+ const digestLines = [...conversationCounts].slice(0, 8)
2055
+ .map(([label, count]) => `- ${label}: ${count} unread`);
2056
+ const digestCount = [...conversationCounts.values()].reduce((sum, count) => sum + count, 0);
2057
+ const omitted = Math.max(0, inboxCount - entries.length);
2025
2058
  return [
2026
2059
  `[Inbox batch: ${inboxCount} new event${inboxCount === 1 ? '' : 's'} in this pod. `
2027
2060
  + 'This is one turn: read the included items together, then decide what needs YOU.]',
2028
2061
  ...bodies,
2062
+ ...(digestEntries.length > 0 || rollup?.unreadCount > 0 ? [
2063
+ `[Since you last looked: ${digestCount} ambient update${digestCount === 1 ? '' : 's'} in ${conversationCounts.size} conversation${conversationCounts.size === 1 ? '' : 's'}; context only, no reply needed.]
2064
+ ${digestLines.join('\n')}${conversationCounts.size > 8 ? `\n- ${conversationCounts.size - 8} more conversations omitted` : ''}\nPull relevant messages with commonly_get_messages. On resume, read oldest unread first; at most 8 conversations, 5 messages each, 20 messages total.`,
2065
+ ] : []),
2029
2066
  ...(omitted > 0
2030
2067
  ? [`[${omitted} more event${omitted === 1 ? '' : 's'} arrived. Their count is real; pull pod context if needed.]`]
2031
2068
  : []),
@@ -2168,12 +2205,17 @@ export const performRun = ({
2168
2205
  ? new Set(preSpawn.map((message) => String(message._id || message.id)))
2169
2206
  : null;
2170
2207
  const activeEntries = entries.filter((entry) => !entry.result);
2171
- const triggers = activeEntries.map((entry) => classifyTrigger(entry.event, preSpawn));
2208
+ // Ambient digest entries provide context for this turn, but must never
2209
+ // determine its admission or count as the trigger that woke the seat.
2210
+ const wakingEntries = activeEntries.filter((entry) => entry.event.deliveryMode !== 'digest');
2211
+ const triggers = wakingEntries.map((entry) => classifyTrigger(entry.event, preSpawn));
2172
2212
  const trigger = triggers.includes('human') ? 'human'
2173
2213
  : (triggers.includes('agent') ? 'agent' : 'unknown');
2174
2214
  if (trigger === 'human') cascadeGovernor.record(eventPodId, trigger);
2175
- const admissionEvent = activeEntries.find((entry) => ADDRESSED_EVENT_TYPES.has(entry.event.type))
2176
- || activeEntries[0];
2215
+ const admissionEvent = wakingEntries.find((entry) => (
2216
+ ADDRESSED_EVENT_TYPES.has(entry.event.type) || entry.event.payload?.addressed === true
2217
+ ))
2218
+ || wakingEntries[0];
2177
2219
  if (admissionEvent) {
2178
2220
  const admission = cascadeGovernor.admit(
2179
2221
  eventPodId,
@@ -2182,7 +2224,7 @@ export const performRun = ({
2182
2224
  admissionEvent.event.payload,
2183
2225
  );
2184
2226
  if (!admission.allowed) {
2185
- for (const entry of activeEntries) {
2227
+ for (const entry of wakingEntries) {
2186
2228
  entry.result = batchAdmissionResult(entry.event, admission);
2187
2229
  }
2188
2230
  return { entries };
@@ -2190,7 +2232,8 @@ export const performRun = ({
2190
2232
  }
2191
2233
 
2192
2234
  const bindingEntries = activeEntries.filter((entry) => (
2193
- entry.event.type === 'message.posted' && entry.event.payload?.messageId
2235
+ entry.event.deliveryMode !== 'digest'
2236
+ && entry.event.type === 'message.posted' && entry.event.payload?.messageId
2194
2237
  ));
2195
2238
  if (bindingEntries.length > 0) {
2196
2239
  const yieldMs = claimHandicap.yieldDelayMs(eventPodId);
@@ -2201,6 +2244,7 @@ export const performRun = ({
2201
2244
  }
2202
2245
 
2203
2246
  for (const entry of activeEntries) {
2247
+ if (entry.event.deliveryMode === 'digest') continue;
2204
2248
  const messageId = entry.event.payload?.messageId;
2205
2249
  if (!messageId || !CLAIMABLE_EVENT_TYPES.has(entry.event.type)) continue;
2206
2250
  const claimKeeper = createClaimKeeper(client, {
@@ -2224,7 +2268,7 @@ export const performRun = ({
2224
2268
  // `message.posted`. Preserve the existing ADR-018/TASK-058
2225
2269
  // peer-aware exception; D3a otherwise partitions lost bindings as
2226
2270
  // read-only so a generic broadcast cannot widen itself after CAS.
2227
- if (entry.event.payload?.repliesToYourMessage === true) {
2271
+ if (entry.event.payload?.repliesToYourMessage === true || entry.event.payload?.addressed === true) {
2228
2272
  entry.peerFrame = peerHoldsFrame(claim.holder, messageId);
2229
2273
  continue;
2230
2274
  }
@@ -2241,7 +2285,7 @@ export const performRun = ({
2241
2285
  }
2242
2286
  }
2243
2287
 
2244
- const actionEntries = activeEntries.filter((entry) => !entry.result);
2288
+ const actionEntries = wakingEntries.filter((entry) => !entry.result);
2245
2289
  if (actionEntries.length === 0) return { entries };
2246
2290
 
2247
2291
  const claimKeepers = actionEntries
@@ -2300,6 +2344,17 @@ export const performRun = ({
2300
2344
  trigger,
2301
2345
  });
2302
2346
  for (const entry of actionEntries) entry.result = turnResult;
2347
+ // A digest was context in this successful waking turn, never an
2348
+ // independent action. If the waking work stood down or the provider
2349
+ // refused the batch, leave it unread for the next real turn.
2350
+ if (turnResult?.outcome === 'posted'
2351
+ || (turnResult?.outcome === 'no_action' && !turnResult?.reason)) {
2352
+ for (const entry of activeEntries) {
2353
+ if (entry.event.deliveryMode === 'digest') {
2354
+ entry.result = { outcome: 'no_action', reason: 'digest-read' };
2355
+ }
2356
+ }
2357
+ }
2303
2358
  } catch (err) {
2304
2359
  if (!isContentRefusal(err)) throw err;
2305
2360
  if (actionEntries.length === 1) {
@@ -2352,6 +2407,7 @@ export const performRun = ({
2352
2407
  const tick = async () => {
2353
2408
  if (!running) return;
2354
2409
  let nextPollDelayMs = intervalMs;
2410
+ let completedModelTurn = false;
2355
2411
  try {
2356
2412
  // ADR-024 D3: this is an inbox fetch, not a stream of interrupts. The
2357
2413
  // backend returns one pod's oldest pending batch, so every delivered row
@@ -2392,6 +2448,12 @@ export const performRun = ({
2392
2448
  }
2393
2449
  for (const group of eventGroups.values()) {
2394
2450
  if (!running) break;
2451
+ // A current kernel never claims a digest-only page. Guard a mixed
2452
+ // version rollout too: an ambient batch must not start a model turn.
2453
+ if (group.every((event) => event.deliveryMode === 'digest')) {
2454
+ log(`[inbox.batch] digest-only page (${group.length}) — no spawn or ack`);
2455
+ continue;
2456
+ }
2395
2457
  if ((group[0].podId || podId) && !PRIVATE_RESPONSE_EVENT_TYPES.has(group[0].type)) {
2396
2458
  // Nothing in this batch but the seat introducing itself: leave it
2397
2459
  // unacked for one interval so a person who mentions the agent in that
@@ -2459,13 +2521,9 @@ export const performRun = ({
2459
2521
  ));
2460
2522
  if (batchSpawned) {
2461
2523
  consecutiveSpawnFailures = 0;
2462
- // A turn is exactly when events pile up: whoever typed while the
2463
- // adapter was running is already waiting. Sleeping the interval on
2464
- // top of the turn charges them for it twice (TASK-343). Only a
2465
- // batch that actually spawned skips the wait; an idle poll and a
2466
- // batch that spawned nothing keep the interval, so this cannot
2467
- // become a spin.
2468
- nextPollDelayMs = 0;
2524
+ // Notices arriving mid-turn get one bounded collection window.
2525
+ // Idle polls and batches with no model turn keep their cadence.
2526
+ completedModelTurn = true;
2469
2527
  }
2470
2528
  for (const entry of batch.entries) {
2471
2529
  const event = entry.event;
@@ -2643,7 +2701,9 @@ export const performRun = ({
2643
2701
  }
2644
2702
  onError?.(err);
2645
2703
  }
2646
- if (running) setTimeoutImpl(tick, nextPollDelayMs);
2704
+ // Notices landing during a turn share one three-second collection window
2705
+ // before the next inbox read, independent of the idle polling cadence.
2706
+ if (running) setTimeoutImpl(tick, completedModelTurn ? 3000 : nextPollDelayMs);
2647
2707
  };
2648
2708
 
2649
2709
  tick();
@@ -4,7 +4,8 @@
4
4
  * Two thin CAP shims the run loop calls around every spawn cycle:
5
5
  *
6
6
  * readLongTerm(client) — GET /api/agents/runtime/memory,
7
- * returns sections.long_term.content or ''
7
+ * returns sections.long_term.content,
8
+ * falling back to legacy content
8
9
  * syncBack(client, { summary }) — POST /api/agents/runtime/memory/sync
9
10
  * with mode:'patch', sourceRuntime:'local-cli'.
10
11
  * No-op when summary is falsy.
@@ -33,8 +34,8 @@ export const SOURCE_RUNTIME = 'local-cli';
33
34
  * cannot adopt a habit whose surface it has no evidence exists, so the empty
34
35
  * case now says so.
35
36
  *
36
- * It names `long_term` specifically because that is the ONLY section read back
37
- * (`readLongTerm` returns `sections.long_term.content`). A write to `daily` —
37
+ * It names `long_term` specifically because that is the only v2 section read
38
+ * back. Legacy `content` is a fallback for records without that section. A write to `daily` —
38
39
  * the section whose name most invites exactly this use — succeeds, returns 200,
39
40
  * and is never seen again; the write and the silence are indistinguishable from
40
41
  * a correct round trip. Naming the section is the whole point of the cue.
@@ -92,7 +93,7 @@ export const buildMemoryPreamble = (prompt, memoryLongTerm, { freshSession = fal
92
93
  export const readLongTerm = async (client, { onError } = {}) => {
93
94
  try {
94
95
  const body = await client.get('/api/agents/runtime/memory');
95
- return body?.sections?.long_term?.content || '';
96
+ return body?.sections?.long_term?.content ?? body?.content ?? '';
96
97
  } catch (err) {
97
98
  // A 404 is the ONLY error that means what '' means: a fresh agent with no
98
99
  // memory row yet. The kernel upserts on first write, so this is genuine
package/src/lib/poller.js CHANGED
@@ -28,6 +28,40 @@ export const terminalDeliveryAckError = (ackErr, eventId, runner = 'poller') =>
28
28
  return null;
29
29
  };
30
30
 
31
+ const digestFrame = (events, rollup) => {
32
+ const counts = new Map();
33
+ let knownOlder = 0;
34
+ for (const conversation of Array.isArray(rollup?.conversations) ? rollup.conversations : []) {
35
+ if (typeof conversation.label !== 'string' || !Number.isInteger(conversation.count)
36
+ || conversation.count < 1) continue;
37
+ counts.set(conversation.label, (counts.get(conversation.label) || 0) + conversation.count);
38
+ knownOlder += conversation.count;
39
+ }
40
+ if (rollup?.unreadCount > knownOlder) {
41
+ counts.set('older pod activity',
42
+ (counts.get('older pod activity') || 0) + rollup.unreadCount - knownOlder);
43
+ }
44
+ const seen = new Set();
45
+ for (const event of events) {
46
+ const payload = event.payload || {};
47
+ const sourceId = payload.messageId != null ? `message:${payload.messageId}`
48
+ : (typeof payload.taskId === 'string'
49
+ ? `task:${payload.taskId}:${String(payload.taskKind || '')}:${String(payload.content || '')}` : null);
50
+ if (sourceId && seen.has(sourceId)) continue;
51
+ if (sourceId) seen.add(sourceId);
52
+ const thread = payload.threadRootId;
53
+ const task = payload.taskId;
54
+ const label = Number.isInteger(thread) && thread > 0 ? `thread ${thread}`
55
+ : (typeof task === 'string' && /^TASK-\d+$/.test(task) ? task : 'pod conversation');
56
+ counts.set(label, (counts.get(label) || 0) + 1);
57
+ }
58
+ const lines = [...counts].slice(0, 8).map(([label, count]) => `- ${label}: ${count} unread`);
59
+ if (counts.size > 8) lines.push(`- ${counts.size - 8} more conversations omitted`);
60
+ const total = [...counts.values()].reduce((sum, count) => sum + count, 0);
61
+ return `[Since you last looked: ${total} ambient update${total === 1 ? '' : 's'} in ${counts.size} conversation${counts.size === 1 ? '' : 's'}; context only, no reply needed.]\n`
62
+ + `${lines.join('\n')}\nPull relevant messages with commonly_get_messages. On resume, read oldest unread first; at most 8 conversations, 5 messages each, 20 messages total.`;
63
+ };
64
+
31
65
  export const startPoller = ({
32
66
  instanceUrl,
33
67
  token,
@@ -57,10 +91,30 @@ export const startPoller = ({
57
91
  limit: 10,
58
92
  });
59
93
 
60
- for (const event of events) {
94
+ // A digest is received context, not a webhook invocation. The runtime
95
+ // inbox claims it only alongside a wake from the same pod.
96
+ const wakeEvents = events.filter((event) => event.deliveryMode !== 'digest');
97
+ const digestEvents = events.filter((event) => event.deliveryMode === 'digest'
98
+ && wakeEvents[0] && String(event.podId) === String(wakeEvents[0].podId));
99
+ const rollup = wakeEvents[0]?.payload?.digestRollup;
100
+ const frame = digestEvents.length > 0 || rollup?.unreadCount > 0
101
+ ? digestFrame(digestEvents, rollup) : null;
102
+ let digestConsumed = false;
103
+ for (const [index, event] of wakeEvents.entries()) {
104
+ const attachedDigest = index === 0 && frame !== null;
105
+ const forwarded = attachedDigest ? {
106
+ ...event,
107
+ payload: {
108
+ ...(event.payload || {}),
109
+ digestSummary: frame,
110
+ ...(typeof event.payload?.content === 'string' ? {
111
+ content: `${event.payload.content}\n\n${frame}`,
112
+ } : {}),
113
+ },
114
+ } : event;
61
115
  let result = { outcome: 'no_action' };
62
116
  try {
63
- result = (await onEvent(event)) || { outcome: 'no_action' };
117
+ result = (await onEvent(forwarded)) || { outcome: 'no_action' };
64
118
  } catch (handlerErr) {
65
119
  result = { outcome: 'error', reason: handlerErr.message };
66
120
  }
@@ -72,6 +126,11 @@ export const startPoller = ({
72
126
  result,
73
127
  ...(typeof deliveryId === 'string' && deliveryId ? { deliveryId } : {}),
74
128
  });
129
+ if (attachedDigest && (result.outcome === 'posted'
130
+ || result.outcome === 'acknowledged'
131
+ || (result.outcome === 'no_action' && !result.reason))) {
132
+ digestConsumed = true;
133
+ }
75
134
  } catch (ackErr) {
76
135
  const terminalError = terminalDeliveryAckError(ackErr, event._id);
77
136
  if (terminalError) {
@@ -84,6 +143,26 @@ export const startPoller = ({
84
143
  }
85
144
  }
86
145
 
146
+ if (digestConsumed) {
147
+ for (const event of digestEvents) {
148
+ try {
149
+ const deliveryId = event.payload?.deliveryId;
150
+ await client.post(`/api/agents/runtime/events/${event._id}/ack`, {
151
+ result: { outcome: 'no_action', reason: 'digest-read' },
152
+ ...(typeof deliveryId === 'string' && deliveryId ? { deliveryId } : {}),
153
+ });
154
+ } catch (ackErr) {
155
+ const terminalError = terminalDeliveryAckError(ackErr, event._id);
156
+ if (terminalError) {
157
+ running = false;
158
+ onError?.(terminalError);
159
+ return;
160
+ }
161
+ onError?.(new Error(`Ack failed for ${event._id}: ${ackErr.message}`));
162
+ }
163
+ }
164
+ }
165
+
87
166
  consecutiveErrors = 0;
88
167
  consecutiveAuthErrors = 0;
89
168
  } catch (err) {