@ouro.bot/cli 0.1.0-alpha.674 → 0.1.0-alpha.676

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.
Files changed (63) hide show
  1. package/README.md +11 -5
  2. package/changelog.json +19 -0
  3. package/dist/arc/evolution.js +13 -10
  4. package/dist/arc/obligations.js +1 -1
  5. package/dist/heart/active-work.js +3 -3
  6. package/dist/heart/agent-entry.js +8 -8
  7. package/dist/heart/commitments.js +1 -1
  8. package/dist/heart/core.js +45 -23
  9. package/dist/heart/daemon/agent-config-check.js +24 -0
  10. package/dist/heart/daemon/agent-discovery.js +28 -17
  11. package/dist/heart/daemon/agent-service.js +6 -6
  12. package/dist/heart/daemon/await-private-wake.js +59 -0
  13. package/dist/heart/daemon/cli-exec.js +180 -24
  14. package/dist/heart/daemon/cli-help.js +20 -2
  15. package/dist/heart/daemon/cli-parse.js +45 -2
  16. package/dist/heart/daemon/cli-render.js +1 -0
  17. package/dist/heart/daemon/daemon-entry.js +122 -25
  18. package/dist/heart/daemon/daemon.js +223 -20
  19. package/dist/heart/daemon/habit-private-wake.js +56 -0
  20. package/dist/heart/daemon/inner-status.js +3 -3
  21. package/dist/heart/daemon/message-router.js +39 -3
  22. package/dist/heart/daemon/pulse.js +43 -7
  23. package/dist/heart/daemon/socket-client.js +14 -2
  24. package/dist/heart/daemon/startup-tui.js +9 -1
  25. package/dist/heart/daemon/thoughts.js +39 -39
  26. package/dist/heart/habits/habit-scheduler.js +24 -4
  27. package/dist/heart/mailbox/mailbox-view.js +1 -1
  28. package/dist/heart/mailbox/readers/agent-machine.js +7 -7
  29. package/dist/heart/primitives.js +1 -1
  30. package/dist/heart/private-runtime/decision-renderer.js +156 -0
  31. package/dist/heart/private-runtime/index.js +18 -0
  32. package/dist/heart/private-runtime/ledger.js +218 -0
  33. package/dist/heart/private-runtime/policy.js +205 -0
  34. package/dist/heart/private-runtime/types.js +2 -0
  35. package/dist/heart/progress-story.js +1 -1
  36. package/dist/heart/session-transcript.js +1 -1
  37. package/dist/heart/tool-activity-callbacks.js +1 -1
  38. package/dist/heart/tool-description.js +2 -2
  39. package/dist/heart/tool-loop.js +2 -2
  40. package/dist/heart/turn-context.js +5 -5
  41. package/dist/mailbox-ui/assets/index-J8zDwHmE.js +1 -0
  42. package/dist/mailbox-ui/index.html +1 -1
  43. package/dist/mailroom/attention.js +1 -1
  44. package/dist/mind/context.js +2 -2
  45. package/dist/mind/pending.js +12 -5
  46. package/dist/mind/prompt.js +32 -25
  47. package/dist/repertoire/coding/feedback.js +25 -4
  48. package/dist/repertoire/tools-awaiting.js +2 -2
  49. package/dist/repertoire/tools-flow.js +4 -4
  50. package/dist/repertoire/tools-record.js +1 -1
  51. package/dist/repertoire/tools-session.js +33 -67
  52. package/dist/repertoire/tools-surface.js +3 -3
  53. package/dist/senses/cli.js +2 -2
  54. package/dist/senses/inner-dialog-worker.js +13 -519
  55. package/dist/senses/inner-dialog.js +10 -961
  56. package/dist/senses/mail.js +21 -5
  57. package/dist/senses/pipeline.js +1 -1
  58. package/dist/senses/private-runtime-worker.js +578 -0
  59. package/dist/senses/private-runtime.js +1145 -0
  60. package/dist/senses/shared-turn.js +1 -1
  61. package/dist/senses/trust-gate.js +2 -2
  62. package/package.json +1 -1
  63. package/dist/mailbox-ui/assets/index-CaTIFDmv.js +0 -1
