forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinProcessRunner.ts
More file actions
1552 lines (1441 loc) · 52.3 KB
/
Copy pathinProcessRunner.ts
File metadata and controls
1552 lines (1441 loc) · 52.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* In-process teammate runner
*
* Wraps runAgent() for in-process teammates, providing:
* - AsyncLocalStorage-based context isolation via runWithTeammateContext()
* - Progress tracking and AppState updates
* - Idle notification to leader when complete
* - Plan mode approval flow support
* - Cleanup on completion or abort
*/
import { feature } from 'bun:bundle'
import type { ContentBlockParam } from '@anthropic-ai/sdk/resources/messages.mjs'
import { getSystemPrompt } from '../../constants/prompts.js'
import { TEAMMATE_MESSAGE_TAG } from '../../constants/xml.js'
import type { CanUseToolFn } from '../../hooks/useCanUseTool.js'
import {
processMailboxPermissionResponse,
registerPermissionCallback,
unregisterPermissionCallback,
} from '../../hooks/useSwarmPermissionPoller.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from '../../services/analytics/index.js'
import { getAutoCompactThreshold } from '../../services/compact/autoCompact.js'
import {
buildPostCompactMessages,
compactConversation,
ERROR_MESSAGE_USER_ABORT,
} from '../../services/compact/compact.js'
import { resetMicrocompactState } from '../../services/compact/microCompact.js'
import type { AppState } from '../../state/AppState.js'
import type { Tool, ToolUseContext } from '../../Tool.js'
import { appendTeammateMessage } from '../../tasks/InProcessTeammateTask/InProcessTeammateTask.js'
import type {
InProcessTeammateTaskState,
TeammateIdentity,
} from '../../tasks/InProcessTeammateTask/types.js'
import { appendCappedMessage } from '../../tasks/InProcessTeammateTask/types.js'
import {
createActivityDescriptionResolver,
createProgressTracker,
getProgressUpdate,
updateProgressFromMessage,
} from '../../tasks/LocalAgentTask/LocalAgentTask.js'
import type { CustomAgentDefinition } from '../../tools/AgentTool/loadAgentsDir.js'
import { runAgent } from '../../tools/AgentTool/runAgent.js'
import { awaitClassifierAutoApproval } from '../../tools/BashTool/bashPermissions.js'
import { BASH_TOOL_NAME } from '../../tools/BashTool/toolName.js'
import { SEND_MESSAGE_TOOL_NAME } from '../../tools/SendMessageTool/constants.js'
import { TASK_CREATE_TOOL_NAME } from '../../tools/TaskCreateTool/constants.js'
import { TASK_GET_TOOL_NAME } from '../../tools/TaskGetTool/constants.js'
import { TASK_LIST_TOOL_NAME } from '../../tools/TaskListTool/constants.js'
import { TASK_UPDATE_TOOL_NAME } from '../../tools/TaskUpdateTool/constants.js'
import { TEAM_CREATE_TOOL_NAME } from '../../tools/TeamCreateTool/constants.js'
import { TEAM_DELETE_TOOL_NAME } from '../../tools/TeamDeleteTool/constants.js'
import type { Message } from '../../types/message.js'
import type { PermissionDecision } from '../../types/permissions.js'
import {
createAssistantAPIErrorMessage,
createUserMessage,
} from '../../utils/messages.js'
import { evictTaskOutput } from '../../utils/task/diskOutput.js'
import { evictTerminalTask } from '../../utils/task/framework.js'
import { tokenCountWithEstimation } from '../../utils/tokens.js'
import { createAbortController } from '../abortController.js'
import { type AgentContext, runWithAgentContext } from '../agentContext.js'
import { count } from '../array.js'
import { logForDebugging } from '../debug.js'
import { cloneFileStateCache } from '../fileStateCache.js'
import {
SUBAGENT_REJECT_MESSAGE,
SUBAGENT_REJECT_MESSAGE_WITH_REASON_PREFIX,
} from '../messages.js'
import type { ModelAlias } from '../model/aliases.js'
import {
applyPermissionUpdates,
persistPermissionUpdates,
} from '../permissions/PermissionUpdate.js'
import type { PermissionUpdate } from '../permissions/PermissionUpdateSchema.js'
import { hasPermissionsToUseTool } from '../permissions/permissions.js'
import { emitTaskTerminatedSdk } from '../sdkEventQueue.js'
import { sleep } from '../sleep.js'
import { jsonStringify } from '../slowOperations.js'
import { asSystemPrompt } from '../systemPromptType.js'
import { claimTask, listTasks, type Task, updateTask } from '../tasks.js'
import type { TeammateContext } from '../teammateContext.js'
import { runWithTeammateContext } from '../teammateContext.js'
import {
createIdleNotification,
getLastPeerDmSummary,
isPermissionResponse,
isShutdownRequest,
markMessageAsReadByIndex,
readMailbox,
writeToMailbox,
} from '../teammateMailbox.js'
import { unregisterAgent as unregisterPerfettoAgent } from '../telemetry/perfettoTracing.js'
import { createContentReplacementState } from '../toolResultStorage.js'
import { TEAM_LEAD_NAME } from './constants.js'
import {
getLeaderSetToolPermissionContext,
getLeaderToolUseConfirmQueue,
} from './leaderPermissionBridge.js'
import {
createPermissionRequest,
sendPermissionRequestViaMailbox,
} from './permissionSync.js'
import { TEAMMATE_SYSTEM_PROMPT_ADDENDUM } from './teammatePromptAddendum.js'
type SetAppStateFn = (updater: (prev: AppState) => AppState) => void
const PERMISSION_POLL_INTERVAL_MS = 500
/**
* Creates a canUseTool function for in-process teammates that properly resolves
* 'ask' permissions via the UI rather than treating them as denials.
*
* Always uses the leader's ToolUseConfirm dialog with a worker badge when
* the bridge is available, giving teammates the same tool-specific UI
* (BashPermissionRequest, FileEditToolDiff, etc.) as the leader's own tools.
*
* Falls back to the mailbox system when the bridge is unavailable:
* sends a permission request to the leader's inbox, waits for the response
* in the teammate's own mailbox.
*/
function createInProcessCanUseTool(
identity: TeammateIdentity,
abortController: AbortController,
onPermissionWaitMs?: (waitMs: number) => void,
): CanUseToolFn {
return async (
tool,
input,
toolUseContext,
assistantMessage,
toolUseID,
forceDecision,
) => {
const result =
forceDecision ??
(await hasPermissionsToUseTool(
tool,
input,
toolUseContext,
assistantMessage,
toolUseID,
))
// Pass through allow/deny decisions directly
if (result.behavior !== 'ask') {
return result
}
// For bash commands, try classifier auto-approval before showing leader dialog.
// Agents await the classifier result (rather than racing it against user
// interaction like the main agent).
if (
feature('BASH_CLASSIFIER') &&
tool.name === BASH_TOOL_NAME &&
result.pendingClassifierCheck
) {
const classifierDecision = await awaitClassifierAutoApproval(
result.pendingClassifierCheck,
abortController.signal,
toolUseContext.options.isNonInteractiveSession,
)
if (classifierDecision) {
return {
behavior: 'allow',
updatedInput: input as Record<string, unknown>,
decisionReason: classifierDecision,
}
}
}
// Check if aborted before showing UI
if (abortController.signal.aborted) {
return { behavior: 'ask', message: SUBAGENT_REJECT_MESSAGE }
}
const appState = toolUseContext.getAppState()
const description = await (tool as Tool).description(input as never, {
isNonInteractiveSession: toolUseContext.options.isNonInteractiveSession,
toolPermissionContext: appState.toolPermissionContext,
tools: toolUseContext.options.tools,
})
if (abortController.signal.aborted) {
return { behavior: 'ask', message: SUBAGENT_REJECT_MESSAGE }
}
const setToolUseConfirmQueue = getLeaderToolUseConfirmQueue()
// Standard path: use ToolUseConfirm dialog with worker badge
if (setToolUseConfirmQueue) {
return new Promise<PermissionDecision>(resolve => {
let decisionMade = false
const permissionStartMs = Date.now()
// Report permission wait time to the caller so it can be
// subtracted from the displayed elapsed time.
const reportPermissionWait = () => {
onPermissionWaitMs?.(Date.now() - permissionStartMs)
}
const onAbortListener = () => {
if (decisionMade) return
decisionMade = true
reportPermissionWait()
resolve({ behavior: 'ask', message: SUBAGENT_REJECT_MESSAGE })
setToolUseConfirmQueue(queue =>
queue.filter(item => item.toolUseID !== toolUseID),
)
}
abortController.signal.addEventListener('abort', onAbortListener, {
once: true,
})
setToolUseConfirmQueue(queue => [
...queue,
{
assistantMessage,
tool: tool as Tool,
description,
input,
toolUseContext,
toolUseID,
permissionResult: result,
permissionPromptStartTimeMs: permissionStartMs,
workerBadge: identity.color
? { name: identity.agentName, color: identity.color }
: undefined,
onUserInteraction() {
// No-op for teammates (no classifier auto-approval)
},
onAbort() {
if (decisionMade) return
decisionMade = true
abortController.signal.removeEventListener(
'abort',
onAbortListener,
)
reportPermissionWait()
resolve({ behavior: 'ask', message: SUBAGENT_REJECT_MESSAGE })
},
async onAllow(
updatedInput: Record<string, unknown>,
permissionUpdates: PermissionUpdate[],
feedback?: string,
contentBlocks?: ContentBlockParam[],
) {
if (decisionMade) return
decisionMade = true
abortController.signal.removeEventListener(
'abort',
onAbortListener,
)
reportPermissionWait()
persistPermissionUpdates(permissionUpdates)
// Write back permission updates to the leader's shared context
if (permissionUpdates.length > 0) {
const setToolPermissionContext =
getLeaderSetToolPermissionContext()
if (setToolPermissionContext) {
const currentAppState = toolUseContext.getAppState()
const updatedContext = applyPermissionUpdates(
currentAppState.toolPermissionContext,
permissionUpdates,
)
// Preserve the leader's mode to prevent workers'
// transformed 'acceptEdits' context from leaking back
// to the coordinator
setToolPermissionContext(updatedContext, {
preserveMode: true,
})
}
}
const trimmedFeedback = feedback?.trim()
resolve({
behavior: 'allow',
updatedInput,
userModified: false,
acceptFeedback: trimmedFeedback || undefined,
...(contentBlocks &&
contentBlocks.length > 0 && { contentBlocks }),
})
},
onReject(feedback?: string, contentBlocks?: ContentBlockParam[]) {
if (decisionMade) return
decisionMade = true
abortController.signal.removeEventListener(
'abort',
onAbortListener,
)
reportPermissionWait()
const message = feedback
? `${SUBAGENT_REJECT_MESSAGE_WITH_REASON_PREFIX}${feedback}`
: SUBAGENT_REJECT_MESSAGE
resolve({ behavior: 'ask', message, contentBlocks })
},
async recheckPermission() {
if (decisionMade) return
const freshResult = await hasPermissionsToUseTool(
tool,
input,
toolUseContext,
assistantMessage,
toolUseID,
)
if (freshResult.behavior === 'allow') {
decisionMade = true
abortController.signal.removeEventListener(
'abort',
onAbortListener,
)
reportPermissionWait()
setToolUseConfirmQueue(queue =>
queue.filter(item => item.toolUseID !== toolUseID),
)
resolve({
...freshResult,
updatedInput: input,
userModified: false,
})
}
},
},
])
})
}
// Fallback: use mailbox system when leader UI queue is unavailable
return new Promise<PermissionDecision>(resolve => {
const request = createPermissionRequest({
toolName: (tool as Tool).name,
toolUseId: toolUseID,
input,
description,
permissionSuggestions: result.suggestions,
workerId: identity.agentId,
workerName: identity.agentName,
workerColor: identity.color,
teamName: identity.teamName,
})
// Register callback to be invoked when the leader responds
registerPermissionCallback({
requestId: request.id,
toolUseId: toolUseID,
onAllow(
updatedInput: Record<string, unknown> | undefined,
permissionUpdates: PermissionUpdate[],
_feedback?: string,
contentBlocks?: ContentBlockParam[],
) {
cleanup()
persistPermissionUpdates(permissionUpdates)
const finalInput =
updatedInput && Object.keys(updatedInput).length > 0
? updatedInput
: input
resolve({
behavior: 'allow',
updatedInput: finalInput,
userModified: false,
...(contentBlocks && contentBlocks.length > 0 && { contentBlocks }),
})
},
onReject(feedback?: string, contentBlocks?: ContentBlockParam[]) {
cleanup()
const message = feedback
? `${SUBAGENT_REJECT_MESSAGE_WITH_REASON_PREFIX}${feedback}`
: SUBAGENT_REJECT_MESSAGE
resolve({ behavior: 'ask', message, contentBlocks })
},
})
// Send request to leader's mailbox
void sendPermissionRequestViaMailbox(request)
// Poll teammate's mailbox for the response
const pollInterval = setInterval(
async (abortController, cleanup, resolve, identity, request) => {
if (abortController.signal.aborted) {
cleanup()
resolve({ behavior: 'ask', message: SUBAGENT_REJECT_MESSAGE })
return
}
const allMessages = await readMailbox(
identity.agentName,
identity.teamName,
)
for (let i = 0; i < allMessages.length; i++) {
const msg = allMessages[i]
if (msg && !msg.read) {
const parsed = isPermissionResponse(msg.text)
if (parsed && parsed.request_id === request.id) {
await markMessageAsReadByIndex(
identity.agentName,
identity.teamName,
i,
)
if (parsed.subtype === 'success') {
processMailboxPermissionResponse({
requestId: parsed.request_id,
decision: 'approved',
updatedInput: parsed.response?.updated_input,
permissionUpdates: parsed.response?.permission_updates,
})
} else {
processMailboxPermissionResponse({
requestId: parsed.request_id,
decision: 'rejected',
feedback: parsed.error,
})
}
return // Callback already resolves the promise
}
}
}
},
PERMISSION_POLL_INTERVAL_MS,
abortController,
cleanup,
resolve,
identity,
request,
)
const onAbortListener = () => {
cleanup()
resolve({ behavior: 'ask', message: SUBAGENT_REJECT_MESSAGE })
}
abortController.signal.addEventListener('abort', onAbortListener, {
once: true,
})
function cleanup() {
clearInterval(pollInterval)
unregisterPermissionCallback(request.id)
abortController.signal.removeEventListener('abort', onAbortListener)
}
})
}
}
/**
* Formats a message as <teammate-message> XML for injection into the conversation.
* This ensures the model sees messages in the same format as tmux teammates.
*/
function formatAsTeammateMessage(
from: string,
content: string,
color?: string,
summary?: string,
): string {
const colorAttr = color ? ` color="${color}"` : ''
const summaryAttr = summary ? ` summary="${summary}"` : ''
return `<${TEAMMATE_MESSAGE_TAG} teammate_id="${from}"${colorAttr}${summaryAttr}>\n${content}\n</${TEAMMATE_MESSAGE_TAG}>`
}
/**
* Configuration for running an in-process teammate.
*/
export type InProcessRunnerConfig = {
/** Teammate identity for context */
identity: TeammateIdentity
/** Task ID in AppState */
taskId: string
/** Initial prompt for the teammate */
prompt: string
/** Optional agent definition (for specialized agents) */
agentDefinition?: CustomAgentDefinition
/** Teammate context for AsyncLocalStorage */
teammateContext: TeammateContext
/** Parent's tool use context */
toolUseContext: ToolUseContext
/** Abort controller linked to parent */
abortController: AbortController
/** Optional model override for this teammate */
model?: string
/** Optional system prompt override for this teammate */
systemPrompt?: string
/** How to apply the system prompt: 'replace' or 'append' to default */
systemPromptMode?: 'default' | 'replace' | 'append'
/** Tool permissions to auto-allow for this teammate */
allowedTools?: string[]
/** Whether this teammate can show permission prompts for unlisted tools.
* When false (default), unlisted tools are auto-denied. */
allowPermissionPrompts?: boolean
/** Short description of the task (used as summary for the initial prompt header) */
description?: string
/** request_id of the API call that spawned this teammate, for lineage
* tracing on tengu_api_* events. */
invokingRequestId?: string
}
/**
* Result from running an in-process teammate.
*/
export type InProcessRunnerResult = {
/** Whether the run completed successfully */
success: boolean
/** Error message if failed */
error?: string
/** Messages produced by the agent */
messages: Message[]
}
/**
* Updates task state in AppState.
*/
function updateTaskState(
taskId: string,
updater: (task: InProcessTeammateTaskState) => InProcessTeammateTaskState,
setAppState: SetAppStateFn,
): void {
setAppState(prev => {
const task = prev.tasks[taskId]
if (!task || task.type !== 'in_process_teammate') {
return prev
}
const updated = updater(task)
if (updated === task) {
return prev
}
return {
...prev,
tasks: {
...prev.tasks,
[taskId]: updated,
},
}
})
}
/**
* Sends a message to the leader's file-based mailbox.
* Uses the same mailbox system as tmux teammates for consistency.
*/
async function sendMessageToLeader(
from: string,
text: string,
color: string | undefined,
teamName: string,
): Promise<void> {
await writeToMailbox(
TEAM_LEAD_NAME,
{
from,
text,
timestamp: new Date().toISOString(),
color,
},
teamName,
)
}
/**
* Sends idle notification to the leader via file-based mailbox.
* Uses agentName (not agentId) for consistency with process-based teammates.
*/
async function sendIdleNotification(
agentName: string,
agentColor: string | undefined,
teamName: string,
options?: {
idleReason?: 'available' | 'interrupted' | 'failed'
summary?: string
completedTaskId?: string
completedStatus?: 'resolved' | 'blocked' | 'failed'
failureReason?: string
},
): Promise<void> {
const notification = createIdleNotification(agentName, options)
await sendMessageToLeader(
agentName,
jsonStringify(notification),
agentColor,
teamName,
)
}
/**
* Find an available task from the team's task list.
* A task is available if it's pending, has no owner, and is not blocked.
*/
function findAvailableTask(tasks: Task[]): Task | undefined {
const unresolvedTaskIds = new Set(
tasks.filter(t => t.status !== 'completed').map(t => t.id),
)
return tasks.find(task => {
if (task.status !== 'pending') return false
if (task.owner) return false
return task.blockedBy.every(id => !unresolvedTaskIds.has(id))
})
}
/**
* Format a task as a prompt for the teammate to work on.
*/
function formatTaskAsPrompt(task: Task): string {
let prompt = `Complete all open tasks. Start with task #${task.id}: \n\n ${task.subject}`
if (task.description) {
prompt += `\n\n${task.description}`
}
return prompt
}
/**
* Try to claim an available task from the team's task list.
* Returns the formatted prompt if a task was claimed, or undefined if none available.
*/
async function tryClaimNextTask(
taskListId: string,
agentName: string,
): Promise<string | undefined> {
try {
const tasks = await listTasks(taskListId)
const availableTask = findAvailableTask(tasks)
if (!availableTask) {
return undefined
}
const result = await claimTask(taskListId, availableTask.id, agentName)
if (!result.success) {
logForDebugging(
`[inProcessRunner] Failed to claim task #${availableTask.id}: ${result.reason}`,
)
return undefined
}
// Also set status to in_progress so the UI reflects it immediately
await updateTask(taskListId, availableTask.id, { status: 'in_progress' })
logForDebugging(
`[inProcessRunner] Claimed task #${availableTask.id}: ${availableTask.subject}`,
)
return formatTaskAsPrompt(availableTask)
} catch (err) {
logForDebugging(`[inProcessRunner] Error checking task list: ${err}`)
return undefined
}
}
/**
* Result of waiting for messages.
*/
type WaitResult =
| {
type: 'shutdown_request'
request: ReturnType<typeof isShutdownRequest>
originalMessage: string
}
| {
type: 'new_message'
message: string
from: string
color?: string
summary?: string
}
| {
type: 'aborted'
}
/**
* Waits for new prompts or shutdown request.
* Polls the teammate's mailbox every 500ms, checking for:
* - Shutdown request from leader (returned to caller for model decision)
* - New messages/prompts from leader
* - Abort signal
*
* This keeps the teammate alive in 'idle' state instead of terminating.
* Does NOT auto-approve shutdown - the model should make that decision.
*/
async function waitForNextPromptOrShutdown(
identity: TeammateIdentity,
abortController: AbortController,
taskId: string,
getAppState: () => AppState,
setAppState: SetAppStateFn,
taskListId: string,
): Promise<WaitResult> {
const POLL_INTERVAL_MS = 500
logForDebugging(
`[inProcessRunner] ${identity.agentName} starting poll loop (abort=${abortController.signal.aborted})`,
)
let pollCount = 0
while (!abortController.signal.aborted) {
// Check for in-memory pending messages on every iteration (from transcript viewing)
const appState = getAppState()
const task = appState.tasks[taskId]
if (
task &&
task.type === 'in_process_teammate' &&
task.pendingUserMessages.length > 0
) {
const message = task.pendingUserMessages[0]! // Safe: checked length > 0
// Pop the message from the queue
setAppState(prev => {
const prevTask = prev.tasks[taskId]
if (!prevTask || prevTask.type !== 'in_process_teammate') {
return prev
}
return {
...prev,
tasks: {
...prev.tasks,
[taskId]: {
...prevTask,
pendingUserMessages: prevTask.pendingUserMessages.slice(1),
},
},
}
})
logForDebugging(
`[inProcessRunner] ${identity.agentName} found pending user message (poll #${pollCount})`,
)
return {
type: 'new_message',
message,
from: 'user',
}
}
// Wait before next poll (skip on first iteration to check immediately)
if (pollCount > 0) {
await sleep(POLL_INTERVAL_MS)
}
pollCount++
// Check for abort
if (abortController.signal.aborted) {
logForDebugging(
`[inProcessRunner] ${identity.agentName} aborted while waiting (poll #${pollCount})`,
)
return { type: 'aborted' }
}
// Check for messages in mailbox
logForDebugging(
`[inProcessRunner] ${identity.agentName} poll #${pollCount}: checking mailbox`,
)
try {
// Read all messages and scan unread for shutdown requests first.
// Shutdown requests are prioritized over regular messages to prevent
// starvation when peer-to-peer messages flood the queue.
const allMessages = await readMailbox(
identity.agentName,
identity.teamName,
)
// Scan all unread messages for shutdown requests (highest priority).
// readMailbox() already reads all messages from disk, so this scan
// adds only ~1-2ms of JSON parsing overhead.
let shutdownIndex = -1
let shutdownParsed: ReturnType<typeof isShutdownRequest> = null
for (let i = 0; i < allMessages.length; i++) {
const m = allMessages[i]
if (m && !m.read) {
const parsed = isShutdownRequest(m.text)
if (parsed) {
shutdownIndex = i
shutdownParsed = parsed
break
}
}
}
if (shutdownIndex !== -1) {
const msg = allMessages[shutdownIndex]!
const skippedUnread = count(
allMessages.slice(0, shutdownIndex),
m => !m.read,
)
logForDebugging(
`[inProcessRunner] ${identity.agentName} received shutdown request from ${shutdownParsed?.from} (prioritized over ${skippedUnread} unread messages)`,
)
await markMessageAsReadByIndex(
identity.agentName,
identity.teamName,
shutdownIndex,
)
return {
type: 'shutdown_request',
request: shutdownParsed,
originalMessage: msg.text,
}
}
// No shutdown request found. Prioritize team-lead messages over peer
// messages — the leader represents user intent and coordination, so
// their messages should not be starved behind peer-to-peer chatter.
// Fall back to FIFO for peer messages.
let selectedIndex = -1
// Check for unread team-lead messages first
for (let i = 0; i < allMessages.length; i++) {
const m = allMessages[i]
if (m && !m.read && m.from === TEAM_LEAD_NAME) {
selectedIndex = i
break
}
}
// Fall back to first unread message (any sender)
if (selectedIndex === -1) {
selectedIndex = allMessages.findIndex(m => !m.read)
}
if (selectedIndex !== -1) {
const msg = allMessages[selectedIndex]
if (msg) {
logForDebugging(
`[inProcessRunner] ${identity.agentName} received new message from ${msg.from} (index ${selectedIndex})`,
)
await markMessageAsReadByIndex(
identity.agentName,
identity.teamName,
selectedIndex,
)
return {
type: 'new_message',
message: msg.text,
from: msg.from,
color: msg.color,
summary: msg.summary,
}
}
}
} catch (err) {
logForDebugging(
`[inProcessRunner] ${identity.agentName} poll error: ${err}`,
)
// Continue polling even if one read fails
}
// Check the team's task list for unclaimed tasks
const taskPrompt = await tryClaimNextTask(taskListId, identity.agentName)
if (taskPrompt) {
return {
type: 'new_message',
message: taskPrompt,
from: 'task-list',
}
}
}
logForDebugging(
`[inProcessRunner] ${identity.agentName} exiting poll loop (abort=${abortController.signal.aborted}, polls=${pollCount})`,
)
return { type: 'aborted' }
}
/**
* Runs an in-process teammate with a continuous prompt loop.
*
* Executes runAgent() within the teammate's AsyncLocalStorage context,
* tracks progress, updates task state, sends idle notification on completion,
* then waits for new prompts or shutdown requests.
*
* Unlike background tasks, teammates stay alive and can receive multiple prompts.
* The loop only exits on abort or after shutdown is approved by the model.
*
* @param config - Runner configuration
* @returns Result with messages and success status
*/
export async function runInProcessTeammate(
config: InProcessRunnerConfig,
): Promise<InProcessRunnerResult> {
const {
identity,
taskId,
prompt,
description,
agentDefinition,
teammateContext,
toolUseContext,
abortController,
model,
systemPrompt,
systemPromptMode,
allowedTools,
allowPermissionPrompts,
invokingRequestId,
} = config
const { setAppState } = toolUseContext
logForDebugging(
`[inProcessRunner] Starting agent loop for ${identity.agentId}`,
)
// Create AgentContext for analytics attribution
const agentContext: AgentContext = {
agentId: identity.agentId,
parentSessionId: identity.parentSessionId,
agentName: identity.agentName,
teamName: identity.teamName,
agentColor: identity.color,
planModeRequired: identity.planModeRequired,
isTeamLead: false,
agentType: 'teammate',
invokingRequestId,
invocationKind: 'spawn',
invocationEmitted: false,
}
// Build system prompt based on systemPromptMode
let teammateSystemPrompt: string
if (systemPromptMode === 'replace' && systemPrompt) {
teammateSystemPrompt = systemPrompt
} else {
const fullSystemPromptParts = await getSystemPrompt(
toolUseContext.options.tools,
toolUseContext.options.mainLoopModel,
undefined,
toolUseContext.options.mcpClients,
)
const systemPromptParts = [
...fullSystemPromptParts,
TEAMMATE_SYSTEM_PROMPT_ADDENDUM,
]
// If custom agent definition provided, append its prompt
if (agentDefinition) {
const customPrompt = agentDefinition.getSystemPrompt()
if (customPrompt) {
systemPromptParts.push(`\n# Custom Agent Instructions\n${customPrompt}`)
}
// Log agent memory loaded event for in-process teammates
if (agentDefinition.memory) {
logEvent('tengu_agent_memory_loaded', {
...(process.env.USER_TYPE === 'ant'
? {
agent_type:
agentDefinition.agentType as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}
: {}),
scope:
agentDefinition.memory as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
source:
'in-process-teammate' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
}
}
// Append mode: add provided system prompt after default
if (systemPromptMode === 'append' && systemPrompt) {
systemPromptParts.push(systemPrompt)
}
teammateSystemPrompt = systemPromptParts.join('\n')
}
// Resolve agent definition - use full system prompt with teammate addendum
// IMPORTANT: Set permissionMode to 'default' so teammates always get full tool
// access regardless of the leader's permission mode.
const resolvedAgentDefinition: CustomAgentDefinition = {
agentType: identity.agentName,
whenToUse: `In-process teammate: ${identity.agentName}`,
getSystemPrompt: () => teammateSystemPrompt,
// Inject team-essential tools so teammates can always respond to
// shutdown requests, send messages, and coordinate via the task list,
// even with explicit tool lists
tools: agentDefinition?.tools
? [
...new Set([
...agentDefinition.tools,
SEND_MESSAGE_TOOL_NAME,
TEAM_CREATE_TOOL_NAME,
TEAM_DELETE_TOOL_NAME,
TASK_CREATE_TOOL_NAME,
TASK_GET_TOOL_NAME,
TASK_LIST_TOOL_NAME,
TASK_UPDATE_TOOL_NAME,
]),
]
: ['*'],
source: 'projectSettings',
permissionMode: 'default',
// Propagate model from custom agent definition so getAgentModel()
// can use it as a fallback when no tool-level model is specified
...(agentDefinition?.model ? { model: agentDefinition.model } : {}),