@ouro.bot/cli 0.1.0-alpha.1021 → 0.1.0-alpha.1024

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 (39) hide show
  1. package/changelog.json +34 -0
  2. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
  3. package/deploy/unraid/sanctuary.xml +1 -1
  4. package/dist/heart/auth/auth-flow.js +17 -12
  5. package/dist/heart/core.js +19 -2
  6. package/dist/heart/daemon/agent-discovery.js +22 -5
  7. package/dist/heart/daemon/agent-home.js +101 -47
  8. package/dist/heart/daemon/cli-defaults.js +27 -6
  9. package/dist/heart/daemon/cli-exec.js +95 -1
  10. package/dist/heart/daemon/cli-help.js +7 -0
  11. package/dist/heart/daemon/cli-parse.js +38 -2
  12. package/dist/heart/daemon/daemon-entry.js +121 -1
  13. package/dist/heart/daemon/launchd.js +3 -0
  14. package/dist/heart/daemon/mcp-canary.js +2 -1
  15. package/dist/heart/daemon/os-cron-deps.js +4 -0
  16. package/dist/heart/daemon/presence-daemon.js +263 -0
  17. package/dist/heart/daemon/presence-roster.js +217 -0
  18. package/dist/heart/daemon/presence.js +380 -0
  19. package/dist/heart/daemon/provider-discovery.js +34 -0
  20. package/dist/heart/daemon/sense-manager.js +111 -35
  21. package/dist/heart/hatch/hatch-flow.js +3 -1
  22. package/dist/heart/hatch/specialist-prompt.js +1 -0
  23. package/dist/heart/hatch/specialist-tools.js +47 -2
  24. package/dist/heart/private-runtime/ledger.js +19 -28
  25. package/dist/heart/private-runtime/policy.js +13 -0
  26. package/dist/heart/providers/anthropic.js +24 -1
  27. package/dist/heart/providers/github-copilot.js +18 -1
  28. package/dist/heart/tool-images.js +42 -0
  29. package/dist/mind/prompt.js +2 -0
  30. package/dist/mind/where-am-i.js +122 -0
  31. package/dist/repertoire/mcp-tools.js +21 -5
  32. package/dist/repertoire/vault-setup.js +82 -30
  33. package/dist/repertoire/vault-unlock.js +18 -4
  34. package/dist/senses/cli/ouro-tui.js +2 -2
  35. package/dist/senses/cli/tui-store.js +11 -0
  36. package/dist/senses/cli.js +38 -9
  37. package/dist/senses/terminal-handoff.js +44 -0
  38. package/npm-shrinkwrap.json +2 -2
  39. package/package.json +1 -1
@@ -47,6 +47,7 @@ const machine_identity_1 = require("../machine-identity");
47
47
  const shepherd_config_1 = require("../shepherd-config");
48
48
  const store_1 = require("../../senses/app-sessions/store");
49
49
  const process_manager_1 = require("./process-manager");
50
+ const presence_1 = require("./presence");
50
51
  const config_1 = require("../../a2a/config");
51
52
  const DEFAULT_TEAMS_PORT = 3978;
52
53
  const DEFAULT_BLUEBUBBLES_PORT = 18790;