@@ -36,532 +36,26 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.HEARTBEAT_OK_REST_SUPPRESSION_MS = exports.HABIT_RECURSION_BURST_THRESHOLD = exports.HABIT_RECURSION_BURST_WINDOW_MS = exports.HABIT_RECURSION_MIN_INTERVAL_MS = exports.MAX_CONSECUTIVE_INSTINCT_TURNS = void 0;
37
37
  exports.createInnerDialogWorker = createInnerDialogWorker;
38
38
  exports.startInnerDialogWorker = startInnerDialogWorker;
39
- const fs = __importStar(require("fs"));
40
- const path = __importStar(require("path"));
41
- const inner_dialog_1 = require("./inner-dialog");
42
39
  const runtime_1 = require("../nerves/runtime");
43
- const identity_1 = require("../heart/identity");
44
- const pending_1 = require("../mind/pending");
45
- const habit_parser_1 = require("../heart/habits/habit-parser");
46
- const habit_runtime_state_1 = require("../heart/habits/habit-runtime-state");
47
- const habit_session_1 = require("../heart/habits/habit-session");
48
- const flight_recorder_1 = require("../arc/flight-recorder");
49
- const habit_session_summary_1 = require("../heart/habits/habit-session-summary");
50
- const friends_1 = require("@ouro.bot/friends");
51
- const tools_base_1 = require("../repertoire/tools-base");
52
- const tools_surface_1 = require("../repertoire/tools-surface");
53
- const tools_1 = require("../repertoire/tools");
54
- /**
55
- * Cap on consecutive `instinct` follow-on turns triggered by `hasPendingWork()`
56
- * with no externally-queued work in between. Without this cap, a turn that
57
- * writes anything back into the inner-dialog pending dir as a side effect of
58
- * processing (e.g. a surface tool routing a response) puts the worker into
59
- * a self-sustaining loop where the next turn's drain produces another write,
60
- * and so on. Real workflows rarely chain more than 2–3 instinct turns; an
61
- * external trigger (habit, poke, chat) resets the counter so legitimate
62
- * follow-on work is unaffected.
63
- *
64
- * Three feels right: legitimate cascading follow-ups (e.g. processing a
65
- * batch of delegated returns) get through; a true self-loop caps fast.
66
- */
40
+ const innerDialog = __importStar(require("./inner-dialog"));
41
+ const privateRuntimeWorker = __importStar(require("./private-runtime-worker"));
67
42
  exports.MAX_CONSECUTIVE_INSTINCT_TURNS = 3;
68
- /**
69
- * Habit recursion detector thresholds. The instinct cap above protects
70
- * against pending-dir self-loops; this protects against the *external*
71
- * IPC self-loop where heartbeat-shaped messages get re-issued faster
72
- * than their cadence — e.g. a hook misconfigured to repost on every
73
- * heartbeat, a daemon retry storm, or a stuck timer firing back-to-back.
74
- *
75
- * MIN_INTERVAL_MS — two of the same habit within this window is suspect
76
- * regardless of cadence (no realistic habit fires every few seconds).
77
- * BURST_THRESHOLD over BURST_WINDOW_MS catches slower runaways that stay
78
- * just under MIN_INTERVAL_MS.
79
- *
80
- * Detection is observation-only: it emits warn-level nerves events, it
81
- * does not drop the message. An operator (or follow-up auto-recovery)
82
- * decides what to do with the signal.
83
- */
84
43
  exports.HABIT_RECURSION_MIN_INTERVAL_MS = 5_000;
85
44
  exports.HABIT_RECURSION_BURST_WINDOW_MS = 60_000;
86
45
  exports.HABIT_RECURSION_BURST_THRESHOLD = 5;
87
46
  exports.HEARTBEAT_OK_REST_SUPPRESSION_MS = 20 * 60_000;
