@lobu/runtime-device 21.2.1 → 22.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +91 -83
  3. package/npm-shrinkwrap.json +492 -438
  4. package/package.json +12 -2
  5. package/vendor/cli/dist/commands/_lib/apply/apply-cmd.js +5 -6
  6. package/vendor/cli/dist/commands/_lib/apply/client.d.ts +1 -0
  7. package/vendor/cli/dist/commands/_lib/apply/client.js +26 -7
  8. package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +9 -1
  9. package/vendor/cli/dist/commands/_lib/apply/diff.d.ts +1 -0
  10. package/vendor/cli/dist/commands/_lib/apply/diff.js +46 -4
  11. package/vendor/cli/dist/commands/_lib/apply/map-config.js +18 -38
  12. package/vendor/cli/dist/commands/_lib/init-from-org/bootstrap.js +5 -17
  13. package/vendor/cli/dist/commands/init.d.ts +0 -2
  14. package/vendor/cli/dist/commands/init.js +0 -27
  15. package/vendor/cli/dist/commands/login.d.ts +17 -0
  16. package/vendor/cli/dist/commands/login.js +43 -17
  17. package/vendor/cli/dist/commands/memory/_lib/errors.d.ts +0 -8
  18. package/vendor/cli/dist/commands/memory/_lib/errors.js +0 -12
  19. package/vendor/cli/dist/commands/memory/_lib/mcp.js +6 -6
  20. package/vendor/cli/dist/commands/memory/_lib/seed-cmd.js +4 -10
  21. package/vendor/cli/dist/config/define.d.ts +21 -15
  22. package/vendor/cli/dist/config/define.js +2 -2
  23. package/vendor/cli/dist/connectors/README.md +7 -5
  24. package/vendor/cli/dist/connectors/_google/actions.ts +270 -0
  25. package/vendor/cli/dist/connectors/_google/discovery/calendar_v3.json +1 -0
  26. package/vendor/cli/dist/connectors/_google/discovery/chat_v1.json +1 -0
  27. package/vendor/cli/dist/connectors/_google/discovery/docs_v1.json +1 -0
  28. package/vendor/cli/dist/connectors/_google/discovery/drive_v3.json +1 -0
  29. package/vendor/cli/dist/connectors/_google/discovery/gmail_v1.json +1 -0
  30. package/vendor/cli/dist/connectors/_google/discovery/people_v1.json +1 -0
  31. package/vendor/cli/dist/connectors/_google/discovery/sheets_v4.json +1 -0
  32. package/vendor/cli/dist/connectors/_google/discovery/tasks_v1.json +1 -0
  33. package/vendor/cli/dist/connectors/_google/discovery/youtube_v3.json +1 -0
  34. package/vendor/cli/dist/connectors/_google/discovery.ts +442 -0
  35. package/vendor/cli/dist/connectors/_google/errors.ts +91 -0
  36. package/vendor/cli/dist/connectors/_google/list-feed.ts +223 -0
  37. package/vendor/cli/dist/connectors/_google/policies.ts +127 -0
  38. package/vendor/cli/dist/connectors/agentid.ts +43 -0
  39. package/vendor/cli/dist/connectors/chat-user-identity.ts +2 -1
  40. package/vendor/cli/dist/connectors/github-automation-events.ts +9 -0
  41. package/vendor/cli/dist/connectors/github-identity.ts +28 -3
  42. package/vendor/cli/dist/connectors/github.ts +101 -59
  43. package/vendor/cli/dist/connectors/google_calendar.ts +207 -719
  44. package/vendor/cli/dist/connectors/google_drive.ts +16 -2
  45. package/vendor/cli/dist/connectors/google_gmail.ts +51 -33
  46. package/vendor/cli/dist/connectors/herdr.ts +406 -0
  47. package/vendor/cli/dist/connectors/jira.ts +6 -6
  48. package/vendor/cli/dist/connectors/linear.ts +7 -4
  49. package/vendor/cli/dist/connectors/postgres.ts +27 -2
  50. package/vendor/cli/dist/connectors/tiktok-inbox-page.js +230 -0
  51. package/vendor/cli/dist/connectors/tiktok-web-page.js +211 -0
  52. package/vendor/cli/dist/connectors/tiktok_web.ts +286 -0
  53. package/vendor/cli/dist/connectors/whatsapp-web-adapter.js +228 -10
  54. package/vendor/cli/dist/connectors/whatsapp-web-helpers.ts +47 -14
  55. package/vendor/cli/dist/connectors/whatsapp-web-identity.ts +121 -0
  56. package/vendor/cli/dist/connectors/whatsapp_web.ts +170 -29
  57. package/vendor/cli/dist/connectors/x.ts +276 -136
  58. package/vendor/cli/dist/index.js +1 -37
  59. package/vendor/cli/dist/internal/context.d.ts +10 -0
  60. package/vendor/cli/dist/internal/context.js +26 -16
  61. package/vendor/cli/dist/internal/node-version.d.ts +1 -1
  62. package/vendor/cli/dist/internal/node-version.js +1 -1
  63. package/vendor/cli/dist/internal/oauth.d.ts +3 -1
  64. package/vendor/cli/dist/internal/oauth.js +4 -3
  65. package/vendor/cli/dist/internal/runtime-components.d.ts +9 -0
  66. package/vendor/cli/dist/internal/runtime-components.js +67 -2
  67. package/vendor/cli/dist/mac-auth.js +17 -1
  68. package/vendor/cli/dist/providers.json +1 -1
  69. package/vendor/cli/dist/runtime-components.json +4 -4
  70. package/vendor/cli/dist/templates/AGENTS.md.tmpl +11 -4
  71. package/vendor/cli/dist/templates/README.md.tmpl +1 -1
  72. package/vendor/cli/dist/vendor/ora/.bun-tag-fde20e9a6df212fa +0 -0
  73. package/vendor/cli/dist/vendor/ora/index.d.ts +332 -0
  74. package/vendor/cli/dist/vendor/ora/index.js +424 -0
  75. package/vendor/cli/dist/vendor/ora/license +9 -0
  76. package/vendor/cli/dist/vendor/ora/package.json +64 -0
  77. package/vendor/cli/dist/vendor/ora/readme.md +329 -0
  78. package/vendor/cli/package.json +2 -2
  79. package/vendor/connector-sdk/dist/browser-requirement.d.ts +36 -0
  80. package/vendor/connector-sdk/dist/browser-requirement.js +60 -0
  81. package/vendor/connector-sdk/dist/connector-runtime.d.ts +3 -1
  82. package/vendor/connector-sdk/dist/connector-runtime.js +10 -0
  83. package/vendor/connector-sdk/dist/connector-types.d.ts +159 -45
  84. package/vendor/connector-sdk/dist/define-connector.d.ts +4 -2
  85. package/vendor/connector-sdk/dist/define-connector.js +3 -0
  86. package/vendor/connector-sdk/dist/index.d.ts +5 -2
  87. package/vendor/connector-sdk/dist/index.js +1 -0
  88. package/vendor/connector-sdk/dist/reaction-client-types.d.ts +16 -21
  89. package/vendor/connector-sdk/dist/reaction-client-types.typecheck.d.ts +5 -0
  90. package/vendor/connector-sdk/package.json +5 -1
  91. package/vendor/connector-worker/dist/agent-turn/guest-entry.js +31 -27
  92. package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +131 -185
  93. package/vendor/connector-worker/dist/agent-turn/memory.d.ts +3 -2
  94. package/vendor/connector-worker/dist/agent-turn/memory.js +3 -20
  95. package/vendor/connector-worker/dist/agent-turn/types.d.ts +3 -15
  96. package/vendor/connector-worker/dist/agent-turn/workspace.d.ts +2 -2
  97. package/vendor/connector-worker/dist/agent-turn/workspace.js +2 -4
  98. package/vendor/connector-worker/dist/daemon/action-monitor.d.ts +12 -0
  99. package/vendor/connector-worker/dist/daemon/action-monitor.js +25 -0
  100. package/vendor/connector-worker/dist/daemon/agent-turn.js +0 -9
  101. package/vendor/connector-worker/dist/daemon/builtins/index.d.ts +12 -0
  102. package/vendor/connector-worker/dist/daemon/builtins/index.js +61 -1
  103. package/vendor/connector-worker/dist/daemon/builtins/os-shell.d.ts +2 -1
  104. package/vendor/connector-worker/dist/daemon/builtins/os-shell.js +40 -27
  105. package/vendor/connector-worker/dist/daemon/client.d.ts +5 -1
  106. package/vendor/connector-worker/dist/daemon/client.js +3 -0
  107. package/vendor/connector-worker/dist/daemon/device-concurrency.d.ts +8 -0
  108. package/vendor/connector-worker/dist/daemon/device-concurrency.js +13 -0
  109. package/vendor/connector-worker/dist/daemon/executor.d.ts +1 -1
  110. package/vendor/connector-worker/dist/daemon/executor.js +48 -117
  111. package/vendor/connector-worker/dist/daemon/log.d.ts +2 -0
  112. package/vendor/connector-worker/dist/daemon/log.js +23 -2
  113. package/vendor/connector-worker/dist/daemon/mac-device-daemon.d.ts +20 -4
  114. package/vendor/connector-worker/dist/daemon/mac-device-daemon.js +53 -13
  115. package/vendor/connector-worker/dist/daemon/native-bridge/client.d.ts +6 -0
  116. package/vendor/connector-worker/dist/daemon/native-bridge/client.js +15 -0
  117. package/vendor/connector-worker/dist/daemon/native-bridge/executor.js +2 -0
  118. package/vendor/connector-worker/dist/daemon/native-bridge/protocol.d.ts +1 -1
  119. package/vendor/connector-worker/dist/daemon/native-bridge/protocol.js +1 -0
  120. package/vendor/connector-worker/dist/daemon/poll-loop.d.ts +3 -0
  121. package/vendor/connector-worker/dist/daemon/poll-loop.js +5 -1
  122. package/vendor/connector-worker/dist/daemon/start.d.ts +1 -0
  123. package/vendor/connector-worker/dist/daemon/start.js +12 -5
  124. package/vendor/connector-worker/dist/executor/interface.d.ts +34 -2
  125. package/vendor/connector-worker/dist/executor/isolate.js +66 -15
  126. package/vendor/connector-worker/dist/executor/redact.d.ts +1 -0
  127. package/vendor/connector-worker/dist/executor/redact.js +97 -26
  128. package/vendor/connector-worker/dist/executor/runtime.d.ts +7 -0
  129. package/vendor/connector-worker/dist/executor/runtime.js +26 -0
  130. package/vendor/connector-worker/dist/isolate/bridge.js +3 -1
  131. package/vendor/connector-worker/dist/mac-device-daemon.js +10 -3
  132. package/vendor/connector-worker/package.json +2 -2
  133. package/vendor/core/dist/agent-policy.js +1 -1
  134. package/vendor/core/dist/agent-store.d.ts +2 -0
  135. package/vendor/core/dist/agent-tooling.d.ts +1 -1
  136. package/vendor/core/dist/agent-tooling.js +1 -1
  137. package/vendor/core/dist/capabilities.js +2 -0
  138. package/vendor/core/dist/contracts/agent-settings.d.ts +0 -11
  139. package/vendor/core/dist/contracts/agent-settings.js +1 -7
  140. package/vendor/core/dist/contracts/tools/collection-presentation.d.ts +93 -0
  141. package/vendor/core/dist/contracts/tools/collection-presentation.js +88 -0
  142. package/vendor/core/dist/contracts/tools/collection-selection.d.ts +47 -0
  143. package/vendor/core/dist/contracts/tools/collection-selection.js +74 -0
  144. package/vendor/core/dist/contracts/tools/manage-agents.d.ts +10 -4
  145. package/vendor/core/dist/contracts/tools/manage-auth-profiles.d.ts +1 -1
  146. package/vendor/core/dist/contracts/tools/manage-auth-profiles.js +5 -1
  147. package/vendor/core/dist/contracts/tools/manage-automations.d.ts +19 -4
  148. package/vendor/core/dist/contracts/tools/manage-automations.js +25 -8
  149. package/vendor/core/dist/contracts/tools/manage-connections.d.ts +1 -0
  150. package/vendor/core/dist/contracts/tools/manage-connections.js +3 -0
  151. package/vendor/core/dist/contracts/tools/manage-entity-schema.d.ts +11 -0
  152. package/vendor/core/dist/contracts/tools/manage-entity-schema.js +42 -3
  153. package/vendor/core/dist/contracts/tools/manage-entity.d.ts +181 -152
  154. package/vendor/core/dist/contracts/tools/manage-entity.js +118 -162
  155. package/vendor/core/dist/contracts/tools/manage-operations.d.ts +41 -3
  156. package/vendor/core/dist/contracts/tools/manage-operations.js +40 -2
  157. package/vendor/core/dist/contracts/tools/manage-views.d.ts +182 -7
  158. package/vendor/core/dist/contracts/tools/manage-views.js +49 -13
  159. package/vendor/core/dist/contracts/tools/read-knowledge.d.ts +11 -2
  160. package/vendor/core/dist/contracts/tools/read-knowledge.js +23 -3
  161. package/vendor/core/dist/contracts/tools/save-memory.d.ts +3 -6
  162. package/vendor/core/dist/contracts/tools/save-memory.js +2 -6
  163. package/vendor/core/dist/contracts/tools/view-attach.d.ts +2 -1
  164. package/vendor/core/dist/contracts/tools/view-attach.js +7 -2
  165. package/vendor/core/dist/contracts/worker/protocol.d.ts +122 -28
  166. package/vendor/core/dist/contracts/worker/protocol.js +81 -17
  167. package/vendor/core/dist/index.d.ts +3 -4
  168. package/vendor/core/dist/index.js +3 -6
  169. package/vendor/core/dist/json-template.d.ts +6 -10
  170. package/vendor/core/dist/json-template.js +5 -9
  171. package/vendor/core/dist/logger.js +11 -5
  172. package/vendor/core/dist/shell-safety.d.ts +9 -0
  173. package/vendor/core/dist/shell-safety.js +154 -0
  174. package/vendor/core/dist/suggestions.d.ts +1 -1
  175. package/vendor/core/dist/suggestions.js +1 -1
  176. package/vendor/core/dist/tool-trace-summary.d.ts +1 -1
  177. package/vendor/core/dist/tool-trace-summary.js +1 -1
  178. package/vendor/core/dist/types.d.ts +1 -3
  179. package/vendor/core/dist/utils/diagnostic-scrubber.d.ts +7 -0
  180. package/vendor/core/dist/utils/{sentry-scrubber.js → diagnostic-scrubber.js} +25 -53
  181. package/vendor/core/dist/worker/auth.d.ts +44 -6
  182. package/vendor/core/dist/worker/auth.js +44 -11
  183. package/vendor/core/package.json +15 -6
  184. package/vendor/ora/.bun-tag-fde20e9a6df212fa +0 -0
  185. package/vendor/ora/index.d.ts +332 -0
  186. package/vendor/ora/index.js +424 -0
  187. package/vendor/ora/license +9 -0
  188. package/vendor/ora/package.json +53 -0
  189. package/vendor/ora/readme.md +329 -0
  190. package/vendor/cli/dist/commands/telemetry.d.ts +0 -10
  191. package/vendor/cli/dist/commands/telemetry.js +0 -66
  192. package/vendor/core/dist/sentry.d.ts +0 -26
  193. package/vendor/core/dist/sentry.js +0 -133
  194. package/vendor/core/dist/tool-policy.d.ts +0 -74
  195. package/vendor/core/dist/tool-policy.js +0 -305
  196. package/vendor/core/dist/utils/sentry-scrubber.d.ts +0 -29