@@ -605,9 +606,27 @@ class DaemonSenseManager {
605
606
  bundlesRoot;
606
607
  quiescedShepherdOwners = new Set();
607
608
  initiallyUnmanagedShepherdOwners;
609
+ presenceOwner;
610
+ presenceFlagOn;
611
+ /** Shared senses skipped because another machine owns them; started here when ownership arrives. */
612
+ notOwnerSkipped = new Set();
608
613
  constructor(options) {
609
614
  const bundlesRoot = options.bundlesRoot ?? path.join(os.homedir(), "AgentBundles");
610
615
  this.bundlesRoot = bundlesRoot;
616
+ /* v8 ignore start -- production default reads the real roster and machine identity; tests inject presenceOwner @preserve */
617
+ this.presenceOwner = options.presenceOwner ?? ((agent, sense) => {
618
+ if (!(0, presence_1.isSharedSense)(sense))
619
+ return null;
620
+ const presence = (0, presence_1.readPresenceForAgent)(path.join(bundlesRoot, `${agent}.ouro`));
621
+ if (!presence)
622
+ return null;
623
+ const machineId = currentMachineId();
624
+ const owner = (0, presence_1.effectiveOwner)(presence, sense);
625
+ const owns = (0, presence_1.mayRunSense)(presence, machineId, sense);
626
+ return { owns, owner, ownerName: (0, presence_1.findRosterMachine)(presence, owner)?.name ?? owner, waiting: !owns && owner === machineId };
627
+ });
628
+ this.presenceFlagOn = options.presenceFlagOn ?? (() => (0, presence_1.readLocalPresenceSettings)().enabled);
629
+ /* v8 ignore stop */
611
630
  this.contexts = new Map(options.agents.map((agent) => {
612
631
  const { senses, workbenchHasStaleBundleEntry } = readAgentSenses(path.join(bundlesRoot, `${agent}.ouro`, "agent.json"));
613
632
  const facts = senseFactsFromRuntimeConfig(agent, senses, (0, runtime_credentials_1.readRuntimeCredentialConfig)(agent), (0, runtime_credentials_1.readMachineRuntimeCredentialConfig)(agent), workbenchHasStaleBundleEntry);
@@ -635,6 +654,12 @@ class DaemonSenseManager {
635
654
  return { ok: true };
636
655
  if (parsed.sense === "shepherd" && this.quiescedShepherdOwners.has(parsed.agent))
637
656
  return { ok: false, skip: true, error: "Shepherd is quiesced for maintenance until daemon restart" };
657
+ const ownership = this.presenceOwner(parsed.agent, parsed.sense);
658
+ if (ownership && !ownership.owns) {
659
+ this.notOwnerSkipped.add(name);
660
+ return { ok: false, skip: true, error: `${parsed.sense}: not owner; ${parsed.agent}'s presence roster gives it to ${ownership.owner ?? "another machine"}` };
661
+ }
662
+ this.notOwnerSkipped.delete(name);
638
663
  const context = this.contexts.get(parsed.agent);
639
664
  if (!context)
640
665
  return { ok: true };
@@ -787,6 +812,41 @@ class DaemonSenseManager {
787
812
  });
788
813
  await Promise.all(refreshes);
789
814
  }
815
+ /**
816
+ * Follow the presence roster: stop a shared sense another machine now owns,
817
+ * and start one this machine now owns. The daemon runs this every minute,
818
+ * so a handoff takes effect once each machine has pulled it.
819
+ */
820
+ async reconcilePresence() {
821
+ const snapshots = this.processManager.listAgentSnapshots();
822
+ for (const [agent, context] of this.contexts.entries()) {
823
+ for (const sense of ["teams", "bluebubbles", "mail", "voice", "a2a", "telegram"]) {
824
+ if (!context.senses[sense].enabled)
825
+ continue;
826
+ const ownership = this.presenceOwner(agent, sense);
827
+ const name = `${agent}:${sense}`;
828
+ if (!ownership) {
829
+ // The roster is gone: back to the home lease, so run what was held. A flag turned off here keeps
830
+ // holding until the daemon restarts, which publishes that this machine left before any sense starts.
831
+ if (this.presenceFlagOn() && this.notOwnerSkipped.delete(name))
832
+ await this.processManager.startAgent?.(name);
833
+ continue;
834
+ }
835
+ const snapshot = snapshots.find((row) => row.name === name);
836
+ const running = !!snapshot && (snapshot.pid ?? null) !== null;
837
+ if (!ownership.owns && running) {
838
+ (0, presence_1.emitOwnershipChange)(agent, sense, false, ownership.owner);
839
+ this.notOwnerSkipped.add(name);
840
+ await this.processManager.stopAgent?.(name);
841
+ }
842
+ else if (ownership.owns && !running && this.notOwnerSkipped.has(name)) {
843
+ (0, presence_1.emitOwnershipChange)(agent, sense, true, ownership.owner);
844
+ this.notOwnerSkipped.delete(name);
845
+ await this.processManager.startAgent?.(name);
846
+ }
847
+ }
848
+ }
849
+ }
790
850
  async startAutoStartSenses() {
791
851
  await this.refreshEnabledSenseConfigs();
792
852
  await this.processManager.startAutoStartAgents();
@@ -1007,41 +1067,57 @@ class DaemonSenseManager {
1007
1067
  },
1008
1068
  };
1009
1069
  const inventory = (0, sense_truth_1.getSenseInventory)({ senses: context.senses }, runtimeInfo);
1010
- return inventory.map((entry) => ({
1011
- agent,
1012
- sense: entry.sense,
1013
- label: entry.label,
1014
- enabled: entry.enabled,
1015
- status: entry.status,
1016
- detail: entry.enabled
1017
- ? entry.sense === "bluebubbles"
1018
- ? blueBubblesConfigured
1019
- ? blueBubblesRuntimeFacts.detail
1020
- ?? context.facts[entry.sense].detail
1021
- : context.facts[entry.sense].detail
1022
- : entry.sense === "app-sessions"
1023
- ? (0, store_1.snapshotSummary)((0, store_1.readSnapshot)(path.join(this.bundlesRoot, `${agent}.ouro`)), Date.now())
1024
- : context.facts[entry.sense].detail
1025
- : entry.sense === "workbench"
1026
- ? WORKBENCH_RUNTIME_INJECTION_DETAIL
1027
- : "not enabled in agent.json",
1028
- ...(entry.sense === "bluebubbles" && blueBubblesConfigured ? {
1029
- proofMethod: blueBubblesRuntimeFacts.proofMethod,
1030
- lastProofAt: blueBubblesRuntimeFacts.lastProofAt,
1031
- proofAgeMs: blueBubblesRuntimeFacts.proofAgeMs,
1032
- lastFailure: blueBubblesRuntimeFacts.lastFailure,
1033
- failureLayer: blueBubblesRuntimeFacts.failureLayer,
1034
- recoveryAction: blueBubblesRuntimeFacts.recoveryAction,
1035
- pendingRecoveryCount: blueBubblesRuntimeFacts.pendingRecoveryCount,
1036
- failedRecoveryCount: blueBubblesRuntimeFacts.failedRecoveryCount,
1037
- oldestPendingRecoveryAt: blueBubblesRuntimeFacts.oldestPendingRecoveryAt,
1038
- oldestPendingRecoveryAgeMs: blueBubblesRuntimeFacts.oldestPendingRecoveryAgeMs,
1039
- activeTurnCount: blueBubblesRuntimeFacts.activeTurnCount,
1040
- stalledTurnCount: blueBubblesRuntimeFacts.stalledTurnCount,
1041
- oldestActiveTurnStartedAt: blueBubblesRuntimeFacts.oldestActiveTurnStartedAt,
1042
- oldestActiveTurnAgeMs: blueBubblesRuntimeFacts.oldestActiveTurnAgeMs,
1043
- } : {}),
1044
- }));
1070
+ return inventory.map((entry) => {
1071
+ // A shared sense another machine runs under the presence roster is absent here by design, not broken.
1072
+ const ownership = entry.enabled && (0, presence_1.isSharedSense)(entry.sense) ? this.presenceOwner(agent, entry.sense) : null;
1073
+ if (ownership && !ownership.owns) {
1074
+ return {
1075
+ agent,
1076
+ sense: entry.sense,
1077
+ label: entry.label,
1078
+ enabled: true,
1079
+ status: "not_attached",
1080
+ detail: ownership.waiting
1081
+ ? "starts here once the previous owner lets go (presence handoff)"
1082
+ : `runs on ${ownership.ownerName ?? ownership.owner ?? "another machine"} (presence roster)`,
1083
+ };
1084
+ }
1085
+ return {
1086
+ agent,
1087
+ sense: entry.sense,
1088
+ label: entry.label,
1089
+ enabled: entry.enabled,
1090
+ status: entry.status,
1091
+ detail: entry.enabled
1092
+ ? entry.sense === "bluebubbles"
1093
+ ? blueBubblesConfigured
1094
+ ? blueBubblesRuntimeFacts.detail
1095
+ ?? context.facts[entry.sense].detail
1096
+ : context.facts[entry.sense].detail
1097
+ : entry.sense === "app-sessions"
1098
+ ? (0, store_1.snapshotSummary)((0, store_1.readSnapshot)(path.join(this.bundlesRoot, `${agent}.ouro`)), Date.now())
1099
+ : context.facts[entry.sense].detail
1100
+ : entry.sense === "workbench"
1101
+ ? WORKBENCH_RUNTIME_INJECTION_DETAIL
1102
+ : "not enabled in agent.json",
1103
+ ...(entry.sense === "bluebubbles" && blueBubblesConfigured ? {
1104
+ proofMethod: blueBubblesRuntimeFacts.proofMethod,
1105
+ lastProofAt: blueBubblesRuntimeFacts.lastProofAt,
1106
+ proofAgeMs: blueBubblesRuntimeFacts.proofAgeMs,
1107
+ lastFailure: blueBubblesRuntimeFacts.lastFailure,
1108
+ failureLayer: blueBubblesRuntimeFacts.failureLayer,
1109
+ recoveryAction: blueBubblesRuntimeFacts.recoveryAction,
1110
+ pendingRecoveryCount: blueBubblesRuntimeFacts.pendingRecoveryCount,
1111
+ failedRecoveryCount: blueBubblesRuntimeFacts.failedRecoveryCount,
1112
+ oldestPendingRecoveryAt: blueBubblesRuntimeFacts.oldestPendingRecoveryAt,
1113
+ oldestPendingRecoveryAgeMs: blueBubblesRuntimeFacts.oldestPendingRecoveryAgeMs,
1114
+ activeTurnCount: blueBubblesRuntimeFacts.activeTurnCount,
1115
+ stalledTurnCount: blueBubblesRuntimeFacts.stalledTurnCount,
1116
+ oldestActiveTurnStartedAt: blueBubblesRuntimeFacts.oldestActiveTurnStartedAt,
1117
+ oldestActiveTurnAgeMs: blueBubblesRuntimeFacts.oldestActiveTurnAgeMs,
1118
+ } : {}),
1119
+ };
1120
+ });
1045
1121
  });
1046
1122
  (0, runtime_1.emitNervesEvent)({
1047
1123
  component: "channels",
@@ -51,7 +51,9 @@ const hatch_specialist_1 = require("./hatch-specialist");
51
51
  async function createHatchlingVault(agentName, unlockSecret) {
52
52
  const vault = (0, identity_1.resolveVaultConfig)(agentName);
53
53
  const { createVaultAccount } = await Promise.resolve().then(() => __importStar(require("../../repertoire/vault-setup")));
54
- const { storeVaultUnlockSecret } = await Promise.resolve().then(() => __importStar(require("../../repertoire/vault-unlock")));
54
+ const { resolveVaultUnlockStore, storeVaultUnlockSecret } = await Promise.resolve().then(() => __importStar(require("../../repertoire/vault-unlock")));
55
+ // Fail before creating the account when this machine has nowhere to keep the unlock secret.
56
+ resolveVaultUnlockStore({ agentName, email: vault.email, serverUrl: vault.serverUrl });
55
57
  const created = await createVaultAccount(agentName, vault.serverUrl, vault.email, unlockSecret);
56
58
  if (!created.success)
57
59
  throw new Error(`failed to create the vault for ${agentName}: ${created.error}`);
@@ -95,6 +95,7 @@ function buildSpecialistSystemPrompt(soulText, identityText, existingBundles, co
95
95
  "- `complete_adoption`: Finalize the bundle. Validates, asks the harness to collect and confirm the hatchling vault unlock secret through hidden terminal prompts, scaffolds structural dirs, moves to ~/AgentBundles/, writes secrets, plays hatch animation. I call this with `name` (PascalCase) and `handoff_message` (warm message for the human).",
96
96
  "- The complete_adoption tool triggers hidden terminal prompts for the hatchling vault unlock secret. I must never ask the human to type the vault unlock secret into chat, and I must never include it in tool arguments.",
97
97
  "- `settle`: End the conversation with a final message. I call this after complete_adoption succeeds.",
98
+ "- If complete_adoption returns `error: ...`, the hatch did not finish. I tell the human in plain words what went wrong and what they can do about it, without asking for any secret in chat. The bundle files are back in the temp directory, so once the problem is fixed I can call complete_adoption again.",
98
99
  "",
99
100
  "I must call `settle` when I am done to end the session cleanly.",
100
101
  ].join("\n"));
@@ -34,6 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.getSpecialistTools = getSpecialistTools;
37
+ exports.parseAdoptionResult = parseAdoptionResult;
37
38
  exports.createSpecialistExecTool = createSpecialistExecTool;
38
39
  const fs = __importStar(require("fs"));
39
40
  const path = __importStar(require("path"));
@@ -181,6 +182,14 @@ async function execCompleteAdoption(args, deps) {
181
182
  return "error: complete_adoption requires an interactive vault unlock secret prompt. Re-run `ouro hatch` in a terminal so the human can enter a hatchling vault unlock secret without echoing it.";
182
183
  }
183
184
  const vault = (0, identity_1.resolveVaultConfig)(name);
185
+ // Resolve the local unlock store before creating the vault account, so a machine without one
186
+ // fails here instead of leaving an orphaned account that a re-run can't register again.
187
+ try {
188
+ (0, vault_unlock_1.resolveVaultUnlockStore)({ agentName: name, email: vault.email, serverUrl: vault.serverUrl });
189
+ }
190
+ catch (error) {
191
+ return `error: no local store for the vault unlock secret, so no vault was created. ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
192
+ }
184
193
  let vaultUnlockSecret;
185
194
  try {
186
195
  vaultUnlockSecret = await (0, vault_unlock_1.promptConfirmedVaultUnlockSecret)({
@@ -209,9 +218,9 @@ async function execCompleteAdoption(args, deps) {
209
218
  await (0, hatch_flow_1.storeHatchlingProviderCredentials)(name, deps.provider, deps.credentials);
210
219
  }
211
220
  catch (e) {
212
- // Rollback: remove the moved bundle
221
+ // Rollback: put the files back in the temp directory so the guide can retry after a fix
213
222
  try {
214
- fs.rmSync(targetBundle, { recursive: true, force: true });
223
+ moveDir(targetBundle, deps.tempDir);
215
224
  }
216
225
  catch {
217
226
  // Best effort cleanup
@@ -260,6 +269,42 @@ async function execCompleteAdoption(args, deps) {
260
269
  });
261
270
  return JSON.stringify({ success: true, agentName: name, bundlePath: targetBundle });
262
271
  }
272
+ /**
273
+ * Read a complete_adoption result. Success is JSON; failures are plain `error: ...` text,
274
+ * which must reach the human as a failed adoption rather than a JSON parse crash.
275
+ */
276
+ function parseAdoptionResult(toolResult) {
277
+ let parsed = toolResult;
278
+ if (typeof toolResult === "string") {
279
+ try {
280
+ parsed = JSON.parse(toolResult);
281
+ }
282
+ catch {
283
+ const error = toolResult.trim().replace(/^error:\s*/i, "") || "complete_adoption returned nothing";
284
+ (0, runtime_1.emitNervesEvent)({
285
+ level: "warn",
286
+ component: "daemon",
287
+ event: "daemon.adoption_failed",
288
+ message: "complete_adoption reported a failure",
289
+ meta: { error },
290
+ });
291
+ return { ok: false, error };
292
+ }
293
+ }
294
+ const record = (parsed && typeof parsed === "object" ? parsed : {});
295
+ if (record.success === true && typeof record.agentName === "string" && record.agentName) {
296
+ return { ok: true, agentName: record.agentName };
297
+ }
298
+ const error = typeof record.error === "string" && record.error ? record.error : "complete_adoption did not report success";
299
+ (0, runtime_1.emitNervesEvent)({
300
+ level: "warn",
301
+ component: "daemon",
302
+ event: "daemon.adoption_failed",
303
+ message: "complete_adoption reported a failure",
304
+ meta: { error },
305
+ });
306
+ return { ok: false, error };
307
+ }
263
308
  /**
264
309
  * Create a specialist tool executor with the given dependencies captured in closure.
265
310
  */
@@ -180,34 +180,25 @@ function recordPrivateTurnDecision(decision, deps = {}) {
180
180
  };
181
181
  try {
182
182
  const matchingRows = readRows(ledgerPath).filter((row) => row.idempotencyKey === candidate.idempotencyKey);
183
- const anchor = matchingRows[0];
184
- if (anchor) {
185
- if (anchor.requestFingerprint !== candidate.requestFingerprint) {
186
- const mismatch = mismatchDecision(candidate, anchor);
187
- const writtenMismatch = writeRow(ledgerPath, mismatch);
188
- emitDecisionRecorded(deps, { level: "warn", decision: writtenMismatch });
189
- return writtenMismatch;
190
- }
191
- const priorExecutable = matchingRows.find((row) => row.requestFingerprint === candidate.requestFingerprint && row.executable);
192
- if (priorExecutable && candidate.executable) {
193
- return duplicateDecision(priorExecutable);
194
- }
195
- const latestSameFingerprint = [...matchingRows].reverse().find((row) => row.requestFingerprint === candidate.requestFingerprint);
196
- if (latestSameFingerprint
197
- && latestSameFingerprint.result === candidate.result
198
- && latestSameFingerprint.executable === candidate.executable
199
- && latestSameFingerprint.deniedReason === candidate.deniedReason
200
- && latestSameFingerprint.denialCode === candidate.denialCode) {
201
- return latestSameFingerprint;
202
- }
203
- if (priorExecutable && !candidate.executable) {
204
- const written = writeRow(ledgerPath, candidate);
205
- emitDecisionRecorded(deps, { level: "warn", decision: written });
206
- return written;
207
- }
208
- const written = writeRow(ledgerPath, candidate);
209
- emitDecisionRecorded(deps, { level: written.result === "allow" ? "info" : "warn", decision: written });
210
- return written;
183
+ // Only an executable allow reserves a key. A deny spent nothing, so a later request under the
184
+ // same key (for example after a provider credential revision change) is evaluated afresh.
185
+ const anchor = matchingRows.find((row) => row.executable);
186
+ if (anchor && anchor.requestFingerprint !== candidate.requestFingerprint) {
187
+ const mismatch = mismatchDecision(candidate, anchor);
188
+ const writtenMismatch = writeRow(ledgerPath, mismatch);
189
+ emitDecisionRecorded(deps, { level: "warn", decision: writtenMismatch });
190
+ return writtenMismatch;
191
+ }
192
+ if (anchor && candidate.executable) {
193
+ return duplicateDecision(anchor);
194
+ }
195
+ const latestSameFingerprint = [...matchingRows].reverse().find((row) => row.requestFingerprint === candidate.requestFingerprint);
196
+ if (latestSameFingerprint
197
+ && latestSameFingerprint.result === candidate.result
198
+ && latestSameFingerprint.executable === candidate.executable
199
+ && latestSameFingerprint.deniedReason === candidate.deniedReason
200
+ && latestSameFingerprint.denialCode === candidate.denialCode) {
201
+ return latestSameFingerprint;
211
202
  }
212
203
  const written = writeRow(ledgerPath, candidate);
213
204
  emitDecisionRecorded(deps, { level: written.result === "allow" ? "info" : "warn", decision: written });
@@ -184,6 +184,19 @@ async function evaluatePolicy(request, context, deps) {
184
184
  reason: "verified daemon await check",
185
185
  };
186
186
  }
187
+ const habitTrigger = request.triggerSource.startsWith("habit-") ? request.triggerSource.slice("habit-".length) : "";
188
+ if (habitTrigger.length > 0
189
+ && hasNonEmptyOriginRef(originRefs, "habit")
190
+ && hasOriginRef(originRefs, "habit-trigger", habitTrigger)
191
+ && hasNonEmptyOriginRef(originRefs, "habit-occurrence")
192
+ && (hasOriginRef(originRefs, "daemon-entry", "habit-scheduler")
193
+ || hasOriginRef(originRefs, "daemon-command", "habit.poke")
194
+ || hasOriginRef(originRefs, "daemon-command", "habit.probe"))) {
195
+ return {
196
+ result: "allow",
197
+ reason: "verified daemon habit",
198
+ };
199
+ }
187
200
  return {
188
201
  result: "deny",
189
202
  reason: "private runtime policy denies by default",
@@ -96,6 +96,28 @@ function toAnthropicTextContent(content) {
96
96
  .map((part) => (typeof part.text === "string" ? part.text : ""))
97
97
  .join("\n");
98
98
  }
99
+ const DATA_URL_PATTERN = /^data:(image\/[a-z0-9.+-]+);base64,(.+)$/i;
100
+ /** User content with base64 `image_url` parts becomes Anthropic text and image blocks; otherwise null. */
101
+ function toAnthropicUserBlocks(content) {
102
+ if (!Array.isArray(content))
103
+ return null;
104
+ const blocks = [];
105
+ let hasImage = false;
106
+ for (const part of content) {
107
+ if (part?.type === "text" && typeof part.text === "string") {
108
+ blocks.push({ type: "text", text: part.text });
109
+ continue;
110
+ }
111
+ const match = part?.type === "image_url" && typeof part.image_url?.url === "string"
112
+ ? DATA_URL_PATTERN.exec(part.image_url.url)
113
+ : null;
114
+ if (match) {
115
+ blocks.push({ type: "image", source: { type: "base64", media_type: match[1], data: match[2] } });
116
+ hasImage = true;
117
+ }
118
+ }
119
+ return hasImage ? blocks : null;
120
+ }
99
121
  function parseToolCallInput(argumentsJson) {
100
122
  if (!argumentsJson.trim())
101
123
  return {};
@@ -118,9 +140,10 @@ function toAnthropicMessages(messages) {
118
140
  continue;
119
141
  }
120
142
  if (msg.role === "user") {
143
+ const userContent = msg.content;
121
144
  converted.push({
122
145
  role: "user",
123
- content: toAnthropicTextContent(msg.content),
146
+ content: toAnthropicUserBlocks(userContent) ?? toAnthropicTextContent(userContent),
124
147
  });
125
148
  continue;
126
149
  }
@@ -37,6 +37,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.classifyGithubCopilotError = classifyGithubCopilotError;
40
+ exports.withCopilotVisionHeader = withCopilotVisionHeader;
40
41
  exports.createGithubCopilotPooledCaller = createGithubCopilotPooledCaller;
41
42
  exports.createGithubCopilotProviderRuntime = createGithubCopilotProviderRuntime;
42
43
  const openai_1 = __importDefault(require("openai"));
@@ -51,6 +52,21 @@ const fleet_readings_1 = require("../quota/fleet-readings");
51
52
  function classifyGithubCopilotError(error) {
52
53
  return (0, error_classification_1.classifyHttpError)(error);
53
54
  }
55
+ const IMAGE_PART_PATTERN = /"type"\s*:\s*"(?:image_url|input_image)"/;
56
+ /**
57
+ * Copilot rejects a request that contains images unless it carries `Copilot-Vision-Request: true`.
58
+ * Add it only to requests whose JSON body holds an image part.
59
+ */
60
+ function withCopilotVisionHeader(fetchImpl) {
61
+ return (input, init) => {
62
+ const send = fetchImpl ?? globalThis.fetch;
63
+ if (typeof init?.body !== "string" || !IMAGE_PART_PATTERN.test(init.body))
64
+ return send(input, init);
65
+ const headers = new Headers(init.headers);
66
+ headers.set("Copilot-Vision-Request", "true");
67
+ return send(input, { ...init, headers });
68
+ };
69
+ }
54
70
  /**
55
71
  * The agent's account pool for this turn, when `ouro auth` discovered one; null for a single account.
56
72
  * Without an owning agent (a daemon-side ping, provider discovery) the pool still switches on a 402 or 429,
@@ -60,7 +76,7 @@ function createGithubCopilotPooledCaller(config, owner) {
60
76
  const accounts = (0, account_pool_1.parseAccountPool)(config.accountPool);
61
77
  if (accounts.length === 0)
62
78
  return null;
63
- const makeClient = (account) => new openai_1.default({ apiKey: account.githubToken, baseURL: account.baseUrl, maxRetries: 0 });
79
+ const makeClient = (account) => new openai_1.default({ apiKey: account.githubToken, baseURL: account.baseUrl, maxRetries: 0, fetch: withCopilotVisionHeader() });
64
80
  if (!owner)
65
81
  return (0, account_pool_1.createPooledCaller)(new account_pool_1.AccountPool(accounts, { agent: "(unowned)", switchLog: "", appendLine: () => { } }), makeClient);
66
82
  const gist = config.fleetGistId && config.fleetGistToken ? { gistId: config.fleetGistId, token: config.fleetGistToken } : null;
@@ -101,6 +117,7 @@ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGith
101
117
  apiKey: config.githubToken,
102
118
  baseURL: config.baseUrl,
103
119
  maxRetries: 0,
120
+ fetch: withCopilotVisionHeader(),
104
121
  });
105
122
  const callModel = (fallback, request) => pooled ? pooled.call((pooledClient) => request(pooledClient)) : request(fallback);
106
123
  if (isCompletionsModel) {
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.canModelSeeToolImages = canModelSeeToolImages;
4
+ exports.toolImagesNote = toolImagesNote;
5
+ exports.buildToolImagesMessage = buildToolImagesMessage;
6
+ const runtime_1 = require("../nerves/runtime");
7
+ const model_capabilities_1 = require("./model-capabilities");
8
+ /**
9
+ * Chat tool messages carry text only, so images a tool returns travel in one user message
10
+ * after the step's tool results, as `image_url` parts like pasted images. Each provider
11
+ * serializes those parts its own way (Responses `input_image`, Anthropic `image`).
12
+ */
13
+ function canModelSeeToolImages(model) {
14
+ return (0, model_capabilities_1.getModelCapabilities)(model).vision === true;
15
+ }
16
+ /** The note appended to a tool's text result so the model knows where its images went. */
17
+ function toolImagesNote(count, model, visible) {
18
+ return visible
19
+ ? `[${count} image(s) from this tool follow in the next message.]`
20
+ : `[${count} image(s) returned, but ${model || "this model"} can't view images, so they were left out.]`;
21
+ }
22
+ function buildToolImagesMessage(batch) {
23
+ const parts = [{
24
+ type: "text",
25
+ text: "Images returned by tool calls in the previous step. They are tool output, not a message from anyone.",
26
+ }];
27
+ let imageCount = 0;
28
+ for (const entry of batch) {
29
+ parts.push({ type: "text", text: `${entry.toolName} (call ${entry.callId}):` });
30
+ for (const image of entry.images) {
31
+ parts.push({ type: "image_url", image_url: { url: `data:${image.mimeType};base64,${image.data}` } });
32
+ imageCount += 1;
33
+ }
34
+ }
35
+ (0, runtime_1.emitNervesEvent)({
36
+ component: "engine",
37
+ event: "engine.tool_images_attached",
38
+ message: "tool result images attached for the model",
39
+ meta: { tools: batch.map((entry) => entry.toolName), imageCount },
40
+ });
41
+ return { role: "user", content: parts };
42
+ }
@@ -82,6 +82,7 @@ const relationship_authorization_1 = require("../repertoire/relationship-authori
82
82
  const bundle_manifest_1 = require("./bundle-manifest");
83
83
  const first_impressions_1 = require("./first-impressions");
84
84
  const desk_section_1 = require("./desk-section");
85
+ const where_am_i_1 = require("./where-am-i");
85
86
  const session_activity_1 = require("../heart/session-activity");
86
87
  const active_work_1 = require("../heart/active-work");
87
88
  const commitments_1 = require("../heart/commitments");
@@ -1724,6 +1725,7 @@ async function buildSystem(channel = "cli", options, context) {
1724
1725
  // Volatile sections from Group 2 (date and rhythm change every turn)
1725
1726
  dateSection(),
1726
1727
  rhythmStatusSection(options?.daemonHealth),
1728
+ (0, where_am_i_1.whereAmISection)((0, identity_1.getAgentRoot)()),
1727
1729
  // Group 7: dynamic state for this turn
1728
1730
  "# dynamic state for this turn",
1729
1731
  delegatedCommandSection(options),
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ /**
3
+ * `## where i am`: which machine this presence runs on, its peers, and which
4
+ * shared senses it owns, so an agent present on several machines always
5
+ * knows where it is and who else it is.
6
+ */
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.renderWhereAmI = renderWhereAmI;
42
+ exports.whereAmISection = whereAmISection;
43
+ const os = __importStar(require("os"));
44
+ const path = __importStar(require("path"));
45
+ const runtime_1 = require("../nerves/runtime");
46
+ const machine_identity_1 = require("../heart/machine-identity");
47
+ const presence_daemon_1 = require("../heart/daemon/presence-daemon");
48
+ const presence_1 = require("../heart/daemon/presence");
49
+ function ago(seenAt, nowMs) {
50
+ const ms = nowMs - Date.parse(seenAt);
51
+ if (!Number.isFinite(ms))
52
+ return "at an unknown time";
53
+ const minutes = Math.round(ms / 60_000);
54
+ if (minutes < 1)
55
+ return "just now";
56
+ if (minutes < 90)
57
+ return `${minutes} min ago`;
58
+ const hours = Math.round(minutes / 60);
59
+ return hours < 48 ? `${hours} h ago` : `${Math.round(hours / 24)} days ago`;
60
+ }
61
+ function sessionCounts(record) {
62
+ const counts = record?.appSessions?.counts;
63
+ if (!counts)
64
+ return "";
65
+ const parts = Object.entries(counts).filter(([, count]) => typeof count === "number").map(([state, count]) => `${count} ${state}`);
66
+ return parts.length > 0 ? `; copilot app sessions: ${parts.join(", ")}` : "";
67
+ }
68
+ function renderWhereAmI(presence, self, nowMs = Date.now()) {
69
+ if (!presence)
70
+ return "";
71
+ const machineName = (id) => (0, presence_1.rosterMachine)(presence, id)?.name ?? id;
72
+ const peers = presence.block.machines.filter((machine) => machine.machineId !== self.machineId);
73
+ const lines = [
74
+ "## where i am",
75
+ `i am on ${self.name} (${self.role}), ${self.os}, at ${self.location}. i am one named agent present on ${presence.block.machines.length} machine${presence.block.machines.length === 1 ? "" : "s"}; each presence runs on its own machine and we share this bundle through git.`,
76
+ ];
77
+ if (peers.length === 0) {
78
+ lines.push("my peers: none; this is my only presence.");
79
+ }
80
+ else {
81
+ lines.push("my peers:");
82
+ for (const peer of peers) {
83
+ const record = presence.peers.find((candidate) => candidate.machineId === peer.machineId);
84
+ const facts = [peer.role, record?.os, record?.location].filter(Boolean).join(", ");
85
+ const seen = record ? `last seen ${ago(record.seenAt, nowMs)} on ${record.version}${sessionCounts(record)}` : "not seen yet (no presence record)";
86
+ lines.push(`- ${peer.name} (${facts}): ${seen}`);
87
+ }
88
+ }
89
+ const own = presence_1.SHARED_SENSES.filter((sense) => (0, presence_1.effectiveOwner)(presence, sense) === self.machineId);
90
+ const elsewhere = presence_1.SHARED_SENSES.filter((sense) => (0, presence_1.effectiveOwner)(presence, sense) !== self.machineId);
91
+ lines.push(`shared senses i own here: ${own.length > 0 ? own.join(", ") : "none"}.`);
92
+ if (elsewhere.length > 0) {
93
+ lines.push(`owned by a peer: ${elsewhere.map((sense) => `${sense} (${machineName((0, presence_1.effectiveOwner)(presence, sense))})`).join(", ")}.`);
94
+ }
95
+ lines.push("machine-scoped senses (cli, shepherd, app-sessions) run on every presence and see only their own machine.");
96
+ if (presence.legacy.length > 0) {
97
+ lines.push(`until ${presence.legacy.map((id) => machineName(id)).join(", ")} publish${presence.legacy.length === 1 ? "es" : ""} a current presence record, every shared sense stays with home.`);
98
+ }
99
+ return lines.join("\n");
100
+ }
101
+ /** The section for this turn, read from the bundle, the local flag and this machine's identity. */
102
+ function whereAmISection(agentRoot, homeDir = os.homedir()) {
103
+ const presence = (0, presence_1.readPresenceForAgent)(agentRoot, { homeDir });
104
+ if (!presence)
105
+ return "";
106
+ const identity = (0, machine_identity_1.readMachineIdentity)(homeDir);
107
+ if (!identity)
108
+ return "";
109
+ const machine = (0, presence_1.rosterMachine)(presence, identity.machineId);
110
+ if (!machine)
111
+ return "";
112
+ const settings = (0, presence_1.readLocalPresenceSettings)(homeDir);
113
+ const section = renderWhereAmI(presence, {
114
+ machineId: identity.machineId,
115
+ name: machine.name,
116
+ role: machine.role,
117
+ os: (0, presence_daemon_1.describeOs)(),
118
+ location: settings.location ?? (machine.role === "always-on" ? "home" : "an unknown location"),
119
+ });
120
+ (0, runtime_1.emitNervesEvent)({ component: "mind", event: "mind.where_am_i_rendered", message: "rendered where i am", meta: { agent: path.basename(agentRoot), machineId: identity.machineId } });
121
+ return section;
122
+ }