88
- function isHeartbeatOkRestResult(result) {
89
- if (!result || typeof result !== "object")
90
- return false;
91
- const maybeResult = result;
92
- return maybeResult.turnOutcome === "rested" && maybeResult.restStatus === "HEARTBEAT_OK";
93
- }
94
- function isRecord(value) {
95
- return !!value && typeof value === "object" && !Array.isArray(value);
96
- }
97
- function contentToText(content) {
98
- if (typeof content === "string")
99
- return content.trim();
100
- if (!Array.isArray(content))
101
- return "";
102
- return content
103
- .map((part) => isRecord(part) && typeof part.text === "string" ? part.text : "")
104
- .filter((text) => text.trim().length > 0)
105
- .join("\n")
106
- .trim();
107
- }
108
- function resultMessages(result) {
109
- if (Array.isArray(result))
110
- return result.flatMap((entry) => resultMessages(entry));
111
- return isRecord(result) && Array.isArray(result.messages) ? result.messages : [];
112
- }
113
- function latestAssistantText(results) {
114
- for (let resultIndex = results.length - 1; resultIndex >= 0; resultIndex--) {
115
- const messages = resultMessages(results[resultIndex]);
116
- for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex--) {
117
- const message = messages[messageIndex];
118
- if (!isRecord(message) || message.role !== "assistant")
119
- continue;
120
- const text = contentToText(message.content);
121
- if (text.length > 0)
122
- return text.replace(/^checkpoint\s*:\s*/i, "").trim() || text;
123
- }
124
- }
125
- return null;
126
- }
127
- function deriveHabitSummarySnapshot(habitRun) {
128
- const assistant = latestAssistantText(habitRun.results);
129
- if (assistant)
130
- return { summary: assistant, decisions: [], nextLikelyStep: null };
131
- if (habitRun.errors.length > 0) {
132
- return {
133
- summary: `Habit ${habitRun.habit.name} finished with errors: ${habitRun.errors.join("; ")}`,
134
- decisions: [],
135
- nextLikelyStep: null,
136
- };
137
- }
138
- const surfaced = habitRun.surfaceAttempts.find((attempt) => attempt.result !== "blocked" && attempt.result !== "failed" && attempt.result !== "unavailable");
139
- if (surfaced) {
140
- return {
141
- summary: `Habit ${habitRun.habit.name} surfaced via ${surfaced.recipient}/${surfaced.channel}.`,
142
- decisions: [],
143
- nextLikelyStep: null,
144
- };
145
- }
146
- const produced = habitRun.producedRefs.find((ref) => ref.kind !== "none");
147
- if (produced) {
148
- return {
149
- summary: `Habit ${habitRun.habit.name} produced ${produced.kind}: ${produced.locator}.`,
150
- decisions: [],
151
- nextLikelyStep: null,
152
- };
153
- }
154
- if (habitRun.results.some(isHeartbeatOkRestResult)) {
155
- return {
156
- summary: `Habit ${habitRun.habit.name} rested with HEARTBEAT_OK.`,
157
- decisions: [],
158
- nextLikelyStep: null,
159
- };
160
- }
161
- return {
162
- summary: `Habit ${habitRun.habit.name} completed without additional surfaced output.`,
163
- decisions: [],
164
- nextLikelyStep: null,
165
- };
166
- }
167
- function fallbackHabitFile(habitName) {
168
- return {
169
- name: habitName,
170
- title: habitName,
171
- cadence: null,
172
- status: "active",
173
- lastRun: null,
174
- created: null,
175
- tools: [],
176
- origin: null,
177
- surface: { family: false, originator: false, extra: [] },
178
- continuity: { mode: "fresh" },
179
- body: "",
180
- };
181
- }
182
- function readHabitForRun(agentRoot, habitName, errors) {
183
- const habitPath = path.join(agentRoot, "habits", `${habitName}.md`);
184
- try {
185
- return (0, habit_parser_1.parseHabitFile)(fs.readFileSync(habitPath, "utf-8"), habitPath);
186
- }
187
- catch (error) {
188
- const reason = error instanceof Error ? error.message : String(error);
189
- errors.push(`habit file could not be read: ${reason}`);
190
- (0, runtime_1.emitNervesEvent)({
191
- level: "warn",
192
- component: "senses",
193
- event: "senses.habit_file_read_error",
194
- message: "habit file could not be read for habit session",
195
- meta: { habitName, habitPath, reason },
196
- });
197
- return fallbackHabitFile(habitName);
198
- }
199
- }
200
- async function prepareHabitRun(habitName, trigger, startedAt) {
201
- const agentRoot = (0, identity_1.getAgentRoot)();
202
- const errors = [];
203
- const habit = (0, habit_runtime_state_1.applyHabitRuntimeState)(agentRoot, readHabitForRun(agentRoot, habitName, errors));
204
- const runId = (0, flight_recorder_1.createHabitRunId)(habitName, new Date(startedAt));
205
- const operationId = habit.continuity.mode === "stateful" ? `habit:${habit.name}` : null;
206
- const priorSessionSummary = readPriorSessionSummary(agentRoot, operationId);
207
- const paths = (0, habit_session_1.createHabitSessionPaths)(agentRoot, runId, habit.name);
208
- const friendStore = new friends_1.FileFriendStore(path.join(agentRoot, "friends"));
209
- const permissionEnvelope = await (0, habit_session_1.normalizeHabitPermissionEnvelope)(habit, { agentRoot, friendStore });
210
- const toolPolicy = (0, habit_session_1.filterHabitToolsForEnvelope)([...tools_base_1.baseToolDefinitions, tools_surface_1.surfaceToolDefinition], habit.tools ?? null, permissionEnvelope, riskProfileForHabitPolicy);
211
- return {
212
- agentRoot,
213
- habit,
214
- runId,
215
- operationId,
216
- trigger,
217
- startedAt,
218
- priorSessionSummary,
219
- paths,
220
- permissionEnvelope,
221
- toolPolicy,
222
- friendStore,
223
- results: [],
224
- errors,
225
- producedRefs: [],
226
- surfaceAttempts: [],
227
- };
228
- }
229
- function riskProfileForHabitPolicy(definition, name) {
230
- const probeArgs = name === "shell" ? { command: "touch /tmp/habit-policy-probe" } : {};
231
- return (0, tools_1.riskProfileForTool)(definition, name, probeArgs);
232
- }
233
- function readPriorSessionSummary(agentRoot, operationId) {
234
- if (operationId === null)
235
- return undefined;
236
- try {
237
- const summary = (0, habit_session_summary_1.readHabitSessionSummary)(agentRoot, { operationId, which: "latest" });
238
- if (!summary)
239
- return { mode: "stateful", summary: null, sources: {}, warnings: [] };
240
- return {
241
- mode: "stateful",
242
- summary: summary.summary,
243
- sources: summary.sources,
244
- warnings: summary.warnings,
245
- };
246
- }
247
- catch (error) {
248
- return {
249
- mode: "stateful",
250
- summary: null,
251
- sources: {},
252
- warnings: [`prior summary read failed: ${String(error)}`],
253
- };
254
- }
255
- }
256
- function createInnerDialogWorker(runTurn = (options) => (0, inner_dialog_1.runInnerDialogTurn)(options), hasPendingWork = (pendingDir) => (0, pending_1.hasPendingMessages)(pendingDir ?? (0, pending_1.getInnerDialogPendingDir)((0, identity_1.getAgentName)())), nowSource = () => Date.now()) {
257
- let running = false;
258
- const queue = [];
259
- const lastFireByHabit = new Map();
260
- const recentHabitFires = [];
261
- let heartbeatOkRestedAt = null;
262
- function recordHabitCompletion(habitRun, endedAt = habitRun.startedAt) {
263
- (0, habit_session_1.completeHabitRun)({
264
- agentRoot: habitRun.agentRoot,
265
- habit: habitRun.habit,
266
- runId: habitRun.runId,
267
- trigger: habitRun.trigger,
268
- startedAt: habitRun.startedAt,
269
- endedAt,
270
- operationId: habitRun.operationId,
271
- permissionEnvelope: habitRun.permissionEnvelope,
272
- toolPolicy: habitRun.toolPolicy,
273
- producedRefs: habitRun.producedRefs,
274
- surfaceAttempts: habitRun.surfaceAttempts,
275
- errors: habitRun.errors,
276
- summarySnapshot: deriveHabitSummarySnapshot(habitRun),
277
- });
278
- }
279
- function clearHeartbeatRestShield() {
280
- heartbeatOkRestedAt = null;
281
- }
282
- function shouldReuseHeartbeatOkRest(habitName) {
283
- if (habitName !== "heartbeat" || heartbeatOkRestedAt === null)
284
- return false;
285
- if (nowSource() - heartbeatOkRestedAt > exports.HEARTBEAT_OK_REST_SUPPRESSION_MS)
286
- return false;
287
- if (hasPendingWork()) {
288
- clearHeartbeatRestShield();
289
- return false;
290
- }
291
- return true;
292
- }
293
- async function reuseHeartbeatOkRest(habitName) {
294
- const nowIso = new Date(nowSource()).toISOString();
295
- const habitRun = await prepareHabitRun(habitName, "overdue", nowIso);
296
- habitRun.results.push({ turnOutcome: "rested", restStatus: "HEARTBEAT_OK" });
297
- recordHabitCompletion(habitRun, nowIso);
298
- (0, runtime_1.emitNervesEvent)({
299
- level: "info",
300
- component: "senses",
301
- event: "senses.heartbeat_ok_rest_reused",
302
- message: "heartbeat skipped because previous HEARTBEAT_OK rest is still valid and no pending work exists",
303
- meta: {
304
- habitName,
305
- quietWindowMs: exports.HEARTBEAT_OK_REST_SUPPRESSION_MS,
306
- restedAgoMs: nowSource() - heartbeatOkRestedAt,
307
- },
308
- });
309
- }
310
- function recordHabitFireForRecursion(habitName) {
311
- const now = nowSource();
312
- const previous = lastFireByHabit.get(habitName);
313
- if (previous !== undefined) {
314
- const intervalMs = now - previous;
315
- if (intervalMs < exports.HABIT_RECURSION_MIN_INTERVAL_MS) {
316
- (0, runtime_1.emitNervesEvent)({
317
- level: "warn",
318
- component: "senses",
319
- event: "senses.habit_recursion_suspected",
320
- message: "habit fired suspiciously fast after the previous fire — possible self-recursion or duplicate dispatch",
321
- meta: {
322
- habitName,
323
- intervalMs,
324
- thresholdMs: exports.HABIT_RECURSION_MIN_INTERVAL_MS,
325
- },
326
- });
327
- }
328
- }
329
- lastFireByHabit.set(habitName, now);
330
- recentHabitFires.push(now);
331
- while (recentHabitFires.length > 0 && now - recentHabitFires[0] > exports.HABIT_RECURSION_BURST_WINDOW_MS) {
332
- recentHabitFires.shift();
333
- }
334
- if (recentHabitFires.length >= exports.HABIT_RECURSION_BURST_THRESHOLD) {
335
- (0, runtime_1.emitNervesEvent)({
336
- level: "warn",
337
- component: "senses",
338
- event: "senses.habit_recursion_burst",
339
- message: "habit messages arriving in a burst — possible runaway loop",
340
- meta: {
341
- count: recentHabitFires.length,
342
- windowMs: exports.HABIT_RECURSION_BURST_WINDOW_MS,
343
- thresholdCount: exports.HABIT_RECURSION_BURST_THRESHOLD,
344
- lastHabitName: habitName,
345
- },
346
- });
347
- }
348
- }
349
- async function run(reason, taskId, habitName, awaitName, trigger) {
350
- if (running) {
351
- queue.push({ reason, taskId, habitName, awaitName, trigger });
352
- return;
353
- }
354
- running = true;
355
- try {
356
- let nextReason = reason;
357
- let nextTaskId = taskId;
358
- let nextHabitName = habitName;
359
- let nextAwaitName = awaitName;
360
- let nextTrigger = trigger;
361
- let nextHabitRun = null;
362
- let consecutiveInstinctTurns = reason === "instinct" ? 1 : 0;
363
- runLoop: do {
364
- const currentReason = nextReason;
365
- const currentHabitName = nextHabitName;
366
- const currentTrigger = nextTrigger ?? "overdue";
367
- const currentHabitRun = currentReason === "habit" && currentHabitName
368
- ? nextHabitRun && nextHabitRun.habit.name === currentHabitName
369
- ? nextHabitRun
370
- : await prepareHabitRun(currentHabitName, currentTrigger, new Date(nowSource()).toISOString())
371
- : null;
372
- nextHabitRun = null;
373
- let currentHabitRunFinalized = false;
374
- const finalizeCurrentHabitRun = () => {
375
- if (!currentHabitRun || currentHabitRunFinalized)
376
- return;
377
- recordHabitCompletion(currentHabitRun, new Date(nowSource()).toISOString());
378
- currentHabitRunFinalized = true;
379
- };
380
- const turnErrors = [];
381
- if (!(currentReason === "habit" && currentHabitName === "heartbeat")) {
382
- clearHeartbeatRestShield();
383
- }
384
- let turnResult;
385
- try {
386
- const turnOptions = {
387
- reason: nextReason,
388
- taskId: nextTaskId,
389
- habitName: nextHabitName,
390
- awaitName: nextAwaitName,
391
- ...(currentHabitRun
392
- ? {
393
- trigger: currentHabitRun.trigger,
394
- preparedHabit: {
395
- runId: currentHabitRun.runId,
396
- trigger: currentHabitRun.trigger,
397
- operationId: currentHabitRun.operationId,
398
- habit: currentHabitRun.habit,
399
- priorSessionSummary: currentHabitRun.priorSessionSummary,
400
- },
401
- habitSession: {
402
- runId: currentHabitRun.runId,
403
- sessionPath: currentHabitRun.paths.sessionPath,
404
- pendingDir: currentHabitRun.paths.pendingDir,
405
- permissionEnvelope: currentHabitRun.permissionEnvelope,
406
- toolPolicy: currentHabitRun.toolPolicy,
407
- friendStore: currentHabitRun.friendStore,
408
- recordProducedRef: (ref) => { currentHabitRun.producedRefs.push(ref); },
409
- recordSurfaceAttempt: (attempt) => { currentHabitRun.surfaceAttempts.push(attempt); },
410
- recordError: (error) => { currentHabitRun.errors.push(error); },
411
- },
412
- }
413
- : {}),
414
- };
415
- turnResult = await runTurn(turnOptions);
416
- }
417
- catch (error) {
418
- clearHeartbeatRestShield();
419
- turnErrors.push(error instanceof Error ? error.message : String(error));
420
- (0, runtime_1.emitNervesEvent)({
421
- level: "error",
422
- component: "senses",
423
- event: "senses.inner_dialog_worker_error",
424
- message: "inner dialog worker turn failed",
425
- meta: {
426
- reason: nextReason,
427
- error: error instanceof Error ? error.message : String(error),
428
- },
429
- });
430
- }
431
- if (currentReason === "habit" && currentHabitName === "heartbeat") {
432
- heartbeatOkRestedAt = isHeartbeatOkRestResult(turnResult) ? nowSource() : null;
433
- }
434
- if (currentHabitRun) {
435
- currentHabitRun.results.push(turnResult);
436
- currentHabitRun.errors.push(...turnErrors);
437
- }
438
- // Drain queue first. Externally-queued work resets the instinct cap
439
- // because a real outside trigger arrived between turns.
440
- while (queue.length > 0) {
441
- const next = queue.shift();
442
- if (next.reason === "habit" && next.habitName === "heartbeat" && shouldReuseHeartbeatOkRest(next.habitName)) {
443
- finalizeCurrentHabitRun();
444
- await reuseHeartbeatOkRest(next.habitName);
445
- continue;
446
- }
447
- if (!(next.reason === "habit" && next.habitName === "heartbeat")) {
448
- clearHeartbeatRestShield();
449
- }
450
- finalizeCurrentHabitRun();
451
- nextReason = next.reason;
452
- nextTaskId = next.taskId;
453
- nextHabitName = next.habitName;
454
- nextAwaitName = next.awaitName;
455
- nextTrigger = next.trigger;
456
- consecutiveInstinctTurns = nextReason === "instinct" ? consecutiveInstinctTurns + 1 : 0;
457
- continue runLoop;
458
- }
459
- // Then check hasPendingWork fallback. This is the loop site: any
460
- // tool that writes to the inner-dialog pending dir during a turn
461
- // would cause hasPendingWork() to be true here, producing a
462
- // self-sustaining "instinct" loop with no external input. Cap it.
463
- if (hasPendingWork(currentHabitRun?.paths.pendingDir)) {
464
- clearHeartbeatRestShield();
465
- if (consecutiveInstinctTurns >= exports.MAX_CONSECUTIVE_INSTINCT_TURNS) {
466
- (0, runtime_1.emitNervesEvent)({
467
- level: "warn",
468
- component: "senses",
469
- event: "senses.inner_dialog_worker_instinct_loop_capped",
470
- message: "inner dialog worker stopped chaining instinct turns; pending work remains for next external trigger",
471
- meta: {
472
- consecutiveInstinctTurns,
473
- cap: exports.MAX_CONSECUTIVE_INSTINCT_TURNS,
474
- lastReason: nextReason,
475
- },
476
- });
477
- finalizeCurrentHabitRun();
478
- break;
479
- }
480
- if (currentReason === "habit" && currentHabitName && currentHabitRun) {
481
- consecutiveInstinctTurns += 1;
482
- nextReason = "habit";
483
- nextTaskId = undefined;
484
- nextHabitName = currentHabitName;
485
- nextAwaitName = undefined;
486
- nextTrigger = currentTrigger;
487
- nextHabitRun = currentHabitRun;
488
- }
489
- else {
490
- finalizeCurrentHabitRun();
491
- consecutiveInstinctTurns += 1;
492
- nextReason = "instinct";
493
- nextTaskId = undefined;
494
- nextHabitName = undefined;
495
- nextAwaitName = undefined;
496
- nextTrigger = undefined;
497
- }
498
- continue;
499
- }
500
- finalizeCurrentHabitRun();
501
- break;
502
- } while (true);
503
- }
504
- finally {
505
- running = false;
506
- }
507
- }
508
- async function handleMessage(message) {
509
- if (!message || typeof message !== "object")
510
- return;
511
- const maybeMessage = message;
512
- if (maybeMessage.type === "habit") {
513
- /* v8 ignore next -- defensive fallback: live habit dispatch always sets habitName @preserve */
514
- const habitName = maybeMessage.habitName ?? "(unnamed)";
515
- if (shouldReuseHeartbeatOkRest(habitName)) {
516
- await reuseHeartbeatOkRest(habitName);
517
- return;
518
- }
519
- recordHabitFireForRecursion(habitName);
520
- await run("habit", undefined, maybeMessage.habitName, undefined, maybeMessage.trigger ?? "overdue");
521
- return;
522
- }
523
- if (maybeMessage.type === "await") {
524
- clearHeartbeatRestShield();
525
- /* v8 ignore next -- defensive fallback: live await dispatch always sets awaitName @preserve */
526
- const awaitName = maybeMessage.awaitName ?? "(unnamed)";
527
- recordHabitFireForRecursion(`await:${awaitName}`);
528
- await run("await", undefined, undefined, maybeMessage.awaitName);
529
- return;
530
- }
531
- if (maybeMessage.type === "heartbeat") {
532
- // Backward compatibility: heartbeat -> habit/heartbeat
533
- if (shouldReuseHeartbeatOkRest("heartbeat")) {
534
- await reuseHeartbeatOkRest("heartbeat");
535
- return;
536
- }
537
- recordHabitFireForRecursion("heartbeat");
538
- await run("habit", undefined, "heartbeat", undefined, "overdue");
539
- return;
540
- }
541
- if (maybeMessage.type === "poke") {
542
- clearHeartbeatRestShield();
543
- await run("instinct", maybeMessage.taskId);
544
- return;
545
- }
546
- if (maybeMessage.type === "chat" ||
547
- maybeMessage.type === "message") {
548
- clearHeartbeatRestShield();
549
- await run("instinct");
550
- return;
551
- }
552
- if (maybeMessage.type === "shutdown") {
553
- process.exit(0);
554
- }
555
- }
556
- return { run, handleMessage };
47
+ function createInnerDialogWorker(runTurn = (options) => {
48
+ return innerDialog.runInnerDialogTurn(options);
49
+ }, hasPendingWork, nowSource) {
50
+ return privateRuntimeWorker.createPrivateRuntimeWorker(runTurn, hasPendingWork, nowSource);
557
51
  }
558
52
  async function startInnerDialogWorker() {
559
- const worker = createInnerDialogWorker();
560
- process.on("message", (message) => {
561
- void worker.handleMessage(message);
562
- });
563
- process.on("disconnect", () => {
564
- process.exit(0);
53
+ (0, runtime_1.emitNervesEvent)({
54
+ level: "info",
55
+ component: "senses",
56
+ event: "senses.inner_dialog_worker_compat_start",
57
+ message: "legacy inner-dialog worker startup delegated to private-runtime worker",
58
+ meta: { target: "private-runtime-worker" },
565
59
  });
566
- await worker.run("boot");
60
+ await privateRuntimeWorker.startPrivateRuntimeWorker();
567
61
  }