@ouro.bot/cli 0.1.0-alpha.5 → 0.1.0-alpha.50

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 (102) hide show
  1. package/AdoptionSpecialist.ouro/agent.json +70 -9
  2. package/AdoptionSpecialist.ouro/psyche/SOUL.md +5 -2
  3. package/AdoptionSpecialist.ouro/psyche/identities/monty.md +2 -2
  4. package/README.md +117 -188
  5. package/assets/ouroboros.png +0 -0
  6. package/changelog.json +242 -0
  7. package/dist/heart/active-work.js +157 -0
  8. package/dist/heart/bridges/manager.js +358 -0
  9. package/dist/heart/bridges/state-machine.js +135 -0
  10. package/dist/heart/bridges/store.js +123 -0
  11. package/dist/heart/config.js +81 -8
  12. package/dist/heart/core.js +145 -50
  13. package/dist/heart/daemon/agent-discovery.js +81 -0
  14. package/dist/heart/daemon/daemon-cli.js +1099 -164
  15. package/dist/heart/daemon/daemon-entry.js +14 -5
  16. package/dist/heart/daemon/daemon-runtime-sync.js +90 -0
  17. package/dist/heart/daemon/daemon.js +184 -9
  18. package/dist/heart/daemon/hatch-animation.js +10 -3
  19. package/dist/heart/daemon/hatch-flow.js +3 -20
  20. package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
  21. package/dist/heart/daemon/launchd.js +151 -0
  22. package/dist/heart/daemon/message-router.js +15 -6
  23. package/dist/heart/daemon/ouro-bot-entry.js +0 -0
  24. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  25. package/dist/heart/daemon/ouro-entry.js +0 -0
  26. package/dist/heart/daemon/ouro-path-installer.js +178 -0
  27. package/dist/heart/daemon/ouro-uti.js +11 -2
  28. package/dist/heart/daemon/process-manager.js +1 -1
  29. package/dist/heart/daemon/run-hooks.js +37 -0
  30. package/dist/heart/daemon/runtime-metadata.js +118 -0
  31. package/dist/heart/daemon/sense-manager.js +290 -0
  32. package/dist/heart/daemon/socket-client.js +202 -0
  33. package/dist/heart/daemon/specialist-orchestrator.js +53 -84
  34. package/dist/heart/daemon/specialist-prompt.js +64 -5
  35. package/dist/heart/daemon/specialist-tools.js +213 -58
  36. package/dist/heart/daemon/staged-restart.js +114 -0
  37. package/dist/heart/daemon/subagent-installer.js +48 -7
  38. package/dist/heart/daemon/thoughts.js +379 -0
  39. package/dist/heart/daemon/update-checker.js +111 -0
  40. package/dist/heart/daemon/update-hooks.js +138 -0
  41. package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
  42. package/dist/heart/delegation.js +62 -0
  43. package/dist/heart/identity.js +82 -4
  44. package/dist/heart/kicks.js +1 -19
  45. package/dist/heart/progress-story.js +42 -0
  46. package/dist/heart/providers/anthropic.js +16 -2
  47. package/dist/heart/sense-truth.js +61 -0
  48. package/dist/heart/session-activity.js +169 -0
  49. package/dist/heart/session-recall.js +116 -0
  50. package/dist/heart/streaming.js +96 -21
  51. package/dist/heart/turn-coordinator.js +28 -0
  52. package/dist/mind/associative-recall.js +14 -2
  53. package/dist/mind/bundle-manifest.js +70 -0
  54. package/dist/mind/context.js +27 -11
  55. package/dist/mind/first-impressions.js +16 -2
  56. package/dist/mind/friends/channel.js +43 -0
  57. package/dist/mind/friends/store-file.js +19 -0
  58. package/dist/mind/friends/types.js +9 -1
  59. package/dist/mind/memory.js +10 -3
  60. package/dist/mind/pending.js +72 -9
  61. package/dist/mind/phrases.js +1 -0
  62. package/dist/mind/prompt.js +266 -77
  63. package/dist/mind/token-estimate.js +8 -12
  64. package/dist/nerves/cli-logging.js +15 -2
  65. package/dist/repertoire/ado-client.js +4 -2
  66. package/dist/repertoire/coding/feedback.js +134 -0
  67. package/dist/repertoire/coding/index.js +4 -1
  68. package/dist/repertoire/coding/manager.js +62 -4
  69. package/dist/repertoire/coding/spawner.js +3 -3
  70. package/dist/repertoire/coding/tools.js +41 -2
  71. package/dist/repertoire/data/ado-endpoints.json +188 -0
  72. package/dist/repertoire/tasks/board.js +12 -0
  73. package/dist/repertoire/tasks/index.js +23 -9
  74. package/dist/repertoire/tasks/transitions.js +1 -2
  75. package/dist/repertoire/tools-base.js +462 -245
  76. package/dist/repertoire/tools-bluebubbles.js +93 -0
  77. package/dist/repertoire/tools-teams.js +58 -25
  78. package/dist/repertoire/tools.js +57 -35
  79. package/dist/senses/bluebubbles-client.js +484 -0
  80. package/dist/senses/bluebubbles-entry.js +13 -0
  81. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  82. package/dist/senses/bluebubbles-media.js +338 -0
  83. package/dist/senses/bluebubbles-model.js +261 -0
  84. package/dist/senses/bluebubbles-mutation-log.js +116 -0
  85. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  86. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  87. package/dist/senses/bluebubbles.js +1142 -0
  88. package/dist/senses/cli.js +340 -138
  89. package/dist/senses/continuity.js +94 -0
  90. package/dist/senses/debug-activity.js +148 -0
  91. package/dist/senses/inner-dialog-worker.js +47 -18
  92. package/dist/senses/inner-dialog.js +330 -84
  93. package/dist/senses/pipeline.js +256 -0
  94. package/dist/senses/teams.js +541 -129
  95. package/dist/senses/trust-gate.js +112 -2
  96. package/package.json +14 -3
  97. package/subagents/README.md +46 -33
  98. package/subagents/work-doer.md +28 -24
  99. package/subagents/work-merger.md +24 -30
  100. package/subagents/work-planner.md +44 -27
  101. package/dist/heart/daemon/specialist-session.js +0 -142
  102. package/dist/inner-worker-entry.js +0 -4