@@ -22,7 +22,6 @@ import { createGatewayTools } from './gateway-tools.js';
22
22
  import { createTurnMediaTools } from './media-tools.js';
23
23
  import { createTurnMemoryHooks } from './memory.js';
24
24
  import { estimatePromptTokenCost, memoryFlushDue, MEMORY_FLUSH_STATE_CUSTOM_TYPE } from '@lobu/core/memory-flush';
25
- import { enforceBashCommandPolicy } from '@lobu/core/tool-policy';
26
25
  import { isRetrievalTool, summarizeToolTrace } from '@lobu/core/tool-trace-summary';
27
26
  import { createNativeSession, nativeSessionJsonl, promptNativeSession } from './native-session.js';
28
27
  import { MAX_TOOL_CALLS_PER_TURN } from './types.js';
@@ -63,8 +62,9 @@ async function callMcpTool(gatewayUrl, credential, tool, args, timeoutMs = TOOL_
63
62
  Authorization: `Bearer ${credential}`,
64
63
  'Content-Type': 'application/json',
65
64
  // A retrieval result is summarised into the tool trace from its
66
- // structured body; the gateway renders markdown unless asked.
67
- ...(isRetrievalTool(tool.name) ? { 'x-mcp-format': 'json' } : {}),
65
+ // structured body; capture validates the save receipt. The gateway
66
+ // renders markdown unless asked.
67
+ ...(isRetrievalTool(tool.name) || tool.name === 'save_memory' ? { 'x-mcp-format': 'json' } : {}),
68
68
  },
