@primusclaw/personal-agent-runtime 0.7.2 → 0.8.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/worker.js ADDED
@@ -0,0 +1,1684 @@
1
+ // packages/runtime/src/worker/assemble.ts
2
+ import {
3
+ InboundStats,
4
+ integrationRegistry,
5
+ neutralPlugins,
6
+ redactText as redactText4,
7
+ SecurityLog,
8
+ SecretsUnavailable
9
+ } from "@primusclaw/personal-agent";
10
+ import {
11
+ alsRequestScope,
12
+ buildServer,
13
+ ChatLog,
14
+ createClawClient,
15
+ cryptoRandom,
16
+ EnvSecretSource,
17
+ healthzRoute as healthzRoute2,
18
+ HttpTokenExchange,
19
+ lineLogger,
20
+ openWorkerStore,
21
+ PrometheusMetrics,
22
+ readSettings,
23
+ secretsSourceOf,
24
+ systemClock,
25
+ wantedSecrets
26
+ } from "@primusclaw/personal-agent-runtime";
27
+
28
+ // packages/runtime/src/worker/build-info.ts
29
+ var BUILD_INFO_METRIC = "personal_agent_build_info";
30
+ function label(value) {
31
+ return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n");
32
+ }
33
+ function buildInfoText(version, node) {
34
+ return [
35
+ `# HELP ${BUILD_INFO_METRIC} The running build of the personal agent: always 1, the build in its labels.`,
36
+ `# TYPE ${BUILD_INFO_METRIC} gauge`,
37
+ `${BUILD_INFO_METRIC}{version="${label(version)}",node="${label(node)}"} 1`,
38
+ ""
39
+ ].join("\n");
40
+ }
41
+ function withBuildInfo(render, info) {
42
+ return () => {
43
+ const text = render();
44
+ return (text === "" || text.endsWith("\n") ? text : text + "\n") + info;
45
+ };
46
+ }
47
+
48
+ // packages/runtime/src/worker/features.ts
49
+ import {
50
+ BOT_NAME,
51
+ chatTurnKey,
52
+ contextInterceptor,
53
+ Guardrails as Guardrails2,
54
+ PublicErrorLog,
55
+ Router,
56
+ reviewStop,
57
+ REVIEW_HANDOFF,
58
+ pendingOf,
59
+ UPGRADE_RETRY_SECONDS,
60
+ noModelRefusalPolicy,
61
+ TerminalApprovalsCommand
62
+ } from "@primusclaw/personal-agent";
63
+
64
+ // packages/runtime/src/worker/startup-error.ts
65
+ var StartupError = class extends Error {
66
+ name = "StartupError";
67
+ };
68
+
69
+ // packages/runtime/src/worker/features-assistant.ts
70
+ import {
71
+ clientLocaleOf,
72
+ agentActionAllowed,
73
+ AssistantActions,
74
+ AssistantChoiceClicks,
75
+ AssistantChatService,
76
+ Board,
77
+ commandArgs,
78
+ DirectChat,
79
+ exactCommand,
80
+ isKnownCommand,
81
+ menuCommand,
82
+ parseCommand,
83
+ pyStrip,
84
+ Receipts,
85
+ remoteDomain,
86
+ remoteView,
87
+ SubscriptionKeeper,
88
+ turn as turn2,
89
+ WatchClicks,
90
+ WorkCardClicks,
91
+ WorkClicks
92
+ } from "@primusclaw/personal-agent";
93
+
94
+ // packages/runtime/src/worker/features-text.ts
95
+ import {
96
+ channelActions,
97
+ channelContext,
98
+ connectionsText,
99
+ limitsText,
100
+ MessageRateLimiter,
101
+ noteMessage,
102
+ peopleOf,
103
+ quoteBlock,
104
+ redactText,
105
+ turn,
106
+ UNKNOWN,
107
+ ASSISTANT_PENDING_SECONDS,
108
+ waitWords,
109
+ withLinks,
110
+ withQuote
111
+ } from "@primusclaw/personal-agent";
112
+ function isGroup(message) {
113
+ return message.conversation.kind === "group";
114
+ }
115
+ var mask = (text) => redactText(text).text;
116
+ function messageTextFor(channelName) {
117
+ return {
118
+ quoteBlock: (message, group) => quoteBlock(message.quotes, { group, redact: mask }),
119
+ withLinks: (text, message) => withLinks(text, message.links, { group: isGroup(message), redact: mask }),
120
+ withQuote,
121
+ unreadable(message) {
122
+ const names = message.unreadableFiles;
123
+ if (names.length === 0) return void 0;
124
+ const line = `${channelName} did not give me ${names.map((n) => turn.shownName(n)).join(", ")}. I can read images pasted into the message.`;
125
+ return { line, count: names.length };
126
+ }
127
+ };
128
+ }
129
+ function routerLimits(limits, clock) {
130
+ const rate = new MessageRateLimiter(limits.messageLimit, limits.messageWindowSeconds, clock);
131
+ return {
132
+ maxConcurrentTasks: limits.maxConcurrentTasks,
133
+ assistantPendingSeconds: ASSISTANT_PENDING_SECONDS,
134
+ checkMessage(userId) {
135
+ const verdict = rate.check(userId);
136
+ if (verdict.allowed) return { allowed: true };
137
+ return {
138
+ allowed: false,
139
+ notify: verdict.notify,
140
+ retryAfterSeconds: verdict.retryAfterSeconds,
141
+ limit: rate.limit,
142
+ windowSeconds: rate.windowSeconds
143
+ };
144
+ },
145
+ rateNotice: (lang, retryAfterSeconds) => limitsText.in(lang).rateLimited({ s: rate.limit > 1 ? "s" : "", wait: waitWords(retryAfterSeconds, lang) }),
146
+ concurrencyNotice: (lang, running, what) => limitsText.in(lang).concurrencyLimited({ running, what })
147
+ };
148
+ }
149
+ function channelContextBuilder(store, pending = () => []) {
150
+ return (request) => {
151
+ const mentions = request.message.mentions.map((m) => ({
152
+ mentioned: { id: m.channelUserId, name: m.name, aadObjectId: m.userId }
153
+ }));
154
+ const known = store.members.knownMembers().map((m) => ({
155
+ id: m.id,
156
+ name: m.name,
157
+ objectId: m.objectId,
158
+ ...m.email ? { email: m.email } : {}
159
+ }));
160
+ const people = peopleOf(
161
+ mentions,
162
+ request.message.text,
163
+ known,
164
+ (aad) => store.links.clawUserIdOf(aad),
165
+ (channelId) => store.members.userForChannelId(channelId)
166
+ );
167
+ const actions = channelActions(request.parts);
168
+ const context = channelContext({
169
+ channelMessageId: request.channelMessageId,
170
+ people,
171
+ pending: [...pending(request.userId)],
172
+ actions,
173
+ handoffs: request.handoffs,
174
+ ..."attached" in request ? { attached: request.attached } : {},
175
+ via: request.via
176
+ });
177
+ return {
178
+ context,
179
+ actions: actions.map((a) => a.name),
180
+ people: people.flatMap((p) => p.user_id ? [p.user_id] : [])
181
+ };
182
+ };
183
+ }
184
+ var TONES = /* @__PURE__ */ new Set(["default", "good", "attention", "warning", "accent"]);
185
+ var noteFactory = (text, options = {}) => {
186
+ const buttons = (options.buttons ?? []).map((b) => ({
187
+ title: b.title,
188
+ verb: b.verb,
189
+ data: { ...b.data },
190
+ ...b.style ? { style: b.style } : {}
191
+ }));
192
+ return noteMessage({
193
+ text,
194
+ ...options.title === void 0 ? {} : { title: options.title },
195
+ ...options.tone !== void 0 && TONES.has(options.tone) ? { tone: options.tone } : {},
196
+ ...buttons.length ? { buttons } : {}
197
+ });
198
+ };
199
+ function whoamiConnections(integrations) {
200
+ return (c) => connectionsText({
201
+ safe: c.owner === void 0 ? null : { name: c.owner.name },
202
+ githubState: c.githubState === void 0 ? null : c.githubState,
203
+ connection: c.connection ?? null,
204
+ connectionKnown: c.connectionKnown,
205
+ githubPart: c.githubPart,
206
+ memory: c.memory ?? UNKNOWN,
207
+ memoryPage: c.memoryPage,
208
+ zh: c.zh,
209
+ extraLines: integrations.connectionLines.map((line) => line(c.owner, c.zh ? "zh" : "en"))
210
+ });
211
+ }
212
+ async function fetchAll(surface, files) {
213
+ const fetched = [];
214
+ const failed = [];
215
+ const names = /* @__PURE__ */ new Set();
216
+ for (const [at, file] of files.entries()) {
217
+ const index = at + 1;
218
+ const got = await surface.fetchFile(file);
219
+ if (!got.ok) {
220
+ failed.push([file.name || `image ${String(index)}`, got.error.reason]);
221
+ continue;
222
+ }
223
+ let name = got.value.name;
224
+ while (names.has(name)) name = `${String(index)}-${name}`;
225
+ names.add(name);
226
+ fetched.push({ ...got.value, name });
227
+ }
228
+ return { fetched, failed };
229
+ }
230
+ function messageFiles(surface) {
231
+ return {
232
+ fetch: (files) => fetchAll(surface, files),
233
+ uploadFolder: (messageId) => turn.uploadFolder(messageId),
234
+ failedLine: (failed) => turn.failedFilesLine(failed)
235
+ };
236
+ }
237
+
238
+ // packages/runtime/src/worker/features-assistant.ts
239
+ var isExactCommand = (text) => exactCommand(text, { menuCommand, isKnownCommand });
240
+ function keeper(base, notifyUrl) {
241
+ if (!notifyUrl) return void 0;
242
+ const { assistant } = base.settings;
243
+ return new SubscriptionKeeper({
244
+ store: base.store,
245
+ claw: base.claw.notifications,
246
+ random: base.random,
247
+ logger: base.logger,
248
+ baseUrl: notifyUrl,
249
+ assistant: assistant.enabled,
250
+ understood: (aadId) => assistant.understandingUsers.has(aadId.toLowerCase()),
251
+ assistantFor: (aadId) => assistant.users.size === 0 || assistant.users.has(aadId.toLowerCase()),
252
+ userIdOf: async (key) => pyStrip((await base.plugins.identityLookup.ownerOfKey(key))?.id ?? "") || void 0,
253
+ // The surface Claw routes this person's assistant messages by (a reply goes back to the surface the message came from).
254
+ surface: base.shape.surfaceId
255
+ });
256
+ }
257
+ function remoteAskCard(request) {
258
+ const lang = request.lang === "zh" ? "zh" : "en";
259
+ if (remoteView.isTerminalAsk(request.ask)) {
260
+ const terminal = remoteView.terminalAskView(
261
+ { ...request, options: remoteDomain.parseOptions(request.options) },
262
+ lang
263
+ );
264
+ return {
265
+ body: {
266
+ type: "view",
267
+ view: { name: "terminalAsk", model: terminal },
268
+ fallbackText: terminal.title
269
+ }
270
+ };
271
+ }
272
+ const model = remoteView.remoteAskView({ ...request, options: remoteDomain.parseOptions(request.options) }, lang);
273
+ return { body: { type: "view", view: { name: "remoteAsk", model }, fallbackText: model.title } };
274
+ }
275
+ function assistantChat(base, integrations, style, parts, hooks) {
276
+ const { settings: settings2, store, claw, metrics } = base;
277
+ return new AssistantChatService({
278
+ store,
279
+ claw: { assistant: claw.assistant, sessions: claw.sessions },
280
+ hasAssistantTypes: parts.subs === void 0 ? void 0 : (aadId) => parts.subs?.hasAssistantTypes(aadId) ?? false,
281
+ receipts: parts.receipts,
282
+ directChat: parts.directChat,
283
+ clock: base.clock,
284
+ random: base.random,
285
+ logger: base.logger,
286
+ stepLabel: (tool, lang) => turn2.lookupLabel(tool, lang, integrations),
287
+ style: () => ({ assistantProgress: style.assistantProgress, assistantStreamSay: style.assistantStreamSay }),
288
+ enabled: settings2.assistant.enabled,
289
+ users: settings2.assistant.users,
290
+ understanding: settings2.assistant.understandingUsers,
291
+ pluginId: settings2.claw.pluginId ?? void 0,
292
+ legacyTurn: (aadId) => hooks.legacyTurn(aadId),
293
+ files: messageFiles(base.surface),
294
+ onFilesDropped: (path, count) => {
295
+ if (count > 0) metrics.filesDropped(path, count);
296
+ },
297
+ board: { show: (userId, key, conversation) => parts.board.show(userId, key, conversation) },
298
+ clientLocale: () => clientLocaleOf(base.requestScope),
299
+ commands: {
300
+ parse: (text) => parseCommand(text) ?? void 0,
301
+ args: (text, name) => commandArgs(text, name) ?? void 0
302
+ }
303
+ });
304
+ }
305
+ function actionClicks(actions) {
306
+ return {
307
+ verbs: ["assistant_action", "assistant_confirm"],
308
+ withCredential: async (click, key) => {
309
+ if (click.action.verb === "assistant_action") await actions.actionClick(click, key);
310
+ else await actions.confirmClick(click);
311
+ }
312
+ };
313
+ }
314
+ function assistantParts(base, inputs) {
315
+ const { style, integrations, notifyUrl, hooks } = inputs;
316
+ const { store, claw, logger, exchange } = base;
317
+ const subs = keeper(base, notifyUrl);
318
+ const receipts = new Receipts(base.clock, logger, () => style.assistantReceipt);
319
+ const directChat = new DirectChat(base.settings.directChat.enabled, base.settings.directChat.users);
320
+ const late = {};
321
+ const board = new Board({
322
+ store,
323
+ claw: claw.workItems,
324
+ logger,
325
+ on: (u) => late.chat?.on(u) ?? false,
326
+ remoteAsk: remoteAskCard,
327
+ clientLocale: () => clientLocaleOf(base.requestScope)
328
+ });
329
+ const assistant = assistantChat(base, integrations, style, { subs, receipts, directChat, board }, hooks);
330
+ late.chat = assistant;
331
+ const actions = new AssistantActions({
332
+ store,
333
+ claw: claw.assistant,
334
+ exchange,
335
+ runCommand: (text, click, key) => hooks.runCommand(text, click.sender, click.conversation, key),
336
+ exactCommand: isExactCommand,
337
+ agentActionAllowed,
338
+ understands: (userId) => assistant.understands(userId),
339
+ reachable: (userId) => assistant.reachable(userId),
340
+ logger,
341
+ // (a review handed back: taken by the review service, dropped without it as Python's with GITHUB_REVIEW off)
342
+ reviewHandoff: inputs.reviewHandoff
343
+ });
344
+ const work = new WorkClicks({
345
+ store,
346
+ claw: claw.workItems,
347
+ board,
348
+ onStopped: (itemId) => {
349
+ hooks.itemStopped(itemId);
350
+ }
351
+ });
352
+ const watch = new WatchClicks({ store, claw: claw.workItems, exchange, logger });
353
+ const linked = (userId) => store.links.getKey(userId) !== null;
354
+ const choices = new AssistantChoiceClicks({ store, deliver: (message) => hooks.typed(message), logger });
355
+ const clicks = [new WorkCardClicks(work, watch, exchange, linked, logger), actionClicks(actions), choices];
356
+ return { subs, chat: assistant, board, receipts, directChat, actions, clicks };
357
+ }
358
+
359
+ // packages/runtime/src/worker/features-proactive.ts
360
+ import {
361
+ clientLocaleOf as clientLocaleOf2,
362
+ errorName,
363
+ fetchChanges,
364
+ looksInternal,
365
+ looksLikeServiceError,
366
+ Proactive,
367
+ publicRunEvent,
368
+ Release,
369
+ remoteDomain as remoteDomain2,
370
+ SaidMessages,
371
+ SayPlanner,
372
+ turn as turn3
373
+ } from "@primusclaw/personal-agent";
374
+ function conversationFor(base) {
375
+ return (reference) => base.surface.conversation(base.shape.refOf(reference));
376
+ }
377
+ function runFollowUps(base, errors) {
378
+ const { claw, clock, logger, settings: settings2 } = base;
379
+ return {
380
+ async lostAnswer(key, sessionId, lead) {
381
+ const answer = await turn3.lastAnswer({ claw: claw.sessions, clock, log: logger, errors }, key, sessionId);
382
+ if (answer === void 0) return void 0;
383
+ return turn3.answerParts(answer, turn3.deepLink(settings2.publicBaseUrl, sessionId), false, lead);
384
+ },
385
+ async offerChanges(key, sessionId, conversation) {
386
+ try {
387
+ const changes = await fetchChanges(claw.sessions, key, sessionId, logger);
388
+ if (changes === void 0) return;
389
+ const model = { changes, sessionId, publicBaseUrl: settings2.publicBaseUrl };
390
+ await conversation.send(turn3.viewMessage("changes", model, "Changes"));
391
+ } catch (error) {
392
+ logger.warn("the changes card of a finished run could not be shown", { error: errorName(error) });
393
+ }
394
+ }
395
+ };
396
+ }
397
+ function proactiveParts(base, style, assistant, errors, router) {
398
+ const { store, claw, surface, settings: settings2 } = base;
399
+ const deps = {
400
+ store,
401
+ conversationFor: conversationFor(base),
402
+ deliverStored: async (envelope) => {
403
+ await surface.conversation(base.shape.refOf(envelope["reference"] ?? {})).deliver(envelope);
404
+ },
405
+ messageIds: surface.caps.messageIds,
406
+ say: new SayPlanner({
407
+ store,
408
+ exactCommand: isExactCommand,
409
+ style: () => ({ citations: style.citations, suggestedReplies: style.suggestedReplies }),
410
+ clientLocale: () => clientLocaleOf2(base.requestScope)
411
+ }),
412
+ receipts: assistant.receipts,
413
+ directChat: assistant.directChat,
414
+ said: new SaidMessages(),
415
+ deliveryLink: (sessionId, deliveryId) => claw.sessions.deliveryLink(sessionId, deliveryId),
416
+ claw: claw.workItems,
417
+ remote: {
418
+ options: (raw) => remoteDomain2.parseOptions(raw),
419
+ askCard: remoteAskCard,
420
+ saidParts: (label2, text) => remoteDomain2.unsolicitedParts(label2, text)
421
+ },
422
+ runs: runFollowUps(base, errors),
423
+ publicBaseUrl: settings2.publicBaseUrl,
424
+ replyWindowSeconds: settings2.assistant.replyWindowSeconds,
425
+ clock: base.clock,
426
+ logger: base.logger,
427
+ publicEvent: (event) => publicRunEvent(event, errors, (text) => looksLikeServiceError(text) || looksInternal(text)),
428
+ botName: "Clawy",
429
+ ...router === void 0 ? {} : { identityAfterRefusal: identityAfterRefusal(base, router) }
430
+ };
431
+ const proactive = new Proactive(deps);
432
+ return { proactive, release: new Release(deps, proactive) };
433
+ }
434
+ function identityAfterRefusal(base, router) {
435
+ return async (userId, conversation, turn6) => {
436
+ const { store } = base;
437
+ const once = `${IDENTITY_REFUSED_PREFIX}${userId}:${turn6}`;
438
+ if (!turn6) return;
439
+ const claim = store.idempotency.claimEvent(once);
440
+ if (claim.state !== "claimed") return;
441
+ let sent = false;
442
+ try {
443
+ const person = {
444
+ id: userId,
445
+ channelUserId: store.members.channelIdOf(userId) ?? "",
446
+ name: store.members.memberName(userId) ?? "",
447
+ email: ""
448
+ };
449
+ const r = router();
450
+ sent = await r.ctx.credentials.identityAfterRefusal(r.chat(person, conversation));
451
+ } finally {
452
+ if (sent) store.idempotency.finishEvent(once);
453
+ else store.idempotency.releaseEvent(once, claim.holder);
454
+ }
455
+ };
456
+ }
457
+ var IDENTITY_REFUSED_PREFIX = "identity-refused:";
458
+ function proactiveHold(parts) {
459
+ return {
460
+ muted: (userId) => parts.proactive.muted(userId) ?? null,
461
+ release: (userId) => parts.release.release(userId)
462
+ };
463
+ }
464
+ function followReach(parts, base) {
465
+ return {
466
+ reachable: (chatKey) => parts.proactive.reachable(chatKey),
467
+ muted: (chatKey) => parts.proactive.muted(chatKey) ?? null,
468
+ holdRemote: (chatKey, label2, text) => {
469
+ parts.proactive.holdRemote(chatKey, label2, text, base.random.hexId());
470
+ }
471
+ };
472
+ }
473
+
474
+ // packages/runtime/src/worker/features-remote.ts
475
+ import { createHash } from "node:crypto";
476
+ import {
477
+ answerLang,
478
+ remoteView as remoteView2,
479
+ ConnectorSetup,
480
+ CredentialUnavailable,
481
+ FollowCredentialUnavailable,
482
+ looksInternal as looksInternal2,
483
+ newRef,
484
+ RemoteAgents,
485
+ REMOTE_FOLLOW_TIMINGS,
486
+ REMOTE_WATCH_TIMINGS,
487
+ setupFrom,
488
+ splitErrorTail
489
+ } from "@primusclaw/personal-agent";
490
+ function remoteErrors(base, errors) {
491
+ return {
492
+ withhold: (where, detail, ids) => errors.withhold(where, detail, ids),
493
+ publicReason: (reason, where, ids) => errors.publicReason(reason, where, ids),
494
+ looksInternal: (text) => looksInternal2(text),
495
+ splitErrorTail: (text) => splitErrorTail(text),
496
+ newRef: () => newRef(base.random)
497
+ };
498
+ }
499
+ function remoteAgents(base, inputs) {
500
+ const { store, claw, settings: settings2, securityLog } = base;
501
+ const { switches, guard } = inputs;
502
+ const ctx = {
503
+ views: remoteView2.createRemoteViews(),
504
+ settings: {
505
+ enabled: switches.remoteAgents,
506
+ follow: switches.remotePush,
507
+ windowDefault: switches.remoteWindow,
508
+ timings: REMOTE_FOLLOW_TIMINGS,
509
+ watchTimings: REMOTE_WATCH_TIMINGS,
510
+ botName: "Clawy",
511
+ streaming: base.surface.caps.streaming
512
+ },
513
+ claw: claw.remoteAgents,
514
+ clawBaseUrl: settings2.clawApiUrl,
515
+ setup: new ConnectorSetup(setupFrom(null, settings2.clawApiUrl)),
516
+ remoteState: store.remoteState,
517
+ sessionNames: store.remoteSessionNames,
518
+ permissions: store.remotePermissions,
519
+ prefs: store.prefs,
520
+ references: store.references,
521
+ conversationFor: conversationFor(base),
522
+ credentialFor: async (person) => {
523
+ try {
524
+ return await inputs.hooks.background(person) ?? null;
525
+ } catch (error) {
526
+ if (error instanceof CredentialUnavailable) throw new FollowCredentialUnavailable();
527
+ throw error;
528
+ }
529
+ },
530
+ reach: inputs.reach,
531
+ guard: {
532
+ take: (person, operation, ticket, ids) => guard.take(person, operation, ticket, ids ?? {}),
533
+ giveBack: (person, operation, ticket) => {
534
+ guard.giveBack(person, operation, ticket ?? void 0);
535
+ }
536
+ },
537
+ audit: (event, fields) => {
538
+ securityLog.event(event, fields);
539
+ },
540
+ errors: remoteErrors(base, inputs.errors),
541
+ clock: base.clock,
542
+ random: base.random,
543
+ logger: base.logger,
544
+ digestHex: (algorithm, text) => createHash(algorithm).update(text, "utf8").digest("hex"),
545
+ langOf: (person) => answerLang(store.prefs.getPrefs(person).lang, ""),
546
+ directChat: inputs.directChat
547
+ };
548
+ return new RemoteAgents(ctx);
549
+ }
550
+
551
+ // packages/runtime/src/worker/features-review.ts
552
+ import {
553
+ GithubReview,
554
+ itemLabel,
555
+ pickLang,
556
+ redactText as redactText2,
557
+ ReviewHandoffAction,
558
+ routedReviewTurns
559
+ } from "@primusclaw/personal-agent";
560
+ import {
561
+ GatewayIntentReader,
562
+ GithubApi,
563
+ GithubDeviceFlow,
564
+ IdentityCredentialClient,
565
+ PublicPullReader
566
+ } from "@primusclaw/personal-agent-runtime";
567
+ var REVIEW_CARD_SWEEP_MS = 12e4;
568
+ function workCardPoster(base) {
569
+ const cards = base.store.assistantCards;
570
+ return async (conversation, owner, item, text) => {
571
+ const cardId = cards.addAssistantCard(owner, item.itemId, item.resultVersion, item.canAccept);
572
+ const watching = cards.autoReply(owner, item.itemId) !== null;
573
+ const model = { item, text, cardId, note: "", watch: false, watching, lang: pickLang(text, item.title) };
574
+ const messageId = await conversation.post({
575
+ body: { type: "view", view: { name: "workCard", model }, fallbackText: "" }
576
+ });
577
+ if (messageId)
578
+ cards.placeAssistantCard(cardId, {
579
+ activityId: messageId,
580
+ reference: conversation.ref.wire,
581
+ render: { kind: "work", title: itemLabel(item), lang: "zh" }
582
+ });
583
+ };
584
+ }
585
+ function reviewHost(base, inputs, afterTurn) {
586
+ const { router, subs } = inputs;
587
+ const chatOf = (sender, conversation, scope = "") => router().chat(sender, conversation, scope);
588
+ const host = {
589
+ startTurn: routedReviewTurns(
590
+ (request) => router().startTurn(request),
591
+ (request) => chatOf(request.sender, request.conversation, request.scope),
592
+ base.store,
593
+ (review, finalAnswer, outcome, asked) => afterTurn().afterTurn(review, finalAnswer, outcome, asked)
594
+ ),
595
+ onboard: (message, sender, conversation, scope) => router().onboarding.member(message, chatOf(sender, conversation, scope), {
596
+ text: message.text,
597
+ quote: "",
598
+ sent: "",
599
+ keep: false,
600
+ identity: true
601
+ }),
602
+ askLink: (person, conversation, lead) => router().ctx.credentials.askToLink(chatOf(person, conversation), lead),
603
+ connectIdentity: (person, conversation, lead) => router().ctx.credentials.connectIdentity(chatOf(person, conversation), lead),
604
+ admitReviews: (message, sender, count, modelKey) => router().admitReviews(
605
+ chatOf(sender, base.surface.conversation(message.conversation)),
606
+ message.id,
607
+ count,
608
+ modelKey
609
+ )
610
+ };
611
+ return subs === void 0 ? host : { ...host, reviewerReach: (userId) => subs.reachable(userId) };
612
+ }
613
+ function reviewDeps(base, inputs, host) {
614
+ const { settings: settings2, shape, clock, logger, securityLog } = base;
615
+ const review = settings2.githubReview;
616
+ const fetch = (url, init) => base.fetch(url, init);
617
+ return {
618
+ store: base.store,
619
+ claw: base.claw,
620
+ credentials: new IdentityCredentialClient({
621
+ baseUrl: review.credentialUrl,
622
+ clientId: settings2.exchange.clientId,
623
+ clientSecret: settings2.exchange.clientSecret,
624
+ issuer: settings2.exchange.issuer,
625
+ fetch
626
+ }),
627
+ device: new GithubDeviceFlow({ clientId: review.clientId, clock, fetch }),
628
+ pulls: new PublicPullReader(new GithubApi({ fetch }), logger),
629
+ intent: review.intentModel ? new GatewayIntentReader({
630
+ baseUrl: `${settings2.safeApiUrl}/llm-proxy/v1`,
631
+ model: review.intentModel,
632
+ logger,
633
+ fetch
634
+ }) : void 0,
635
+ surface: base.surface,
636
+ exchange: base.exchange,
637
+ clock,
638
+ logger,
639
+ errors: inputs.errors,
640
+ mask: (text) => redactText2(text).text,
641
+ guard: inputs.guard,
642
+ audit: (event, fields) => {
643
+ securityLog.event(event, fields);
644
+ },
645
+ host,
646
+ followWire: (asked) => shape.followWire(asked),
647
+ restoreRef: (stored) => shape.restoreRef(stored),
648
+ owners: review.owners,
649
+ installUrl: shape.installHintUrl,
650
+ defaultModel: settings2.models.review
651
+ };
652
+ }
653
+ function reviewParts(base, inputs, assistant) {
654
+ if (!base.settings.githubReview.enabled) return void 0;
655
+ const late = {};
656
+ const self = () => {
657
+ if (late.service === void 0) throw new Error("the review service was used before it was built");
658
+ return late.service;
659
+ };
660
+ const deps = reviewDeps(base, inputs, reviewHost(base, inputs, self));
661
+ const service = new GithubReview(deps, base.random, workCardPoster(base));
662
+ late.service = service;
663
+ const handoff = new ReviewHandoffAction(deps, {
664
+ review: service,
665
+ receipts: assistant.receipts,
666
+ understands: (userId) => assistant.chat.understands(userId),
667
+ reachable: (userId) => assistant.chat.reachable(userId)
668
+ });
669
+ base.logger.info("github review: on", {
670
+ owners: settings(base).owners.join(","),
671
+ requests: settings(base).intentModel ? "model then rules" : "rules"
672
+ });
673
+ return { service, handoff };
674
+ }
675
+ function settings(base) {
676
+ return base.settings.githubReview;
677
+ }
678
+
679
+ // packages/runtime/src/worker/features-switches.ts
680
+ import { own, pyStrip as pyStrip2 } from "@primusclaw/personal-agent";
681
+ function on(env, name) {
682
+ return (own(env, name) ?? "") === "1";
683
+ }
684
+ function notifyUrlFromEnv(proactive, raw) {
685
+ const url = pyStrip2(raw);
686
+ if (proactive && !url) {
687
+ throw new StartupError(
688
+ "PROACTIVE_ENABLED needs NOTIFY_WEBHOOK_URL (the address Claw sends this worker's events to)"
689
+ );
690
+ }
691
+ return proactive ? url : "";
692
+ }
693
+ function remotePushWanted(proactive, raw) {
694
+ return proactive && !["0", "false", "no", "off"].includes(pyStrip2(raw).toLowerCase());
695
+ }
696
+ function remoteWindowDefault(raw) {
697
+ return pyStrip2(raw).toLowerCase() === "chat" ? "chat" : "card";
698
+ }
699
+ function featureSwitches(env) {
700
+ const proactive = on(env, "PROACTIVE_ENABLED");
701
+ return {
702
+ brief: on(env, "BRIEF_ENABLED"),
703
+ schedules: on(env, "ASSISTANT_SCHEDULES_ENABLED"),
704
+ jobWatch: on(env, "ASSISTANT_JOB_WATCH_ENABLED"),
705
+ remoteAgents: on(env, "REMOTE_AGENTS_ENABLED"),
706
+ remotePush: remotePushWanted(proactive, env["REMOTE_PUSH_ENABLED"] ?? "1"),
707
+ remoteWindow: remoteWindowDefault(env["REMOTE_WINDOW_DEFAULT"] ?? "card"),
708
+ proactive,
709
+ notifyUrl: notifyUrlFromEnv(proactive, env["NOTIFY_WEBHOOK_URL"] ?? "")
710
+ };
711
+ }
712
+
713
+ // packages/runtime/src/worker/features-turns.ts
714
+ import {
715
+ ApprovalClicks,
716
+ ApprovalDecisions,
717
+ approvalTurnCards,
718
+ correlationId,
719
+ thumbsMessage,
720
+ turn as turn4,
721
+ turnApprovals
722
+ } from "@primusclaw/personal-agent";
723
+ function turnRunner(base, inputs) {
724
+ const { claw, clock, logger, store, metrics, plugins, settings: settings2, surface } = base;
725
+ const { style } = inputs;
726
+ const approvals = turnApprovals(store);
727
+ return {
728
+ lastAnswer: (credential, sessionId) => turn4.lastAnswer({ claw: claw.sessions, clock, log: logger, errors: inputs.errors }, credential, sessionId),
729
+ run(run, hooks) {
730
+ const engine = new turn4.TurnEngine({
731
+ claw: claw.sessions,
732
+ clock,
733
+ log: logger,
734
+ refusals: plugins.modelRefusalPolicy,
735
+ errors: inputs.errors,
736
+ publicBaseUrl: settings2.publicBaseUrl,
737
+ style: {
738
+ streamText: style.streamText,
739
+ suggestedReplies: style.suggestedReplies,
740
+ streamsIn: (kind) => style.streamsIn(kind)
741
+ },
742
+ approvals,
743
+ fetchFiles: async (files) => {
744
+ const got = await fetchAll(surface, files);
745
+ return [got.fetched, got.failed];
746
+ },
747
+ onFilesDropped: (count) => {
748
+ if (count > 0) metrics.filesDropped("session", count);
749
+ },
750
+ integrations: inputs.integrations,
751
+ cards: { ...approvalTurnCards, thumbs: () => thumbsMessage() }
752
+ });
753
+ return engine.run(run, hooks);
754
+ }
755
+ };
756
+ }
757
+ function stopCards(base) {
758
+ return new turn4.StopButtons({ clock: base.clock, random: base.random, log: base.logger });
759
+ }
760
+ function auditApproval(base) {
761
+ return (record) => {
762
+ base.securityLog.event("approval_answered", {
763
+ operation: "approval",
764
+ aad_object_id: record.userId,
765
+ session_id: record.sessionId || null,
766
+ approval_id: record.approvalId,
767
+ tool: record.tool,
768
+ decision: record.decision,
769
+ outcome: record.outcome,
770
+ status: record.status || null,
771
+ correlation_id: correlationId(record.sessionId, record.toolUseId)
772
+ });
773
+ };
774
+ }
775
+ function approvalClicks(base, guard, hooks) {
776
+ const { store, claw, exchange, logger } = base;
777
+ const decisions = new ApprovalDecisions({
778
+ store,
779
+ claw: claw.sessions,
780
+ exchange,
781
+ allowance: {
782
+ take: (userId, ticket, ids) => guard.take(userId, "approval", ticket, {
783
+ session_id: ids.sessionId || null,
784
+ approval_id: ids.approvalId,
785
+ tool: ids.tool,
786
+ correlation_id: correlationId(ids.sessionId, ids.toolUseId)
787
+ })?.text(),
788
+ giveBack: (userId, ticket) => {
789
+ guard.giveBack(userId, "approval", ticket);
790
+ }
791
+ },
792
+ audit: auditApproval(base),
793
+ logger,
794
+ onDenied: (userId, scope) => {
795
+ hooks.toolDenied(userId, scope);
796
+ }
797
+ });
798
+ return new ApprovalClicks(
799
+ decisions,
800
+ (sessionId) => store.reviewDelegation.isActingSession(sessionId),
801
+ (userId) => Promise.resolve(store.links.getKey(userId))
802
+ );
803
+ }
804
+
805
+ // packages/runtime/src/worker/features-w8.ts
806
+ import { createHash as createHash2 } from "node:crypto";
807
+ import {
808
+ chatCredentialOf,
809
+ DailyBrief,
810
+ FeedbackFlow,
811
+ FeedbackReporting,
812
+ FeedbackService,
813
+ FeedbackThumbs,
814
+ GroupContext,
815
+ noFeedbackSink,
816
+ Observer,
817
+ pyStr,
818
+ pyStrip as pyStrip3,
819
+ redactText as redactText3,
820
+ reportMessage,
821
+ turn as turn5,
822
+ withoutRule
823
+ } from "@primusclaw/personal-agent";
824
+ import { workerInfoFromEnv } from "@primusclaw/personal-agent-runtime";
825
+ function isObject(value) {
826
+ return typeof value === "object" && value !== null && !Array.isArray(value);
827
+ }
828
+ function listOf(value) {
829
+ return Array.isArray(value) ? value : [];
830
+ }
831
+ function briefMarkdown(brief) {
832
+ const zh = brief["lang"] === "zh";
833
+ const sep = zh ? "\uFF1A" : ": ";
834
+ const out = [`**${turn5.plain((zh ? "\u6BCF\u65E5\u7B80\u62A5 " : "Daily brief, ") + pyStr(brief["date"]))}**`];
835
+ const sections = listOf(brief["sections"]);
836
+ for (const section of sections) {
837
+ if (!isObject(section)) continue;
838
+ out.push(`**${turn5.plain(pyStr(section["title"]))}**${sep}${turn5.plain(pyStr(section["summary"]))}`);
839
+ const lines = listOf(section["lines"]);
840
+ out.push(...lines.slice(0, 5).map((line) => `- ${turn5.plain(pyStr(line))}`));
841
+ }
842
+ const needs = listOf(brief["needs_you"]).slice(0, 3).map((n) => pyStr(n));
843
+ if (needs.length) {
844
+ out.push((zh ? "**\u9700\u8981\u4F60**" : "**Needs you**") + sep, ...needs.map((n) => `- ${turn5.plain(n)}`));
845
+ } else out.push(zh ? "\u4ECA\u5929\u6CA1\u6709\u9700\u8981\u4F60\u5904\u7406\u7684\u4E8B\u3002" : "Nothing needs you today.");
846
+ return out.join("\n\n");
847
+ }
848
+ function feedbackService(base, mask2) {
849
+ const { store, claw, clock, logger, settings: settings2, plugins, env } = base;
850
+ return new FeedbackService({
851
+ reports: store.feedback,
852
+ links: store.links,
853
+ sessions: claw.sessions,
854
+ // (no sink configured: reports are only recorded, as the Python worker's with no FEEDBACK_REPO)
855
+ sink: plugins.feedbackSink === noFeedbackSink ? void 0 : plugins.feedbackSink,
856
+ clock,
857
+ log: logger,
858
+ mask: mask2,
859
+ turnText: {
860
+ withoutRule,
861
+ answerOf: (turnId, events) => {
862
+ const state = new turn5.TurnState(turnId);
863
+ for (const event of events) state.feed(event);
864
+ return pyStrip3(state.answer);
865
+ }
866
+ },
867
+ wording: { botName: "Clawy", channelName: base.shape.channelName },
868
+ publicBaseUrl: settings2.publicBaseUrl,
869
+ worker: workerInfoFromEnv(env, {
870
+ pluginId: settings2.claw.pluginId === null ? "" : String(settings2.claw.pluginId),
871
+ version: base.shape.version
872
+ }),
873
+ logs: base.chatLog
874
+ });
875
+ }
876
+ function w8Parts(base, options) {
877
+ const { store, claw, clock, logger, settings: settings2, plugins } = base;
878
+ const mask2 = (text) => redactText3(text).text;
879
+ const service = feedbackService(base, mask2);
880
+ const credential = (sender) => Promise.resolve(store.links.getKey(sender.id) ?? void 0);
881
+ const reporting = new FeedbackReporting({
882
+ service,
883
+ sessions: store.sessions,
884
+ assistant: claw.assistant,
885
+ assistantOn: options.assistantOn,
886
+ credential,
887
+ identity: plugins.identityLookup,
888
+ clock,
889
+ log: logger
890
+ });
891
+ const thumbs = new FeedbackThumbs({
892
+ reporting,
893
+ sessions: store.sessions,
894
+ claw: { sessions: claw.sessions, assistant: claw.assistant },
895
+ // A vote is cast as the person's chats run: someone bound but never linked has no key, and their turns run on the
896
+ // exchanged token, so a key-only vote was never recorded for them.
897
+ credential: chatCredentialOf(store.links, settings2.exchange.forChat ? base.exchange : void 0),
898
+ assistantOn: options.assistantOn,
899
+ sha256Hex: (text) => createHash2("sha256").update(text, "utf8").digest("hex"),
900
+ mask: mask2,
901
+ log: logger
902
+ });
903
+ const observer = new Observer({
904
+ observe: store.observe,
905
+ links: store.links,
906
+ assistant: claw.assistant,
907
+ users: [...settings2.observeUsers],
908
+ conversationOf: conversationFor(base),
909
+ pluginId: settings2.claw.pluginId ?? void 0,
910
+ log: logger
911
+ });
912
+ const groupContext = new GroupContext({
913
+ settings: settings2.groupContext,
914
+ clock,
915
+ mask: mask2,
916
+ off: store.groupContext,
917
+ log: logger
918
+ });
919
+ const brief = new DailyBrief({
920
+ enabled: options.briefEnabled,
921
+ links: store.links,
922
+ prefs: store.prefs,
923
+ triggers: claw.triggers,
924
+ assistant: claw.assistant,
925
+ assistantOn: options.assistantOn,
926
+ briefMarkdown,
927
+ log: logger
928
+ });
929
+ return {
930
+ service,
931
+ flow: new FeedbackFlow({ reports: store.feedback, reporting, service, log: logger }),
932
+ thumbs,
933
+ observer,
934
+ groupContext,
935
+ brief,
936
+ reportView: (userId, scope) => {
937
+ const view = service.reportView(userId, scope);
938
+ return reportMessage(view.promptId, view.group);
939
+ }
940
+ };
941
+ }
942
+
943
+ // packages/runtime/src/worker/features.ts
944
+ var SWEEP_MS = 6e4;
945
+ var ASSISTANT_ACTION = "assistant.action";
946
+ function recordingClaw(claw, made) {
947
+ const create = async (key, session) => {
948
+ const created = await claw.sessions.create(key, session);
949
+ made.push(created.sessionId);
950
+ return created;
951
+ };
952
+ const sessions = new Proxy(claw.sessions, {
953
+ get(target, prop) {
954
+ if (prop === "create") return create;
955
+ const value = Reflect.get(target, prop, target);
956
+ return typeof value === "function" ? value.bind(target) : value;
957
+ }
958
+ });
959
+ return new Proxy(claw, {
960
+ get(target, prop) {
961
+ return prop === "sessions" ? sessions : Reflect.get(target, prop, target);
962
+ }
963
+ });
964
+ }
965
+ var ON_BEHALF_PATH = "/primus-claw-agent/on-behalf";
966
+ function refuseMissing(base) {
967
+ const { settings: settings2, plugins } = base;
968
+ if (settings2.models.fallback !== "" && plugins.modelRefusalPolicy === noModelRefusalPolicy)
969
+ throw new StartupError(
970
+ "CLAWY_FALLBACK_MODEL is set, but no plugin says when a model refused (modelRefusalPolicy): the fallback would never be used"
971
+ );
972
+ if (settings2.onBehalfUsers.size > 0 && !plugins.routeExtensions.some((route) => route.method === "POST" && route.path === ON_BEHALF_PATH))
973
+ throw new StartupError(
974
+ `TEAMS_ON_BEHALF_USERS is set, but no plugin serves ${ON_BEHALF_PATH}: unset it or run with the plugin that does`
975
+ );
976
+ }
977
+ function listenForStops(router, service) {
978
+ router.ctx.onItemStopped((itemId) => {
979
+ service.itemStopped(itemId);
980
+ });
981
+ }
982
+ function held(c) {
983
+ return { confirmation_id: c.confirmationId, repo: c.repo, pr: c.pr, kind: c.kind, expires_at: c.expiresAt };
984
+ }
985
+ function lateHooks(get) {
986
+ return {
987
+ legacyTurn: (userId) => get().hasPersonalTurn(userId),
988
+ itemStopped: (itemId) => {
989
+ get().itemStopped(itemId);
990
+ },
991
+ toolDenied: (userId, scope) => {
992
+ const running = get().ctx.turns.of(chatTurnKey(userId, scope))[0];
993
+ if (running !== void 0) running.toolDenied = true;
994
+ },
995
+ runCommand: (text, sender, conversation, key) => {
996
+ const router = get();
997
+ return router.commands.run(text, router.chat(sender, conversation), key);
998
+ },
999
+ background: (userId) => get().ctx.credentials.background(userId),
1000
+ typed: (message) => get().handle(message)
1001
+ };
1002
+ }
1003
+ function routerDeps(base, built, errors) {
1004
+ const { settings: settings2, store, clock, plugins, securityLog, shape } = base;
1005
+ const { switches, assistant, proactive, remote, w8 } = built;
1006
+ const subs = assistant.subs;
1007
+ return {
1008
+ config: {
1009
+ publicBaseUrl: settings2.publicBaseUrl,
1010
+ botName: BOT_NAME,
1011
+ pluginId: settings2.claw.pluginId === null ? "" : String(settings2.claw.pluginId),
1012
+ model: settings2.models.chat,
1013
+ reviewModel: settings2.models.review,
1014
+ fallbackModel: settings2.models.fallback,
1015
+ exchangeForChat: settings2.exchange.forChat,
1016
+ briefEnabled: switches.brief,
1017
+ schedulesEnabled: switches.schedules,
1018
+ jobWatchEnabled: switches.jobWatch,
1019
+ ownThumbsMobile: shape.style.ownThumbsMobile
1020
+ },
1021
+ surface: base.surface,
1022
+ channel: { refOf: (stored) => shape.refOf(stored) },
1023
+ store,
1024
+ claw: base.claw,
1025
+ clock,
1026
+ random: base.random,
1027
+ logger: base.logger,
1028
+ metrics: base.metrics,
1029
+ securityEvent: (name, fields) => {
1030
+ securityLog.event(name, fields);
1031
+ },
1032
+ requestScope: base.requestScope,
1033
+ identity: plugins.identityLookup,
1034
+ keyRevoker: plugins.keyRevoker,
1035
+ exchange: base.exchange,
1036
+ limits: routerLimits(settings2.userLimits, clock),
1037
+ assistant: assistant.chat,
1038
+ remote,
1039
+ turns: turnRunner(base, { style: shape.style, errors, integrations: plugins.integrations }),
1040
+ stopCards: stopCards(base),
1041
+ proactive: proactiveHold(proactive),
1042
+ observing: w8.observer,
1043
+ groupHistory: w8.groupContext,
1044
+ github: built.review?.service,
1045
+ reviewStop: (text) => reviewStop(text),
1046
+ handoffs: built.review === void 0 ? [] : [REVIEW_HANDOFF],
1047
+ // (`review_for_other` only with the review service)
1048
+ // (Python: `pending_of(store.pending_github_confirmations(...))` with the review service, else none)
1049
+ channelContext: channelContextBuilder(
1050
+ store,
1051
+ (userId) => built.review === void 0 ? [] : pendingOf(store.githubConfirmations.pendingGithubConfirmations(userId).map(held))
1052
+ ),
1053
+ messageText: messageTextFor(shape.channelName),
1054
+ connectionsText: whoamiConnections(plugins.integrations),
1055
+ reportView: (userId, scope) => w8.reportView(userId, scope),
1056
+ note: noteFactory,
1057
+ subscriptions: subs === void 0 ? void 0 : { ensure: (u, credential) => subs.ensure(u, credential), remove: (u, key) => subs.remove(u, key) },
1058
+ handlers: built.handlers,
1059
+ integrations: plugins.integrations
1060
+ };
1061
+ }
1062
+ function featureTimers(base, built) {
1063
+ const { store, plugins } = base;
1064
+ const { release } = built.proactive;
1065
+ const subs = built.assistant.subs;
1066
+ const timers = [
1067
+ {
1068
+ name: "sweep_expired",
1069
+ // (pending keys nobody redeemed are deleted and revoked)
1070
+ everyMs: SWEEP_MS,
1071
+ runAtStart: false,
1072
+ run: async () => {
1073
+ for (const key of store.links.takeExpiredPending()) await plugins.keyRevoker.revoke(key);
1074
+ }
1075
+ },
1076
+ {
1077
+ name: "retry_feedback",
1078
+ // (reports that could not be filed are filed once they can be)
1079
+ everyMs: SWEEP_MS,
1080
+ runAtStart: false,
1081
+ run: async () => {
1082
+ await built.w8.service.delivery.replayPending();
1083
+ }
1084
+ },
1085
+ { name: "release_held", everyMs: SWEEP_MS, runAtStart: false, run: () => release.releaseDue() },
1086
+ {
1087
+ name: "sweep_group_context",
1088
+ // (a quiet group's recent messages are dropped once they are too old)
1089
+ everyMs: SWEEP_MS,
1090
+ runAtStart: false,
1091
+ run: () => {
1092
+ built.w8.groupContext.sweep();
1093
+ return Promise.resolve();
1094
+ }
1095
+ },
1096
+ {
1097
+ name: "resend_approval_cards",
1098
+ everyMs: SWEEP_MS,
1099
+ runAtStart: true,
1100
+ run: async () => {
1101
+ await release.resendUnsentApprovals();
1102
+ }
1103
+ }
1104
+ ];
1105
+ if (subs !== void 0) {
1106
+ timers.push({
1107
+ name: "mend_subscriptions",
1108
+ everyMs: UPGRADE_RETRY_SECONDS * 1e3,
1109
+ runAtStart: true,
1110
+ run: async () => {
1111
+ await subs.ensureAll();
1112
+ }
1113
+ });
1114
+ }
1115
+ const review = built.review?.service;
1116
+ if (review !== void 0) {
1117
+ timers.push({
1118
+ name: "sweep_review_cards",
1119
+ // (open review cards whose item is over show how it ended; first at start)
1120
+ everyMs: REVIEW_CARD_SWEEP_MS,
1121
+ runAtStart: true,
1122
+ run: () => sweepOnce(review)
1123
+ });
1124
+ }
1125
+ return timers;
1126
+ }
1127
+ async function sweepOnce(review) {
1128
+ const once = new AbortController();
1129
+ const swept = review.sweepCards(once.signal);
1130
+ once.abort();
1131
+ await swept;
1132
+ }
1133
+ function deliverer(base, built, get) {
1134
+ const { store, surface } = base;
1135
+ return async (userId, reference, event) => {
1136
+ if (event["type"] !== ASSISTANT_ACTION) return built.proactive.proactive.handle(userId, reference, event);
1137
+ const sender = {
1138
+ id: userId,
1139
+ name: store.members.memberName(userId) ?? "",
1140
+ email: "",
1141
+ channelUserId: store.members.channelIdOf(userId) ?? ""
1142
+ };
1143
+ const router = get();
1144
+ const conversation = surface.conversation(base.shape.refOf(reference));
1145
+ return built.assistant.actions.runAction(
1146
+ userId,
1147
+ event,
1148
+ (text) => router.runCommand(text, router.chat(sender, conversation))
1149
+ );
1150
+ };
1151
+ }
1152
+ function gateOf(built, base, made) {
1153
+ const subs = built.assistant.subs;
1154
+ const subscriptions = subs === void 0 ? void 0 : {
1155
+ ensure: (userId) => subs.ensure(userId),
1156
+ remove: (userId) => subs.remove(userId, base.store.links.getKey(userId)),
1157
+ hasAssistantTypes: (userId) => subs.hasAssistantTypes(userId)
1158
+ };
1159
+ return { subscriptions, madeSessions: () => [...made] };
1160
+ }
1161
+ function buildFeatures(given) {
1162
+ const switches = featureSwitches(given.env);
1163
+ refuseMissing(given);
1164
+ const made = [];
1165
+ const base = { ...given, claw: recordingClaw(given.claw, made) };
1166
+ const { settings: settings2, clock, securityLog, shape } = base;
1167
+ const late = {};
1168
+ const get = () => {
1169
+ if (late.router === void 0) throw new Error("a feature called the router before it was built");
1170
+ return late.router;
1171
+ };
1172
+ const hooks = lateHooks(get);
1173
+ const lateReview = {};
1174
+ const errors = new PublicErrorLog(base.logger, base.random);
1175
+ const guard = new Guardrails2(clock, (event, fields) => securityLog.event(event, fields), settings2.sensitiveLimits);
1176
+ const assistant = assistantParts(base, {
1177
+ style: shape.style,
1178
+ integrations: base.plugins.integrations,
1179
+ notifyUrl: switches.notifyUrl,
1180
+ hooks,
1181
+ reviewHandoff: (userId, event) => lateReview.handoff?.take(userId, event) ?? "dropped"
1182
+ });
1183
+ const proactive = proactiveParts(base, shape.style, assistant, errors, get);
1184
+ const reach = followReach(proactive, base);
1185
+ const remote = remoteAgents(base, { switches, guard, reach, errors, directChat: assistant.directChat, hooks });
1186
+ const w8 = w8Parts(base, { briefEnabled: switches.brief, assistantOn: (userId) => assistant.chat.on(userId) });
1187
+ const review = reviewParts(base, { guard, errors, router: get, subs: assistant.subs }, assistant);
1188
+ lateReview.handoff = review?.handoff;
1189
+ const reviewHandlers = review?.service.routeHandlers();
1190
+ const groupInterceptors = [
1191
+ contextInterceptor(w8.groupContext),
1192
+ w8.observer.interceptor,
1193
+ w8.flow.interceptor
1194
+ ];
1195
+ const handlers = {
1196
+ // (1:1: the review's typed answers, mode words and requests come before the feedback answer, as in Python)
1197
+ personalInterceptors: [...reviewHandlers?.personalInterceptors ?? [], w8.flow.interceptor],
1198
+ groupInterceptors,
1199
+ commands: [
1200
+ w8.brief,
1201
+ ...switches.remoteAgents ? [new TerminalApprovalsCommand(base.claw.remoteAgents)] : [],
1202
+ ...reviewHandlers?.commands ?? []
1203
+ ],
1204
+ clicks: [
1205
+ ...reviewHandlers?.clicks ?? [],
1206
+ ...assistant.clicks,
1207
+ approvalClicks(base, guard, hooks),
1208
+ remote.clickHandler,
1209
+ w8.flow.clicks,
1210
+ w8.thumbs.clicks,
1211
+ w8.observer.clicks
1212
+ ],
1213
+ votes: {
1214
+ vote: (route) => {
1215
+ w8.thumbs.onVote(route, route.vote);
1216
+ return Promise.resolve();
1217
+ }
1218
+ }
1219
+ };
1220
+ const parts = { switches, assistant, proactive, remote, w8, review, handlers };
1221
+ const router = new Router(routerDeps(base, parts, errors));
1222
+ late.router = router;
1223
+ groupInterceptors.push(router.group.reviewStopInterceptor(), ...reviewHandlers?.groupInterceptors ?? []);
1224
+ if (review !== void 0) listenForStops(router, review.service);
1225
+ return {
1226
+ router,
1227
+ deliverEvent: deliverer(base, parts, get),
1228
+ timers: featureTimers(base, parts),
1229
+ start: () => {
1230
+ remote.resume();
1231
+ review?.service.resume();
1232
+ return Promise.resolve();
1233
+ },
1234
+ stop: () => {
1235
+ assistant.receipts.stop();
1236
+ },
1237
+ gate: gateOf(parts, base, made),
1238
+ review: review?.service,
1239
+ groupContext: w8.groupContext
1240
+ };
1241
+ }
1242
+
1243
+ // packages/runtime/src/worker/http.ts
1244
+ import {
1245
+ bearerOf,
1246
+ bodyJson,
1247
+ clawEventsRoute,
1248
+ healthzRoute,
1249
+ linkRoute
1250
+ } from "@primusclaw/personal-agent-runtime";
1251
+ function extensionRoute(extension) {
1252
+ return {
1253
+ method: extension.method,
1254
+ path: extension.path,
1255
+ async handle(request) {
1256
+ const answer = await extension.handle({
1257
+ headers: request.headers,
1258
+ bearer: bearerOf(request),
1259
+ body: bodyJson(request)
1260
+ });
1261
+ return { status: answer.status, json: answer.body };
1262
+ }
1263
+ };
1264
+ }
1265
+ function workerRoutes(parts) {
1266
+ const routes = [
1267
+ healthzRoute,
1268
+ linkRoute(parts.store.links, async (key) => {
1269
+ try {
1270
+ await parts.claw.sessions.checkKey(key);
1271
+ return true;
1272
+ } catch {
1273
+ return false;
1274
+ }
1275
+ })
1276
+ ];
1277
+ if (parts.proactive) {
1278
+ routes.push(
1279
+ clawEventsRoute({
1280
+ notifySubs: parts.store.notifySubs,
1281
+ links: parts.store.links,
1282
+ references: parts.store.references,
1283
+ claims: parts.store.idempotency,
1284
+ deliver: parts.deliverEvent,
1285
+ clock: parts.clock,
1286
+ gone: parts.gone,
1287
+ metrics: parts.metrics,
1288
+ logger: parts.logger
1289
+ })
1290
+ );
1291
+ }
1292
+ return [...routes, ...parts.plugins.routeExtensions.map(extensionRoute)];
1293
+ }
1294
+ function metricsRoutes(render) {
1295
+ return [
1296
+ {
1297
+ method: "GET",
1298
+ path: "/metrics",
1299
+ handle: () => Promise.resolve({ status: 200, text: render(), contentType: "text/plain; version=0.0.4" })
1300
+ }
1301
+ ];
1302
+ }
1303
+
1304
+ // packages/runtime/src/worker/plugins.ts
1305
+ import {
1306
+ noFeedbackSink as noFeedbackSink2,
1307
+ noIdentityLookup,
1308
+ noKeyRevoker
1309
+ } from "@primusclaw/personal-agent";
1310
+ import {
1311
+ feedbackConfigFromEnv,
1312
+ feedbackSink,
1313
+ HttpIdentityLookup,
1314
+ HttpKeyRevoker
1315
+ } from "@primusclaw/personal-agent-runtime";
1316
+ function platformPlugins(plugins, deps) {
1317
+ const { env, settings: settings2, secrets, logger } = deps;
1318
+ const identityLookup = plugins.identityLookup === noIdentityLookup ? new HttpIdentityLookup(settings2.safeApiUrl, (url, init) => deps.fetch(url, init), void 0, {
1319
+ clawApiUrl: settings2.clawApiUrl,
1320
+ logger
1321
+ }) : plugins.identityLookup;
1322
+ const keyRevoker = plugins.keyRevoker === noKeyRevoker ? new HttpKeyRevoker(settings2.safeApiUrl, (url, init) => deps.fetch(url, init)) : plugins.keyRevoker;
1323
+ const config = feedbackConfigFromEnv(env, secrets.get("FEEDBACK_GITHUB_APP_KEY") ?? "");
1324
+ const sink = plugins.feedbackSink === noFeedbackSink2 ? feedbackSink(config, { fetch: (url, init) => deps.fetch(url, init), clock: deps.now, log: logger }) ?? noFeedbackSink2 : plugins.feedbackSink;
1325
+ if (sink === noFeedbackSink2) logger.info("feedback: not configured; reports are stored only");
1326
+ else if (plugins.feedbackSink === noFeedbackSink2)
1327
+ logger.info("feedback: issues go to the configured repository", { repo: config.repo });
1328
+ return { ...plugins, identityLookup, keyRevoker, feedbackSink: sink };
1329
+ }
1330
+
1331
+ // packages/runtime/src/worker/runner.ts
1332
+ import { errorName as errorName3 } from "@primusclaw/personal-agent";
1333
+ import { listen } from "@primusclaw/personal-agent-runtime";
1334
+
1335
+ // packages/runtime/src/worker/timers.ts
1336
+ import { errorName as errorName2 } from "@primusclaw/personal-agent";
1337
+ async function loop(timer, clock, logger, signal) {
1338
+ let first = true;
1339
+ while (!signal.aborted) {
1340
+ if (!(first && timer.runAtStart)) {
1341
+ try {
1342
+ await clock.sleep(timer.everyMs, signal);
1343
+ } catch {
1344
+ return;
1345
+ }
1346
+ }
1347
+ first = false;
1348
+ try {
1349
+ await timer.run();
1350
+ } catch (error) {
1351
+ logger.error("a background task failed", { task: timer.name, error: errorName2(error) });
1352
+ }
1353
+ }
1354
+ }
1355
+ async function startTimers(timers, clock, logger, signal) {
1356
+ await Promise.all(timers.map((timer) => loop(timer, clock, logger, signal)));
1357
+ }
1358
+
1359
+ // packages/runtime/src/worker/runner.ts
1360
+ function waitFor(signal) {
1361
+ return new Promise((resolve) => {
1362
+ if (signal.aborted) resolve();
1363
+ else
1364
+ signal.addEventListener(
1365
+ "abort",
1366
+ () => {
1367
+ resolve();
1368
+ },
1369
+ { once: true }
1370
+ );
1371
+ });
1372
+ }
1373
+ async function listenMetrics(parts) {
1374
+ try {
1375
+ await listen(parts.metricsApp, "0.0.0.0", parts.metricsPort);
1376
+ } catch (error) {
1377
+ parts.logger.error("metrics: GET /metrics could not be served; the worker goes on without it", {
1378
+ port: parts.metricsPort,
1379
+ error: errorName3(error)
1380
+ });
1381
+ }
1382
+ }
1383
+ async function closeAll(logger, closes) {
1384
+ for (const close of closes) {
1385
+ try {
1386
+ await close();
1387
+ } catch (error) {
1388
+ logger.error("a part of the worker could not be closed", { error: errorName3(error) });
1389
+ }
1390
+ }
1391
+ }
1392
+ function runner(parts) {
1393
+ const stopped = new AbortController();
1394
+ return {
1395
+ async run() {
1396
+ await listen(parts.app, parts.host, parts.port);
1397
+ await listenMetrics(parts);
1398
+ await parts.start();
1399
+ const timers = startTimers(parts.timers, parts.clock, parts.logger, stopped.signal);
1400
+ try {
1401
+ await (parts.consumer ? parts.consumer.run() : waitFor(stopped.signal));
1402
+ } finally {
1403
+ stopped.abort();
1404
+ await timers;
1405
+ await closeAll(parts.logger, [() => parts.app.close(), () => parts.metricsApp.close(), () => parts.close()]);
1406
+ }
1407
+ },
1408
+ stop() {
1409
+ parts.consumer?.stop();
1410
+ stopped.abort();
1411
+ return Promise.resolve();
1412
+ }
1413
+ };
1414
+ }
1415
+
1416
+ // packages/runtime/src/worker/worker-services.ts
1417
+ import {
1418
+ errorName as errorName4
1419
+ } from "@primusclaw/personal-agent";
1420
+ function workerServices(parts) {
1421
+ const { store, surface, securityLog, logger } = parts;
1422
+ const late = {};
1423
+ const tasks = /* @__PURE__ */ new Set();
1424
+ const router = () => {
1425
+ if (late.router === void 0)
1426
+ throw new Error("the worker is not assembled yet: a plugin called it while it was built");
1427
+ return late.router;
1428
+ };
1429
+ const services = {
1430
+ channelUsersOf: (clawUserId) => store.links.usersForClawUser(clawUserId),
1431
+ clawUserOf: (userId) => store.links.clawUserIdOf(userId) ?? void 0,
1432
+ hasKey: (userId) => store.links.getKey(userId) !== null,
1433
+ conversationOf: (userId) => {
1434
+ const stored = store.references.getReference(userId);
1435
+ return stored === null ? void 0 : parts.restoreRef(stored);
1436
+ },
1437
+ knownPeople: () => store.members.knownMembers().map((m) => ({ name: m.name, objectId: m.objectId })),
1438
+ post: (conversation, text) => surface.conversation(conversation).post({ body: { type: "text", text } }),
1439
+ async handleAsTyped(conversation, userId, messageId, text) {
1440
+ const read = parts.typedEvent(conversation, messageId, text);
1441
+ if (read?.type !== "message" || read.sender.id !== userId) {
1442
+ logger.warn("a message sent on someone's behalf could not be read as theirs; not handled");
1443
+ return;
1444
+ }
1445
+ await router().handle({ ...read, provenance: "on_behalf" });
1446
+ },
1447
+ spawn(task) {
1448
+ router();
1449
+ const running = task().catch((error) => {
1450
+ logger.error("a background task of a plugin failed", { error: errorName4(error) });
1451
+ });
1452
+ tasks.add(running);
1453
+ void running.finally(() => tasks.delete(running));
1454
+ },
1455
+ audit(fields) {
1456
+ securityLog.event("on_behalf_message", { ...fields, operation: "on_behalf" });
1457
+ },
1458
+ logger
1459
+ };
1460
+ return {
1461
+ services,
1462
+ bind(built) {
1463
+ late.router = built;
1464
+ },
1465
+ idle: async () => {
1466
+ while (tasks.size > 0) await Promise.all([...tasks]);
1467
+ }
1468
+ };
1469
+ }
1470
+
1471
+ // packages/runtime/src/worker/assemble.ts
1472
+ var MAX_BODY_BYTES = 4 * 1024 * 1024;
1473
+ function basics(name, options) {
1474
+ const clock = options.clock ?? systemClock;
1475
+ const write = (line) => {
1476
+ process.stderr.write(line + "\n");
1477
+ };
1478
+ const requestScope = alsRequestScope();
1479
+ const chatLog = new ChatLog(
1480
+ requestScope,
1481
+ (text) => redactText4(text).text,
1482
+ () => clock.epochMs() / 1e3
1483
+ );
1484
+ const inner = options.logger ?? lineLogger({ level: "info", now: () => clock.epochMs(), write });
1485
+ return {
1486
+ clock,
1487
+ logger: chatLog.logger(inner, `${name}_agent`),
1488
+ fetch: options.fetch ?? globalThis.fetch,
1489
+ requestScope,
1490
+ chatLog
1491
+ };
1492
+ }
1493
+ function withInboundStats(prometheus, stats) {
1494
+ return {
1495
+ eventDelivered: (eventType, handleSeconds, since) => {
1496
+ prometheus.eventDelivered(eventType, handleSeconds, since);
1497
+ },
1498
+ securityEvent: (record) => {
1499
+ prometheus.securityEvent(record);
1500
+ },
1501
+ processed: (lagMs, handleMs, ok) => {
1502
+ stats.processed(lagMs, handleMs, ok);
1503
+ },
1504
+ limited: (reason) => {
1505
+ stats.limited(reason);
1506
+ },
1507
+ filesDropped: (path, count) => {
1508
+ prometheus.filesDropped(path, count);
1509
+ }
1510
+ };
1511
+ }
1512
+ async function envSecrets(env, names) {
1513
+ const source = secretsSourceOf(env);
1514
+ if (source !== "env") throw new SecretsUnavailable(`SECRETS_SOURCE=${source} is not one this surface reads`);
1515
+ return new EnvSecretSource(env).load([...names]);
1516
+ }
1517
+ async function assemblyBase(env, prepared, deps) {
1518
+ const names = wantedSecrets(env);
1519
+ const secrets = await (prepared.loadSecrets ? prepared.loadSecrets(names, deps) : envSecrets(env, names));
1520
+ const settings2 = readSettings(env, secrets);
1521
+ const configured = prepared.configure(settings2);
1522
+ const prometheus = new PrometheusMetrics(deps.clock);
1523
+ const metrics = withInboundStats(prometheus, new InboundStats(deps.clock, deps.logger, prometheus));
1524
+ const securityLog = new SecurityLog(deps.logger, metrics, deps.requestScope);
1525
+ const store = openWorkerStore(settings2, {
1526
+ securityEvent: (event, fields) => securityLog.event(event, fields),
1527
+ logger: deps.logger,
1528
+ clock: deps.clock,
1529
+ random: cryptoRandom
1530
+ });
1531
+ const claw = createClawClient({
1532
+ baseUrl: settings2.clawApiUrl,
1533
+ clock: deps.clock,
1534
+ logger: deps.logger,
1535
+ pluginId: settings2.claw.pluginId,
1536
+ model: settings2.models.chat,
1537
+ ruleToolId: settings2.claw.ruleToolId,
1538
+ clientLabel: settings2.claw.clientLabel,
1539
+ fetch: (url, init) => deps.fetch(url, init)
1540
+ });
1541
+ const shape = configured.shape;
1542
+ return { secrets, settings: settings2, configured, shape, metrics, prometheus, securityLog, store, claw };
1543
+ }
1544
+ function withRegistered(integrations, register) {
1545
+ if (register === void 0) return integrations;
1546
+ const registry = integrationRegistry();
1547
+ for (const [name, shown] of integrations.mcpServers) {
1548
+ registry.addMcpServer(name, shown, { query: integrations.queryServers.has(name) });
1549
+ }
1550
+ for (const line of integrations.connectionLines) registry.addConnectionLine(line);
1551
+ register(registry);
1552
+ return registry;
1553
+ }
1554
+ function pluginsOf(given, env, parts, services, deps) {
1555
+ const built = typeof given === "function" ? neutralPlugins(given(services)) : given;
1556
+ const own2 = { ...built, integrations: withRegistered(built.integrations, deps.registerIntegrations) };
1557
+ const plugins = platformPlugins(own2, {
1558
+ env,
1559
+ settings: parts.settings,
1560
+ secrets: parts.secrets,
1561
+ fetch: deps.fetch,
1562
+ now: () => deps.clock.epochMs() / 1e3,
1563
+ logger: deps.logger
1564
+ });
1565
+ const exchange = parts.settings.exchange.enabled ? new HttpTokenExchange(parts.settings.exchange, deps.clock, deps.fetch) : plugins.tokenExchange;
1566
+ return { plugins, exchange };
1567
+ }
1568
+ async function assembleWorker(adapter, env, plugins, options = {}) {
1569
+ const deps = basics(adapter.name, options);
1570
+ const prepared = adapter.prepare(env);
1571
+ const parts = await assemblyBase(env, prepared, deps);
1572
+ const opened = parts.configured.open({ ...deps, random: cryptoRandom });
1573
+ const surface = opened.surface;
1574
+ const bound = workerServices({
1575
+ ...parts,
1576
+ surface,
1577
+ logger: deps.logger,
1578
+ restoreRef: (stored) => parts.shape.restoreRef(stored),
1579
+ typedEvent: (conversation, messageId, text) => opened.typedEvent(conversation, messageId, text)
1580
+ });
1581
+ const resolved = pluginsOf(plugins, env, parts, bound.services, {
1582
+ ...deps,
1583
+ registerIntegrations: options.registerIntegrations
1584
+ });
1585
+ const base = { ...parts, ...deps, ...resolved, surface, random: cryptoRandom, env };
1586
+ const features = buildFeatures(base);
1587
+ bound.bind(features.router);
1588
+ const connected = opened.connect({
1589
+ route: (event) => features.router.handle(event),
1590
+ groupContext: features.groupContext,
1591
+ store: parts.store,
1592
+ exchange: resolved.exchange,
1593
+ gate: features.gate,
1594
+ metrics: parts.metrics,
1595
+ clock: deps.clock,
1596
+ logger: deps.logger
1597
+ });
1598
+ const routes = workerRoutes({
1599
+ store: base.store,
1600
+ claw: base.claw,
1601
+ clock: base.clock,
1602
+ metrics: base.metrics,
1603
+ logger: base.logger,
1604
+ plugins: base.plugins,
1605
+ proactive: (env["PROACTIVE_ENABLED"] ?? "") === "1",
1606
+ gone: base.settings.clawEventsGone,
1607
+ deliverEvent: features.deliverEvent
1608
+ });
1609
+ return runner({
1610
+ app: buildServer({
1611
+ routes: [...routes, ...connected.routes],
1612
+ maxBodyBytes: MAX_BODY_BYTES,
1613
+ accessLog: deps.logger,
1614
+ quietRoutes: [healthzRoute2.path]
1615
+ }),
1616
+ metricsApp: buildServer({
1617
+ routes: metricsRoutes(
1618
+ withBuildInfo(() => parts.prometheus.render(), buildInfoText(parts.shape.version, process.version))
1619
+ ),
1620
+ maxBodyBytes: 1024
1621
+ }),
1622
+ host: parts.configured.host,
1623
+ port: parts.settings.listenPort,
1624
+ metricsPort: parts.settings.metricsPort,
1625
+ consumer: connected.source,
1626
+ start: () => features.start(),
1627
+ timers: features.timers,
1628
+ clock: deps.clock,
1629
+ logger: deps.logger,
1630
+ close: () => closeAll(deps.logger, [
1631
+ () => {
1632
+ features.stop();
1633
+ },
1634
+ () => bound.idle(),
1635
+ ...opened.closes,
1636
+ () => {
1637
+ parts.store.close();
1638
+ }
1639
+ ])
1640
+ });
1641
+ }
1642
+
1643
+ // packages/runtime/src/worker/run-main.ts
1644
+ import { SecretsUnavailable as SecretsUnavailable2 } from "@primusclaw/personal-agent";
1645
+ async function runMain(build, write = (line) => process.stderr.write(line + "\n")) {
1646
+ let worker;
1647
+ try {
1648
+ worker = await build();
1649
+ } catch (error) {
1650
+ const why = error instanceof Error ? error.message : "the worker could not be built";
1651
+ if (error instanceof SecretsUnavailable2) {
1652
+ write(`${(/* @__PURE__ */ new Date()).toISOString()} CRITICAL secrets: ${why}; the worker does not start without them`);
1653
+ return 2;
1654
+ }
1655
+ write(`${(/* @__PURE__ */ new Date()).toISOString()} CRITICAL the worker does not start: ${why}`);
1656
+ return 1;
1657
+ }
1658
+ const stop = () => {
1659
+ void worker.stop();
1660
+ };
1661
+ process.once("SIGTERM", stop);
1662
+ process.once("SIGINT", stop);
1663
+ await worker.run();
1664
+ return 0;
1665
+ }
1666
+ export {
1667
+ ASSISTANT_ACTION,
1668
+ BUILD_INFO_METRIC,
1669
+ ON_BEHALF_PATH,
1670
+ SWEEP_MS,
1671
+ StartupError,
1672
+ assembleWorker,
1673
+ buildFeatures,
1674
+ buildInfoText,
1675
+ envSecrets,
1676
+ platformPlugins,
1677
+ remoteAskCard,
1678
+ runMain,
1679
+ withBuildInfo,
1680
+ withInboundStats,
1681
+ withRegistered,
1682
+ workCardPoster,
1683
+ workerServices
1684
+ };