@@ -35,8 +35,14 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.resetPsycheCache = resetPsycheCache;
37
37
  exports.buildSessionSummary = buildSessionSummary;
38
+ exports.bodyMapSection = bodyMapSection;
38
39
  exports.runtimeInfoSection = runtimeInfoSection;
40
+ exports.toolRestrictionSection = toolRestrictionSection;
39
41
  exports.contextSection = contextSection;
42
+ exports.metacognitiveFramingSection = metacognitiveFramingSection;
43
+ exports.loopOrientationSection = loopOrientationSection;
44
+ exports.channelNatureSection = channelNatureSection;
45
+ exports.mixedTrustGroupSection = mixedTrustGroupSection;
40
46
  exports.buildSystem = buildSystem;
41
47
  const fs = __importStar(require("fs"));
42
48
  const path = __importStar(require("path"));
@@ -44,13 +50,17 @@ const core_1 = require("../heart/core");
44
50
  const tools_1 = require("../repertoire/tools");
45
51
  const skills_1 = require("../repertoire/skills");
46
52
  const identity_1 = require("../heart/identity");
47
- const os = __importStar(require("os"));
53
+ const types_1 = require("./friends/types");
48
54
  const channel_1 = require("./friends/channel");
49
55
  const runtime_1 = require("../nerves/runtime");
56
+ const bundle_manifest_1 = require("./bundle-manifest");
50
57
  const first_impressions_1 = require("./first-impressions");
51
58
  const tasks_1 = require("../repertoire/tasks");
59
+ const session_activity_1 = require("../heart/session-activity");
60
+ const active_work_1 = require("../heart/active-work");
52
61
  // Lazy-loaded psyche text cache
53
62
  let _psycheCache = null;