69
69
  body: JSON.stringify(args ?? {}),
70
70
  signal: AbortSignal.timeout(timeoutMs),
@@ -84,10 +84,15 @@ async function callMcpTool(gatewayUrl, credential, tool, args, timeoutMs = TOOL_
84
84
  throw new Error(`${tool.name} returned a non-JSON response (status ${response.status}): ${error instanceof Error ? error.message : String(error)}`);
85
85
  }
86
86
  const text = joinText(reply.content);
87
- if (!response.ok || reply.isError) {
87
+ if (!response.ok) {
88
88
  throw new Error(reply.error || text || `${tool.name} failed (${response.status})`);
89
89
  }
90
- return text || `${tool.name} completed.`;
90
+ // Keep the canonical failure flag and receipt through the plugin boundary.
91
+ // Ordinary agent tools render this same result below; no second transport.
92
+ return {
93
+ ...reply,
94
+ content: [{ type: 'text', text: text || reply.error || '' }],
95
+ };
91
96
  }
92
97
  /**
93
98
  * pi's tool objects for the turn's manifest: the gateway's MCP tools, then its
@@ -107,7 +112,7 @@ function buildTools(input, credential, onAskUserPosted, onInBandReplyDelivered,
107
112
  // On a sandbox-pinned conversation `bash` runs in the remote runtime through
108
113
  // the host; file tools stay on the in-memory workspace.
109
114
  const remote = tools.remoteRuntime && runtimeExec ? { exec: runtimeExec } : undefined;
110
- const workspace = tools.builtin && tools.builtin.length > 0 ? createWorkspace(tools.builtin, tools.bashPolicy, remote) : null;
115
+ const workspace = tools.builtin && tools.builtin.length > 0 ? createWorkspace(tools.builtin, remote) : null;
111
116
  const gateway = tools.gateway && tools.gateway.length > 0 && tools.conversation
112
117
  ? createGatewayTools(tools.gateway, {
113
118
  gatewayUrl: tools.gatewayUrl,
@@ -134,25 +139,19 @@ function buildTools(input, credential, onAskUserPosted, onInBandReplyDelivered,
134
139
  description: tool.description,
135
140
  // A plain JSON schema: pi-ai validates arguments against it as-is.
136
141
  parameters: tool.inputSchema,
137
- execute: async (_toolCallId, args) => ({
138
- content: [{ type: 'text', text: await callMcpTool(tools.gatewayUrl, credential, tool, args) }],
139
- details: {},
140
- }),
142
+ execute: async (_toolCallId, args) => {
143
+ const result = await callMcpTool(tools.gatewayUrl, credential, tool, args);
144
+ const text = joinText(result.content);
145
+ if (result.isError === true)
146
+ throw new Error(String(result.error || text || `${tool.name} failed`));
147
+ return {
148
+ content: [{ type: 'text', text: text || `${tool.name} completed.` }],
149
+ details: {},
150
+ };
151
+ },
141
152
  }));
142
- // `read` opens a seeded file directly. `bash` counts only when its command
143
- // policy admits `cat`; a strict bash allowlist can expose the tool while
144
- // still making every seeded file unreachable.
145
- let bashCanRead = false;
146
- if ((tools.builtin ?? []).includes('bash') && !tools.remoteRuntime) {
147
- try {
148
- if (tools.bashPolicy)
149
- enforceBashCommandPolicy('cat input/attachment', tools.bashPolicy);
150
- bashCanRead = true;
151
- }
152
- catch {
153
- // The prompt must not advertise a path this turn cannot open.
154
- }
155
- }
153
+ // Remote bash cannot open the isolate's seeded files.
154
+ const bashCanRead = (tools.builtin ?? []).includes('bash') && !tools.remoteRuntime;
156
155
  const canReadFiles = workspace !== null && ((tools.builtin ?? []).includes('read') || bashCanRead);
157
156
  return {
158
157
  tools: [...mcp, ...gateway, ...media, ...(workspace?.tools ?? [])],
@@ -714,7 +713,13 @@ export async function runAgentTurn(input, emit, takeSteering = () => [], runtime
714
713
  // but a spent budget or an asked question is a deliberate stop, and the
715
714
  // text streamed before it is a real answer worth delivering — throwing
716
715
  // here would turn it into a failed turn with nothing shown.
717
- const ended = guardStopped ? null : agent.state.errorMessage;
716
+ settleAnswer();
717
+ const finalText = ownerAnswer ?? ownerText;
718
+ // Tool-only turns can already have delivered their reply. Reject only a
719
+ // provider-only turn with nothing to show, after native recovery settles.
720
+ const ended = (guardStopped ? null : agent.state.errorMessage) ||
721
+ (!finalText.trim() && toolsUsed.size === 0 && steeredToolsUsed.size === 0
722
+ ? 'The model returned no response. Please try again.' : null);
718
723
  // Capture BEFORE returning, and await it. `agentEnd` itself only starts the
719
724
  // write; this isolate is disposed the moment this function resolves, so an
720
725
  // unawaited capture would be cancelled every time
@@ -729,7 +734,6 @@ export async function runAgentTurn(input, emit, takeSteering = () => [], runtime
729
734
  }
730
735
  if (ended)
731
736
  throw new Error(ended);
732
- settleAnswer();
733
737
  return {
734
738
  // The answer is the last assistant message WITH TEXT after each user
735
739
  // message, not the accumulated stream: a model that narrates before a
@@ -752,7 +756,7 @@ export async function runAgentTurn(input, emit, takeSteering = () => [], runtime
752
756
  // aborted mid-answer still owes the user what it managed to say. The
753
757
  // fallback is the owner's only: a steered input without its own settled
754
758
  // answer fails below rather than borrowing a sibling's text.
755
- text: ownerAnswer ?? ownerText,
759
+ text: finalText,
756
760
  stopReason,
757
761
  usage,
758
762
  sessionJsonl: nativeSessionJsonl(session),
@@ -4333,7 +4333,7 @@ var init_agent_policy = __esm({
4333
4333
  description: "Post a message to one of your conversations. Pass a conversation handle (from list_conversations) to post to the channel, or a thread handle (returned by a previous send_message) to reply in that thread. This is how an automated/scheduled run speaks in its channel."
4334
4334
  },
4335
4335
  present_event: {
4336
- description: "Render an existing Lobu event in the current conversation through its declared json_template. Use the event id returned by knowledge.save; do not hand-author platform card JSON or action ids."
4336
+ description: "Present an existing Lobu event as a summary and Open event link in the current conversation. Custom interactions open in its React view. Use the event id returned by knowledge.save; do not hand-author platform card JSON or action ids."
4337
4337
  },
4338
4338
  schedule_followup: {
4339
4339
  description: "Schedule one durable future wake-up for yourself in the current conversation. The server fixes the agent and destination from the signed turn; provide a stable idempotency key so retries do not duplicate the wake-up."
@@ -17146,7 +17146,7 @@ var require_agent_policy = __commonJS({
17146
17146
  description: "Post a message to one of your conversations. Pass a conversation handle (from list_conversations) to post to the channel, or a thread handle (returned by a previous send_message) to reply in that thread. This is how an automated/scheduled run speaks in its channel."
17147
17147
  },
17148
17148
  present_event: {
17149
- description: "Render an existing Lobu event in the current conversation through its declared json_template. Use the event id returned by knowledge.save; do not hand-author platform card JSON or action ids."
17149
+ description: "Present an existing Lobu event as a summary and Open event link in the current conversation. Custom interactions open in its React view. Use the event id returned by knowledge.save; do not hand-author platform card JSON or action ids."
17150
17150
  },
17151
17151
  schedule_followup: {
17152
17152
  description: "Schedule one durable future wake-up for yourself in the current conversation. The server fixes the agent and destination from the signed turn; provide a stable idempotency key so retries do not duplicate the wake-up."
@@ -18015,19 +18015,14 @@ var require_bash_command_parser = __commonJS({
18015
18015
  }
18016
18016
  });
18017
18017
 
18018
- // ../core/dist/tool-policy.js
18019
- var require_tool_policy = __commonJS({
18020
- "../core/dist/tool-policy.js"(exports2) {
18018
+ // ../core/dist/shell-safety.js
18019
+ var require_shell_safety = __commonJS({
18020
+ "../core/dist/shell-safety.js"(exports2) {
18021
18021
  "use strict";
18022
18022
  Object.defineProperty(exports2, "__esModule", { value: true });
18023
- exports2.DEFAULT_PACKAGE_MANAGER_DENY_PREFIXES = void 0;
18024
- exports2.normalizeToolList = normalizeToolList;
18025
- exports2.buildToolPolicy = buildToolPolicy;
18026
- exports2.isToolAllowedByPolicy = isToolAllowedByPolicy;
18027
18023
  exports2.isDirectPackageInstallCommand = isDirectPackageInstallCommand2;
18028
- exports2.enforceBashCommandPolicy = enforceBashCommandPolicy3;
18029
18024
  var bash_command_parser_1 = require_bash_command_parser();
18030
- exports2.DEFAULT_PACKAGE_MANAGER_DENY_PREFIXES = [
18025
+ var PACKAGE_MANAGER_DENY_PREFIXES = [
18031
18026
  "apt ",
18032
18027
  "apt-get ",
18033
18028
  "yum ",
@@ -18106,85 +18101,6 @@ var require_tool_policy = __commonJS({
18106
18101
  "poetry add ",
18107
18102
  "composer require "
18108
18103
  ];
18109
- function normalizeToolName(name) {
18110
- return name.trim().toLowerCase();
18111
- }
18112
- function normalizeToolList(value) {
18113
- if (!value) {
18114
- return [];
18115
- }
18116
- const rawList = Array.isArray(value) ? value : value.split(/[,\n]/);
18117
- return rawList.map((entry) => typeof entry === "string" ? entry.trim() : String(entry).trim()).filter((entry) => entry.length > 0);
18118
- }
18119
- function parseBashFilter(pattern) {
18120
- const match2 = pattern.match(/^Bash\(([^:]+):\*\)$/i);
18121
- const prefix = match2?.[1]?.trim();
18122
- return prefix || null;
18123
- }
18124
- function matchesToolPattern(toolName, pattern) {
18125
- const normalizedTool = normalizeToolName(toolName);
18126
- const normalizedPattern = pattern.trim();
18127
- const normalizedPatternLower = normalizedPattern.toLowerCase();
18128
- if (normalizedPattern === "*") {
18129
- return true;
18130
- }
18131
- if (normalizedPatternLower.endsWith("*")) {
18132
- const prefix = normalizedPatternLower.slice(0, -1);
18133
- return normalizedTool.startsWith(prefix);
18134
- }
18135
- return normalizedTool === normalizedPatternLower;
18136
- }
18137
- function buildToolPolicy(params) {
18138
- const allowedPatterns = normalizeToolList(params.allowedTools);
18139
- const deniedPatterns = normalizeToolList(params.disallowedTools);
18140
- const toolsConfig = params.toolsConfig;
18141
- const strictMode = toolsConfig?.strictMode === true;
18142
- const mergedAllowed = [
18143
- ...toolsConfig?.allowedTools ?? [],
18144
- ...allowedPatterns
18145
- ].map((p) => p.trim());
18146
- const mergedDenied = [
18147
- ...toolsConfig?.deniedTools ?? [],
18148
- ...deniedPatterns
18149
- ].map((p) => p.trim());
18150
- const bashAllowPrefixes = mergedAllowed.map((pattern) => parseBashFilter(pattern)).filter((prefix) => Boolean(prefix));
18151
- const bashDenyPrefixes = mergedDenied.map((pattern) => parseBashFilter(pattern)).filter((prefix) => Boolean(prefix));
18152
- const bashAllowAll = mergedAllowed.some((pattern) => matchesToolPattern("bash", pattern));
18153
- return {
18154
- toolsConfig,
18155
- allowedPatterns: mergedAllowed,
18156
- deniedPatterns: mergedDenied,
18157
- strictMode,
18158
- bashPolicy: {
18159
- allowAll: bashAllowAll,
18160
- allowPrefixes: bashAllowPrefixes,
18161
- denyPrefixes: [
18162
- ...exports2.DEFAULT_PACKAGE_MANAGER_DENY_PREFIXES,
18163
- ...bashDenyPrefixes
18164
- ]
18165
- }
18166
- };
18167
- }
18168
- function isToolAllowedByPolicy(toolName, policy) {
18169
- const normalizedName = normalizeToolName(toolName);
18170
- const { allowedPatterns, deniedPatterns, strictMode } = policy;
18171
- const explicitDenied = deniedPatterns.some((pattern) => !parseBashFilter(pattern) && matchesToolPattern(normalizedName, pattern));
18172
- if (explicitDenied) {
18173
- return false;
18174
- }
18175
- if (normalizedName === "bash") {
18176
- if (strictMode) {
18177
- const explicitlyAllowed = allowedPatterns.some((pattern) => matchesToolPattern(normalizedName, pattern));
18178
- const hasCommandAllowlist = policy.bashPolicy.allowPrefixes.length > 0;
18179
- return explicitlyAllowed || hasCommandAllowlist;
18180
- }
18181
- return true;
18182
- }
18183
- if (!strictMode) {
18184
- return true;
18185
- }
18186
- return allowedPatterns.some((pattern) => matchesToolPattern(normalizedName, pattern));
18187
- }
18188
18104
  var DIRECT_PACKAGE_INSTALL_PATTERNS = [
18189
18105
  /(^|[\s;|&()])(?:sudo\s+)?(?:apt|apt-get|yum|dnf|apk|pacman|zypper|brew)\s+(?:install|upgrade|add)\b/i,
18190
18106
  /(^|[\s;|&()])(?:sudo\s+)?(?:nix-shell|nix-env)\b/i,
@@ -18216,7 +18132,9 @@ var require_tool_policy = __commonJS({
18216
18132
  if (trimmed.length > MAX_SCANNED_COMMAND_LENGTH) {
18217
18133
  return true;
18218
18134
  }
18219
- const matches = (text2) => exports2.DEFAULT_PACKAGE_MANAGER_DENY_PREFIXES.some((prefix) => text2.startsWith(prefix.toLowerCase())) || DIRECT_PACKAGE_INSTALL_PATTERNS.some((pattern) => pattern.test(text2));
18135
+ if ((0, bash_command_parser_1.splitShellCommands)(command).some((segment) => PACKAGE_MANAGER_DENY_PREFIXES.some((prefix) => segment.toLowerCase().startsWith(prefix.toLowerCase()))))
18136
+ return true;
18137
+ const matches = (text2) => PACKAGE_MANAGER_DENY_PREFIXES.some((prefix) => text2.startsWith(prefix.toLowerCase())) || DIRECT_PACKAGE_INSTALL_PATTERNS.some((pattern) => pattern.test(text2));
18220
18138
  if ((0, bash_command_parser_1.matchesBeforeArgumentData)((0, bash_command_parser_1.blankQuotedSpans)(trimmed), matches)) {
18221
18139
  return true;
18222
18140
  }
@@ -18229,29 +18147,6 @@ var require_tool_policy = __commonJS({
18229
18147
  }
18230
18148
  return false;
18231
18149
  }
18232
- function enforceBashCommandPolicy3(command, policy) {
18233
- if (!command.trim()) {
18234
- return;
18235
- }
18236
- const segments = (0, bash_command_parser_1.splitShellCommands)(command);
18237
- if (segments.length === 0) {
18238
- return;
18239
- }
18240
- const hasAllowlist = !policy.allowAll && policy.allowPrefixes.length > 0;
18241
- for (const segment of segments) {
18242
- const normalizedSegment = segment.toLowerCase();
18243
- const denied = policy.denyPrefixes.some((prefix) => normalizedSegment.startsWith(prefix.toLowerCase()));
18244
- if (denied) {
18245
- throw new Error("Bash command denied by policy");
18246
- }
18247
- if (hasAllowlist) {
18248
- const allowed = policy.allowPrefixes.some((prefix) => normalizedSegment.startsWith(prefix.toLowerCase()));
18249
- if (!allowed) {
18250
- throw new Error("Bash command not allowed by policy");
18251
- }
18252
- }
18253
- }
18254
- }
18255
18150
  }
18256
18151
  });
18257
18152
 
@@ -35856,6 +35751,57 @@ var require_dist6 = __commonJS({
35856
35751
  var plugin_toolkit_1 = require_dist2();
35857
35752
  var MEMORY_RECALL_LIMIT = 6;
35858
35753
  var MEMORY_TOOL_TIMEOUT_MS = 8e3;
35754
+ function withoutRecall(text2) {
35755
+ return text2.replace(/<lobu-memory\b[^>]*>[\s\S]*?(?:<\/lobu-memory\s*>|$)/gi, "").trim();
35756
+ }
35757
+ function quotedExcerpt(text2, budget) {
35758
+ const quoted = JSON.stringify(text2);
35759
+ if (quoted.length <= budget)
35760
+ return quoted;
35761
+ const marker = "\n[... excerpt truncated ...]\n";
35762
+ let keep = budget - JSON.stringify(marker).length - 2;
35763
+ while (keep > 0) {
35764
+ const head = Math.floor(keep / 3);
35765
+ const excerpt = JSON.stringify(text2.slice(0, head) + marker + text2.slice(-(keep - head)));
35766
+ if (excerpt.length <= budget)
35767
+ return excerpt;
35768
+ keep -= Math.max(1, Math.ceil((excerpt.length - budget) / 6));
35769
+ }
35770
+ return JSON.stringify(marker);
35771
+ }
35772
+ function recallQuery(prompt, messages) {
35773
+ if (prompt.length > 200 || !/^(?:(?:what|how) about (?:it|its|that|this|them|their|those|these)\b|(?:why|how|when|where) (?:is|was|does|did|will|would|can|should) (?:it|that|this|they|those|these)\b|(?:can you |please )?(?:explain|expand on|summarize) (?:that|this|it)[?.!]*$|(?:can you |please )?(?:draft|write|prepare|revise|update|fix) (?:it|that|this|them)(?:[?.!]*$| (?:using|with|based on|again|now|up)\b)|(?:what did we decide|go on|continue)[?.!]*$)/i.test(prompt))
35774
+ return prompt;
35775
+ const recent = messages.slice(-12);
35776
+ const current = lastMessage(recent, "user");
35777
+ if (current?.text === prompt && current.index === recent.length - 1)
35778
+ recent.pop();
35779
+ const user = lastMessage(recent, "user");
35780
+ if (!user)
35781
+ return prompt;
35782
+ const assistant = lastMessage(recent, "assistant");
35783
+ const context = [`user: ${quotedExcerpt(user.text, 700)}`];
35784
+ if (assistant && assistant.index > user.index) {
35785
+ context.push(`assistant (not user assertions): ${quotedExcerpt(assistant.text, 700)}`);
35786
+ }
35787
+ return `${prompt}
35788
+ Recent conversation excerpts (context only):
35789
+ ${context.join("\n")}`;
35790
+ }
35791
+ function resultText(result) {
35792
+ const text2 = (0, plugin_toolkit_1.joinTextContent)(result.content).trim();
35793
+ if (result.isError === true || result.isError === void 0 && /^error:/i.test(text2)) {
35794
+ throw new Error(text2 || "Memory tool failed");
35795
+ }
35796
+ return text2;
35797
+ }
35798
+ function checkReceipt(result) {
35799
+ const text2 = resultText(result);
35800
+ const receipt = result.structuredContent !== void 0 ? result.structuredContent : JSON.parse(text2);
35801
+ if (!receipt || typeof receipt !== "object" || !Number.isSafeInteger(receipt.id) || receipt.id <= 0 || typeof receipt.durable_at !== "string" || !Number.isFinite(Date.parse(receipt.durable_at))) {
35802
+ throw new Error("save_memory returned an invalid durable receipt");
35803
+ }
35804
+ }
35859
35805
  function messageText2(message) {
35860
35806
  if (typeof message !== "object" || message === null)
35861
35807
  return "";
@@ -35866,20 +35812,21 @@ var require_dist6 = __commonJS({
35866
35812
  return "";
35867
35813
  return content.filter((part) => typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
35868
35814
  }
35869
- function lastMessage(messages, role, before = messages.length) {
35870
- for (let index2 = Math.min(before, messages.length) - 1; index2 >= 0; index2--) {
35815
+ function lastMessage(messages, role) {
35816
+ for (let index2 = messages.length - 1; index2 >= 0; index2--) {
35871
35817
  const message = messages[index2];
35872
35818
  if (typeof message !== "object" || message === null || message.role !== role) {
35873
35819
  continue;
35874
35820
  }
35875
- const text2 = messageText2(message).trim();
35821
+ const text2 = withoutRecall(messageText2(message));
35876
35822
  if (text2)
35877
35823
  return { index: index2, text: text2 };
35824
+ if (role === "user")
35825
+ return null;
35878
35826
  }
35879
35827
  return null;
35880
35828
  }
35881
35829
  function createMemoryPlugin2(gateway, invokeTool) {
35882
- let promptForCapture = "";
35883
35830
  let capture = null;
35884
35831
  const plugin = (0, plugin_api_1.defineLobuPlugin)({
35885
35832
  manifest: {
@@ -35890,26 +35837,27 @@ var require_dist6 = __commonJS({
35890
35837
  },
35891
35838
  hooks: {
35892
35839
  beforeAgentStart: async (event, context) => {
35893
- const query = event.prompt.trim();
35894
- promptForCapture = query;
35895
- if (!query || /heartbeat|question:q_/i.test(query))
35840
+ const prompt = withoutRecall(event.prompt);
35841
+ if (!prompt)
35896
35842
  return;
35897
- const result = await invokeTool(gateway, "lobu", "search_memory", {
35898
- query,
35899
- include_content: true,
35900
- content_limit: MEMORY_RECALL_LIMIT,
35901
- include_connections: false,
35902
- limit: 3
35903
- }, { timeoutMs: MEMORY_TOOL_TIMEOUT_MS });
35904
- const recalled = (0, plugin_toolkit_1.joinTextContent)(result.content).trim();
35905
- if (!recalled || /^error:/i.test(recalled)) {
35906
- if (recalled) {
35907
- context.logger.warn("Plugin memory recall skipped", {
35908
- error: recalled
35909
- });
35910
- }
35843
+ let recalled;
35844
+ try {
35845
+ const result = await invokeTool(gateway, "lobu", "search_memory", {
35846
+ query: recallQuery(prompt, event.messages),
35847
+ include_content: true,
35848
+ content_limit: MEMORY_RECALL_LIMIT,
35849
+ include_connections: false,
35850
+ limit: 3
35851
+ }, { timeoutMs: MEMORY_TOOL_TIMEOUT_MS });
35852
+ recalled = resultText(result);
35853
+ } catch (error) {
35854
+ context.logger.warn("Plugin memory recall skipped", {
35855
+ error: error instanceof Error ? error.message : String(error)
35856
+ });
35911
35857
  return;
35912
35858
  }
35859
+ if (!recalled)
35860
+ return;
35913
35861
  return {
35914
35862
  prependContext: `<lobu-memory>
35915
35863
  Use these long-term memories only when directly relevant to the user's request.
@@ -35922,21 +35870,30 @@ ${recalled}
35922
35870
  agentEnd: (event, context) => {
35923
35871
  if (event.error)
35924
35872
  return;
35873
+ const user = lastMessage(event.messages, "user");
35925
35874
  const assistant = lastMessage(event.messages, "assistant");
35926
- if (!assistant)
35927
- return;
35928
- const user = lastMessage(event.messages, "user", assistant.index);
35929
- if (!user)
35930
- return;
35931
- const userText = promptForCapture && user.text.endsWith(promptForCapture) ? promptForCapture : user.text.replace(/<lobu-memory>[\s\S]*?<\/lobu-memory>/gi, "").trim();
35932
- const combined = `User: ${userText}
35933
- Assistant: ${assistant.text}`;
35934
- if (combined.length < 16)
35875
+ if (!user || !assistant || assistant.index <= user.index)
35935
35876
  return;
35877
+ const content = [
35878
+ "Conversation excerpts, not a full transcript. Use the original conversation transcript as primary evidence.",
35879
+ `User (verbatim excerpt): ${quotedExcerpt(user.text, 800)}`,
35880
+ `Assistant (generated response, not user assertions): ${quotedExcerpt(assistant.text, 800)}`
35881
+ ].join("\n");
35936
35882
  capture = invokeTool(gateway, "lobu", "save_memory", {
35937
- content: combined.slice(0, 2e3),
35883
+ content,
35884
+ // Existing extensible payload, with only references the host supplied.
35885
+ payload_data: {
35886
+ ...context.agentId ? { agent_id: context.agentId } : {},
35887
+ ...context.conversationId ? { conversation_id: context.conversationId } : {},
35888
+ ...context.actorId ? { actor_id: context.actorId } : {},
35889
+ ...context.runId > 0 ? { run_id: context.runId } : {},
35890
+ ...context.messageId ? { message_id: context.messageId } : {}
35891
+ },
35938
35892
  semantic_type: "observation"
35939
- }, { timeoutMs: MEMORY_TOOL_TIMEOUT_MS }).then(() => context.logger.info("Captured conversation observation")).catch((error) => context.logger.warn("Plugin memory capture failed", {
35893
+ }, { timeoutMs: MEMORY_TOOL_TIMEOUT_MS }).then((result) => {
35894
+ checkReceipt(result);
35895
+ context.logger.info("Captured conversation observation");
35896
+ }).catch((error) => context.logger.warn("Plugin memory capture failed", {
35940
35897
  error: error instanceof Error ? error.message : String(error)
35941
35898
  }));
35942
35899
  }
@@ -43724,7 +43681,7 @@ function createFindTool(cwd, options) {
43724
43681
  }
43725
43682
 
43726
43683
  // dist/agent-turn/workspace.js
43727
- var import_tool_policy = __toESM(require_tool_policy(), 1);
43684
+ var import_shell_safety = __toESM(require_shell_safety(), 1);
43728
43685
 
43729
43686
  // ../../node_modules/just-bash/dist/bundle/browser.js
43730
43687
  var import_sprintf_js = __toESM(require_sprintf(), 1);
@@ -79509,7 +79466,7 @@ Command exited with code 1`;
79509
79466
  Command exited with code ${exitCode}`;
79510
79467
  return rendered;
79511
79468
  }
79512
- function createWorkspace(names, bashPolicy, remote) {
79469
+ function createWorkspace(names, remote) {
79513
79470
  const fs2 = new Gn();
79514
79471
  const ready = fs2.mkdir(WORKSPACE_ROOT, { recursive: true });
79515
79472
  const shell = new rf({ fs: fs2, cwd: WORKSPACE_ROOT, executionLimits: BASH_LIMITS });
@@ -79651,9 +79608,7 @@ function createWorkspace(names, bashPolicy, remote) {
79651
79608
  execute: async (_id, args) => {
79652
79609
  const command = requireString(args, "command");
79653
79610
  const timeout = optionalNumber(args, "timeout");
79654
- if (bashPolicy)
79655
- (0, import_tool_policy.enforceBashCommandPolicy)(command, bashPolicy);
79656
- if ((0, import_tool_policy.isDirectPackageInstallCommand)(command)) {
79611
+ if ((0, import_shell_safety.isDirectPackageInstallCommand)(command)) {
79657
79612
  throw new Error(remote ? "DIRECT PACKAGE INSTALL BLOCKED. Use the sandbox packages configured by an admin." : "DIRECT PACKAGE INSTALL BLOCKED. This workspace has no package manager and no network; use your other tools to reach data instead.");
79658
79613
  }
79659
79614
  if (remote)
@@ -79850,18 +79805,7 @@ function createTurnMediaTools(allowed, args) {
79850
79805
  var import_plugin_host = __toESM(require_dist5(), 1);
79851
79806
  var import_plugin_memory = __toESM(require_dist6(), 1);
79852
79807
  function createTurnMemory(context) {
79853
- const invoke = async (_gateway, _mcpId, toolName, args, options) => {
79854
- try {
79855
- const text2 = await context.callTool(context.mcpId, toolName, args, options);
79856
- return { content: [{ type: "text", text: text2 }] };
79857
- } catch (error) {
79858
- return {
79859
- content: [
79860
- { type: "text", text: `Error: ${error instanceof Error ? error.message : String(error)}` }
79861
- ]
79862
- };
79863
- }
79864
- };
79808
+ const invoke = (_gateway, _mcpId, toolName, args, options) => context.callTool(context.mcpId, toolName, args, options);
79865
79809
  const plugin = (0, import_plugin_memory.createMemoryPlugin)({
79866
79810
  // The plugin passes these straight back to the invoker, which ignores
79867
79811
  // them: this lane addresses the MCP route itself. They are filled in
@@ -79921,7 +79865,6 @@ function createTurnMemoryHooks(context) {
79921
79865
 
79922
79866
  // dist/agent-turn/guest-entry.js
79923
79867
  var import_memory_flush = __toESM(require_memory_flush(), 1);
79924
- var import_tool_policy2 = __toESM(require_tool_policy(), 1);
79925
79868
  var import_tool_trace_summary = __toESM(require_tool_trace_summary(), 1);
79926
79869
 
79927
79870
  // ../../node_modules/@mariozechner/pi-ai/dist/api-registry.js
@@ -132276,8 +132219,9 @@ async function callMcpTool(gatewayUrl, credential, tool, args, timeoutMs = TOOL_
132276
132219
  Authorization: `Bearer ${credential}`,
132277
132220
  "Content-Type": "application/json",
132278
132221
  // A retrieval result is summarised into the tool trace from its
132279
- // structured body; the gateway renders markdown unless asked.
132280
- ...(0, import_tool_trace_summary.isRetrievalTool)(tool.name) ? { "x-mcp-format": "json" } : {}
132222
+ // structured body; capture validates the save receipt. The gateway
132223
+ // renders markdown unless asked.
132224
+ ...(0, import_tool_trace_summary.isRetrievalTool)(tool.name) || tool.name === "save_memory" ? { "x-mcp-format": "json" } : {}
132281
132225
  },
132282
132226
  body: JSON.stringify(args ?? {}),
132283
132227
  signal: AbortSignal.timeout(timeoutMs)
@@ -132295,17 +132239,20 @@ async function callMcpTool(gatewayUrl, credential, tool, args, timeoutMs = TOOL_
132295
132239
  throw new Error(`${tool.name} returned a non-JSON response (status ${response.status}): ${error instanceof Error ? error.message : String(error)}`);
132296
132240
  }
132297
132241
  const text2 = joinText(reply.content);
132298
- if (!response.ok || reply.isError) {
132242
+ if (!response.ok) {
132299
132243
  throw new Error(reply.error || text2 || `${tool.name} failed (${response.status})`);
132300
132244
  }
132301
- return text2 || `${tool.name} completed.`;
132245
+ return {
132246
+ ...reply,
132247
+ content: [{ type: "text", text: text2 || reply.error || "" }]
132248
+ };
132302
132249
  }
132303
132250
  function buildTools(input, credential, onAskUserPosted, onInBandReplyDelivered, emit, runtimeExec) {
132304
132251
  const tools = input.tools;
132305
132252
  if (!tools)
132306
132253
  return { tools: [], workspace: null, canReadFiles: false };
132307
132254
  const remote = tools.remoteRuntime && runtimeExec ? { exec: runtimeExec } : void 0;
132308
- const workspace = tools.builtin && tools.builtin.length > 0 ? createWorkspace(tools.builtin, tools.bashPolicy, remote) : null;
132255
+ const workspace = tools.builtin && tools.builtin.length > 0 ? createWorkspace(tools.builtin, remote) : null;
132309
132256
  const gateway = tools.gateway && tools.gateway.length > 0 && tools.conversation ? createGatewayTools(tools.gateway, {
132310
132257
  gatewayUrl: tools.gatewayUrl,
132311
132258
  credential,
@@ -132328,20 +132275,18 @@ function buildTools(input, credential, onAskUserPosted, onInBandReplyDelivered,
132328
132275
  description: tool.description,
132329
132276
  // A plain JSON schema: pi-ai validates arguments against it as-is.
132330
132277
  parameters: tool.inputSchema,
132331
- execute: async (_toolCallId, args) => ({
132332
- content: [{ type: "text", text: await callMcpTool(tools.gatewayUrl, credential, tool, args) }],
132333
- details: {}
132334
- })
132335
- }));
132336
- let bashCanRead = false;
132337
- if ((tools.builtin ?? []).includes("bash") && !tools.remoteRuntime) {
132338
- try {
132339
- if (tools.bashPolicy)
132340
- (0, import_tool_policy2.enforceBashCommandPolicy)("cat input/attachment", tools.bashPolicy);
132341
- bashCanRead = true;
132342
- } catch {
132278
+ execute: async (_toolCallId, args) => {
132279
+ const result = await callMcpTool(tools.gatewayUrl, credential, tool, args);
132280
+ const text2 = joinText(result.content);
132281
+ if (result.isError === true)
132282
+ throw new Error(String(result.error || text2 || `${tool.name} failed`));
132283
+ return {
132284
+ content: [{ type: "text", text: text2 || `${tool.name} completed.` }],
132285
+ details: {}
132286
+ };
132343
132287
  }
132344
- }
132288
+ }));
132289
+ const bashCanRead = (tools.builtin ?? []).includes("bash") && !tools.remoteRuntime;
132345
132290
  const canReadFiles = workspace !== null && ((tools.builtin ?? []).includes("read") || bashCanRead);
132346
132291
  return {
132347
132292
  tools: [...mcp, ...gateway, ...media, ...workspace?.tools ?? []],
@@ -132670,14 +132615,15 @@ ${flush.prompt}`);
132670
132615
  }
132671
132616
  }
132672
132617
  await promptNativeSession(session, input.userMessage, input.images);
132673
- const ended = guardStopped ? null : agent.state.errorMessage;
132618
+ settleAnswer();
132619
+ const finalText = ownerAnswer ?? ownerText;
132620
+ const ended = (guardStopped ? null : agent.state.errorMessage) || (!finalText.trim() && toolsUsed.size === 0 && steeredToolsUsed.size === 0 ? "The model returned no response. Please try again." : null);
132674
132621
  if (memory) {
132675
132622
  const messages = session.sessionManager.getBranch().flatMap((entry) => entry.type === "message" ? [entry.message] : []);
132676
132623
  await memory.capture(messages, ended ?? void 0);
132677
132624
  }
132678
132625
  if (ended)
132679
132626
  throw new Error(ended);
132680
- settleAnswer();
132681
132627
  return {
132682
132628
  // The answer is the last assistant message WITH TEXT after each user
132683
132629
  // message, not the accumulated stream: a model that narrates before a
@@ -132700,7 +132646,7 @@ ${flush.prompt}`);
132700
132646
  // aborted mid-answer still owes the user what it managed to say. The
132701
132647
  // fallback is the owner's only: a steered input without its own settled
132702
132648
  // answer fails below rather than borrowing a sibling's text.
132703
- text: ownerAnswer ?? ownerText,
132649
+ text: finalText,
132704
132650
  stopReason,
132705
132651
  usage,
132706
132652
  sessionJsonl: nativeSessionJsonl(session),
@@ -16,10 +16,11 @@
16
16
  * 2. The SETTLE. `agentEnd` starts the `save_memory` write and returns
17
17
  * without waiting, which is correct on a runtime that outlives the turn and
18
18
  * silently lossy on one that does not: this isolate is disposed the moment
19
- * `runAgentTurn` resolves. `runTurnMemory` therefore awaits the plugin's
19
+ * `runAgentTurn` resolves. `capture` therefore awaits the plugin's
20
20
  * `settle()` before returning, so the capture actually reaches the gateway.
21
21
  */
22
22
  import type { PluginLogger } from '@lobu/plugin-api';
23
+ import type { TextResult } from '@lobu/plugin-toolkit';
23
24
  /** What the guest needs from a turn to run its memory hooks. */
24
25
  export interface TurnMemoryContext {
25
26
  gatewayUrl: string;
@@ -39,7 +40,7 @@ export interface TurnMemoryContext {
39
40
  */
40
41
  callTool: (mcpId: string, toolName: string, args: Record<string, unknown>, options?: {
41
42
  timeoutMs?: number;
42
- }) => Promise<string>;
43
+ }) => Promise<TextResult>;
43
44
  /** Where a hook's own diagnostics go. The host redacts and budgets them. */
44
45
  logger: PluginLogger;
45
46
  }