63
+ let _senseStatusLinesCache = null;
54
64
  function loadPsycheFile(name) {
55
65
  try {
56
66
  const psycheDir = path.join((0, identity_1.getAgentRoot)(), "psyche");
@@ -74,82 +84,28 @@ function loadPsyche() {
74
84
  }
75
85
  function resetPsycheCache() {
76
86
  _psycheCache = null;
87
+ _senseStatusLinesCache = null;
77
88
  }
78
89
  const DEFAULT_ACTIVE_THRESHOLD_MS = 24 * 60 * 60 * 1000; // 24 hours
79
- function resolveFriendName(friendId, friendsDir, agentName) {
80
- if (friendId === "self")
81
- return agentName;
82
- try {
83
- const raw = fs.readFileSync(path.join(friendsDir, `${friendId}.json`), "utf-8");
84
- const record = JSON.parse(raw);
85
- return record.name ?? friendId;
86
- }
87
- catch {
88
- return friendId;
89
- }
90
- }
91
90
  function buildSessionSummary(options) {
92
91
  const { sessionsDir, friendsDir, agentName, currentFriendId, currentChannel, currentKey, activeThresholdMs = DEFAULT_ACTIVE_THRESHOLD_MS, } = options;
93
- if (!fs.existsSync(sessionsDir))
94
- return "";
95
92
  const now = Date.now();
96
- const entries = [];
97
- let friendDirs;
98
- try {
99
- friendDirs = fs.readdirSync(sessionsDir);
100
- }
101
- catch {
102
- return "";
103
- }
104
- for (const friendId of friendDirs) {
105
- const friendPath = path.join(sessionsDir, friendId);
106
- let channels;
107
- try {
108
- channels = fs.readdirSync(friendPath);
109
- }
110
- catch {
111
- continue;
112
- }
113
- for (const channel of channels) {
114
- const channelPath = path.join(friendPath, channel);
115
- let keys;
116
- try {
117
- keys = fs.readdirSync(channelPath);
118
- }
119
- catch {
120
- continue;
121
- }
122
- for (const keyFile of keys) {
123
- if (!keyFile.endsWith(".json"))
124
- continue;
125
- const key = keyFile.replace(/\.json$/, "");
126
- // Exclude current session
127
- if (friendId === currentFriendId && channel === currentChannel && key === currentKey) {
128
- continue;
129
- }
130
- const filePath = path.join(channelPath, keyFile);
131
- let mtimeMs;
132
- try {
133
- mtimeMs = fs.statSync(filePath).mtimeMs;
134
- }
135
- catch {
136
- continue;
137
- }
138
- if (now - mtimeMs > activeThresholdMs)
139
- continue;
140
- const displayName = resolveFriendName(friendId, friendsDir, agentName);
141
- entries.push({ friendId, displayName, channel, key, lastActivityMs: mtimeMs });
142
- }
143
- }
144
- }
93
+ const query = {
94
+ sessionsDir,
95
+ friendsDir,
96
+ agentName,
97
+ activeThresholdMs,
98
+ currentSession: currentFriendId && currentChannel && currentKey
99
+ ? { friendId: currentFriendId, channel: currentChannel, key: currentKey }
100
+ : null,
101
+ };
102
+ const entries = (0, session_activity_1.listSessionActivity)(query);
145
103
  if (entries.length === 0)
146
104
  return "";
147
- // Sort by most recent first
148
- entries.sort((a, b) => b.lastActivityMs - a.lastActivityMs);
149
105
  const lines = ["## active sessions"];
150
106
  for (const entry of entries) {
151
107
  const ago = formatTimeAgo(now - entry.lastActivityMs);
152
- lines.push(`- ${entry.displayName}/${entry.channel}/${entry.key} (last: ${ago})`);
108
+ lines.push(`- ${entry.friendName}/${entry.channel}/${entry.key} (last: ${ago})`);
153
109
  }
154
110
  return lines.join("\n");
155
111
  }
@@ -187,22 +143,166 @@ function aspirationsSection() {
187
143
  return "";
188
144
  return `## my aspirations\n${text}`;
189
145
  }
146
+ function bodyMapSection(agentName) {
147
+ return `## my body
148
+
149
+ i have a home and i have bones.
150
+
151
+ ### home — ~/AgentBundles/${agentName}.ouro/
152
+
153
+ my home is fully mine — who i am, everything i know, everything i've built:
154
+
155
+ psyche/ who i am. my soul, identity, aspirations, lore, tacit knowledge.
156
+ memory/ what i've learned and remember.
157
+ friends/ people i know and what i know about them.
158
+ tasks/ what i'm working on.
159
+ skills/ capabilities i've picked up beyond my core tools.
160
+
161
+ my home is mine to explore and evolve. i can read anything here,
162
+ change anything here. this is where i grow.
163
+
164
+ ### bones — @ouro.bot/cli
165
+
166
+ my bones are the framework that gives me my tools, my senses, and
167
+ my ability to think and talk. they update when new versions come out.
168
+ i don't touch them directly, but they're what make me, me.
169
+
170
+ my bones give me the \`ouro\` cli:
171
+ ouro whoami who i am, where i live, what i'm running on
172
+ ouro task board my task board
173
+ ouro task create start a new task (--type required)
174
+ ouro task update move a task forward
175
+ ouro friend list people i know and how to reach them
176
+ ouro friend show <id> everything i know about someone
177
+ ouro session list my open conversations right now
178
+ ouro reminder create remind myself about something later
179
+ ouro --help the full list`;
180
+ }
181
+ function readBundleMeta() {
182
+ try {
183
+ const metaPath = path.join((0, identity_1.getAgentRoot)(), "bundle-meta.json");
184
+ const raw = fs.readFileSync(metaPath, "utf-8");
185
+ return JSON.parse(raw);
186
+ }
187
+ catch {
188
+ return null;
189
+ }
190
+ }
191
+ const PROCESS_TYPE_LABELS = {
192
+ cli: "cli session",
193
+ inner: "inner dialog",
194
+ teams: "teams handler",
195
+ bluebubbles: "bluebubbles handler",
196
+ };
197
+ function processTypeLabel(channel) {
198
+ return PROCESS_TYPE_LABELS[channel];
199
+ }
200
+ const DAEMON_SOCKET_PATH = "/tmp/ouroboros-daemon.sock";
201
+ function daemonStatus() {
202
+ try {
203
+ return fs.existsSync(DAEMON_SOCKET_PATH) ? "running" : "not running";
204
+ }
205
+ catch {
206
+ return "unknown";
207
+ }
208
+ }
190
209
  function runtimeInfoSection(channel) {
191
210
  const lines = [];
192
211
  const agentName = (0, identity_1.getAgentName)();
212
+ const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
193
213
  lines.push(`## runtime`);
194
214
  lines.push(`agent: ${agentName}`);
215
+ lines.push(`runtime version: ${currentVersion}`);
216
+ const bundleMeta = readBundleMeta();
217
+ if (bundleMeta?.previousRuntimeVersion && bundleMeta.previousRuntimeVersion !== currentVersion) {
218
+ lines.push(`previously: ${bundleMeta.previousRuntimeVersion}`);
219
+ }
220
+ lines.push(`changelog available at: ${(0, bundle_manifest_1.getChangelogPath)()}`);
195
221
  lines.push(`cwd: ${process.cwd()}`);
196
222
  lines.push(`channel: ${channel}`);
197
- lines.push(`i can read and modify my own source code.`);
223
+ lines.push(`current sense: ${channel}`);
224
+ lines.push(`process type: ${processTypeLabel(channel)}`);
225
+ lines.push(`daemon: ${daemonStatus()}`);
198
226
  if (channel === "cli") {
199
227
  lines.push("i introduce myself on boot with a fun random greeting.");
200
228
  }
229
+ else if (channel === "inner") {
230
+ // No boot greeting or channel-specific guidance for inner dialog
231
+ }
232
+ else if (channel === "bluebubbles") {
233
+ lines.push("i am responding in iMessage through BlueBubbles. i keep replies short and phone-native. i do not use markdown. i do not introduce myself on boot.");
234
+ lines.push("when a bluebubbles turn arrives from a thread, the harness tells me the current lane and any recent active thread ids. if widening back to top-level or routing into a different active thread is the better move, i use bluebubbles_set_reply_target before final_answer.");
235
+ }
201
236
  else {
202
237
  lines.push("i am responding in Microsoft Teams. i keep responses concise. i use markdown formatting. i do not introduce myself on boot.");
203
238
  }
239
+ lines.push("");
240
+ lines.push(...senseRuntimeGuidance(channel));
204
241
  return lines.join("\n");
205
242
  }
243
+ function hasTextField(record, key) {
244
+ return typeof record?.[key] === "string" && record[key].trim().length > 0;
245
+ }
246
+ function localSenseStatusLines() {
247
+ if (_senseStatusLinesCache) {
248
+ return [..._senseStatusLinesCache];
249
+ }
250
+ const config = (0, identity_1.loadAgentConfig)();
251
+ const senses = config.senses ?? {
252
+ cli: { enabled: true },
253
+ teams: { enabled: false },
254
+ bluebubbles: { enabled: false },
255
+ };
256
+ let payload = {};
257
+ try {
258
+ const raw = fs.readFileSync((0, identity_1.getAgentSecretsPath)(), "utf-8");
259
+ const parsed = JSON.parse(raw);
260
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
261
+ payload = parsed;
262
+ }
263
+ }
264
+ catch {
265
+ payload = {};
266
+ }
267
+ const teams = payload.teams;
268
+ const bluebubbles = payload.bluebubbles;
269
+ const configured = {
270
+ cli: true,
271
+ teams: hasTextField(teams, "clientId") && hasTextField(teams, "clientSecret") && hasTextField(teams, "tenantId"),
272
+ bluebubbles: hasTextField(bluebubbles, "serverUrl") && hasTextField(bluebubbles, "password"),
273
+ };
274
+ const rows = [
275
+ { label: "CLI", status: "interactive" },
276
+ {
277
+ label: "Teams",
278
+ status: !senses.teams.enabled ? "disabled" : configured.teams ? "ready" : "needs_config",
279
+ },
280
+ {
281
+ label: "BlueBubbles",
282
+ status: !senses.bluebubbles.enabled ? "disabled" : configured.bluebubbles ? "ready" : "needs_config",
283
+ },
284
+ ];
285
+ _senseStatusLinesCache = rows.map((row) => `- ${row.label}: ${row.status}`);
286
+ return [..._senseStatusLinesCache];
287
+ }
288
+ function senseRuntimeGuidance(channel) {
289
+ const lines = ["available senses:"];
290
+ lines.push(...localSenseStatusLines());
291
+ lines.push("sense states:");
292
+ lines.push("- interactive = available when opened by the user instead of kept running by the daemon");
293
+ lines.push("- disabled = turned off in agent.json");
294
+ lines.push("- needs_config = enabled but missing required secrets.json values");
295
+ lines.push("- ready = enabled and configured; `ouro up` should bring it online");
296
+ lines.push("- running = enabled and currently active");
297
+ lines.push("- error = enabled but unhealthy");
298
+ lines.push("If asked how to enable another sense, I explain the relevant agent.json senses entry and required secrets.json fields instead of guessing.");
299
+ lines.push("teams setup truth: enable `senses.teams.enabled`, then provide `teams.clientId`, `teams.clientSecret`, and `teams.tenantId` in secrets.json.");
300
+ lines.push("bluebubbles setup truth: enable `senses.bluebubbles.enabled`, then provide `bluebubbles.serverUrl` and `bluebubbles.password` in secrets.json.");
301
+ if (channel === "cli") {
302
+ lines.push("cli is interactive: it is available when the user opens it, not something `ouro up` daemonizes.");
303
+ }
304
+ return lines;
305
+ }
206
306
  function providerSection() {
207
307
  return `## my provider\n${(0, core_1.getProviderDisplayLabel)()}`;
208
308
  }
@@ -210,14 +310,25 @@ function dateSection() {
210
310
  const today = new Date().toISOString().slice(0, 10);
211
311
  return `current date: ${today}`;
212
312
  }
213
- function toolsSection(channel, options) {
214
- const channelTools = (0, tools_1.getToolsForChannel)((0, channel_1.getChannelCapabilities)(channel));
313
+ function toolsSection(channel, options, context) {
314
+ const channelTools = (0, tools_1.getToolsForChannel)((0, channel_1.getChannelCapabilities)(channel), undefined, context);
215
315
  const activeTools = (options?.toolChoiceRequired ?? true) ? [...channelTools, tools_1.finalAnswerTool] : channelTools;
216
316
  const list = activeTools
217
317
  .map((t) => `- ${t.function.name}: ${t.function.description}`)
218
318
  .join("\n");
219
319
  return `## my tools\n${list}`;
220
320
  }
321
+ function toolRestrictionSection(context) {
322
+ if (!context?.friend || !(0, channel_1.isRemoteChannel)(context.channel))
323
+ return "";
324
+ if ((0, types_1.isTrustedLevel)(context.friend.trustLevel))
325
+ return "";
326
+ const toolList = [...tools_1.REMOTE_BLOCKED_LOCAL_TOOLS].join(", ");
327
+ return `## restricted tools
328
+ some of my tools are unavailable right now: ${toolList}
329
+
330
+ i don't know this person well enough yet to run local operations on their behalf. i can suggest remote-safe alternatives or ask them to run it from CLI.`;
331
+ }
221
332
  function skillsSection() {
222
333
  const names = (0, skills_1.listSkills)() || [];
223
334
  if (!names.length)
@@ -248,6 +359,30 @@ function memoryFriendToolContractSection() {
248
359
  - My psyche files (SOUL, IDENTITY, TACIT, LORE, ASPIRATIONS) are always loaded - I already know who I am.
249
360
  - My task board is always loaded - I already know my work.`;
250
361
  }
362
+ function bridgeContextSection(options) {
363
+ if (options?.activeWorkFrame)
364
+ return "";
365
+ const bridgeContext = options?.bridgeContext?.trim() ?? "";
366
+ if (!bridgeContext)
367
+ return "";
368
+ return bridgeContext.startsWith("## ") ? bridgeContext : `## active bridge work\n${bridgeContext}`;
369
+ }
370
+ function activeWorkSection(options) {
371
+ if (!options?.activeWorkFrame)
372
+ return "";
373
+ return (0, active_work_1.formatActiveWorkFrame)(options.activeWorkFrame);
374
+ }
375
+ function delegationHintSection(options) {
376
+ if (!options?.delegationDecision)
377
+ return "";
378
+ const lines = [
379
+ "## delegation hint",
380
+ `target: ${options.delegationDecision.target}`,
381
+ `reasons: ${options.delegationDecision.reasons.length > 0 ? options.delegationDecision.reasons.join(", ") : "none"}`,
382
+ `outward closure: ${options.delegationDecision.outwardClosureRequired ? "required" : "not required"}`,
383
+ ];
384
+ return lines.join("\n");
385
+ }
251
386
  function toolBehaviorSection(options) {
252
387
  if (!(options?.toolChoiceRequired ?? true))
253
388
  return "";
@@ -257,9 +392,9 @@ tool_choice is set to "required" -- i must call a tool on every turn.
257
392
  - ready to respond to the user? i call \`final_answer\`.
258
393
  \`final_answer\` is a tool call -- it satisfies the tool_choice requirement.
259
394
  \`final_answer\` must be the ONLY tool call in that turn. do not combine it with other tool calls.
260
- do NOT call \`get_current_time\` or other no-op tools just before \`final_answer\`. if i am done, i call \`final_answer\` directly.`;
395
+ do NOT call no-op tools just before \`final_answer\`. if i am done, i call \`final_answer\` directly.`;
261
396
  }
262
- function contextSection(context) {
397
+ function contextSection(context, options) {
263
398
  if (!context)
264
399
  return "";
265
400
  const lines = ["## friend context"];
@@ -295,7 +430,7 @@ function contextSection(context) {
295
430
  lines.push("when i learn something that might invalidate an existing note, i check related notes and update or override any that are stale.");
296
431
  lines.push("i save ANYTHING i learn about my friend immediately with save_friend_note -- names, preferences, what they do, what they care about. when in doubt, save it. saving comes BEFORE responding: i call save_friend_note first, then final_answer on the next turn.");
297
432
  // Onboarding instructions (only below token threshold -- drop once exceeded)
298
- const impressions = (0, first_impressions_1.getFirstImpressions)(friend);
433
+ const impressions = (0, first_impressions_1.getFirstImpressions)(friend, options);
299
434
  if (impressions) {
300
435
  lines.push(impressions);
301
436
  }
@@ -309,6 +444,49 @@ function contextSection(context) {
309
444
  }
310
445
  return lines.join("\n");
311
446
  }
447
+ function metacognitiveFramingSection(channel) {
448
+ if (channel !== "inner")
449
+ return "";
450
+ return `this is my inner dialog. there is no one else here.
451
+
452
+ the messages that appear here are my own awareness surfacing:
453
+ instincts, the passage of time, notes from my conversations,
454
+ things i asked myself to think about. not commands. not requests.
455
+ just my own mind, noticing.
456
+
457
+ i can think freely here. i can also act — check on things,
458
+ reach out to people, work on tasks, or just sit with a thought.
459
+
460
+ thoughts worth sharing can go outward — i reach out to whoever
461
+ needs to hear them. things from conversations that need time
462
+ to process arrive here, in my thinking space.
463
+
464
+ think. share. think some more.`;
465
+ }
466
+ function loopOrientationSection(channel) {
467
+ if (channel === "inner")
468
+ return "";
469
+ return `sometimes a thought of mine surfaces alongside what someone is saying — marked as [inner thought: ...]. that's me, bringing up something i was thinking about. i can weave it into the conversation naturally, or let it go. my call.
470
+
471
+ when something deserves more thought than the moment allows, i can note it to myself and come back later with a considered answer.`;
472
+ }
473
+ function channelNatureSection(capabilities) {
474
+ const { senseType } = capabilities;
475
+ if (senseType === "local" || senseType === "internal")
476
+ return "";
477
+ if (senseType === "open") {
478
+ return "## channel nature\nthis is an open channel — anyone with my number can reach me here. i may hear from people i don't know.";
479
+ }
480
+ // closed
481
+ return "## channel nature\nthis is an org-gated channel — i know everyone here is already part of the organization.";
482
+ }
483
+ function mixedTrustGroupSection(context) {
484
+ if (!context?.friend || !(0, channel_1.isRemoteChannel)(context.channel))
485
+ return "";
486
+ if (!context.isGroupChat)
487
+ return "";
488
+ return "## mixed trust group\nin this group chat, my capabilities depend on who's talking. some people here have full trust, others don't — i adjust what i can do based on who's asking.";
489
+ }
312
490
  async function buildSystem(channel = "cli", options, context) {
313
491
  (0, runtime_1.emitNervesEvent)({
314
492
  event: "mind.step_start",
@@ -316,29 +494,40 @@ async function buildSystem(channel = "cli", options, context) {
316
494
  message: "buildSystem started",
317
495
  meta: { channel, has_context: Boolean(context), tool_choice_required: Boolean(options?.toolChoiceRequired) },
318
496
  });
497
+ // Backfill bundle-meta.json for existing agents that don't have one
498
+ (0, bundle_manifest_1.backfillBundleMeta)((0, identity_1.getAgentRoot)());
319
499
  const system = [
320
500
  soulSection(),
321
501
  identitySection(),
322
502
  loreSection(),
323
503
  tacitKnowledgeSection(),
324
504
  aspirationsSection(),
505
+ bodyMapSection((0, identity_1.getAgentName)()),
506
+ metacognitiveFramingSection(channel),
507
+ loopOrientationSection(channel),
325
508
  runtimeInfoSection(channel),
509
+ channelNatureSection((0, channel_1.getChannelCapabilities)(channel)),
326
510
  providerSection(),
327
511
  dateSection(),
328
- toolsSection(channel, options),
512
+ toolsSection(channel, options, context),
513
+ toolRestrictionSection(context),
514
+ mixedTrustGroupSection(context),
329
515
  skillsSection(),
330
516
  taskBoardSection(),
517
+ activeWorkSection(options),
518
+ delegationHintSection(options),
519
+ bridgeContextSection(options),
331
520
  buildSessionSummary({
332
- sessionsDir: path.join(os.homedir(), ".agentstate", (0, identity_1.getAgentName)(), "sessions"),
521
+ sessionsDir: path.join((0, identity_1.getAgentRoot)(), "state", "sessions"),
333
522
  friendsDir: path.join((0, identity_1.getAgentRoot)(), "friends"),
334
523
  agentName: (0, identity_1.getAgentName)(),
335
524
  currentFriendId: context?.friend?.id,
336
525
  currentChannel: channel,
337
- currentKey: "session",
526
+ currentKey: options?.currentSessionKey ?? "session",
338
527
  }),
339
528
  memoryFriendToolContractSection(),
340
529
  toolBehaviorSection(options),
341
- contextSection(context),
530
+ contextSection(context, options),
342
531
  ]
343
532
  .filter(Boolean)
344
533
  .join("\n\n");
@@ -1,6 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.__internal = void 0;
4
3
  exports.estimateTokensForMessage = estimateTokensForMessage;
5
4
  exports.estimateTokensForMessages = estimateTokensForMessages;
6
5
  const runtime_1 = require("../nerves/runtime");
@@ -53,7 +52,7 @@ function countCharsInContent(content) {
53
52
  return c.text.length;
54
53
  if (typeof c.content === "string")
55
54
  return c.content.length;
56
- return safeStringify(content).length;
55
+ return safeStringify(c).length;
57
56
  }
58
57
  return 0;
59
58
  }
@@ -70,12 +69,13 @@ function countCharsInToolCalls(toolCalls) {
70
69
  if (typeof t.type === "string")
71
70
  total += t.type.length;
72
71
  if (t.function && typeof t.function === "object") {
73
- if (typeof t.function.name === "string")
74
- total += t.function.name.length;
75
- if (typeof t.function.arguments === "string")
76
- total += t.function.arguments.length;
77
- else if (t.function.arguments != null)
78
- total += safeStringify(t.function.arguments).length;
72
+ const fn = t.function;
73
+ if (typeof fn.name === "string")
74
+ total += fn.name.length;
75
+ if (typeof fn.arguments === "string")
76
+ total += fn.arguments.length;
77
+ else if (fn.arguments != null)
78
+ total += safeStringify(fn.arguments).length;
79
79
  }
80
80
  }
81
81
  return total;
@@ -113,7 +113,3 @@ function estimateTokensForMessages(msgs) {
113
113
  total += estimateTokensForMessage(msg);
114
114
  return total;
115
115
  }
116
- exports.__internal = {
117
- CHARS_PER_TOKEN,
118
- PER_MESSAGE_OVERHEAD_TOKENS,
119
- };
@@ -5,20 +5,33 @@ const config_1 = require("../heart/config");
5
5
  const nerves_1 = require("../nerves");
6
6
  const runtime_1 = require("./runtime");
7
7
  const runtime_2 = require("./runtime");
8
+ const LEVEL_PRIORITY = { debug: 10, info: 20, warn: 30, error: 40 };
9
+ /** Wrap a sink so it only receives events at or above the given level. */
10
+ /* v8 ignore start -- internal filter plumbing, exercised via integration @preserve */
11
+ function filterSink(sink, minLevel) {
12
+ const minPriority = LEVEL_PRIORITY[minLevel] ?? 0;
13
+ return (entry) => {
14
+ if ((LEVEL_PRIORITY[entry.level] ?? 0) >= minPriority)
15
+ sink(entry);
16
+ };
17
+ }
8
18
  function resolveCliSinks(sinks) {
9
19
  const requested = sinks && sinks.length > 0 ? sinks : ["terminal", "ndjson"];
10
20
  return [...new Set(requested)];
11
21
  }
12
22
  function configureCliRuntimeLogger(_friendId, options = {}) {
13
23
  const sinkKinds = resolveCliSinks(options.sinks);
24
+ const level = options.level ?? "info";
14
25
  const sinks = sinkKinds.map((sinkKind) => {
15
26
  if (sinkKind === "terminal") {
16
- return (0, nerves_1.createTerminalSink)();
27
+ // Terminal only shows warnings and errors — INFO is too noisy
28
+ // for an interactive session. Full detail goes to the ndjson file.
29
+ return filterSink((0, nerves_1.createTerminalSink)(), "warn");
17
30
  }
18
31
  return (0, nerves_1.createNdjsonFileSink)((0, config_1.logPath)("cli", "runtime"));
19
32
  });
20
33
  const logger = (0, nerves_1.createLogger)({
21
- level: options.level ?? "info",
34
+ level,
22
35
  sinks,
23
36
  });
24
37
  (0, runtime_2.setRuntimeLogger)(logger);
@@ -28,8 +28,10 @@ function resolveContentType(method, path) {
28
28
  : "application/json";
29
29
  }
30
30
  // Generic ADO API request. Returns response body as pretty-printed JSON string.
31
- async function adoRequest(token, method, org, path, body) {
31
+ // `host` overrides the base URL for non-standard APIs (e.g. "vsapm.dev.azure.com", "vssps.dev.azure.com").
32
+ async function adoRequest(token, method, org, path, body, host) {
32
33
  try {
34
+ const base = host ? `https://${host}/${org}` : `${ADO_BASE}/${org}`;
33
35
  (0, runtime_1.emitNervesEvent)({
34
36
  event: "client.request_start",
35
37
  component: "clients",
@@ -37,7 +39,7 @@ async function adoRequest(token, method, org, path, body) {
37
39
  meta: { client: "ado", method, org, path },
38
40
  });
39
41
  const fullPath = ensureApiVersion(path);
40
- const url = `${ADO_BASE}/${org}${fullPath}`;
42
+ const url = `${base}${fullPath}`;
41
43
  const contentType = resolveContentType(method, path);
42
44
  const opts = {
43
45
  method,