You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by as...@apache.org on 2026/09/12 08:43:11 UTC
(maka) branch main updated: feat(settings): opt in to Code Mode for new tasks (#5219)
This is an automated email from the ASF dual-hosted git repository.
Astro-Han pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/main by this push:
new 3cfcb09fd9 feat(settings): opt in to Code Mode for new tasks (#5219)
3cfcb09fd9 is described below
commit 3cfcb09fd903bfbf94cbc4684b78c67be616342a
Author: AstroHan <le...@outlook.com>
AuthorDate: Sat Sep 12 16:43:06 2026 +0800
feat(settings): opt in to Code Mode for new tasks (#5219)
Enable opt-in Code Mode for newly created Sessions, preserve frozen scheduled task modes, and separate sandbox execution budget from asynchronous host waiting.
Generated-by: Codex
---
LICENSE | 23 +-
apps/desktop/e2e-budget.json | 4 +-
apps/desktop/e2e/settings.spec.ts | 22 ++
apps/desktop/renderer-architecture.json | 2 +-
.../resources/licenses/npm/THIRD_PARTY_NOTICES.txt | 28 +-
.../renderer/locales/settings-preferences-copy.ts | 4 +
.../renderer/settings/general-settings-page.tsx | 61 +++-
package-lock.json | 262 ++++++++++-----
package.json | 5 +-
packages/cli/THIRD_PARTY_NOTICES.txt | 28 +-
.../src/__tests__/runtime-policy-codec.test.ts | 20 ++
packages/core/src/runtime-inputs.ts | 2 +
packages/core/src/runtime-policy.ts | 1 +
packages/core/src/runtime-policy/policy-codec.ts | 6 +-
packages/core/src/scheduled-task.ts | 7 +
packages/core/src/session.ts | 3 +
packages/core/src/settings.ts | 3 +
.../scheduled-task-coordinator-recovery.test.ts | 4 +-
.../__tests__/session-catalog-coordinator.test.ts | 68 ++++
packages/runtime-host/src/protocol/index.ts | 3 +-
.../src/server/execution-composition.ts | 2 +-
.../src/server/scheduled-task-coordinator.ts | 45 +--
.../src/server/session-catalog-coordinator.ts | 14 +-
.../src/server/session-revision-coordinator.ts | 1 +
packages/runtime/package.json | 18 +-
.../runtime/src/__tests__/ai-sdk-backend.test.ts | 11 +-
.../src/__tests__/code-mode-backend.test.ts | 181 +++++++++-
packages/runtime/src/__tests__/code-mode.test.ts | 107 ++++++
packages/runtime/src/__tests__/plan-mode.test.ts | 8 -
.../stream-graph-supervisor-tools.test.ts | 1 -
packages/runtime/src/agent-run.ts | 11 +-
packages/runtime/src/agent-swarm-status-tool.ts | 1 -
packages/runtime/src/ai-sdk-turn.ts | 105 +++---
packages/runtime/src/ask-user-question-tool.ts | 1 -
packages/runtime/src/code-mode.ts | 11 +-
packages/runtime/src/plan-tools.ts | 3 -
packages/runtime/src/session-manager.ts | 4 +-
.../runtime/src/stream-graph-supervisor-tools.ts | 3 -
packages/runtime/src/subagent-tools.ts | 3 -
packages/runtime/src/tool-availability.ts | 1 -
.../storage/src/__tests__/session-store.test.ts | 16 +
packages/storage/src/session-store.ts | 3 +
...4.patch => @ai-sdk+provider-utils+5.0.40.patch} | 8 +-
.../@maka+runtime++@ai-sdk+code-mode+1.0.56.patch | 74 +++++
patches/README.md | 41 ++-
patches/run+2.1.4.patch | 192 +++++++++++
patches/run-2.1.4-notices.md | 87 +++++
patches/run-2.1.4-source.diff | 366 +++++++++++++++++++++
scripts/asf-license-headers.mjs | 2 +
scripts/generate-third-party-notices.mjs | 4 +-
50 files changed, 1611 insertions(+), 269 deletions(-)
diff --git a/LICENSE b/LICENSE
index 568a613557..8c47e3748c 100644
--- a/LICENSE
+++ b/LICENSE
@@ -203,15 +203,32 @@
THIRD-PARTY COMPONENTS
+Vercel Code Mode and run execution-budget patches
+
+Source: https://www.npmjs.com/package/@ai-sdk/code-mode/v/1.0.56
+ https://www.npmjs.com/package/run/v/2.1.4
+Repository: https://github.com/vercel/ai/tree/main/packages/code-mode
+ https://github.com/vercel-labs/run/tree/run%402.1.4/packages/run
+Dependency patches: patches/@maka+runtime++@ai-sdk+code-mode+1.0.56.patch
+ patches/run+2.1.4.patch
+Readable source changes: patches/run-2.1.4-source.diff
+Copyright 2023 Vercel, Inc.
+License: Apache-2.0
+
+These patches modify the execution time policy and its SDK forwarding. The
+Apache License, Version 2.0 above applies. The generated run Worker includes
+embedded third-party code; its upstream notices and license texts are retained
+in patches/run-2.1.4-notices.md.
+
Vercel AI SDK
Source: https://www.npmjs.com/package/@ai-sdk/provider-utils/v/5.0.11
https://www.npmjs.com/package/@ai-sdk/provider/v/4.0.3
-Patched package: https://www.npmjs.com/package/@ai-sdk/provider-utils/v/5.0.34
+Patched package: https://www.npmjs.com/package/@ai-sdk/provider-utils/v/5.0.40
Repository: https://github.com/vercel/ai/tree/main/packages/provider-utils
https://github.com/vercel/ai/tree/main/packages/provider
Adapted declarations: @ai-sdk/provider-utils 5.0.11, @ai-sdk/provider 4.0.3
-Dependency patch: patches/@ai-sdk+provider-utils+5.0.34.patch
+Dependency patch: patches/@ai-sdk+provider-utils+5.0.40.patch
Copyright 2023 Vercel, Inc.
License: Apache-2.0
@@ -223,7 +240,7 @@ License, Version 2.0 above applies to the adapted material.
The pinned versions are the ones present when the adaptation was made. The
adapted declarations are unchanged through @ai-sdk/provider-utils 5.0.25 and
@ai-sdk/provider 4.0.7, the versions recorded by the code origin audit. Maka
-also redistributes a patch against @ai-sdk/provider-utils 5.0.34; that patch
+also redistributes a patch against @ai-sdk/provider-utils 5.0.40; that patch
modifies Apache-2.0 source and is covered by the license reproduced above.
Astryx
diff --git a/apps/desktop/e2e-budget.json b/apps/desktop/e2e-budget.json
index 39c83efbda..fa464f77f1 100644
--- a/apps/desktop/e2e-budget.json
+++ b/apps/desktop/e2e-budget.json
@@ -46,8 +46,8 @@
"electron": "Git changes re-read on window focus, terminal PTY ownership across Sessions, Side Chat's fork lifecycle, a first send that has to reach the Host, and per-Session collapse persisted across a renderer reload; the composer-usage test is renderer-only and rides along on those windows until app-shell.tsx's composer-to-workbar wiring has a story host"
},
"settings.spec.ts": {
- "tests": 4,
- "electron": "the preload makaE2eLatch holds the settings chunk mid-load, and the rename it commits is a Host write; the workbar-chrome test rides along on that window and would move to a story the day app-shell.tsx's settings wiring has one"
+ "tests": 5,
+ "electron": "Code Mode persistence crosses renderer/preload/main/Host settings IPC; the preload makaE2eLatch holds the settings chunk mid-load, and the rename it commits is a Host write; the workbar-chrome test rides along on that window and would move to a story the day app-shell.tsx's settings wiring has one"
},
"sidebar-project-reload.spec.ts": {
"tests": 1,
diff --git a/apps/desktop/e2e/settings.spec.ts b/apps/desktop/e2e/settings.spec.ts
index 9e947dca4f..412e035844 100644
--- a/apps/desktop/e2e/settings.spec.ts
+++ b/apps/desktop/e2e/settings.spec.ts
@@ -26,6 +26,28 @@ interface SettingsChunkLatchWindow extends Window {
};
}
+test('Code Mode persists as a global setting after reopening settings', async ({ window: page }, testInfo) => {
+ await ensureSidebarExpanded(page);
+ await page.getByRole('button', { name: '设置' }).click();
+ await page.getByRole('button', { name: '通用', exact: true }).click();
+ const toggle = page.getByRole('switch', { name: 'Code Mode', exact: true });
+ await expect(toggle).not.toBeChecked();
+ await toggle.click();
+ await expect.poll(() => page.evaluate(async () => (await window.maka.settings.get()).chatDefaults.codeModeEnabled)).toBe(true);
+ await page.keyboard.press('Escape');
+ await page.getByRole('button', { name: '设置' }).click();
+ await expect(toggle).toBeChecked();
+ await toggle.scrollIntoViewIfNeeded();
+ const screenshotPath = testInfo.outputPath('code-mode-settings.png');
+ await page.screenshot({ path: screenshotPath });
+ await testInfo.attach('Code Mode in General settings', {
+ path: screenshotPath,
+ contentType: 'image/png',
+ });
+ await toggle.click();
+ await expect.poll(() => page.evaluate(async () => (await window.maka.settings.get()).chatDefaults.codeModeEnabled === true)).toBe(false);
+});
+
test('Settings loading surface owns unmodified Escape', async ({ window: page }) => {
const latchInstalled = await page.evaluate(() => {
const e2eLatch = (window as unknown as SettingsChunkLatchWindow).makaE2eLatch;
diff --git a/apps/desktop/renderer-architecture.json b/apps/desktop/renderer-architecture.json
index e802e9e29a..172b1f8087 100644
--- a/apps/desktop/renderer-architecture.json
+++ b/apps/desktop/renderer-architecture.json
@@ -2647,7 +2647,7 @@
"useOptimisticSettingsDraft": 1,
"useOptionalRuntimeHostSettingsTarget": 2,
"useRuntimeHostSettingsTarget": 2,
- "useState": 7,
+ "useState": 5,
"useToast": 4,
"useUiLocale": 4
},
diff --git a/apps/desktop/resources/licenses/npm/THIRD_PARTY_NOTICES.txt b/apps/desktop/resources/licenses/npm/THIRD_PARTY_NOTICES.txt
index ddad9c74a8..764c5ec5cb 100644
--- a/apps/desktop/resources/licenses/npm/THIRD_PARTY_NOTICES.txt
+++ b/apps/desktop/resources/licenses/npm/THIRD_PARTY_NOTICES.txt
@@ -209,7 +209,7 @@ Apache License
================================================================================
-Package: @ai-sdk/anthropic@4.0.46
+Package: @ai-sdk/anthropic@4.0.53
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/anthropic
@@ -231,7 +231,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/code-mode@1.0.42
+Package: @ai-sdk/code-mode@1.0.56
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/code-mode
@@ -253,7 +253,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/cohere@4.0.35
+Package: @ai-sdk/cohere@4.0.41
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/cohere
@@ -275,7 +275,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/gateway@4.0.69
+Package: @ai-sdk/gateway@4.0.80
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/gateway
@@ -297,7 +297,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/google@4.0.58
+Package: @ai-sdk/google@4.0.69
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/google
@@ -319,7 +319,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/open-responses@2.0.36
+Package: @ai-sdk/open-responses@2.0.44
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/open-responses
@@ -341,7 +341,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/openai@4.0.52
+Package: @ai-sdk/openai@4.0.66
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/openai
@@ -363,7 +363,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/openai-compatible@3.0.41
+Package: @ai-sdk/openai-compatible@3.0.48
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/openai-compatible
@@ -385,7 +385,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/provider@4.0.9
+Package: @ai-sdk/provider@4.0.14
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/provider
@@ -407,7 +407,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/provider-utils@5.0.34
+Package: @ai-sdk/provider-utils@5.0.40
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/provider-utils
@@ -5107,7 +5107,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================================================
-Package: ai@7.0.85
+Package: ai@7.0.99
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/ai
@@ -13073,7 +13073,7 @@ SOFTWARE.
================================================================================
-Package: run@2.0.0
+Package: run@2.1.4
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: git+https://github.com/vercel-labs/run.git#packages/run
@@ -14530,7 +14530,7 @@ SOFTWARE.
================================================================================
Embedded component: quickjs-emscripten (embedded runtime)
-Embedded by: @ai-sdk/code-mode@1.0.42
+Embedded by: @ai-sdk/code-mode@1.0.56
Selected license: MIT
Repository: https://github.com/justjake/quickjs-emscripten
@@ -14560,7 +14560,7 @@ SOFTWARE.
================================================================================
Embedded component: QuickJS JavaScript engine (embedded runtime)
-Embedded by: @ai-sdk/code-mode@1.0.42
+Embedded by: @ai-sdk/code-mode@1.0.56
Selected license: MIT
Repository: https://github.com/bellard/quickjs
diff --git a/apps/desktop/src/renderer/locales/settings-preferences-copy.ts b/apps/desktop/src/renderer/locales/settings-preferences-copy.ts
index 24c085a036..9941054271 100644
--- a/apps/desktop/src/renderer/locales/settings-preferences-copy.ts
+++ b/apps/desktop/src/renderer/locales/settings-preferences-copy.ts
@@ -181,6 +181,7 @@ export type SettingsPreferencesCopy = {
defaultPermissionHelp: string;
defaultThinking: string;
defaultThinkingHelp: string;
+ codeModeHelp: string;
followModelDefault: string;
saveDefaultThinkingFailed: string;
saveDefaultPermissionFailed: string;
@@ -338,6 +339,7 @@ const SETTINGS_PREFERENCES_COPY_BY_LOCALE = {
removeErrors: { invalid_id: '宠物 ID 无效。', remove_failed: '无法删除本地宠物包。' },
},
general: {
+ codeModeHelp: '开启后,新任务通过代码编排和调用工具。仅影响新建任务,已有任务保持不变。',
incognito: '隐身模式', incognitoHelp: '开启后暂停本地记忆读写、联网搜索和定时任务触发。', enableIncognito: '启用隐身模式', incognitoFailed: '隐身模式切换失败', notifications: '完成时发送系统通知', notificationsHelp: '窗口不在前台时,在回答完成或出错后发送桌面通知。', notificationsFailed: '通知设置切换失败', workspaceInstructions: '遵循项目指令', workspaceInstructionsHelp: '自动读取每个项目中已有的 AGENTS.md、CLAUDE.md 或 GEMINI.md;文件仍由各自项目管理。', workspaceInstructionsFailed: '项目指令设置切换失败', workHub: '启用 WorkHub', workHubHelp: 'WorkHub 目前仍不可用。此开关仅供开发测试,开启后也不能保证正常使用。', workHubFailed: 'Wor [...]
defaultModel: '默认模型', defaultModelHelp: '新任务默认使用的模型。', notSet: '未设置', saveDefaultModelFailed: '保存默认模型失败', defaultPermission: '默认权限模式', defaultPermissionHelp: '新任务默认使用的权限模式;可在任务内随时切换。', saveDefaultPermissionFailed: '保存默认权限模式失败', defaultThinking: '默认思考级别', defaultThinkingHelp: '新任务的思考级别;当前模型不支持所选级别时用模型默认。', followModelDefault: '跟随模型默认', saveDefaultThinkingFailed: '保存默认思考级别失败',
shellPreference: 'Bash 工具 shell', shellPreferenceHelp: '自动模式保持 Windows 的 PowerShell 优先规则;Git Bash 是仅对当前 Runtime Host 生效的显式覆盖。', shellAuto: '自动(推荐)', shellGitBash: 'Git Bash', shellExecutable: 'Git Bash 可执行文件', shellExecutableHelp: '填写 Runtime Host 所在 Windows 机器上 bash.exe 的绝对路径。也支持该机器上的旧版 System32 WSL Bash;保存时会验证 GNU Bash。', saveShell: '保存 shell 设置', savingShell: '正在保存…', shellSaved: '已保存', saveShellFailed: '保存 shell 设置失败', shellExecutableRejected: '当前 Runtime Host 无法把该路径作为 GNU Bash [...]
@@ -442,6 +444,7 @@ const SETTINGS_PREFERENCES_COPY_BY_LOCALE = {
removeErrors: { invalid_id: '寵物 ID 無效。', remove_failed: '無法刪除本機寵物包。' },
},
general: {
+ codeModeHelp: '開啟後,新任務透過程式碼編排和呼叫工具。僅影響新建任務,既有任務保持不變。',
incognito: '隱身模式', incognitoHelp: '開啟後暫停本地記憶讀寫、聯網搜尋和定時任務觸發。', enableIncognito: '啟用隱身模式', incognitoFailed: '隱身模式切換失敗', notifications: '完成時傳送系統通知', notificationsHelp: '視窗不在前臺時,在回答完成或出錯後傳送桌面通知。', notificationsFailed: '通知設定切換失敗', workspaceInstructions: '遵循專案指令', workspaceInstructionsHelp: '自動讀取每個專案中已有的 AGENTS.md、CLAUDE.md 或 GEMINI.md;檔案仍由各自專案管理。', workspaceInstructionsFailed: '專案指令設定切換失敗', workHub: '啟用 WorkHub', workHubHelp: '在一個入口檢視已有工作,並將新輸入保守地送往普通任務。', workHubFailed: 'WorkHub 設定切換失敗 [...]
defaultModel: '預設模型', defaultModelHelp: '新任務預設使用的模型。', notSet: '未設定', saveDefaultModelFailed: '儲存預設模型失敗', defaultPermission: '預設權限模式', defaultPermissionHelp: '新任務預設使用的權限模式;可在任務內隨時切換。', saveDefaultPermissionFailed: '儲存預設權限模式失敗', defaultThinking: '預設思考級別', defaultThinkingHelp: '新任務的思考級別;目前模型不支援所選級別時用模型預設。', followModelDefault: '跟隨模型預設', saveDefaultThinkingFailed: '儲存預設思考級別失敗',
shellPreference: 'Bash 工具 shell', shellPreferenceHelp: '自動模式保持 Windows 的 PowerShell 優先規則;Git Bash 是僅對目前 Runtime Host 生效的顯式覆蓋。', shellAuto: '自動(推薦)', shellGitBash: 'Git Bash', shellExecutable: 'Git Bash 執行檔', shellExecutableHelp: '填寫 Runtime Host 所在 Windows 機器上 bash.exe 的絕對路徑。也支援該機器上的舊版 System32 WSL Bash;儲存時會驗證 GNU Bash。', saveShell: '儲存 shell 設定', savingShell: '正在儲存…', shellSaved: '已儲存', saveShellFailed: '儲存 shell 設定失敗', shellExecutableRejected: '目前 Runtime Host 無法把該路徑作為 GNU Bash 執 [...]
@@ -503,6 +506,7 @@ const SETTINGS_PREFERENCES_COPY_BY_LOCALE = {
removeErrors: { invalid_id: 'The pet ID is invalid.', remove_failed: 'The local pet pack could not be removed.' },
},
general: {
+ codeModeHelp: 'New tasks use code to compose and call tools. Changes apply only to new tasks; existing tasks keep their mode.',
incognito: 'Incognito mode', incognitoHelp: 'Pause local memory, web search, and scheduled task triggers.', enableIncognito: 'Enable incognito mode', incognitoFailed: 'Could not change incognito mode', notifications: 'Send a system notification when finished', notificationsHelp: 'Notify when a response finishes or fails while the window is in the background.', notificationsFailed: 'Could not change notification settings', workspaceInstructions: 'Follow project instructions', worksp [...]
shellPreference: 'Bash tool shell', shellPreferenceHelp: 'Automatic keeps the PowerShell-first Windows default. Git Bash is an explicit override for the current Runtime Host.', shellAuto: 'Automatic (recommended)', shellGitBash: 'Git Bash', shellExecutable: 'Git Bash executable', shellExecutableHelp: 'Enter the absolute path to bash.exe on the Windows machine running the Runtime Host. The legacy System32 WSL Bash shim is also recognized; Maka verifies GNU Bash before saving.', save [...]
passwordSavedPlaceholder: 'Password saved; enter a new password to replace it',
diff --git a/apps/desktop/src/renderer/settings/general-settings-page.tsx b/apps/desktop/src/renderer/settings/general-settings-page.tsx
index 64ce616df8..65a6cbcb4f 100644
--- a/apps/desktop/src/renderer/settings/general-settings-page.tsx
+++ b/apps/desktop/src/renderer/settings/general-settings-page.tsx
@@ -306,6 +306,7 @@ export function GeneralSettingsPage(props: {
onRefresh={props.onRefreshConnections}
permissionMode={props.settings.chatDefaults.permissionMode}
thinkingLevel={props.settings.chatDefaults.thinkingLevel}
+ codeModeEnabled={props.settings.chatDefaults.codeModeEnabled === true}
onUpdate={props.onUpdate}
/>
) : null}
@@ -502,6 +503,7 @@ function GeneralDefaultsCard(props: {
onRefresh(): Promise<void>;
permissionMode: ChatDefaultPermissionMode;
thinkingLevel?: ThinkingLevel;
+ codeModeEnabled: boolean;
onUpdate(
patch: Parameters<typeof window.maka.settings.update>[0],
): Promise<UpdateAppSettingsResult>;
@@ -516,12 +518,12 @@ function GeneralDefaultsCard(props: {
const boundaryCopy = getShellCopy(locale).sessionSettingsActions;
const toast = useToast();
const mountedRef = useMountedRef();
- const persistGuard = useKeyedActionGuard<
- "default-model" | "permission-mode" | "thinking-level"
- >();
- const [saving, setSaving] = useState(false);
- const [savingPermissionMode, setSavingPermissionMode] = useState(false);
- const [savingThinkingLevel, setSavingThinkingLevel] = useState(false);
+ type SaveKey = "default-model" | "permission-mode" | "thinking-level";
+ const persistGuard = useKeyedActionGuard<SaveKey>();
+ const [savingRows, setSavingRows] = useState<Partial<Record<SaveKey, boolean>>>({});
+ function setRowSaving(key: SaveKey, saving: boolean) {
+ setSavingRows((current) => ({ ...current, [key]: saving }));
+ }
const modelChoices = useMemo(
() => buildChatModelChoices(props.connections),
@@ -549,7 +551,7 @@ function GeneralDefaultsCard(props: {
if (!props.connectionsBridge || !props.connectionsInteractive) return;
const releaseSave = persistGuard.begin("default-model");
if (!releaseSave) return;
- setSaving(true);
+ setRowSaving("default-model", true);
try {
const parsed = parseModelChoiceValue(nextValue);
await props.connectionsBridge.setDefaultModel(
@@ -573,7 +575,7 @@ function GeneralDefaultsCard(props: {
}
} finally {
releaseSave();
- if (mountedRef.current) setSaving(false);
+ if (mountedRef.current) setRowSaving("default-model", false);
}
}
@@ -610,7 +612,7 @@ function GeneralDefaultsCard(props: {
return;
}
}
- setSavingPermissionMode(true);
+ setRowSaving("permission-mode", true);
try {
await props.onUpdate({ chatDefaults: { permissionMode: nextMode } });
} catch (error) {
@@ -624,7 +626,7 @@ function GeneralDefaultsCard(props: {
}
} finally {
releaseSave();
- if (mountedRef.current) setSavingPermissionMode(false);
+ if (mountedRef.current) setRowSaving("permission-mode", false);
}
}
@@ -632,7 +634,7 @@ function GeneralDefaultsCard(props: {
if (!props.settingsInteractive) return;
const releaseSave = persistGuard.begin("thinking-level");
if (!releaseSave) return;
- setSavingThinkingLevel(true);
+ setRowSaving("thinking-level", true);
try {
await props.onUpdate({ chatDefaults: { thinkingLevel: next } });
} catch (error) {
@@ -646,7 +648,19 @@ function GeneralDefaultsCard(props: {
}
} finally {
releaseSave();
- if (mountedRef.current) setSavingThinkingLevel(false);
+ if (mountedRef.current) setRowSaving("thinking-level", false);
+ }
+ }
+
+ async function persistCodeMode(codeModeEnabled: boolean) {
+ if (!props.settingsInteractive) return;
+ try {
+ await props.onUpdate({ chatDefaults: { codeModeEnabled } });
+ } catch (error) {
+ if (mountedRef.current) {
+ toast.error(copy.updateFailed, settingsActionErrorMessage(error, locale), undefined,
+ host ? { profileId: host.profileId } : undefined);
+ }
}
}
@@ -655,6 +669,23 @@ function GeneralDefaultsCard(props: {
title={sections.chatDefaults}
description={sections.chatDefaultsHelp}
>
+ {props.settingsAvailable ? (
+ <SettingsRow
+ label="Code Mode"
+ description={copy.codeModeHelp}
+ end={
+ <Switch
+ label="Code Mode"
+ isLabelHidden
+ value={props.codeModeEnabled}
+ isDisabled={!props.settingsInteractive}
+ changeAction={persistCodeMode}
+ />
+ }
+ />
+ ) : props.showSettingsPlaceholder ? (
+ <SettingsRowSkeleton label="Code Mode" description={copy.codeModeHelp} width="3rem" />
+ ) : null}
{props.connectionsAvailable ? (
<SettingsRow
label={copy.defaultModel}
@@ -666,7 +697,7 @@ function GeneralDefaultsCard(props: {
leadingOption={{ value: "", label: copy.notSet }}
renderProviderMark={(type) => <ProviderBrandMark type={type} />}
ariaLabel={copy.defaultModel}
- disabled={saving || !props.connectionsInteractive}
+ disabled={savingRows["default-model"] || !props.connectionsInteractive}
triggerClassName="settingsModelPickerTrigger"
onValueChange={persistDefault}
/>
@@ -690,7 +721,7 @@ function GeneralDefaultsCard(props: {
void persistPermissionMode(mode);
}}
align="end"
- disabled={savingPermissionMode || !props.settingsInteractive}
+ disabled={savingRows["permission-mode"] || !props.settingsInteractive}
ariaLabel={copy.defaultPermission}
/>
}
@@ -727,7 +758,7 @@ function GeneralDefaultsCard(props: {
label: conversationCopy.model.level[level],
})),
]}
- isDisabled={savingThinkingLevel || !props.settingsInteractive}
+ isDisabled={savingRows["thinking-level"] || !props.settingsInteractive}
/>
}
/>
diff --git a/package-lock.json b/package-lock.json
index aa41fac297..cb24194404 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -23,7 +23,7 @@
"website"
],
"devDependencies": {
- "@ai-sdk/provider-utils": "5.0.34",
+ "@ai-sdk/provider-utils": "5.0.40",
"@astryxdesign/cli": "0.5.2",
"@astryxdesign/core": "0.5.2",
"@biomejs/biome": "2.5.11",
@@ -136,13 +136,13 @@
}
},
"node_modules/@ai-sdk/anthropic": {
- "version": "4.0.46",
- "resolved": "https://registry.npmjs.org/@ai-sdk/anthropic/-/anthropic-4.0.46.tgz",
- "integrity": "sha512-/q/wWLArkavQHeOYdv8kZyJRTuasTRwrzoAnvUaY0sHx/BGDYDWW9ENn7lu/H5iUeYId6NhtYAVv+TlqHpp9Cg==",
+ "version": "4.0.53",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/anthropic/-/anthropic-4.0.53.tgz",
+ "integrity": "sha512-JMxAuCFte6mFOvoaUcig3Dp2LObin0wU2Li8ncsveh7hHKW7cG3g1bFjooxn1paxeT8UUf5XMSjhxtXG9wFLig==",
"license": "Apache-2.0",
"dependencies": {
- "@ai-sdk/provider": "4.0.9",
- "@ai-sdk/provider-utils": "5.0.34"
+ "@ai-sdk/provider": "4.0.14",
+ "@ai-sdk/provider-utils": "5.0.40"
},
"engines": {
"node": ">=22"
@@ -151,29 +151,26 @@
"zod": "^3.25.76 || ^4.1.8"
}
},
- "node_modules/@ai-sdk/code-mode": {
- "version": "1.0.42",
- "resolved": "https://registry.npmjs.org/@ai-sdk/code-mode/-/code-mode-1.0.42.tgz",
- "integrity": "sha512-XmoYdaUkH+giggm5KQsAhxbSq06NaZrI7ExccLaFk8ZDebMfRYVMRh0V5fHe6vIsY24T/BAMjakWwJ3c9iUoqQ==",
+ "node_modules/@ai-sdk/anthropic/node_modules/@ai-sdk/provider": {
+ "version": "4.0.14",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-4.0.14.tgz",
+ "integrity": "sha512-yukP2tbcQQErG5gLCMBGvpvb/rM3D3KlTKG6eKKOdNHLHqtNNDEeBxdYrY/JL+O76B2ig5dXY19H/f1HFSvRiQ==",
"license": "Apache-2.0",
"dependencies": {
- "run": "^2.0.0"
+ "json-schema": "^0.4.0"
},
"engines": {
- "node": ">=22.13.0"
- },
- "peerDependencies": {
- "ai": "7.0.85"
+ "node": ">=22"
}
},
"node_modules/@ai-sdk/cohere": {
- "version": "4.0.35",
- "resolved": "https://registry.npmjs.org/@ai-sdk/cohere/-/cohere-4.0.35.tgz",
- "integrity": "sha512-RQN7PgmJM+qK7LLz2mfoX3ENGLoEHP8KZrf/5zwOWkCE/3DBppcxeUa/xHL+70a2L2L+eWFlxYTWD3dJEZXkeg==",
+ "version": "4.0.41",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/cohere/-/cohere-4.0.41.tgz",
+ "integrity": "sha512-5ZwA2gCk3R6HwNsBqoyFOedfvnkj5SxuOpDhnDxUixfDhGAUHs+Q5qN+CmIvY7itglqAFZB1ZwEEVT8ijjgCGQ==",
"license": "Apache-2.0",
"dependencies": {
- "@ai-sdk/provider": "4.0.9",
- "@ai-sdk/provider-utils": "5.0.34"
+ "@ai-sdk/provider": "4.0.14",
+ "@ai-sdk/provider-utils": "5.0.40"
},
"engines": {
"node": ">=22"
@@ -182,31 +179,26 @@
"zod": "^3.25.76 || ^4.1.8"
}
},
- "node_modules/@ai-sdk/gateway": {
- "version": "4.0.69",
- "resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-4.0.69.tgz",
- "integrity": "sha512-W5MMdyqsaziQy/A4kxlK74iEQ+NuO6OaszH32cEQpUgBW0o15S2fAdP0aYSH2/5lrVZSMXLQLCzuMkRGHBua3A==",
+ "node_modules/@ai-sdk/cohere/node_modules/@ai-sdk/provider": {
+ "version": "4.0.14",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-4.0.14.tgz",
+ "integrity": "sha512-yukP2tbcQQErG5gLCMBGvpvb/rM3D3KlTKG6eKKOdNHLHqtNNDEeBxdYrY/JL+O76B2ig5dXY19H/f1HFSvRiQ==",
"license": "Apache-2.0",
"dependencies": {
- "@ai-sdk/provider": "4.0.9",
- "@ai-sdk/provider-utils": "5.0.34",
- "@vercel/oidc": "3.2.0"
+ "json-schema": "^0.4.0"
},
"engines": {
"node": ">=22"
- },
- "peerDependencies": {
- "zod": "^3.25.76 || ^4.1.8"
}
},
"node_modules/@ai-sdk/google": {
- "version": "4.0.58",
- "resolved": "https://registry.npmjs.org/@ai-sdk/google/-/google-4.0.58.tgz",
- "integrity": "sha512-4xd28cAErn/aO0yoG95qwPO7QvoBlSKw7UeQuxivbTwFCSjA5hy/OrMEM4adPLPoPrnTi4PXFVzNesNBtKHI0Q==",
+ "version": "4.0.69",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/google/-/google-4.0.69.tgz",
+ "integrity": "sha512-clIivD3RQwutykzKQ8CV+BXIA6EX3xcrfJyXXvAni2SlR9JVATSRbu+JFK/j25a330aZ6WiDwbGyD/u951qXOg==",
"license": "Apache-2.0",
"dependencies": {
- "@ai-sdk/provider": "4.0.9",
- "@ai-sdk/provider-utils": "5.0.34"
+ "@ai-sdk/provider": "4.0.14",
+ "@ai-sdk/provider-utils": "5.0.40"
},
"engines": {
"node": ">=22"
@@ -215,14 +207,26 @@
"zod": "^3.25.76 || ^4.1.8"
}
},
+ "node_modules/@ai-sdk/google/node_modules/@ai-sdk/provider": {
+ "version": "4.0.14",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-4.0.14.tgz",
+ "integrity": "sha512-yukP2tbcQQErG5gLCMBGvpvb/rM3D3KlTKG6eKKOdNHLHqtNNDEeBxdYrY/JL+O76B2ig5dXY19H/f1HFSvRiQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "json-schema": "^0.4.0"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+ },
"node_modules/@ai-sdk/open-responses": {
- "version": "2.0.36",
- "resolved": "https://registry.npmjs.org/@ai-sdk/open-responses/-/open-responses-2.0.36.tgz",
- "integrity": "sha512-zork7/Ro8NONrQlEmbwIIfNNIMQ9uwvAJ9h6Ig1x1C3/fE45iJLrBTNLUDvwhaqnZ8JXkIaoK4dUAwCzuMZtUA==",
+ "version": "2.0.44",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/open-responses/-/open-responses-2.0.44.tgz",
+ "integrity": "sha512-UbCp5I3uUPv55ATphwgba1phwMHFt6s2lF+3ED61zyx0L+rvUwMitCT0NxvOsp6sftEPJlm1jaofuBMGLqIslw==",
"license": "Apache-2.0",
"dependencies": {
- "@ai-sdk/provider": "4.0.9",
- "@ai-sdk/provider-utils": "5.0.34"
+ "@ai-sdk/provider": "4.0.14",
+ "@ai-sdk/provider-utils": "5.0.40"
},
"engines": {
"node": ">=22"
@@ -231,14 +235,26 @@
"zod": "^3.25.76 || ^4.1.8"
}
},
+ "node_modules/@ai-sdk/open-responses/node_modules/@ai-sdk/provider": {
+ "version": "4.0.14",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-4.0.14.tgz",
+ "integrity": "sha512-yukP2tbcQQErG5gLCMBGvpvb/rM3D3KlTKG6eKKOdNHLHqtNNDEeBxdYrY/JL+O76B2ig5dXY19H/f1HFSvRiQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "json-schema": "^0.4.0"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+ },
"node_modules/@ai-sdk/openai": {
- "version": "4.0.52",
- "resolved": "https://registry.npmjs.org/@ai-sdk/openai/-/openai-4.0.52.tgz",
- "integrity": "sha512-I44DlHmBe8Sv5HVOaxAQEX3IbeG8Voz78z9abg6QJtWpL/oz42/ytGNWGAJPvKOJ9jFQ4ofalySFviUCRQk9MA==",
+ "version": "4.0.66",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/openai/-/openai-4.0.66.tgz",
+ "integrity": "sha512-W4GooZjROdOmf7dfjWlRWNVs+Vvr7ZwfDZbyAJRPo1bgQbpRoDd9ZcCwy/PX1X0s2G7B/dhN2RWOORsHtr0wGg==",
"license": "Apache-2.0",
"dependencies": {
- "@ai-sdk/provider": "4.0.9",
- "@ai-sdk/provider-utils": "5.0.34"
+ "@ai-sdk/provider": "4.0.14",
+ "@ai-sdk/provider-utils": "5.0.40"
},
"engines": {
"node": ">=22"
@@ -248,13 +264,13 @@
}
},
"node_modules/@ai-sdk/openai-compatible": {
- "version": "3.0.41",
- "resolved": "https://registry.npmjs.org/@ai-sdk/openai-compatible/-/openai-compatible-3.0.41.tgz",
- "integrity": "sha512-djOLRg4WOq5EINvWLfw2dniO14vBrf0iMRs/aXAQqsp4a67Wi49aMpZuvC7C7L3VpL43rnFzS1fWw7T6vpzgUQ==",
+ "version": "3.0.48",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/openai-compatible/-/openai-compatible-3.0.48.tgz",
+ "integrity": "sha512-WbalnkqFWBnLOQt0w5Jba4LROZz6nacpm5FXKNiJmcZkPbOju0K/DYFtPal2kLP4DiE9q23T0GIM8Zq6/O73tw==",
"license": "Apache-2.0",
"dependencies": {
- "@ai-sdk/provider": "4.0.9",
- "@ai-sdk/provider-utils": "5.0.34"
+ "@ai-sdk/provider": "4.0.14",
+ "@ai-sdk/provider-utils": "5.0.40"
},
"engines": {
"node": ">=22"
@@ -263,10 +279,22 @@
"zod": "^3.25.76 || ^4.1.8"
}
},
- "node_modules/@ai-sdk/provider": {
- "version": "4.0.9",
- "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-4.0.9.tgz",
- "integrity": "sha512-XnGXPWiBIfqjsVEud5pOaVneRByJQOu2sYNwlSVJTPCvakdCDkVuYKKfNuStkIpMUYl7JIkBZGBx+B5YfNeVjA==",
+ "node_modules/@ai-sdk/openai-compatible/node_modules/@ai-sdk/provider": {
+ "version": "4.0.14",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-4.0.14.tgz",
+ "integrity": "sha512-yukP2tbcQQErG5gLCMBGvpvb/rM3D3KlTKG6eKKOdNHLHqtNNDEeBxdYrY/JL+O76B2ig5dXY19H/f1HFSvRiQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "json-schema": "^0.4.0"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+ },
+ "node_modules/@ai-sdk/openai/node_modules/@ai-sdk/provider": {
+ "version": "4.0.14",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-4.0.14.tgz",
+ "integrity": "sha512-yukP2tbcQQErG5gLCMBGvpvb/rM3D3KlTKG6eKKOdNHLHqtNNDEeBxdYrY/JL+O76B2ig5dXY19H/f1HFSvRiQ==",
"license": "Apache-2.0",
"dependencies": {
"json-schema": "^0.4.0"
@@ -276,16 +304,16 @@
}
},
"node_modules/@ai-sdk/provider-utils": {
- "version": "5.0.34",
- "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-5.0.34.tgz",
- "integrity": "sha512-tRBdgRcys/4d8wyQdOdyYScq1AxfMdMd0hIlwolxJKVIbBwXUgClZuQT0VIsz4e7pylY8FE6utYCCZ494UAMJQ==",
+ "version": "5.0.40",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-5.0.40.tgz",
+ "integrity": "sha512-zsXPwSAQ9mRJ2hvyITaLOYUyuGrBmzFhJXOg4mllGmla1PfNxZcm4GwqMiV2xQaDgcgBMdUGxXkp9xekZZNIkg==",
"license": "Apache-2.0",
"dependencies": {
- "@ai-sdk/provider": "4.0.9",
+ "@ai-sdk/provider": "4.0.14",
"@standard-schema/spec": "^1.1.0",
"@workflow/serde": "4.1.0",
"eventsource-parser": "^3.0.8",
- "undici": "^7.28.0"
+ "undici": "^7.29.0"
},
"engines": {
"node": ">=22"
@@ -294,6 +322,18 @@
"zod": "^3.25.76 || ^4.1.8"
}
},
+ "node_modules/@ai-sdk/provider-utils/node_modules/@ai-sdk/provider": {
+ "version": "4.0.14",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-4.0.14.tgz",
+ "integrity": "sha512-yukP2tbcQQErG5gLCMBGvpvb/rM3D3KlTKG6eKKOdNHLHqtNNDEeBxdYrY/JL+O76B2ig5dXY19H/f1HFSvRiQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "json-schema": "^0.4.0"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+ },
"node_modules/@ai-sdk/provider-utils/node_modules/undici": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",
@@ -6331,23 +6371,6 @@
"node": ">= 6.0.0"
}
},
- "node_modules/ai": {
- "version": "7.0.85",
- "resolved": "https://registry.npmjs.org/ai/-/ai-7.0.85.tgz",
- "integrity": "sha512-HVtPz0qLbTUad+QBnWWReIUmwk+U4PcRENMx+9PsHGVoinoc5CLDiVjNR+VBXTKOSaNgce8kSU/Rtbb4kjZsSw==",
- "license": "Apache-2.0",
- "dependencies": {
- "@ai-sdk/gateway": "4.0.69",
- "@ai-sdk/provider": "4.0.9",
- "@ai-sdk/provider-utils": "5.0.34"
- },
- "engines": {
- "node": ">=22"
- },
- "peerDependencies": {
- "zod": "^3.25.76 || ^4.1.8"
- }
- },
"node_modules/ajv": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
@@ -14566,12 +14589,12 @@
}
},
"node_modules/run": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/run/-/run-2.0.0.tgz",
- "integrity": "sha512-7fO5AYmPotAiBBdCoQg9gfKBmA+mGKy3Yq5aW8nuRVkHcVOTD2eA96ISE5i5gNMgMqnt0oBTfUm0D3+rhHPn3g==",
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/run/-/run-2.1.4.tgz",
+ "integrity": "sha512-Rd8W2wO0LWdwlNbqKJm/o0WpQ/VQ42KRR6MUgnaujjjVOdS0o3bTMZ9dCjWCQAeuIj6jhG58WkqkeGz0cvOIrA==",
"license": "Apache-2.0",
"engines": {
- "node": ">=22.13.0"
+ "node": ">=22.19.0"
}
},
"node_modules/run-applescript": {
@@ -17148,14 +17171,14 @@
"version": "0.1.0",
"license": "Apache-2.0",
"dependencies": {
- "@ai-sdk/anthropic": "4.0.46",
- "@ai-sdk/code-mode": "1.0.42",
- "@ai-sdk/cohere": "4.0.35",
- "@ai-sdk/google": "4.0.58",
- "@ai-sdk/open-responses": "2.0.36",
- "@ai-sdk/openai": "4.0.52",
- "@ai-sdk/openai-compatible": "3.0.41",
- "@ai-sdk/provider": "4.0.9",
+ "@ai-sdk/anthropic": "4.0.53",
+ "@ai-sdk/code-mode": "1.0.56",
+ "@ai-sdk/cohere": "4.0.41",
+ "@ai-sdk/google": "4.0.69",
+ "@ai-sdk/open-responses": "2.0.44",
+ "@ai-sdk/openai": "4.0.66",
+ "@ai-sdk/openai-compatible": "3.0.48",
+ "@ai-sdk/provider": "4.0.14",
"@larksuiteoapi/node-sdk": "1.73.0",
"@maka/core": "0.1.0",
"@mozilla/readability": "^0.6.0",
@@ -17165,7 +17188,7 @@
"@wecom/aibot-node-sdk": "1.0.7",
"@xterm/addon-unicode11": "^0.9.0",
"@xterm/headless": "^6.0.0",
- "ai": "7.0.85",
+ "ai": "7.0.99",
"ajv": "^8.20.0",
"https-proxy-agent": "^9.1.0",
"image-dimensions": "^2.5.1",
@@ -17207,6 +17230,50 @@
"electron": "^43.4.1"
}
},
+ "packages/runtime/node_modules/@ai-sdk/code-mode": {
+ "version": "1.0.56",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/code-mode/-/code-mode-1.0.56.tgz",
+ "integrity": "sha512-PjTYI+VCvylQLoMv3aAD+JjdepU2lNDwkQQ/ipShk8ALWNgcAHRXXHjcKy+2h1pYoNfhScEXmd8PAP4+OEkfeQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "run": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=22.13.0"
+ },
+ "peerDependencies": {
+ "ai": "7.0.99"
+ }
+ },
+ "packages/runtime/node_modules/@ai-sdk/gateway": {
+ "version": "4.0.80",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-4.0.80.tgz",
+ "integrity": "sha512-6t+07o8lSthpKf64Xb1qHWR2bWvJ3Fd2oFvS9fQc45p31bi2OUqan246e/ojAmZpWCiMPjKyQ4TBr4MYytnTiQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider": "4.0.14",
+ "@ai-sdk/provider-utils": "5.0.40",
+ "@vercel/oidc": "3.2.0"
+ },
+ "engines": {
+ "node": ">=22"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.76 || ^4.1.8"
+ }
+ },
+ "packages/runtime/node_modules/@ai-sdk/provider": {
+ "version": "4.0.14",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-4.0.14.tgz",
+ "integrity": "sha512-yukP2tbcQQErG5gLCMBGvpvb/rM3D3KlTKG6eKKOdNHLHqtNNDEeBxdYrY/JL+O76B2ig5dXY19H/f1HFSvRiQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "json-schema": "^0.4.0"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+ },
"packages/runtime/node_modules/@slack/socket-mode": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@slack/socket-mode/-/socket-mode-3.0.1.tgz",
@@ -17245,6 +17312,23 @@
"node": ">= 20"
}
},
+ "packages/runtime/node_modules/ai": {
+ "version": "7.0.99",
+ "resolved": "https://registry.npmjs.org/ai/-/ai-7.0.99.tgz",
+ "integrity": "sha512-Ov+3j/nSajaVH5hO8C94wN9wisG5tAJ8HWsLV9d/+nlzrRGUh3oYO3Kp1fRyUNWjAWLSpGLHLPaHCdfxb307Vg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/gateway": "4.0.80",
+ "@ai-sdk/provider": "4.0.14",
+ "@ai-sdk/provider-utils": "5.0.40"
+ },
+ "engines": {
+ "node": ">=22"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.76 || ^4.1.8"
+ }
+ },
"packages/runtime/node_modules/https-proxy-agent": {
"version": "9.1.0",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-9.1.0.tgz",
diff --git a/package.json b/package.json
index 862fe01018..be83413c74 100644
--- a/package.json
+++ b/package.json
@@ -110,7 +110,7 @@
"smoke:windows:dist": "node scripts/windows-smoke.mjs"
},
"devDependencies": {
- "@ai-sdk/provider-utils": "5.0.34",
+ "@ai-sdk/provider-utils": "5.0.40",
"@astryxdesign/cli": "0.5.2",
"@astryxdesign/core": "0.5.2",
"@biomejs/biome": "2.5.11",
@@ -129,6 +129,9 @@
"node-pty@1.2.0-beta.15": true
},
"overrides": {
+ "@ai-sdk/code-mode": {
+ "run": "2.1.4"
+ },
"@astryxdesign/core": {
"react-dom": "19.2.8"
},
diff --git a/packages/cli/THIRD_PARTY_NOTICES.txt b/packages/cli/THIRD_PARTY_NOTICES.txt
index de25d90b90..edb50ca5ed 100644
--- a/packages/cli/THIRD_PARTY_NOTICES.txt
+++ b/packages/cli/THIRD_PARTY_NOTICES.txt
@@ -208,7 +208,7 @@ Apache License
================================================================================
-Package: @ai-sdk/anthropic@4.0.46
+Package: @ai-sdk/anthropic@4.0.53
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/anthropic
@@ -230,7 +230,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/code-mode@1.0.42
+Package: @ai-sdk/code-mode@1.0.56
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/code-mode
@@ -252,7 +252,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/cohere@4.0.35
+Package: @ai-sdk/cohere@4.0.41
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/cohere
@@ -274,7 +274,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/gateway@4.0.69
+Package: @ai-sdk/gateway@4.0.80
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/gateway
@@ -296,7 +296,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/google@4.0.58
+Package: @ai-sdk/google@4.0.69
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/google
@@ -318,7 +318,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/open-responses@2.0.36
+Package: @ai-sdk/open-responses@2.0.44
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/open-responses
@@ -340,7 +340,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/openai@4.0.52
+Package: @ai-sdk/openai@4.0.66
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/openai
@@ -362,7 +362,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/openai-compatible@3.0.41
+Package: @ai-sdk/openai-compatible@3.0.48
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/openai-compatible
@@ -384,7 +384,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/provider@4.0.9
+Package: @ai-sdk/provider@4.0.14
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/provider
@@ -406,7 +406,7 @@ limitations under the License.
================================================================================
-Package: @ai-sdk/provider-utils@5.0.34
+Package: @ai-sdk/provider-utils@5.0.40
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/provider-utils
@@ -2186,7 +2186,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================================================
-Package: ai@7.0.85
+Package: ai@7.0.99
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: https://github.com/vercel/ai#packages/ai
@@ -6643,7 +6643,7 @@ Felix Geisendörfer (felix@debuggable.com)
================================================================================
-Package: run@2.0.0
+Package: run@2.1.4
Declared license: Apache-2.0
Selected license: Apache-2.0
Repository: git+https://github.com/vercel-labs/run.git#packages/run
@@ -7573,7 +7573,7 @@ SOFTWARE.
================================================================================
Embedded component: quickjs-emscripten (embedded runtime)
-Embedded by: @ai-sdk/code-mode@1.0.42
+Embedded by: @ai-sdk/code-mode@1.0.56
Selected license: MIT
Repository: https://github.com/justjake/quickjs-emscripten
@@ -7603,7 +7603,7 @@ SOFTWARE.
================================================================================
Embedded component: QuickJS JavaScript engine (embedded runtime)
-Embedded by: @ai-sdk/code-mode@1.0.42
+Embedded by: @ai-sdk/code-mode@1.0.56
Selected license: MIT
Repository: https://github.com/bellard/quickjs
diff --git a/packages/core/src/__tests__/runtime-policy-codec.test.ts b/packages/core/src/__tests__/runtime-policy-codec.test.ts
index 021f5d792a..efc0d0ad9b 100644
--- a/packages/core/src/__tests__/runtime-policy-codec.test.ts
+++ b/packages/core/src/__tests__/runtime-policy-codec.test.ts
@@ -61,6 +61,26 @@ test('normalizes policy input while canonical policy decode rejects producer dri
);
});
+test('Code Mode is opt-in and survives policy decoding', () => {
+ const policy = createDefaultRuntimePolicy();
+ assert.notEqual(decodeCanonicalRuntimePolicy(policy).chatDefaults.codeModeEnabled, true);
+ assert.equal(
+ decodeCanonicalRuntimePolicy({
+ ...policy,
+ chatDefaults: { ...policy.chatDefaults, codeModeEnabled: true },
+ }).chatDefaults.codeModeEnabled,
+ true,
+ );
+ assert.throws(
+ () =>
+ decodeCanonicalRuntimePolicy({
+ ...policy,
+ chatDefaults: { ...policy.chatDefaults, codeModeEnabled: 'true' },
+ }),
+ RuntimePolicyDomainDecodeError,
+ );
+});
+
test('preserves a valid default thinking level and rejects unknown levels', () => {
const policy = {
...createDefaultRuntimePolicy(),
diff --git a/packages/core/src/runtime-inputs.ts b/packages/core/src/runtime-inputs.ts
index 6f59dfb3b6..42bccd337a 100644
--- a/packages/core/src/runtime-inputs.ts
+++ b/packages/core/src/runtime-inputs.ts
@@ -70,6 +70,8 @@ export interface CreateSessionInput {
thinkingLevel?: ThinkingLevel;
/** Immutable versioned prompt/tool contract for this Session. */
toolProfile?: SessionToolProfile;
+ /** Internal creation-time choice; not a per-task UI control. */
+ toolMode?: ToolMode;
permissionMode: PermissionMode;
/** Defaults to `agent`. */
collaborationMode?: CollaborationMode;
diff --git a/packages/core/src/runtime-policy.ts b/packages/core/src/runtime-policy.ts
index 9d5e85259c..de3496bc2b 100644
--- a/packages/core/src/runtime-policy.ts
+++ b/packages/core/src/runtime-policy.ts
@@ -154,6 +154,7 @@ export interface RuntimePolicy {
readonly chatDefaults: {
readonly permissionMode: ChatDefaultPermissionMode;
readonly thinkingLevel?: ThinkingLevel;
+ readonly codeModeEnabled?: boolean;
};
readonly webSearch: {
readonly enabled: boolean;
diff --git a/packages/core/src/runtime-policy/policy-codec.ts b/packages/core/src/runtime-policy/policy-codec.ts
index 5d7591a845..99e761d2c4 100644
--- a/packages/core/src/runtime-policy/policy-codec.ts
+++ b/packages/core/src/runtime-policy/policy-codec.ts
@@ -408,7 +408,7 @@ function normalizeChatDefaults(value: unknown): RuntimePolicy['chatDefaults'] {
const item = exactRecord(
value,
'chat defaults',
- ['permissionMode', 'thinkingLevel'],
+ ['permissionMode', 'thinkingLevel', 'codeModeEnabled'],
['permissionMode'],
);
if (!(CHAT_DEFAULT_PERMISSION_MODES as readonly unknown[]).includes(item.permissionMode)) {
@@ -417,8 +417,12 @@ function normalizeChatDefaults(value: unknown): RuntimePolicy['chatDefaults'] {
if (item.thinkingLevel !== undefined && !isThinkingLevel(item.thinkingLevel)) {
throw domainError('chat default thinking level is invalid');
}
+ if (item.codeModeEnabled !== undefined && typeof item.codeModeEnabled !== 'boolean') {
+ throw domainError('chat default code mode is invalid');
+ }
return {
permissionMode: item.permissionMode as RuntimePolicy['chatDefaults']['permissionMode'],
+ ...(item.codeModeEnabled === true ? { codeModeEnabled: true } : {}),
...(item.thinkingLevel === undefined ? {} : { thinkingLevel: item.thinkingLevel }),
};
}
diff --git a/packages/core/src/scheduled-task.ts b/packages/core/src/scheduled-task.ts
index d1eac46fb8..afc87cf752 100644
--- a/packages/core/src/scheduled-task.ts
+++ b/packages/core/src/scheduled-task.ts
@@ -28,6 +28,7 @@ import { compileCronExpression } from './cron-expression.js';
import { isCollaborationMode, type CollaborationMode } from './collaboration.js';
import { isOrchestrationMode, type OrchestrationMode } from './orchestration.js';
import { isThinkingLevel, type ThinkingLevel } from './model-thinking.js';
+import { isToolMode, type ToolMode } from './tool-mode.js';
import {
decodePersistedPermissionMode,
isPermissionMode,
@@ -73,6 +74,8 @@ export type ScheduledTaskEffect =
/** Frozen at create time so later settings changes do not rewrite past jobs. */
export interface ScheduledTaskExecutionTemplate {
+ /** Omitted legacy templates use direct tools. */
+ readonly toolMode?: ToolMode;
readonly cwd: string;
readonly projectId?: string | null;
/** Immutable Connection entity identity. Omitted only on legacy slug-only rows. */
@@ -530,6 +533,9 @@ function normalizeExecution(
if (!isOrchestrationMode(value.orchestrationMode)) {
return fail('execution.orchestrationMode is required');
}
+ if (value.toolMode !== undefined && !isToolMode(value.toolMode)) {
+ return fail('execution.toolMode is invalid');
+ }
if (value.thinkingLevel !== undefined && !isThinkingLevel(value.thinkingLevel)) {
return fail('execution.thinkingLevel is invalid');
}
@@ -553,6 +559,7 @@ function normalizeExecution(
permissionMode: value.permissionMode,
collaborationMode: value.collaborationMode,
orchestrationMode: value.orchestrationMode,
+ ...(value.toolMode === undefined ? {} : { toolMode: value.toolMode }),
},
};
}
diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts
index d60d0de5aa..097f9bfbbd 100644
--- a/packages/core/src/session.ts
+++ b/packages/core/src/session.ts
@@ -42,6 +42,7 @@ import {
} from './permission.js';
import type { CollaborationMode } from './collaboration.js';
import type { OrchestrationMode } from './orchestration.js';
+import type { ToolMode } from './tool-mode.js';
import {
defineObjectShape,
hasExactShape,
@@ -239,6 +240,8 @@ export interface SessionExternalOrigin {
}
export interface SessionHeader {
+ /** Frozen at creation; absent on older tasks means direct tool calling. */
+ toolMode?: ToolMode;
// Identity
id: string;
/** Absent means an ordinary Session; special roles remain on the same Session substrate. */
diff --git a/packages/core/src/settings.ts b/packages/core/src/settings.ts
index a886b2a010..4708c1a5fd 100644
--- a/packages/core/src/settings.ts
+++ b/packages/core/src/settings.ts
@@ -511,6 +511,8 @@ export function isChatDefaultPermissionMode(value: unknown): value is ChatDefaul
/** Seeds new sessions' starting permission mode (Settings → 通用 → 默认权限模式). */
export interface ChatDefaultsSettings {
permissionMode: ChatDefaultPermissionMode;
+ /** Applies only when a new task is created. */
+ codeModeEnabled?: boolean;
/**
* Seeds new sessions' thinking level. `undefined` means "whatever the model
* does on its own" — the absence of a preference, not a level.
@@ -1092,6 +1094,7 @@ function defaultChatDefaultsSettings(): ChatDefaultsSettings {
// doesn't recognize -- fall back to the safest default instead.
function normalizeChatDefaultsSettings(settings: ChatDefaultsSettings): ChatDefaultsSettings {
return {
+ ...(settings.codeModeEnabled === true ? { codeModeEnabled: true } : {}),
// Same fail-closed reasoning as the mode below: a garbage persisted level
// drops to "no preference" (the model's own default) rather than reaching
// session creation as a rung no picker recognizes.
diff --git a/packages/runtime-host/src/__tests__/scheduled-task-coordinator-recovery.test.ts b/packages/runtime-host/src/__tests__/scheduled-task-coordinator-recovery.test.ts
index a9e1940a63..9b8213245f 100644
--- a/packages/runtime-host/src/__tests__/scheduled-task-coordinator-recovery.test.ts
+++ b/packages/runtime-host/src/__tests__/scheduled-task-coordinator-recovery.test.ts
@@ -342,8 +342,9 @@ test('ScheduledTask with an exact Connection identity reaches Session and AgentR
},
} as never,
nativeEffects: null as never,
- createSession: async (input) => {
+ createSession: async (input, toolMode) => {
createSessionCalls += 1;
+ assert.equal(toolMode, 'code_mode');
assert.deepEqual(input.modelTarget, {
kind: 'explicit',
connectionId: 'connection-a',
@@ -371,6 +372,7 @@ test('ScheduledTask with an exact Connection identity reaches Session and AgentR
permissionMode: 'ask',
collaborationMode: 'agent',
orchestrationMode: 'default',
+ toolMode: 'code_mode',
},
},
createdBy: { kind: 'user' },
diff --git a/packages/runtime-host/src/__tests__/session-catalog-coordinator.test.ts b/packages/runtime-host/src/__tests__/session-catalog-coordinator.test.ts
index bab0bd5ceb..66d8eacd43 100644
--- a/packages/runtime-host/src/__tests__/session-catalog-coordinator.test.ts
+++ b/packages/runtime-host/src/__tests__/session-catalog-coordinator.test.ts
@@ -1024,6 +1024,74 @@ test('creation rejects explore permission without a declared mode', async () =>
assert.equal(fixture.drainRequests(), 0);
});
+test('new tasks snapshot the current global Code Mode setting', async () => {
+ let enabled = true;
+ const runtimePolicy: RuntimePolicy = {
+ ...runtimePolicyFixture({}),
+ runtimePolicy: {
+ getSnapshot: async () => ({
+ revision: 1,
+ policy: {
+ ...createDefaultRuntimePolicy(),
+ chatDefaults: { permissionMode: 'ask', codeModeEnabled: enabled },
+ },
+ }),
+ },
+ };
+ const modes: unknown[] = [];
+ const fixture = createFixture({
+ runtimePolicy,
+ stores: {
+ createStableSession: async (request) => {
+ modes.push(request.input.toolMode);
+ return {
+ kind: 'existing',
+ record: headerSnapshot(sessionHeader(request.sessionId, []), 3),
+ };
+ },
+ },
+ });
+ for (const value of [true, false]) {
+ enabled = value;
+ const expectedMode = value ? 'code_mode' : 'direct';
+ assert.equal(
+ (await fixture.coordinator.resolveExternalSessionImportTarget()).toolMode,
+ expectedMode,
+ );
+ assert.equal((await fixture.coordinator.resolveDefaultCreateTarget()).toolMode, expectedMode);
+ const outcome = await fixture.coordinator.handlers['session.create'](
+ {
+ sessionId: fixture.sessionId,
+ workspace: { kind: 'host_path', path: process.cwd() },
+ modelTarget: { kind: 'default' },
+ },
+ context,
+ );
+ assert.equal(outcome.ok, true);
+ }
+ assert.deepEqual(modes, ['code_mode', 'direct']);
+ // A scheduled task carries its frozen mode through the internal creation
+ // path even when the user's global default has since changed.
+ await fixture.coordinator.createForHost(
+ {
+ sessionId: fixture.sessionId,
+ workspace: { kind: 'host_path', path: process.cwd() },
+ modelTarget: { kind: 'default' },
+ },
+ 'code_mode',
+ );
+ enabled = true;
+ await fixture.coordinator.createForHost(
+ {
+ sessionId: fixture.sessionId,
+ workspace: { kind: 'host_path', path: process.cwd() },
+ modelTarget: { kind: 'default' },
+ },
+ 'direct',
+ );
+ assert.deepEqual(modes.slice(2), ['code_mode', 'direct']);
+});
+
test('creation materializes Deep Research semantics inside the Host transaction', async () => {
let created: Parameters<CatalogStores['createStableSession']>[0] | undefined;
const fixture = createFixture({
diff --git a/packages/runtime-host/src/protocol/index.ts b/packages/runtime-host/src/protocol/index.ts
index 5e1dd03b9e..1be2456a82 100644
--- a/packages/runtime-host/src/protocol/index.ts
+++ b/packages/runtime-host/src/protocol/index.ts
@@ -101,7 +101,8 @@ export const RUNTIME_HOST_REGISTRATION_SCHEMA_VERSION = 1 as const;
export const RUNTIME_HOST_PROTOCOL_VERSION = 0 as const;
// Increment when the same protocol version no longer guarantees safe Client-Host
// interoperability. Mismatches are rejected before domain commands are admitted.
-export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 145 as const;
+export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 146 as const;
+// 146: Code Mode settings and Session tool mode join the epoch-145 Host contract.
// 145: Combine Antigravity setup with Session bundle Host operations and explicit
// missing/archived Skill query refusals.
// 144: Antigravity setup combined with explicit missing/archived Skill query refusals.
diff --git a/packages/runtime-host/src/server/execution-composition.ts b/packages/runtime-host/src/server/execution-composition.ts
index d0c4562137..4a46686566 100644
--- a/packages/runtime-host/src/server/execution-composition.ts
+++ b/packages/runtime-host/src/server/execution-composition.ts
@@ -2287,7 +2287,7 @@ export async function createExecutionRuntimeHostComposition(
root: coordinator,
runtimePolicy: runtimePolicyStores,
nativeEffects: clientCapabilities,
- createSession: (input) => sessionCatalog.createForHost(input),
+ createSession: (input, toolMode) => sessionCatalog.createForHost(input, toolMode),
changes: {
publish: (
revision: number,
diff --git a/packages/runtime-host/src/server/scheduled-task-coordinator.ts b/packages/runtime-host/src/server/scheduled-task-coordinator.ts
index 9df2251876..4ecec77c40 100644
--- a/packages/runtime-host/src/server/scheduled-task-coordinator.ts
+++ b/packages/runtime-host/src/server/scheduled-task-coordinator.ts
@@ -66,6 +66,7 @@ import type { RuntimeHostResidency } from './host-kernel.js';
import type { HostResidencyKind } from './host-residency-registry.js';
import type { HostedExecutionAuthority } from './hosted-execution-authority.js';
import type { SessionCreateInput } from '../protocol/session-catalog.js';
+import { DEFAULT_TOOL_MODE, type ToolMode } from '@maka/core/tool-mode';
const MAX_TIMER_DELAY_MS = 2_147_483_647;
const NATIVE_PROVIDER_RETRY_MS = 5_000;
@@ -94,7 +95,7 @@ export interface HostScheduledTaskCoordinatorInput {
readonly root: ScheduledTaskRoot;
readonly runtimePolicy: RuntimePolicyStoresWriter;
readonly nativeEffects: ScheduledTaskNativeEffects;
- readonly createSession: (input: SessionCreateInput) => Promise<void>;
+ readonly createSession: (input: SessionCreateInput, toolMode: ToolMode) => Promise<void>;
readonly changes: {
publish(revision: number, reason: ScheduledTaskChangedReason, taskId: string): void;
};
@@ -722,25 +723,30 @@ export class HostScheduledTaskCoordinator implements ScheduledTaskToolAuthority
} catch (error) {
if (!isSessionNotFoundError(error) && !isMissingRecord(error)) throw error;
}
- await this.#createSession({
- sessionId: identity.sessionId,
- workspace:
- execution.projectId != null && execution.projectId !== ''
- ? { kind: 'project', projectId: execution.projectId }
- : { kind: 'host_path', path: execution.cwd },
- name: task.title,
- labels: ['scheduled-task'],
- modelTarget: {
- kind: 'explicit',
- connectionId: connection.connectionId,
- connectionSlug: execution.llmConnectionSlug,
- model: execution.model,
+ await this.#createSession(
+ {
+ sessionId: identity.sessionId,
+ workspace:
+ execution.projectId != null && execution.projectId !== ''
+ ? { kind: 'project', projectId: execution.projectId }
+ : { kind: 'host_path', path: execution.cwd },
+ name: task.title,
+ labels: ['scheduled-task'],
+ modelTarget: {
+ kind: 'explicit',
+ connectionId: connection.connectionId,
+ connectionSlug: execution.llmConnectionSlug,
+ model: execution.model,
+ },
+ ...(execution.thinkingLevel === undefined
+ ? {}
+ : { thinkingLevel: execution.thinkingLevel }),
+ permissionMode: execution.permissionMode,
+ collaborationMode: execution.collaborationMode,
+ orchestrationMode: execution.orchestrationMode,
},
- ...(execution.thinkingLevel === undefined ? {} : { thinkingLevel: execution.thinkingLevel }),
- permissionMode: execution.permissionMode,
- collaborationMode: execution.collaborationMode,
- orchestrationMode: execution.orchestrationMode,
- });
+ execution.toolMode ?? DEFAULT_TOOL_MODE,
+ );
}
async #resolveAgentRunConnection(
@@ -949,6 +955,7 @@ function executionTemplateFromHeader(header: SessionHeader): ScheduledTaskExecut
permissionMode: header.permissionMode,
collaborationMode: header.collaborationMode ?? 'agent',
orchestrationMode: header.orchestrationMode ?? 'default',
+ toolMode: header.toolMode ?? DEFAULT_TOOL_MODE,
};
}
diff --git a/packages/runtime-host/src/server/session-catalog-coordinator.ts b/packages/runtime-host/src/server/session-catalog-coordinator.ts
index c2a3b1b5d2..7811aefbd4 100644
--- a/packages/runtime-host/src/server/session-catalog-coordinator.ts
+++ b/packages/runtime-host/src/server/session-catalog-coordinator.ts
@@ -28,6 +28,7 @@ import {
type ExecutionBoundarySummary,
} from '@maka/core/sandbox-boundary';
import type { CreateSessionInput } from '@maka/core/runtime-inputs';
+import type { ToolMode } from '@maka/core/tool-mode';
import type { ConnectionCatalogEntry, ConnectionCatalogSnapshot } from '@maka/core/runtime-policy';
import { DEFAULT_SESSION_NAME, normalizeUserSessionName } from '@maka/core/session-name';
import {
@@ -344,13 +345,14 @@ export class HostSessionCatalogCoordinator {
llmConnectionSlug: model.connectionSlug,
model: model.model,
permissionMode: policy.policy.chatDefaults.permissionMode,
+ toolMode: policy.policy.chatDefaults.codeModeEnabled ? 'code_mode' : 'direct',
collaborationMode: 'agent',
orchestrationMode: 'default',
};
}
- async createForHost(input: SessionCreateInput): Promise<void> {
- const outcome = await this.#create(input);
+ async createForHost(input: SessionCreateInput, toolMode: ToolMode): Promise<void> {
+ const outcome = await this.#create(input, toolMode);
if (!outcome.ok) throw new Error(outcome.error.message);
}
@@ -381,6 +383,7 @@ export class HostSessionCatalogCoordinator {
...(input.thinkingLevel === undefined ? {} : { thinkingLevel: input.thinkingLevel }),
...(input.toolProfile === undefined ? {} : { toolProfile: input.toolProfile }),
permissionMode: prepared.permissionMode ?? policy.policy.chatDefaults.permissionMode,
+ toolMode: policy.policy.chatDefaults.codeModeEnabled ? 'code_mode' : 'direct',
collaborationMode: input.collaborationMode ?? 'agent',
orchestrationMode: input.orchestrationMode ?? 'default',
},
@@ -562,7 +565,10 @@ export class HostSessionCatalogCoordinator {
}
}
- async #create(input: SessionCreateInput): Promise<OperationOutcome<'session.create'>> {
+ async #create(
+ input: SessionCreateInput,
+ toolMode?: ToolMode,
+ ): Promise<OperationOutcome<'session.create'>> {
if (isWorkHubCoordinationSessionId(input.sessionId)) {
return createFailure(
'operation_conflict',
@@ -613,6 +619,8 @@ export class HostSessionCatalogCoordinator {
...(input.thinkingLevel === undefined ? {} : { thinkingLevel: input.thinkingLevel }),
...(input.toolProfile === undefined ? {} : { toolProfile: input.toolProfile }),
permissionMode: prepared.permissionMode ?? policy.policy.chatDefaults.permissionMode,
+ toolMode:
+ toolMode ?? (policy.policy.chatDefaults.codeModeEnabled ? 'code_mode' : 'direct'),
collaborationMode: input.collaborationMode ?? 'agent',
orchestrationMode: input.orchestrationMode ?? 'default',
};
diff --git a/packages/runtime-host/src/server/session-revision-coordinator.ts b/packages/runtime-host/src/server/session-revision-coordinator.ts
index 4f0344d0fa..74625e621f 100644
--- a/packages/runtime-host/src/server/session-revision-coordinator.ts
+++ b/packages/runtime-host/src/server/session-revision-coordinator.ts
@@ -716,6 +716,7 @@ export class HostSessionRevisionCoordinator {
model: source.model,
...(source.thinkingLevel !== undefined ? { thinkingLevel: source.thinkingLevel } : {}),
permissionMode: source.permissionMode,
+ toolMode: source.toolMode ?? 'direct',
collaborationMode: source.collaborationMode ?? 'agent',
orchestrationMode: source.orchestrationMode ?? 'default',
name: source.name,
diff --git a/packages/runtime/package.json b/packages/runtime/package.json
index f6da740324..3c8da57741 100644
--- a/packages/runtime/package.json
+++ b/packages/runtime/package.json
@@ -147,14 +147,14 @@
"test:dist": "node --test \"dist/**/*.test.js\""
},
"dependencies": {
- "@ai-sdk/anthropic": "4.0.46",
- "@ai-sdk/code-mode": "1.0.42",
- "@ai-sdk/cohere": "4.0.35",
- "@ai-sdk/google": "4.0.58",
- "@ai-sdk/open-responses": "2.0.36",
- "@ai-sdk/openai": "4.0.52",
- "@ai-sdk/openai-compatible": "3.0.41",
- "@ai-sdk/provider": "4.0.9",
+ "@ai-sdk/anthropic": "4.0.53",
+ "@ai-sdk/code-mode": "1.0.56",
+ "@ai-sdk/cohere": "4.0.41",
+ "@ai-sdk/google": "4.0.69",
+ "@ai-sdk/open-responses": "2.0.44",
+ "@ai-sdk/openai": "4.0.66",
+ "@ai-sdk/openai-compatible": "3.0.48",
+ "@ai-sdk/provider": "4.0.14",
"@larksuiteoapi/node-sdk": "1.73.0",
"@maka/core": "0.1.0",
"@mozilla/readability": "^0.6.0",
@@ -164,7 +164,7 @@
"@wecom/aibot-node-sdk": "1.0.7",
"@xterm/addon-unicode11": "^0.9.0",
"@xterm/headless": "^6.0.0",
- "ai": "7.0.85",
+ "ai": "7.0.99",
"ajv": "^8.20.0",
"https-proxy-agent": "^9.1.0",
"image-dimensions": "^2.5.1",
diff --git a/packages/runtime/src/__tests__/ai-sdk-backend.test.ts b/packages/runtime/src/__tests__/ai-sdk-backend.test.ts
index f31f1f785d..b6c3679b20 100644
--- a/packages/runtime/src/__tests__/ai-sdk-backend.test.ts
+++ b/packages/runtime/src/__tests__/ai-sdk-backend.test.ts
@@ -1092,10 +1092,9 @@ describe('AiSdkBackend sandbox boundary convergence', () => {
{
type: 'tool-call',
toolCallId: 'code-boundary-request',
- toolName: 'request_sandbox_boundary',
+ toolName: 'exec',
input: JSON.stringify({
- expansion: { network: { enabled: true } },
- justification: 'Use the network.',
+ code: 'return await tools.request_sandbox_boundary({ expansion: { network: { enabled: true } }, justification: "Use the network." })',
}),
},
{
@@ -1213,7 +1212,11 @@ describe('AiSdkBackend sandbox boundary convergence', () => {
);
if (!inheritedDenial) {
- await waitFor(() => events.some((event) => event.type === 'sandbox_boundary_request'));
+ await pollFor(() => events.some((event) => event.type === 'sandbox_boundary_request'), {
+ attempts: 500,
+ pollMs: 10,
+ message: 'Code Mode did not request the sandbox boundary',
+ });
const request = events.find((event) => event.type === 'sandbox_boundary_request');
assert.ok(request?.type === 'sandbox_boundary_request');
await backend.respondToSandboxBoundary({
diff --git a/packages/runtime/src/__tests__/code-mode-backend.test.ts b/packages/runtime/src/__tests__/code-mode-backend.test.ts
index 226fbf66d3..f6de93fb99 100644
--- a/packages/runtime/src/__tests__/code-mode-backend.test.ts
+++ b/packages/runtime/src/__tests__/code-mode-backend.test.ts
@@ -34,6 +34,12 @@ import { MockLanguageModelV4, convertArrayToReadableStream } from 'ai/test';
import { z } from 'zod';
import type { AiSdkBackendInput } from '../ai-sdk-backend.js';
import { buildMcpTools } from '../mcp-tools.js';
+import { buildAskUserQuestionTool } from '../ask-user-question-tool.js';
+import type { RuntimeEvent } from '@maka/core/runtime-event';
+import {
+ createSessionEventMapMemory,
+ mapSessionEventToRuntimeEvent,
+} from '../session-event-runtime-mapper.js';
import type { ToolArtifactRecorderInput } from '../tool-artifacts.js';
import type { MakaTool } from '../tool-runtime.js';
import type { RuntimeCommitSink, ToolPreparedCommit } from '../runtime-commit-sink.js';
@@ -44,7 +50,7 @@ const ZERO_USAGE: LanguageModelV4Usage = {
outputTokens: { total: 0, text: 0, reasoning: 0 },
};
-test('adds exec only for the explicit code_mode provider surface', async () => {
+test('replaces direct tool schemas with exec in code_mode', async () => {
const directSurface: string[][] = [];
const codeSurface: string[][] = [];
@@ -65,7 +71,172 @@ test('adds exec only for the explicit code_mode provider surface', async () => {
);
assert.deepEqual(directSurface[0], ['lookup']);
- assert.deepEqual(codeSurface[0], ['exec', 'lookup']);
+ assert.deepEqual(codeSurface[0], ['exec']);
+});
+
+test('uses the persisted task mode without a per-turn override', async () => {
+ const surface: string[][] = [];
+ const calls: unknown[] = [];
+ await drain(
+ backend(capturingModel(surface), [], undefined, {
+ header: { ...header(), toolMode: 'code_mode' },
+ }).send({ turnId: 'persisted-mode', text: 'inspect', context: [] }),
+ );
+ assert.deepEqual(surface[0], ['exec']);
+ await drain(
+ backend(execThenStopModel(), calls, undefined, {
+ header: { ...header(), toolMode: 'code_mode' },
+ }).send({ turnId: 'persisted-execution', text: 'inspect', context: [] }),
+ );
+ assert.deepEqual(calls, [{ id: 'nested' }]);
+});
+
+test('tool search refreshes the catalog for the next code cell', async () => {
+ const ledger: RuntimeEvent[] = [
+ {
+ id: 'search-user',
+ sessionId: 'session-1',
+ turnId: 'search-code',
+ runId: 'run-1',
+ invocationId: 'invocation-1',
+ ts: 1,
+ partial: false,
+ role: 'user',
+ author: 'user',
+ content: { kind: 'text', text: 'inspect' },
+ },
+ ];
+ const memory = createSessionEventMapMemory();
+ let step = 0;
+ const catalogs: string[] = [];
+ const calls: unknown[] = [];
+ const model = new MockLanguageModelV4({
+ doStream: async ({ tools }) => {
+ catalogs.push(JSON.stringify(tools));
+ const code =
+ step++ === 0
+ ? 'return await tools.tool_search({ query: "lookup" })'
+ : 'return await tools.lookup({ id: "discovered" })';
+ return {
+ stream: convertArrayToReadableStream<LanguageModelV4StreamPart>([
+ { type: 'stream-start', warnings: [] },
+ {
+ type: 'tool-call',
+ toolCallId: `exec-${step}`,
+ toolName: 'exec',
+ input: JSON.stringify({ code }),
+ },
+ {
+ type: 'finish',
+ finishReason: { unified: 'tool-calls', raw: 'tool_calls' },
+ usage: ZERO_USAGE,
+ },
+ ]),
+ };
+ },
+ });
+ const events: SessionEvent[] = [];
+ for await (const event of backend(model, calls, undefined, {
+ maxSteps: 2,
+ toolAvailability: {},
+ loadTurnRuntimeEvents: async () => ledger,
+ header: { ...header(), toolMode: 'code_mode' },
+ }).send({ turnId: 'search-code', text: 'inspect', context: [] })) {
+ events.push(event);
+ const mapped = mapSessionEventToRuntimeEvent(
+ event,
+ {
+ sessionId: 'session-1',
+ turnId: 'search-code',
+ runId: 'run-1',
+ invocationId: 'invocation-1',
+ now: () => 1,
+ },
+ memory,
+ );
+ if (mapped.partial !== true && mapped.content?.kind !== 'error') ledger.push(mapped);
+ }
+ assert.deepEqual(calls, [{ id: 'discovered' }], JSON.stringify(events));
+ assert.match(catalogs[0]!, /tool_search/);
+ assert.match(catalogs[1]!, /Look up a node/);
+});
+
+test('a nested question can be answered and a parked question can be stopped', async () => {
+ for (const stop of [false, true]) {
+ const instance = backend(
+ execThenStopModel(
+ 'return await tools.AskUserQuestion({ questions: [{ question: "Continue?", options: [{ label: "Yes" }, { label: "No" }] }] })',
+ ),
+ [],
+ undefined,
+ {
+ tools: [buildAskUserQuestionTool()],
+ header: { ...header(), toolMode: 'code_mode' },
+ },
+ );
+ const events: SessionEvent[] = [];
+ for await (const event of instance.send({
+ turnId: 'question-code',
+ text: 'ask',
+ context: [],
+ })) {
+ events.push(event);
+ if (event.type === 'user_question_request') {
+ if (stop) await instance.stop('user_stop');
+ else await instance.respondToUserQuestion({ requestId: event.requestId, answers: ['Yes'] });
+ }
+ }
+ assert.ok(events.some((event) => event.type === 'user_question_request'));
+ assert.ok(events.some((event) => event.type === 'tool_result'));
+ if (!stop)
+ assert.match(JSON.stringify(events.filter((event) => event.type === 'tool_result')), /Yes/);
+ }
+});
+
+test('nested plan submission hands off the turn and prevents subsequent calls', async () => {
+ let afterSubmit = false;
+ const events: SessionEvent[] = [];
+ const instance = backend(
+ execThenStopModel('await tools.SubmitPlan({}); return await tools.afterSubmit({})'),
+ [],
+ undefined,
+ {
+ header: { ...header(), toolMode: 'code_mode' },
+ tools: [
+ {
+ name: 'SubmitPlan',
+ description: 'Submit plan',
+ parameters: z.object({}),
+ impl: () => ({
+ kind: 'plan_submitted',
+ storeVersion: 1,
+ proposal: {
+ planId: 'plan-1',
+ proposalId: 'proposal-1',
+ revision: 1,
+ title: 'Test plan',
+ steps: [],
+ },
+ }),
+ },
+ {
+ name: 'afterSubmit',
+ description: 'Must not run',
+ parameters: z.object({}),
+ impl: () => {
+ afterSubmit = true;
+ },
+ },
+ ],
+ },
+ );
+ for await (const event of instance.send({ turnId: 'plan-code', text: 'plan', context: [] }))
+ events.push(event);
+ assert.equal(afterSubmit, false);
+ assert.ok(events.some((event) => event.type === 'plan_submitted' && event.title === 'Test plan'));
+ assert.ok(
+ events.some((event) => event.type === 'complete' && event.stopReason === 'plan_handoff'),
+ );
});
test('allows a custom exec tool in direct mode', async () => {
@@ -938,7 +1109,7 @@ test('admits exec exclusively while allowing its nested calls', async () => {
event.type === 'tool_result' && event.toolUseId === 'lookup-direct',
);
assert.equal(directResult?.isError, true);
- assert.match(JSON.stringify(directResult?.content), /cannot share an assistant step|exclusive/i);
+ assert.match(JSON.stringify(directResult?.content), /cannot share an assistant step/i);
});
function backend(
@@ -949,6 +1120,10 @@ function backend(
Pick<
AiSdkBackendInput,
| 'tools'
+ | 'header'
+ | 'maxSteps'
+ | 'toolAvailability'
+ | 'loadTurnRuntimeEvents'
| 'readExecutionBoundary'
| 'createSandboxBoundaryRequest'
| 'settleSandboxBoundaryRequest'
diff --git a/packages/runtime/src/__tests__/code-mode.test.ts b/packages/runtime/src/__tests__/code-mode.test.ts
index a245704b9d..9c02e81320 100644
--- a/packages/runtime/src/__tests__/code-mode.test.ts
+++ b/packages/runtime/src/__tests__/code-mode.test.ts
@@ -37,6 +37,45 @@ function execute(code: string, input: Partial<Omit<ExecuteCodeCellInput, 'code'>
});
}
+test('excludes host waiting from the execution budget and preserves dependent Promise.race progress', async () => {
+ let releaseSlow!: (value: string) => void;
+ const slow = new Promise<string>((resolve) => {
+ releaseSlow = resolve;
+ });
+ const calls: string[] = [];
+ const result = await execute(
+ `
+ const slow = tools.slow({});
+ const fast = tools.fast({});
+ const winner = await Promise.race([slow, fast]);
+ await tools.after({});
+ await Promise.all([slow, fast]);
+ return winner;
+ `,
+ {
+ tools: ['slow', 'fast', 'after'].map((name) => ({ name })),
+ signal: AbortSignal.timeout(5_000),
+ executionPolicy: { ...DEFAULT_CODE_MODE_EXECUTION_POLICY, timeoutMs: 200 },
+ callTool: async (name, _input, signal) => {
+ calls.push(name);
+ if (name === 'slow') {
+ signal.addEventListener('abort', () => releaseSlow('cancelled'), { once: true });
+ return slow;
+ }
+ if (name === 'fast') {
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ return 'fast';
+ }
+ releaseSlow('slow');
+ return null;
+ },
+ },
+ ).finally(() => releaseSlow('cleanup'));
+ assert.equal(result.ok, true);
+ if (result.ok) assert.equal(result.value, 'fast');
+ assert.deepEqual(calls, ['slow', 'fast', 'after']);
+});
+
test('executes standard JavaScript without an interpreter subset', async () => {
const result = await execute(`
const key = 'answer';
@@ -62,6 +101,18 @@ test('executes TypeScript syntax', async () => {
assert.deepEqual(result, { ok: true, value: { value: 42 }, toolCalls: [] });
});
+test('does not read the execution result through a guest-controlled global', async () => {
+ const result = await execute(`
+ Object.defineProperty(globalThis, '__runResult', {
+ get() { throw new Error('Guest getter must not run'); },
+ set() {},
+ });
+ return 'actual result';
+ `);
+ assert.equal(result.ok, true);
+ if (result.ok) assert.equal(result.value, 'actual result');
+});
+
test('reports invalid source as a parse error', async () => {
const result = await execute('const value = ;');
@@ -406,6 +457,62 @@ test('preempts a pure compute loop at the sandbox-time limit', async () => {
if (!result.ok) assert.equal(result.error.kind, 'limit_exceeded');
});
+test('still preempts compute while a host tool is pending', async () => {
+ let aborted = false;
+ const result = await execute(
+ 'const pending = tools.wait({}).then(value => value); await tools.started({}); while (true) {}',
+ {
+ tools: [{ name: 'wait' }, { name: 'started' }],
+ signal: AbortSignal.timeout(5_000),
+ executionPolicy: { ...DEFAULT_CODE_MODE_EXECUTION_POLICY, timeoutMs: 100 },
+ callTool: async (name, _input, signal) => {
+ if (name === 'started') return null;
+ await new Promise<void>((resolve) => {
+ const onAbort = () => {
+ aborted = true;
+ resolve();
+ };
+ if (signal.aborted) onAbort();
+ else signal.addEventListener('abort', onAbort, { once: true });
+ });
+ return null;
+ },
+ },
+ );
+ assert.equal(result.ok, false);
+ if (!result.ok) assert.equal(result.error.kind, 'limit_exceeded');
+ assert.equal(aborted, true);
+});
+
+test('accumulates compute across awaits instead of resetting the budget', async () => {
+ // Keep the single slice well below the budget on a loaded runner, with
+ // enough repeated slices to exercise cumulative accounting on faster hosts.
+ const work = 'let total = 0; for (let i = 0; i < 10_000; i++) total += Math.sqrt(i);';
+ const executionPolicy = {
+ ...DEFAULT_CODE_MODE_EXECUTION_POLICY,
+ timeoutMs: 1_000,
+ maxBridgeRequests: 8_192,
+ };
+ const single = await execute(`${work} return total;`, { executionPolicy });
+ assert.equal(single.ok, true, JSON.stringify(single));
+ let calls = 0;
+ const result = await execute(
+ `for (let step = 0; step < 5_000; step++) { ${work} await tools.tick({}); }`,
+ {
+ executionPolicy,
+ tools: [{ name: 'tick' }],
+ signal: AbortSignal.timeout(15_000),
+ callTool: async () => {
+ calls++;
+ return null;
+ },
+ },
+ );
+ assert.equal(result.ok, false);
+ if (!result.ok) assert.match(result.error.message, /timed out after 1000ms/);
+ assert.ok(calls > 1 && calls < 5_000, `completed ${calls} slices`);
+});
+
test('waits for an aborted host operation to settle before rejecting', async () => {
const controller = new AbortController();
const reason = new Error('stop requested');
diff --git a/packages/runtime/src/__tests__/plan-mode.test.ts b/packages/runtime/src/__tests__/plan-mode.test.ts
index d042bee6fc..17e519d786 100644
--- a/packages/runtime/src/__tests__/plan-mode.test.ts
+++ b/packages/runtime/src/__tests__/plan-mode.test.ts
@@ -25,14 +25,6 @@ import { buildCancelPlanTool, buildSubmitPlanTool, buildUpdatePlanTool } from '.
import type { MakaTool } from '../tool-runtime.js';
describe('Plan Mode tool surface', () => {
- test('keeps plan lifecycle controls outside nested Code Mode execution', () => {
- const store = {} as never;
-
- assert.equal(buildSubmitPlanTool(store).nesting, 'direct_only');
- assert.equal(buildUpdatePlanTool(store, 'execution-1').nesting, 'direct_only');
- assert.equal(buildCancelPlanTool(store, 'execution-1').nesting, 'direct_only');
- });
-
test('requires plain-text step titles and descriptions', () => {
const submitPlan = buildSubmitPlanTool({} as never);
assert.equal(submitPlan.recoveryMode, 'idempotent');
diff --git a/packages/runtime/src/__tests__/stream-graph-supervisor-tools.test.ts b/packages/runtime/src/__tests__/stream-graph-supervisor-tools.test.ts
index 2e91fe60f0..e81b336899 100644
--- a/packages/runtime/src/__tests__/stream-graph-supervisor-tools.test.ts
+++ b/packages/runtime/src/__tests__/stream-graph-supervisor-tools.test.ts
@@ -49,7 +49,6 @@ describe('stream graph supervisor tools', () => {
assert.equal(viewTool.recoveryMode, 'replay_safe');
assert.equal(updateTool.recoveryMode, 'idempotent');
assert.equal(yieldTool.recoveryMode, 'replay_safe');
- assert.equal(yieldTool.nesting, 'direct_only');
await assert.rejects(
async () =>
diff --git a/packages/runtime/src/agent-run.ts b/packages/runtime/src/agent-run.ts
index 6ad82960db..e693903960 100644
--- a/packages/runtime/src/agent-run.ts
+++ b/packages/runtime/src/agent-run.ts
@@ -337,8 +337,17 @@ export class AgentRun {
acceptedInput.header.orchestrationMode,
acceptedInput.userInput.turnOrchestration,
);
+ if (
+ acceptedInput.userInput.toolMode !== undefined &&
+ !isToolMode(acceptedInput.userInput.toolMode)
+ ) {
+ throw new Error(`Invalid tool mode: ${String(acceptedInput.userInput.toolMode)}`);
+ }
const requestedToolMode =
- acceptedInput.effectiveToolMode ?? acceptedInput.userInput.toolMode ?? DEFAULT_TOOL_MODE;
+ acceptedInput.effectiveToolMode ??
+ acceptedInput.header.toolMode ??
+ acceptedInput.userInput.toolMode ??
+ DEFAULT_TOOL_MODE;
if (!isToolMode(requestedToolMode)) {
throw new Error(`Invalid tool mode: ${String(requestedToolMode)}`);
}
diff --git a/packages/runtime/src/agent-swarm-status-tool.ts b/packages/runtime/src/agent-swarm-status-tool.ts
index 8c7044ad80..f4d2427c39 100644
--- a/packages/runtime/src/agent-swarm-status-tool.ts
+++ b/packages/runtime/src/agent-swarm-status-tool.ts
@@ -162,7 +162,6 @@ export function buildAgentSwarmStatusTool(input: {
'Read compact status-only progress for the asynchronous swarm. This omits child logs, tool activity, reasoning, and partial output.',
parameters: z.object({}).strip(),
categoryHint: 'read',
- nesting: 'direct_only',
recoveryMode: 'replay_safe',
impl: async () => projectAgentSwarmStatus(await input.readSnapshot()),
};
diff --git a/packages/runtime/src/ai-sdk-turn.ts b/packages/runtime/src/ai-sdk-turn.ts
index 37960a3e48..50d544c34c 100644
--- a/packages/runtime/src/ai-sdk-turn.ts
+++ b/packages/runtime/src/ai-sdk-turn.ts
@@ -424,44 +424,31 @@ function projectToolModePlan(
plan: ToolAvailabilityPlan,
toolMode: ToolMode,
execTool: MakaTool,
+ nested: ReadonlyMap<string, MakaTool>,
): ToolAvailabilityPlan {
if (toolMode === 'direct') return plan;
- const withExec = (names: readonly string[]): string[] =>
- [...new Set([...names, execTool.name])].sort((a, b) => a.localeCompare(b));
- const invalid = plan.providerTools.filter((tool) => tool.name === INVALID_TOOL_NAME);
- const visible = [
- ...plan.providerTools.filter((tool) => tool.name !== INVALID_TOOL_NAME),
- execTool,
- ].sort((a, b) => a.name.localeCompare(b.name));
+ const catalog = requestCompositionToolSchemas([...nested.values()], [...nested.keys()]);
+ const projectedExec = {
+ ...execTool,
+ description: [
+ execTool.description,
+ 'This is the only callable tool. Call the following tools from inside exec.',
+ 'After tool_search, return its result and use the refreshed catalog in the next exec call.',
+ JSON.stringify(catalog),
+ ].join('\n'),
+ };
return {
...plan,
- providerTools: [...visible, ...invalid],
- activeTools: withExec(plan.activeTools),
+ providerTools: [
+ projectedExec,
+ ...plan.providerTools.filter((tool) => tool.name === INVALID_TOOL_NAME),
+ ],
+ activeTools: [execTool.name],
...(plan.projectActiveTools
- ? {
- projectActiveTools: (options) => ({
- activeTools: withExec(plan.projectActiveTools?.(options).activeTools ?? []),
- }),
- }
+ ? { projectActiveTools: () => ({ activeTools: [execTool.name] }) }
: {}),
- currentRepairToolNames: () => withExec(plan.currentRepairToolNames()),
- diagnostics: (activeTools, visibleToolSchemaChars) => {
- const baseActive = activeTools.filter((name) => name !== execTool.name);
- const baseChars = toolSchemaCharsForDiagnostics(plan.providerTools, baseActive);
- const diagnostic = plan.diagnostics(baseActive, baseChars);
- if (!diagnostic) return undefined;
- const execSchemaChars = Math.max(0, visibleToolSchemaChars - baseChars);
- return {
- ...diagnostic,
- visibleToolCount: (diagnostic.visibleToolCount ?? baseActive.length) + 1,
- fullToolCount:
- (diagnostic.fullToolCount ?? baseActive.length + (diagnostic.hiddenToolCount ?? 0)) + 1,
- visibleToolSchemaChars,
- fullToolSchemaChars:
- (diagnostic.fullToolSchemaChars ??
- baseChars + (diagnostic.toolSchemaCharReduction ?? 0)) + execSchemaChars,
- };
- },
+ currentRepairToolNames: () => [execTool.name],
+ diagnostics: () => undefined,
};
}
@@ -846,7 +833,9 @@ export class AiSdkTurn {
: { disposition: 'policy_denied', dispatch: false };
}
- private createCodeModeExecTool(eventSink: DurableSessionEventSink): MakaTool<{ code: string }> {
+ private createCodeModeExecTool(
+ eventSink: AsyncEventQueue<SessionEvent>,
+ ): MakaTool<{ code: string }> {
return {
name: 'exec',
description: [
@@ -1117,7 +1106,7 @@ export class AiSdkTurn {
])
: new Set<string>();
const requestedToolMode: unknown =
- input.toolMode === undefined ? DEFAULT_TOOL_MODE : input.toolMode;
+ input.toolMode ?? this.deps.backend.header.toolMode ?? DEFAULT_TOOL_MODE;
if (!isToolMode(requestedToolMode)) {
throw new Error(`Invalid tool mode: ${String(requestedToolMode)}`);
}
@@ -1127,10 +1116,17 @@ export class AiSdkTurn {
if (toolMode === 'code_mode' && snapshot.hostTools.some((tool) => tool.name === 'exec')) {
throw new Error('Tool name "exec" is reserved for Code Mode.');
}
+ const basePlan = snapshot.runtime.prepare(this.activeTools, requiredOrchestrationTools);
+ const nestedTools = nestableToolSnapshot(basePlan.providerTools, basePlan.activeTools);
const plan = projectToolModePlan(
- snapshot.runtime.prepare(this.activeTools, requiredOrchestrationTools),
+ basePlan,
toolMode,
codeModeExecTool,
+ toolRuntime.hasSandboxBoundaryDenial()
+ ? new Map(
+ [...nestedTools].filter(([name]) => name !== REQUEST_SANDBOX_BOUNDARY_TOOL_NAME),
+ )
+ : nestedTools,
);
const modelTools: ModelToolSet = {};
for (const tool of plan.providerTools) {
@@ -1139,9 +1135,9 @@ export class AiSdkTurn {
: { kind: 'function', description: tool.description, inputSchema: tool.parameters };
}
toolRuntime.setGating(plan.gating);
- return { plan, providerTools: plan.providerTools, modelTools };
+ return { plan, providerTools: plan.providerTools, modelTools, nestedTools };
};
- let { plan, providerTools, modelTools } = snapshotStepTools();
+ let { plan, providerTools, modelTools, nestedTools } = snapshotStepTools();
let activeToolResultPruneDiagnosticPatch: ActiveToolResultPruneDiagnosticPatch = {};
let midTurnCompactDiagnosticPatch: Partial<ContextBudgetDiagnostic> | undefined;
// Tool names the repair path matches a mis-cased call against — follows the
@@ -1462,7 +1458,7 @@ export class AiSdkTurn {
let finishReason: ModelFinishReason = 'stop';
let terminalProviderError: unknown;
agentLoop: for (;;) {
- ({ plan, providerTools, modelTools } = snapshotStepTools());
+ ({ plan, providerTools, modelTools, nestedTools } = snapshotStepTools());
resolvedSystemPrompt = await this.resolveSystemPrompt();
systemPrompt = joinPromptFragments([
resolvedSystemPrompt.text,
@@ -1596,13 +1592,9 @@ export class AiSdkTurn {
// no longer sees it as a direct tool, but a nested retry must still
// reach ToolRuntime's denial latch instead of becoming an endlessly
// variable unknown-tool error inside `exec`.
- const codeModeActiveTools =
- toolRuntime.hasSandboxBoundaryDenial() && activeToolsForRequest.includes('exec')
- ? [...activeToolsForRequest, REQUEST_SANDBOX_BOUNDARY_TOOL_NAME]
- : activeToolsForRequest;
this.codeModeTools =
- toolMode === 'code_mode'
- ? nestableToolSnapshot(providerTools, codeModeActiveTools)
+ toolMode === 'code_mode' && activeToolsForRequest.includes('exec')
+ ? nestedTools
: undefined;
const requestWatchdog = watchdogState.current;
// Read here, beside the messages it describes: `attemptMessages` is
@@ -2710,7 +2702,7 @@ export class AiSdkTurn {
}
private async executeCodeModeCell(
- eventSink: DurableSessionEventSink,
+ eventSink: AsyncEventQueue<SessionEvent>,
code: string,
context: MakaToolContext,
): Promise<unknown> {
@@ -2734,15 +2726,9 @@ export class AiSdkTurn {
},
pushAndWaitUntilConsumed: (event) => eventSink.pushAndWaitUntilConsumed(event),
};
- // A permit is held across the cell's complete lifecycle, not just its
- // sandbox run: `executeCodeCell` settles only once the cell's host
- // operations have drained, so releasing on settlement covers the drain.
- // The sandbox worker cap cannot serve this purpose — on cancellation
- // `runCodeMode` releases its worker and rejects at once, by design, while
- // host operations started by the cell may still be running with durable
- // side effects. Only the Runtime waits for those, so only the Runtime can
- // bound them; releasing when the worker is released would let repeated
- // cancellation accumulate host work without bound.
+ // Admission covers the whole cell, including host waits. executeCodeCell
+ // waits for every started host call
+ // on both success and cancellation, so settlement is the release boundary.
//
// One cell may wait; the next is turned away rather than queued, which is
// what the Code Mode adapter did before this moved to the side that owns
@@ -2765,6 +2751,8 @@ export class AiSdkTurn {
})),
isFatalToolError: isRuntimeCommitBoundaryError,
callTool: async (name, input, signal) => {
+ if (this.loopStopRequested)
+ throw new Error('The turn has yielded; no further tools may run.');
const tool = snapshot.get(name);
if (!tool) throw new Error(`Tool "${name}" is not active or nestable in this cell`);
const parsedInput = await validateCodeModeToolInput(tool, input);
@@ -2772,6 +2760,7 @@ export class AiSdkTurn {
tool,
turnId: context.turnId,
toolCallId: `${context.toolCallId}:nested:${this.deps.newId()}`,
+ stepId: `${context.toolCallId}:nested`,
input: parsedInput,
abortSignal: signal,
eventSink: nestedEventSink,
@@ -2786,6 +2775,14 @@ export class AiSdkTurn {
if (nestedOutputLimitExceeded) {
throw new Error('Code Mode nested output byte limit exceeded');
}
+ if (isPlanToolResult(settlement.result))
+ this.handlePlanToolResult(settlement.result, eventSink);
+ if (
+ name === YIELD_AGENT_GRAPH_TOOL_NAME &&
+ isAgentGraphYieldToolResult(settlement.result)
+ ) {
+ this.handleAgentGraphYieldToolResult(settlement.result);
+ }
return settlement.result;
},
});
diff --git a/packages/runtime/src/ask-user-question-tool.ts b/packages/runtime/src/ask-user-question-tool.ts
index 3400ee785b..ba06d81e93 100644
--- a/packages/runtime/src/ask-user-question-tool.ts
+++ b/packages/runtime/src/ask-user-question-tool.ts
@@ -43,7 +43,6 @@ export function buildAskUserQuestionTool(): MakaTool<
parameters: z.object({
questions: z.array(questionSchema).min(1).max(3),
}),
- nesting: 'direct_only',
impl: ({ questions }, context) => {
// Unreachable from any ToolRuntime-driven call: ToolRuntime injects
// `askUserQuestion` into every tool context unconditionally, so this
diff --git a/packages/runtime/src/code-mode.ts b/packages/runtime/src/code-mode.ts
index ebaeb7d2d0..61a501b6ae 100644
--- a/packages/runtime/src/code-mode.ts
+++ b/packages/runtime/src/code-mode.ts
@@ -40,8 +40,9 @@ export interface CodeModeToolDefinition {
*/
export const DEFAULT_CODE_MODE_EXECUTION_POLICY: Readonly<Required<CodeModeExecutionPolicy>> =
Object.freeze({
- /** Sandbox invocation deadline; aborted host operations still drain before settlement. */
+ /** Cumulative VM execution budget; tool waits follow Runtime cancellation. */
timeoutMs: 30_000,
+ timeoutMode: 'execution',
memoryLimitBytes: 64 * 1024 * 1024,
maxStackSizeBytes: 2 * 1024 * 1024,
maxResultBytes: 1024 * 1024,
@@ -189,7 +190,8 @@ async function drainHostToolOperations(operations: ReadonlySet<Promise<unknown>>
function normalizeQuickJsError(error: unknown): CodeModeDiagnostic {
const message = error instanceof Error ? error.message : String(error);
const isRunError =
- error instanceof Error && (error as Error & { code?: unknown }).code === 'RUN_ERROR';
+ error instanceof Error &&
+ (error as Error & { code?: unknown }).code === 'RUN_USER_SOURCE_ERROR';
const isSourceSyntaxRunError =
isRunError &&
error.name === 'SyntaxError' &&
@@ -199,8 +201,9 @@ function normalizeQuickJsError(error: unknown): CodeModeDiagnostic {
}
if (
isRunError &&
- error.name === 'InternalError' &&
- (/^interrupted$/i.test(message) || /out of memory|stack (?:size|overflow)/i.test(message))
+ (error.name === 'InternalError' || error.name === 'RangeError') &&
+ (/^interrupted$/i.test(message) ||
+ /out of memory|stack (?:size|overflow)|maximum call stack size exceeded/i.test(message))
) {
return { kind: 'limit_exceeded', message };
}
diff --git a/packages/runtime/src/plan-tools.ts b/packages/runtime/src/plan-tools.ts
index a02a4e95df..daba995c5e 100644
--- a/packages/runtime/src/plan-tools.ts
+++ b/packages/runtime/src/plan-tools.ts
@@ -130,7 +130,6 @@ export function buildSubmitPlanTool(
'Plan proposal cannot fit its execution lifecycle projection',
),
recoveryMode: 'idempotent',
- nesting: 'direct_only',
impl: async (input, context) => {
const result = await planStore.submitProposal({
operationId: planToolOperationId('submit', context),
@@ -170,7 +169,6 @@ export function buildUpdatePlanTool(
explanation: boundedTextSchema('Plan progress explanation').optional(),
}),
recoveryMode: 'idempotent',
- nesting: 'direct_only',
impl: async (input, context) => {
const result = await planStore.updateExecution({
operationId: planToolOperationId('update', context),
@@ -195,7 +193,6 @@ export function buildCancelPlanTool(
reason: boundedTextSchema('Plan cancellation reason', PLAN_LIFECYCLE_REASON_MAX_BYTES),
}),
recoveryMode: 'idempotent',
- nesting: 'direct_only',
impl: async ({ reason }, context) => {
const result = await planStore.cancelExecution({
operationId: planToolOperationId('cancel', context),
diff --git a/packages/runtime/src/session-manager.ts b/packages/runtime/src/session-manager.ts
index e107e5b4de..06cb73e3da 100644
--- a/packages/runtime/src/session-manager.ts
+++ b/packages/runtime/src/session-manager.ts
@@ -2592,6 +2592,7 @@ export class SessionManager {
permissionMode: childPermissionMode,
collaborationMode: 'agent',
orchestrationMode: 'default',
+ toolMode: parentHeader.toolMode ?? DEFAULT_TOOL_MODE,
subagentParent: {
kind: 'subagent',
parentSessionId: input.source.sessionId,
@@ -3134,6 +3135,7 @@ export class SessionManager {
permissionMode: definition.permissionMode,
collaborationMode: 'agent',
orchestrationMode: 'default',
+ toolMode: parentHeader.toolMode ?? DEFAULT_TOOL_MODE,
subagentParent: {
kind: 'subagent',
parentSessionId,
@@ -3865,7 +3867,7 @@ export class SessionManager {
cwd: session.cwd,
permissionMode: session.permissionMode,
collaborationMode: session.collaborationMode ?? 'agent',
- toolMode: DEFAULT_TOOL_MODE,
+ toolMode: session.toolMode ?? DEFAULT_TOOL_MODE,
...orchestration,
...(workspaceIdentity !== undefined ? { workspaceIdentity } : {}),
},
diff --git a/packages/runtime/src/stream-graph-supervisor-tools.ts b/packages/runtime/src/stream-graph-supervisor-tools.ts
index df4328bbe5..fef66a8d9c 100644
--- a/packages/runtime/src/stream-graph-supervisor-tools.ts
+++ b/packages/runtime/src/stream-graph-supervisor-tools.ts
@@ -553,7 +553,6 @@ export function buildAgentGraphSupervisorTools(
'Inspect the durable graph. Use mode=latest without a cursor for the current view; use mode=page only with a nextCursor returned by an earlier view.',
parameters: viewSchema,
categoryHint: 'read',
- nesting: 'direct_only',
recoveryMode: 'replay_safe',
impl: async (toolInput) => {
const view = await readToolGraphView(
@@ -577,7 +576,6 @@ export function buildAgentGraphSupervisorTools(
'Adjust the graph durably. Always set operation. Prefer target_kind=new_preset with a user-approved subagent_id from agent_list; legacy agent_id remains supported. Unrelated provider-filled optional fields are ignored.',
parameters: updateSchema,
categoryHint: 'subagent',
- nesting: 'direct_only',
recoveryMode: 'idempotent',
impl: async (toolInput, context) => {
const request = compileAgentGraphScheduleUpdate({
@@ -614,7 +612,6 @@ export function buildAgentGraphSupervisorTools(
categoryHint: 'subagent',
recoveryMode: 'replay_safe',
executionSemantics: 'exclusive_step',
- nesting: 'direct_only',
impl: async ({ reason }) => {
const permit = input.prepareYieldPermit?.();
try {
diff --git a/packages/runtime/src/subagent-tools.ts b/packages/runtime/src/subagent-tools.ts
index 19a479c17d..ade65bd679 100644
--- a/packages/runtime/src/subagent-tools.ts
+++ b/packages/runtime/src/subagent-tools.ts
@@ -169,7 +169,6 @@ export function buildSubagentSpawnTool(
}),
),
categoryHint: 'subagent',
- nesting: 'direct_only',
impl: async (input, ctx) => {
const definition = input.subagent_id
? await resolvePresetDefinition(input.subagent_id, ctx, definitions)
@@ -318,7 +317,6 @@ export function buildSubagentListTool(): MakaTool<
})
.strip(),
categoryHint: 'read',
- nesting: 'direct_only',
impl: async (input, ctx) => {
// Runtime Host supplies this capability to production clients. Keep the
// failure explicit at the embedding boundary.
@@ -566,7 +564,6 @@ export function buildSubagentOutputTool(): MakaTool<
}),
),
categoryHint: 'read',
- nesting: 'direct_only',
impl: async (input, ctx) => {
if (!ctx.readChildAgentOutput) {
// Same reachability as `agent_list` above.
diff --git a/packages/runtime/src/tool-availability.ts b/packages/runtime/src/tool-availability.ts
index 3cbd6bfdfd..3b751fab67 100644
--- a/packages/runtime/src/tool-availability.ts
+++ b/packages/runtime/src/tool-availability.ts
@@ -369,7 +369,6 @@ export class ToolAvailabilityRuntime {
.optional()
.describe(`Maximum matches to activate; defaults to ${TOOL_SEARCH_DEFAULT_LIMIT}.`),
}),
- nesting: 'direct_only',
impl: ({ query, limit = TOOL_SEARCH_DEFAULT_LIMIT }, context) => {
const normalizedQuery = query.trim();
const ranked = this.searchIndex!.search(normalizedQuery)
diff --git a/packages/storage/src/__tests__/session-store.test.ts b/packages/storage/src/__tests__/session-store.test.ts
index a712b3b01e..582590be52 100644
--- a/packages/storage/src/__tests__/session-store.test.ts
+++ b/packages/storage/src/__tests__/session-store.test.ts
@@ -42,6 +42,22 @@ import { OPERATIONAL_STATE_DATABASE_NAME } from '../operational-state-store.js';
import { createSqliteSessionMetadataStore } from '../sqlite-session-metadata-store.js';
describe('SQLite SessionStore', () => {
+ test('persists the creation-time tool mode across reloads', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'maka-tool-mode-'));
+ let store = createSessionStore(root);
+ try {
+ const code = await store.create(makeInput({ cwd: root, toolMode: 'code_mode' }));
+ const direct = await store.create(makeInput({ cwd: root }));
+ await store.close?.();
+ store = createSessionStore(root);
+ assert.equal((await store.readHeader(code.id)).toolMode, 'code_mode');
+ assert.equal((await store.readHeader(direct.id)).toolMode, 'direct');
+ } finally {
+ await store.close?.();
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
test('requires the reserved WorkHub Coordination identity and role together', async () => {
const root = await mkdtemp(join(tmpdir(), 'maka-workhub-coordination-identity-role-'));
const store = createSessionStore(root);
diff --git a/packages/storage/src/session-store.ts b/packages/storage/src/session-store.ts
index 33bdfaa5bf..2679e6b21e 100644
--- a/packages/storage/src/session-store.ts
+++ b/packages/storage/src/session-store.ts
@@ -70,6 +70,7 @@ import type {
} from '@maka/core/sandbox-boundary';
import type { CreateSessionInput, SessionListFilter } from '@maka/core/runtime-inputs';
+import { DEFAULT_TOOL_MODE, isToolMode } from '@maka/core/tool-mode';
import {
isSessionToolProfile,
@@ -1348,6 +1349,7 @@ function buildSessionHeader(
connectionLocked: input.subagentParent !== undefined,
model: input.model ?? 'default',
...(input.toolProfile !== undefined ? { toolProfile: input.toolProfile } : {}),
+ toolMode: input.toolMode ?? DEFAULT_TOOL_MODE,
permissionMode: input.permissionMode,
collaborationMode: input.collaborationMode ?? 'agent',
orchestrationMode: input.orchestrationMode ?? 'default',
@@ -1409,6 +1411,7 @@ export function normalizeSessionHeader(
typeof header.connectionLocked === 'boolean' &&
typeof header.model === 'string' &&
(header.toolProfile === undefined || isSessionToolProfile(header.toolProfile)) &&
+ (header.toolMode === undefined || isToolMode(header.toolMode)) &&
isPermissionMode(header.permissionMode) &&
isCollaborationMode(header.collaborationMode) &&
isOrchestrationMode(header.orchestrationMode) &&
diff --git a/patches/@ai-sdk+provider-utils+5.0.34.patch b/patches/@ai-sdk+provider-utils+5.0.40.patch
similarity index 98%
rename from patches/@ai-sdk+provider-utils+5.0.34.patch
rename to patches/@ai-sdk+provider-utils+5.0.40.patch
index 115f823aa0..7c13eaf792 100644
--- a/patches/@ai-sdk+provider-utils+5.0.34.patch
+++ b/patches/@ai-sdk+provider-utils+5.0.40.patch
@@ -1,8 +1,8 @@
diff --git a/node_modules/@ai-sdk/provider-utils/dist/index.js b/node_modules/@ai-sdk/provider-utils/dist/index.js
-index dfba4b2..55ed538 100644
+index bbf563c..aba09ea 100644
--- a/node_modules/@ai-sdk/provider-utils/dist/index.js
+++ b/node_modules/@ai-sdk/provider-utils/dist/index.js
-@@ -3932,11 +3932,12 @@
+@@ -4232,11 +4232,12 @@
import {
InvalidResponseDataError
} from "@ai-sdk/provider";
@@ -18,7 +18,7 @@ index dfba4b2..55ed538 100644
var _a3, _b3;
this.controller = controller;
this._generateId = (_a3 = options.generateId) != null ? _a3 : generateId;
-@@ -3950,31 +3951,90 @@
+@@ -4250,31 +4251,90 @@
* events as appropriate.
*/
processDelta(toolCallDelta) {
@@ -120,7 +120,7 @@ index dfba4b2..55ed538 100644
if (this.typeValidation === "required") {
if (toolCallDelta.type !== "function") {
throw new InvalidResponseDataError({
-@@ -3990,38 +4050,32 @@
+@@ -4290,38 +4350,32 @@
});
}
}
diff --git a/patches/@maka+runtime++@ai-sdk+code-mode+1.0.56.patch b/patches/@maka+runtime++@ai-sdk+code-mode+1.0.56.patch
new file mode 100644
index 0000000000..7e185cfa33
--- /dev/null
+++ b/patches/@maka+runtime++@ai-sdk+code-mode+1.0.56.patch
@@ -0,0 +1,74 @@
+diff --git a/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/src/types.ts b/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/src/types.ts
+index b317e9d..5beb1c2 100644
+--- a/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/src/types.ts
++++ b/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/src/types.ts
+@@ -160,6 +160,8 @@
+ * Execution limits applied to each sandbox invocation.
+ */
+ export interface CodeModeExecutionPolicy {
++ /** Whether timeoutMs counts total elapsed time or synchronous VM execution. */
++ timeoutMode?: 'wall' | 'execution';
+ /** @defaultValue `30_000` */
+ timeoutMs?: number;
+ /** @defaultValue `64 * 1024 * 1024` */
+diff --git a/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/src/run-code-mode.ts b/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/src/run-code-mode.ts
+index 95435bd..fb7ba60 100644
+--- a/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/src/run-code-mode.ts
++++ b/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/src/run-code-mode.ts
+@@ -159,6 +159,7 @@
+ }
+
+ interface ResolvedExecutionPolicy {
++ timeoutMode: 'wall' | 'execution';
+ timeoutMs: number;
+ memoryLimitBytes: number;
+ maxStackSizeBytes: number;
+@@ -176,6 +177,7 @@
+ ): ResolvedExecutionPolicy {
+ return {
+ timeoutMs: policy.timeoutMs ?? DEFAULT_TIMEOUT_MS,
++ timeoutMode: policy.timeoutMode ?? 'wall',
+ memoryLimitBytes: policy.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES,
+ maxStackSizeBytes: policy.maxStackSizeBytes ?? DEFAULT_STACK_LIMIT_BYTES,
+ maxResultBytes: policy.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES,
+@@ -363,6 +365,7 @@
+ ): RunLimits {
+ return {
+ timeoutMs: policy.timeoutMs,
++ timeoutMode: policy.timeoutMode,
+ memoryLimitBytes: policy.memoryLimitBytes,
+ maxStackSizeBytes: policy.maxStackSizeBytes,
+ maxResultBytes: expandedSerializationLimit(policy.maxResultBytes),
+diff --git a/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/dist/index.d.ts b/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/dist/index.d.ts
+index 9cafdbb..3c924f1 100644
+--- a/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/dist/index.d.ts
++++ b/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/dist/index.d.ts
+@@ -117,6 +117,8 @@
+ * Execution limits applied to each sandbox invocation.
+ */
+ interface CodeModeExecutionPolicy {
++ /** Whether timeoutMs counts total elapsed time or synchronous VM execution. */
++ timeoutMode?: 'wall' | 'execution';
+ /** @defaultValue `30_000` */
+ timeoutMs?: number;
+ /** @defaultValue `64 * 1024 * 1024` */
+diff --git a/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/dist/run-code-mode.js b/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/dist/run-code-mode.js
+index 257b976..8095276 100644
+--- a/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/dist/run-code-mode.js
++++ b/node_modules/@maka/runtime/node_modules/@ai-sdk/code-mode/dist/run-code-mode.js
+@@ -117,6 +117,7 @@
+ function resolveExecutionPolicy(policy = {}) {
+ return {
+ timeoutMs: policy.timeoutMs ?? DEFAULT_TIMEOUT_MS,
++ timeoutMode: policy.timeoutMode ?? "wall",
+ memoryLimitBytes: policy.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES,
+ maxStackSizeBytes: policy.maxStackSizeBytes ?? DEFAULT_STACK_LIMIT_BYTES,
+ maxResultBytes: policy.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES,
+@@ -260,6 +261,7 @@
+ function toRunLimits(policy, source, userSource) {
+ return {
+ timeoutMs: policy.timeoutMs,
++ timeoutMode: policy.timeoutMode,
+ memoryLimitBytes: policy.memoryLimitBytes,
+ maxStackSizeBytes: policy.maxStackSizeBytes,
+ maxResultBytes: expandedSerializationLimit(policy.maxResultBytes),
diff --git a/patches/README.md b/patches/README.md
index f80e43147e..49de7d4cf6 100644
--- a/patches/README.md
+++ b/patches/README.md
@@ -30,8 +30,47 @@ Keep this directory small. Prefer product code that uses the dependency's
published API; only patch for bugs that block shipping and cannot be worked
around at the call site.
+## `run@2.1.4` and `@ai-sdk/code-mode@1.0.56`
+
+Code Mode awaits normal Runtime tools, including user interactions. The upstream
+wall deadline aborts those waits. The opt-in `timeoutMode: 'execution'` instead
+counts cumulative synchronous QuickJS execution, retaining the VM and normal
+Promise completion order during asynchronous host waits. Cancellation and worker
+pool/memory bounds remain in effect. Wall mode is unchanged. Execution mode
+rejects synchronous host functions/module loaders, which Maka does not expose.
+Callers must supply a reachable cancellation signal: a guest Promise that never
+settles retains its Worker until cancelled, even without an outstanding Host tool.
+There is no automatic liveness deadline or deadlock detector.
+
+The patched package requires Maka's Node >=22.19 baseline and drops the optional
+TypeScript peer used only by upstream's older-Node fallback. Maka uses native
+`node:module.stripTypeScriptTypes`, so a second compiler is unnecessary and the
+upstream peer range otherwise conflicts with the repository's TypeScript 7.
+
+The SDK patch only forwards this policy. Its nested patch path follows the locked
+workspace installation through `node_modules/@maka/runtime`. No continuation,
+replay, result ordering, or Worker pool is added to Maka.
+
+`run-2.1.4-source.diff` is the readable source corresponding to the run patch.
+To rebuild, check out upstream `vercel-labs/run` tag `run@2.1.4`
+(`0207eebde4fc9c04b35d8414773a7dea6c552115`), apply that diff, install with
+`pnpm install --frozen-lockfile --ignore-scripts --filter run...`, and run
+`pnpm --filter run build`. Copy the changed `dist` files into the installed run
+package and regenerate with `node node_modules/patch-package/index.js run`.
+Copy the patched package manifest as well, and pass `--exclude '^$'` when
+regenerating so patch-package includes that manifest change.
+The large generated hunk is the inline Worker with unchanged embedded WASM;
+`run-2.1.4-notices.md` retains its embedded dependency notices.
+
+Remove both patches and the run override when published versions support the
+same execution budget semantics. Regression coverage lives in
+`packages/runtime/src/__tests__/code-mode.test.ts`: long host waits with dependent
+Promise.race progress, pending-host compute timeout, cumulative compute across
+awaits, and the existing cancellation/drain and resource-limit cases.
+
## `@earendil-works/pi-tui@0.84.4`
+
Editor undo snapshots deep-clone all stored paste strings for each typed word,
so a 1 MiB paste followed by 60 words retains roughly 60 MiB of duplicate text.
The editor now copies its mutable state, lines array, and paste Map while
@@ -91,7 +130,7 @@ the queue at the native exit fence. See #2978.
Delete when node-pty ships an equivalent Unix write-lifecycle fix.
-## `@ai-sdk/provider-utils@5.0.34`
+## `@ai-sdk/provider-utils@5.0.40`
Streaming tool-call association for gateways that reuse or omit `index` / `id`
(Ollama-style, Anthropic→OpenAI translators). See #1967 / #1976 and
diff --git a/patches/run+2.1.4.patch b/patches/run+2.1.4.patch
new file mode 100644
index 0000000000..b0d9a7a36e
--- /dev/null
+++ b/patches/run+2.1.4.patch
@@ -0,0 +1,192 @@
+diff --git a/node_modules/run/dist/index.d.ts b/node_modules/run/dist/index.d.ts
+index b3bc968..d3cf5d6 100644
+--- a/node_modules/run/dist/index.d.ts
++++ b/node_modules/run/dist/index.d.ts
+@@ -118,6 +118,8 @@ interface RunModuleLoader {
+ }
+ /** Resource limits applied to one sandbox invocation. */
+ interface RunLimits {
++ /** Count elapsed invocation time (default), or synchronous VM execution only. */
++ timeoutMode?: 'wall' | 'execution';
+ /** @default `30_000` */
+ timeoutMs?: number;
+ /** @default `64 * 1024 * 1024` */
+diff --git a/node_modules/run/dist/runtime/guest-sources.js b/node_modules/run/dist/runtime/guest-sources.js
+index 81d9d95..76a3a16 100644
+--- a/node_modules/run/dist/runtime/guest-sources.js
++++ b/node_modules/run/dist/runtime/guest-sources.js
+@@ -627,7 +627,7 @@ return Object.freeze({
+ `;
+ };
+ const wrapUserCode = (js) => `
+-globalThis.__runResult = (async () => {
++(async () => {
+ ${js}
+ })();
+ `;
+diff --git a/node_modules/run/dist/runtime/guest-sources.js.map b/node_modules/run/dist/runtime/guest-sources.js.map
+index 65929d4..8d39be5 100644
+--- a/node_modules/run/dist/runtime/guest-sources.js.map
++++ b/node_modules/run/dist/runtime/guest-sources.js.map
+@@ -1 +1 @@
+-{"version":3,"sources":["../../src/runtime/guest-sources.ts"],"sourcesContent":["import { GUEST_SERDE_SOURCE } from './guest-serde-source.js';\n\nconst BASE64_SOURCE = `\nconst __runBase64Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nfunction btoa(input) {\n var output = '';\n for (var index = 0; index < input.length; index += 3) {\n var first = input.charCodeAt(index);\n var hasSecond = index + 1 < input.length;\n var hasThird = index + 2 < [...]
+\ No newline at end of file
++{"version":3,"sources":["../../src/runtime/guest-sources.ts"],"sourcesContent":["import { GUEST_SERDE_SOURCE } from './guest-serde-source.js';\n\nconst BASE64_SOURCE = `\nconst __runBase64Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nfunction btoa(input) {\n var output = '';\n for (var index = 0; index < input.length; index += 3) {\n var first = input.charCodeAt(index);\n var hasSecond = index + 1 < input.length;\n var hasThird = index + 2 < [...]
+\ No newline at end of file
+diff --git a/node_modules/run/dist/runtime/manager.js b/node_modules/run/dist/runtime/manager.js
+index 911351e..09e9359 100644
+--- a/node_modules/run/dist/runtime/manager.js
++++ b/node_modules/run/dist/runtime/manager.js
+@@ -255,6 +255,9 @@ async function runManaged(input) {
+ throw new RunAbortedError();
+ }
+ const needsSyncBridge = input.moduleLoader !== void 0 || input.syncHostFunctionManifest.size > 0;
++ if (normalizedOptions.timeoutMode === "execution" && needsSyncBridge) {
++ throw new TypeError("Execution time budgets require asynchronous host functions.");
++ }
+ const syncBridgeBytes = needsSyncBridge ? getSyncBridgeBufferBytes(
+ normalizedOptions.maxHostFunctionInputBytes,
+ normalizedOptions.maxHostFunctionOutputBytes
+@@ -320,7 +323,7 @@ async function runManaged(input) {
+ }
+ const workerOptions = {
+ ...normalizedOptions,
+- timeoutMs: Math.max(1, deadlineMs - Date.now())
++ timeoutMs: normalizedOptions.timeoutMode === "execution" ? normalizedOptions.timeoutMs : Math.max(1, deadlineMs - Date.now())
+ };
+ const run = startWorkerRun({
+ ...input,
+@@ -565,12 +568,12 @@ function startWorkerRun({
+ const onAbort = bindInvocationContext(() => {
+ failTerminal(new RunAbortedError());
+ });
+- const timeoutHandle = setTimeout(
++ const timeoutHandle = normalizedOptions.timeoutMode === "wall" ? setTimeout(
+ bindInvocationContext(() => {
+ failTerminal(new RunTimeoutError(timeoutErrorMs));
+ }),
+ normalizedOptions.timeoutMs
+- );
++ ) : void 0;
+ const onMessage = bindInvocationContext((value) => {
+ try {
+ assertWorkerToMainMessage(value);
+@@ -711,9 +714,8 @@ function startWorkerRun({
+ invocationId,
+ moduleLoader: moduleLoader !== void 0,
+ options: {
+- executionTimeoutMs: getWorkerExecutionTimeoutMs(
+- normalizedOptions.timeoutMs
+- ),
++ executionTimeoutMs: normalizedOptions.timeoutMode === "execution" ? normalizedOptions.timeoutMs : getWorkerExecutionTimeoutMs(normalizedOptions.timeoutMs),
++ timeoutMode: normalizedOptions.timeoutMode,
+ maxConsoleOutputBytes: normalizedOptions.maxConsoleOutputBytes,
+ maxHostFunctionInputBytes: normalizedOptions.maxHostFunctionInputBytes,
+ maxResultBytes: normalizedOptions.maxResultBytes,
+@@ -1263,7 +1265,7 @@ function startWorkerRun({
+ context
+ ),
+ outerAbortSignal,
+- deadlineMs,
++ normalizedOptions.timeoutMode === "execution" ? Date.now() + timeoutErrorMs : deadlineMs,
+ timeoutErrorMs
+ );
+ assertContinuationTokenSize(
+diff --git a/node_modules/run/dist/runtime/manager.js.map b/node_modules/run/dist/runtime/manager.js.map
+index e8a2b49..785d71e 100644
+--- a/node_modules/run/dist/runtime/manager.js.map
++++ b/node_modules/run/dist/runtime/manager.js.map
+@@ -1 +1 @@
+-{"version":3,"sources":["../../src/runtime/manager.ts"],"sourcesContent":["import { AsyncResource } from 'node:async_hooks';\nimport { Buffer } from 'node:buffer';\nimport { createHash, randomBytes } from 'node:crypto';\nimport { Worker } from 'node:worker_threads';\nimport {\n RunAbortedError,\n RunBridgeLimitError,\n RunConcurrencyError,\n RunDetachedBridgeRequestError,\n RunError,\n RunProtocolError,\n RunTimeoutError,\n MAX_SERIALIZED_ERROR_BYTES,\n deserializeError,\n ser [...]
+\ No newline at end of file
++{"version":3,"sources":["../../src/runtime/manager.ts"],"sourcesContent":["import { AsyncResource } from 'node:async_hooks';\nimport { Buffer } from 'node:buffer';\nimport { createHash, randomBytes } from 'node:crypto';\nimport { Worker } from 'node:worker_threads';\nimport {\n RunAbortedError,\n RunBridgeLimitError,\n RunConcurrencyError,\n RunDetachedBridgeRequestError,\n RunError,\n RunProtocolError,\n RunTimeoutError,\n MAX_SERIALIZED_ERROR_BYTES,\n deserializeError,\n ser [...]
+\ No newline at end of file
+diff --git a/node_modules/run/dist/runtime/protocol-validation.js b/node_modules/run/dist/runtime/protocol-validation.js
+index 1e4a1f9..5bfb17f 100644
+--- a/node_modules/run/dist/runtime/protocol-validation.js
++++ b/node_modules/run/dist/runtime/protocol-validation.js
+@@ -33,13 +33,14 @@ const isRunOptions = (value) => {
+ "maxResultBytes",
+ "maxStackSizeBytes",
+ "memoryLimitBytes",
+- "timeoutMs"
++ "timeoutMs",
++ "timeoutMode"
+ ]);
+ } catch {
+ return false;
+ }
+- return Object.values(value).every(
+- (item) => Number.isSafeInteger(item) && item > 0
++ return Object.entries(value).every(
++ ([key, item]) => key === "timeoutMode" ? item === "wall" || item === "execution" : Number.isSafeInteger(item) && item > 0
+ );
+ };
+ const isDeterminism = (value) => {
+diff --git a/node_modules/run/dist/runtime/protocol-validation.js.map b/node_modules/run/dist/runtime/protocol-validation.js.map
+index 1158e5b..4c00afa 100644
+--- a/node_modules/run/dist/runtime/protocol-validation.js.map
++++ b/node_modules/run/dist/runtime/protocol-validation.js.map
+@@ -1 +1 @@
+-{"version":3,"sources":["../../src/runtime/protocol-validation.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport { RunProtocolError } from '../errors.js';\nimport type { SerializableError } from '../types.js';\nimport type { MainToWorkerMessage, WorkerToMainMessage } from './protocol.js';\n\nconst invalidMessage = (kind: string): RunProtocolError =>\n new RunProtocolError(`Invalid ${kind} worker protocol message.`);\n\nconst isRecord = (value: unknown): value is Rec [...]
+\ No newline at end of file
++{"version":3,"sources":["../../src/runtime/protocol-validation.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport { RunProtocolError } from '../errors.js';\nimport type { SerializableError } from '../types.js';\nimport type { MainToWorkerMessage, WorkerToMainMessage } from './protocol.js';\n\nconst invalidMessage = (kind: string): RunProtocolError =>\n new RunProtocolError(`Invalid ${kind} worker protocol message.`);\n\nconst isRecord = (value: unknown): value is Rec [...]
+\ No newline at end of file
+diff --git a/node_modules/run/dist/runtime/worker-source.js b/node_modules/run/dist/runtime/worker-source.js
+index df1fc01..254a45b 100644
+--- a/node_modules/run/dist/runtime/worker-source.js
++++ b/node_modules/run/dist/runtime/worker-source.js
+@@ -1,2 +1,2 @@
+ // This file is generated by scripts/embed-inline-worker.mjs.
+-export const INLINE_RUN_WORKER_SOURCE = "globalThis.__RUN_QUICKJS_WASM_BASE64__ = \"AGFzbQEAAAAB8QZuYAN/f38Bf2AEf35/fwF+YAJ/fwBgAn9/AX9gAX8Bf2ADf39/AGAFf35/f38BfmAEf39/fwF/YAJ/fgF+YAF/AGABfAF8YAJ/fgBgAn9+AX9gAn9/AX5gA39/fwF+YAN/f34Bf2AGf35/f39/AX5gAX4Bf2ADf35/AGADf35/AX5gBX9/f39/AX9gA39+fwF/YAABf2AEf39/fwF+YAN/fn4BfmAGf35+f39/AX5gA39+fgF/YAZ/f39/f38Bf2AEf39/fwBgBH9/fn8Bf2ABfwF+YAJ8fAF8YAR/f39+AX9gBX9/f39/AX5gBX9+fn9/AX5gAABgBX9/f39/AGAFf35/fn8Bf2ACfn8Bf2AEf35/fwF/YAd/fn9+fn5/AX9gBX9+fn5 [...]
++export const INLINE_RUN_WORKER_SOURCE = "globalThis.__RUN_QUICKJS_WASM_BASE64__ = \"AGFzbQEAAAAB8QZuYAN/f38Bf2AEf35/fwF+YAJ/fwBgAn9/AX9gAX8Bf2ADf39/AGAFf35/f38BfmAEf39/fwF/YAJ/fgF+YAF/AGABfAF8YAJ/fgBgAn9+AX9gAn9/AX5gA39/fwF+YAN/f34Bf2AGf35/f39/AX5gAX4Bf2ADf35/AGADf35/AX5gBX9/f39/AX9gA39+fwF/YAABf2AEf39/fwF+YAN/fn4BfmAGf35+f39/AX5gA39+fgF/YAZ/f39/f38Bf2AEf39/fwBgBH9/fn8Bf2ABfwF+YAJ8fAF8YAR/f39+AX9gBX9/f39/AX5gBX9+fn9/AX5gAABgBX9/f39/AGAFf35/fn8Bf2ACfn8Bf2AEf35/fwF/YAd/fn9+fn5/AX9gBX9+fn5 [...]
+diff --git a/node_modules/run/dist/utils/options.js b/node_modules/run/dist/utils/options.js
+index f6f32a5..436849c 100644
+--- a/node_modules/run/dist/utils/options.js
++++ b/node_modules/run/dist/utils/options.js
+@@ -20,7 +20,14 @@ const positiveInteger = (value, fallback, path, max = MAX_LIMIT_VALUE) => {
+ }
+ return resolved;
+ };
++const normalizeTimeoutMode = (mode) => {
++ if (mode !== void 0 && mode !== "wall" && mode !== "execution") {
++ throw new TypeError("limits.timeoutMode must be wall or execution.");
++ }
++ return mode ?? "wall";
++};
+ const normalizeOptions = (limits = {}) => ({
++ timeoutMode: normalizeTimeoutMode(limits.timeoutMode),
+ maxBridgeRequests: positiveInteger(
+ limits.maxBridgeRequests,
+ DEFAULT_MAX_BRIDGE_REQUESTS,
+diff --git a/node_modules/run/dist/utils/options.js.map b/node_modules/run/dist/utils/options.js.map
+index 2b2c2a4..3a53630 100644
+--- a/node_modules/run/dist/utils/options.js.map
++++ b/node_modules/run/dist/utils/options.js.map
+@@ -1 +1 @@
+-{"version":3,"sources":["../../src/utils/options.ts"],"sourcesContent":["import type { NormalizedRunOptions, RunLimits } from '../types.js';\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;\nconst DEFAULT_STACK_LIMIT_BYTES = 2 * 1024 * 1024;\nconst DEFAULT_MAX_RESULT_BYTES = 1024 * 1024;\nconst DEFAULT_MAX_CONSOLE_OUTPUT_BYTES = 64 * 1024;\nconst DEFAULT_MAX_SOURCE_BYTES = 256 * 1024;\nconst DEFAULT_MAX_HOST_FUNCTION_ARGUMENTS_BYTES = 1024 * 10 [...]
+\ No newline at end of file
++{"version":3,"sources":["../../src/utils/options.ts"],"sourcesContent":["import type { NormalizedRunOptions, RunLimits } from '../types.js';\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;\nconst DEFAULT_STACK_LIMIT_BYTES = 2 * 1024 * 1024;\nconst DEFAULT_MAX_RESULT_BYTES = 1024 * 1024;\nconst DEFAULT_MAX_CONSOLE_OUTPUT_BYTES = 64 * 1024;\nconst DEFAULT_MAX_SOURCE_BYTES = 256 * 1024;\nconst DEFAULT_MAX_HOST_FUNCTION_ARGUMENTS_BYTES = 1024 * 10 [...]
+\ No newline at end of file
+diff --git a/node_modules/run/package.json b/node_modules/run/package.json
+index 5477e41..8b66aa9 100644
+--- a/node_modules/run/package.json
++++ b/node_modules/run/package.json
+@@ -41,16 +41,8 @@
+ "ultracite": "7.3.2",
+ "vitest": "^4.1.6"
+ },
+- "peerDependencies": {
+- "typescript": ">=5.1.6 <7"
+- },
+- "peerDependenciesMeta": {
+- "typescript": {
+- "optional": true
+- }
+- },
+ "engines": {
+- "node": ">=20.19.0"
++ "node": ">=22.19.0"
+ },
+ "publishConfig": {
+ "access": "public"
diff --git a/patches/run-2.1.4-notices.md b/patches/run-2.1.4-notices.md
new file mode 100644
index 0000000000..84acce4728
--- /dev/null
+++ b/patches/run-2.1.4-notices.md
@@ -0,0 +1,87 @@
+# Third-party notices
+
+`run` embeds the `devalue` serializer and a QuickJS WebAssembly runtime built by the
+[`quickjs-wasi`](https://github.com/vercel-labs/quickjs-wasi) project.
+The following packages are used to build the published JavaScript and embedded
+WebAssembly artifact:
+
+| Package | Version | License |
+| -------------- | ------- | ------- |
+| `devalue` | 5.8.2 | MIT |
+| `quickjs-wasi` | 3.6.0 | MIT |
+
+The release verification script rejects unreviewed changes to these embedded
+dependencies.
+
+## devalue
+
+Copyright (c) 2018-19 [devalue contributors](https://github.com/sveltejs/devalue/graphs/contributors)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+## quickjs-wasi
+
+The MIT License
+
+Copyright (c) quickjs-wasi contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+## QuickJS
+
+QuickJS Javascript Engine
+
+Copyright (c) 2017-2026 Fabrice Bellard
+Copyright (c) 2017-2025 Charlie Gordon
+Copyright (c) 2023-2026 Ben Noordhuis
+Copyright (c) 2023-2026 Saúl Ibarra Corretgé
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/patches/run-2.1.4-source.diff b/patches/run-2.1.4-source.diff
new file mode 100644
index 0000000000..e3538093c6
--- /dev/null
+++ b/patches/run-2.1.4-source.diff
@@ -0,0 +1,366 @@
+diff --git a/packages/run/package.json b/packages/run/package.json
+index b205c66..c5aad28 100644
+--- a/packages/run/package.json
++++ b/packages/run/package.json
+@@ -62,16 +62,8 @@
+ "ultracite": "7.3.2",
+ "vitest": "^4.1.6"
+ },
+- "peerDependencies": {
+- "typescript": ">=5.1.6 <7"
+- },
+- "peerDependenciesMeta": {
+- "typescript": {
+- "optional": true
+- }
+- },
+ "engines": {
+- "node": ">=20.19.0"
++ "node": ">=22.19.0"
+ },
+ "publishConfig": {
+ "access": "public"
+diff --git a/packages/run/src/resource-hardening.test.ts b/packages/run/src/resource-hardening.test.ts
+index 60cf6a4..b499b1f 100644
+--- a/packages/run/src/resource-hardening.test.ts
++++ b/packages/run/src/resource-hardening.test.ts
+@@ -60,7 +60,9 @@ describe('resource and lifecycle hardening', () => {
+ LIMIT_NAMES.map(name => [name, MAX_LIMIT_VALUE]),
+ ) as RunLimits;
+
+- expect(Object.values(normalizeOptions(limits))).toEqual(
++ const { timeoutMode, ...numericLimits } = normalizeOptions(limits);
++ expect(timeoutMode).toBe('wall');
++ expect(Object.values(numericLimits)).toEqual(
+ Array.from({ length: LIMIT_NAMES.length }, () => MAX_LIMIT_VALUE),
+ );
+ });
+diff --git a/packages/run/src/runtime/guest-sources.ts b/packages/run/src/runtime/guest-sources.ts
+index 1f526a7..dbbcbd3 100644
+--- a/packages/run/src/runtime/guest-sources.ts
++++ b/packages/run/src/runtime/guest-sources.ts
+@@ -640,7 +640,7 @@ return Object.freeze({
+ };
+
+ export const wrapUserCode = (js: string): string => `
+-globalThis.__runResult = (async () => {
++(async () => {
+ ${js}
+ })();
+ `;
+diff --git a/packages/run/src/runtime/manager.ts b/packages/run/src/runtime/manager.ts
+index 94a79fa..169fc51 100644
+--- a/packages/run/src/runtime/manager.ts
++++ b/packages/run/src/runtime/manager.ts
+@@ -365,6 +365,9 @@ export async function runManaged(input: InternalRunInput): Promise<RunResult> {
+ }
+ const needsSyncBridge =
+ input.moduleLoader !== undefined || input.syncHostFunctionManifest.size > 0;
++ if (normalizedOptions.timeoutMode === 'execution' && needsSyncBridge) {
++ throw new TypeError('Execution time budgets require asynchronous host functions.');
++ }
+ const syncBridgeBytes = needsSyncBridge
+ ? getSyncBridgeBufferBytes(
+ normalizedOptions.maxHostFunctionInputBytes,
+@@ -434,7 +437,9 @@ export async function runManaged(input: InternalRunInput): Promise<RunResult> {
+ }
+ const workerOptions = {
+ ...normalizedOptions,
+- timeoutMs: Math.max(1, deadlineMs - Date.now()),
++ timeoutMs: normalizedOptions.timeoutMode === 'execution'
++ ? normalizedOptions.timeoutMs
++ : Math.max(1, deadlineMs - Date.now()),
+ };
+ const run = startWorkerRun({
+ ...input,
+@@ -729,12 +734,12 @@ function startWorkerRun({
+ failTerminal(new RunAbortedError());
+ });
+
+- const timeoutHandle = setTimeout(
++ const timeoutHandle = normalizedOptions.timeoutMode === 'wall' ? setTimeout(
+ bindInvocationContext(() => {
+ failTerminal(new RunTimeoutError(timeoutErrorMs));
+ }),
+ normalizedOptions.timeoutMs,
+- );
++ ) : undefined;
+
+ const onMessage = bindInvocationContext((value: unknown) => {
+ try {
+@@ -893,9 +898,10 @@ function startWorkerRun({
+ invocationId,
+ moduleLoader: moduleLoader !== undefined,
+ options: {
+- executionTimeoutMs: getWorkerExecutionTimeoutMs(
+- normalizedOptions.timeoutMs,
+- ),
++ executionTimeoutMs: normalizedOptions.timeoutMode === 'execution'
++ ? normalizedOptions.timeoutMs
++ : getWorkerExecutionTimeoutMs(normalizedOptions.timeoutMs),
++ timeoutMode: normalizedOptions.timeoutMode,
+ maxConsoleOutputBytes: normalizedOptions.maxConsoleOutputBytes,
+ maxHostFunctionInputBytes: normalizedOptions.maxHostFunctionInputBytes,
+ maxResultBytes: normalizedOptions.maxResultBytes,
+@@ -1546,7 +1552,7 @@ function startWorkerRun({
+ context,
+ ),
+ outerAbortSignal,
+- deadlineMs,
++ normalizedOptions.timeoutMode === 'execution' ? Date.now() + timeoutErrorMs : deadlineMs,
+ timeoutErrorMs,
+ );
+ assertContinuationTokenSize(
+diff --git a/packages/run/src/runtime/protocol-validation.ts b/packages/run/src/runtime/protocol-validation.ts
+index 958b7bb..d43d80e 100644
+--- a/packages/run/src/runtime/protocol-validation.ts
++++ b/packages/run/src/runtime/protocol-validation.ts
+@@ -58,12 +58,15 @@ const isRunOptions = (value: unknown): boolean => {
+ 'maxStackSizeBytes',
+ 'memoryLimitBytes',
+ 'timeoutMs',
++ 'timeoutMode',
+ ]);
+ } catch {
+ return false;
+ }
+- return Object.values(value).every(
+- item => Number.isSafeInteger(item) && (item as number) > 0,
++ return Object.entries(value).every(
++ ([key, item]) => key === 'timeoutMode'
++ ? item === 'wall' || item === 'execution'
++ : Number.isSafeInteger(item) && (item as number) > 0,
+ );
+ };
+
+diff --git a/packages/run/src/runtime/protocol.test.ts b/packages/run/src/runtime/protocol.test.ts
+index 7b9ef6b..57b0ff2 100644
+--- a/packages/run/src/runtime/protocol.test.ts
++++ b/packages/run/src/runtime/protocol.test.ts
+@@ -5,6 +5,7 @@ import {
+ } from './protocol-validation.js';
+
+ const WORKER_OPTIONS = {
++ timeoutMode: 'wall',
+ executionTimeoutMs: 950,
+ maxConsoleOutputBytes: 64 * 1024,
+ maxHostFunctionInputBytes: 1024 * 1024,
+diff --git a/packages/run/src/runtime/protocol.ts b/packages/run/src/runtime/protocol.ts
+index 03b47c5..6ce42a4 100644
+--- a/packages/run/src/runtime/protocol.ts
++++ b/packages/run/src/runtime/protocol.ts
+@@ -17,6 +17,7 @@ export interface WorkerRunMessage {
+ options: Pick<
+ NormalizedRunOptions,
+ | 'timeoutMs'
++ | 'timeoutMode'
+ | 'memoryLimitBytes'
+ | 'maxStackSizeBytes'
+ | 'maxResultBytes'
+diff --git a/packages/run/src/runtime/worker-message.test.ts b/packages/run/src/runtime/worker-message.test.ts
+index 4aa91e1..f2763a7 100644
+--- a/packages/run/src/runtime/worker-message.test.ts
++++ b/packages/run/src/runtime/worker-message.test.ts
+@@ -17,6 +17,7 @@ const createRunMessage = (
+ invocationId,
+ moduleLoader: false,
+ options: {
++ timeoutMode: 'wall',
+ executionTimeoutMs: 950,
+ maxConsoleOutputBytes: 64 * 1024,
+ maxHostFunctionInputBytes: 1024 * 1024,
+diff --git a/packages/run/src/runtime/worker.ts b/packages/run/src/runtime/worker.ts
+index 49e93c6..a100f5f 100644
+--- a/packages/run/src/runtime/worker.ts
++++ b/packages/run/src/runtime/worker.ts
+@@ -195,10 +195,17 @@ async function execute(message: WorkerRunMessage): Promise<string> {
+ let interruptChecks = 0;
+ let cancelled = false;
+ let executionTimedOut = false;
++ const cancellation = createPromiseWithResolvers<never>();
++ void cancellation.promise.catch(() => undefined);
++ let executedMs = 0;
++ let executingSince: number | undefined;
++ const executionOnly = message.options.timeoutMode === 'execution';
+ const quickJSOptions: Parameters<typeof createQuickJSContext>[0] = {
+ interruptHandler: () => {
+ interruptChecks += 1;
+- const timedOut = interruptChecks > 10_000 || Date.now() > deadline;
++ const timedOut = interruptChecks > 10_000 || (executionOnly
++ ? executedMs + (executingSince === undefined ? 0 : performance.now() - executingSince) > message.options.executionTimeoutMs
++ : Date.now() > deadline);
+ executionTimedOut ||= timedOut;
+ return cancelled || timedOut;
+ },
+@@ -213,6 +220,40 @@ async function execute(message: WorkerRunMessage): Promise<string> {
+ };
+ }
+ const context = await createQuickJSContext(quickJSOptions);
++ if (executionOnly) {
++ // Only synchronous entries into QuickJS consume the shared budget. Reentrant
++ // calls (e.g. console formatting) are already inside the outer entry.
++ const measure = <T>(operation: () => T): T => {
++ if (executingSince !== undefined) return operation();
++ if (executionTimedOut) throw new RunTimeoutError(message.options.timeoutMs);
++ executingSince = performance.now();
++ let result: T;
++ try {
++ result = operation();
++ } catch (error) {
++ if (executionTimedOut) throw new RunTimeoutError(message.options.timeoutMs);
++ throw error;
++ } finally {
++ executedMs += performance.now() - executingSince;
++ executingSince = undefined;
++ executionTimedOut ||= executedMs > message.options.executionTimeoutMs;
++ }
++ if (executionTimedOut) throw new RunTimeoutError(message.options.timeoutMs);
++ return result;
++ };
++ const evalCode = context.evalCode.bind(context);
++ context.evalCode = (...args) => measure(() => evalCode(...args));
++ const callFunction = context.callFunction.bind(context);
++ context.callFunction = (...args) => measure(() => callFunction(...args));
++ const executePendingJobs = context.executePendingJobs.bind(context);
++ context.executePendingJobs = (...args) => measure(() => executePendingJobs(...args));
++ const dump = context.dump.bind(context);
++ context.dump = (...args) => measure(() => dump(...args));
++ const setProp = context.setProp.bind(context);
++ context.setProp = (...args) => measure(() => setProp(...args));
++ const resolvePromise = context.resolvePromise.bind(context);
++ context.resolvePromise = (...args) => measure(() => resolvePromise(...args));
++ }
+ let bridgeFunctions:
+ | {
+ invokeHostFunction: JSValueHandle;
+@@ -231,10 +272,12 @@ async function execute(message: WorkerRunMessage): Promise<string> {
+ activeCancellation = {
+ cancel: () => {
+ cancelled = true;
++ cancellation.reject(new Error('Worker execution cancelled by host'));
+ },
+ fail: error => {
+ executionFailure ??= { error };
+ cancelled = true;
++ cancellation.reject(error);
+ },
+ invocationId: message.invocationId,
+ isCancelled: () => cancelled,
+@@ -280,6 +323,7 @@ async function execute(message: WorkerRunMessage): Promise<string> {
+ throw new Error('Worker execution cancelled by host');
+ }
+ },
++ cancellation.promise,
+ );
+ const completedFailure = getExecutionFailure();
+ if (completedFailure !== undefined) {
+@@ -380,6 +424,7 @@ async function evaluateUserSource(
+ serializeJsonPayload: JSValueHandle,
+ getTrustedErrorCode: JSValueHandle,
+ assertActive: () => void,
++ cancellation: Promise<never>,
+ ): Promise<string> {
+ if (message.sourceType === 'module') {
+ let modulePromise: JSValueHandle;
+@@ -396,6 +441,7 @@ async function evaluateUserSource(
+ context,
+ modulePromise,
+ assertActive,
++ cancellation,
+ );
+ if (!modulePromise.disposed) {
+ modulePromise.dispose();
+@@ -422,17 +468,18 @@ async function evaluateUserSource(
+ );
+ }
+ const wrapped = wrapUserCode(message.source);
++ let promiseHandle: JSValueHandle;
+ try {
+- context.evalCode(wrapped, 'run.js').dispose();
++ promiseHandle = context.evalCode(wrapped, 'run.js');
+ } catch (error) {
+ throw toUserSourceError(dumpQuickJSError(context, error), message.source);
+ }
+
+- const promiseHandle = context.global.getProp('__runResult');
+ const resolvedResult = await resolveQuickJSPromise(
+ context,
+ promiseHandle,
+ assertActive,
++ cancellation,
+ );
+ if (!promiseHandle.disposed) {
+ promiseHandle.dispose();
+@@ -1005,21 +1052,16 @@ async function resolveQuickJSPromise(
+ context: QuickJS,
+ promiseHandle: JSValueHandle,
+ assertActive: () => void,
++ cancellation: Promise<never>,
+ ) {
+ const resolved = context.resolvePromise(promiseHandle);
+- const notSettled = Symbol('not-settled');
+- for (;;) {
+- assertActive();
+- drainPendingJobs(context);
+- const nextTurn = createPromiseWithResolvers<typeof notSettled>();
+- setTimeout(() => nextTurn.resolve(notSettled), 0);
+- const result = await Promise.race([resolved, nextTurn.promise]);
+- if (result !== notSettled) {
+- assertActive();
+- drainPendingJobs(context);
+- return result;
+- }
+- }
++ assertActive();
++ drainPendingJobs(context);
++ // Bridge responses drain newly runnable jobs. An idle VM needs no polling.
++ const result = await Promise.race([resolved, cancellation]);
++ assertActive();
++ drainPendingJobs(context);
++ return result;
+ }
+
+ function toError(
+diff --git a/packages/run/src/types.ts b/packages/run/src/types.ts
+index 352b1dd..983fdb3 100644
+--- a/packages/run/src/types.ts
++++ b/packages/run/src/types.ts
+@@ -63,6 +63,8 @@ export type HostFunctionManifest = ReadonlyMap<string, ReadonlySet<string>>;
+
+ /** Resource limits applied to one sandbox invocation. */
+ export interface RunLimits {
++ /** Count elapsed invocation time (default), or synchronous VM execution only. */
++ timeoutMode?: 'wall' | 'execution';
+ /** @default `30_000` */
+ timeoutMs?: number;
+ /** @default `64 * 1024 * 1024` */
+@@ -284,6 +286,7 @@ export interface InternalRunInput extends RunInput<unknown> {
+
+ /** @internal */
+ export interface NormalizedRunOptions {
++ timeoutMode: 'wall' | 'execution';
+ timeoutMs: number;
+ memoryLimitBytes: number;
+ maxStackSizeBytes: number;
+diff --git a/packages/run/src/utils/options.ts b/packages/run/src/utils/options.ts
+index 7606a03..4ad4871 100644
+--- a/packages/run/src/utils/options.ts
++++ b/packages/run/src/utils/options.ts
+@@ -29,9 +29,17 @@ const positiveInteger = (
+ return resolved;
+ };
+
++const normalizeTimeoutMode = (mode: RunLimits['timeoutMode']) => {
++ if (mode !== undefined && mode !== 'wall' && mode !== 'execution') {
++ throw new TypeError('limits.timeoutMode must be wall or execution.');
++ }
++ return mode ?? 'wall';
++};
++
+ export const normalizeOptions = (
+ limits: RunLimits = {},
+ ): NormalizedRunOptions => ({
++ timeoutMode: normalizeTimeoutMode(limits.timeoutMode),
+ maxBridgeRequests: positiveInteger(
+ limits.maxBridgeRequests,
+ DEFAULT_MAX_BRIDGE_REQUESTS,
diff --git a/scripts/asf-license-headers.mjs b/scripts/asf-license-headers.mjs
index edfe6194c4..960c22eaef 100644
--- a/scripts/asf-license-headers.mjs
+++ b/scripts/asf-license-headers.mjs
@@ -195,6 +195,7 @@ export const exclusionRules = [
'packages/cli/RUNTIME_HOST_PEER_DEPENDENCIES.rust.tsv',
'packages/cli/RUNTIME_HOST_PEER_THIRD_PARTY_NOTICES.txt',
'packages/cli/THIRD_PARTY_NOTICES.txt',
+ 'patches/run-2.1.4-notices.md',
),
},
{
@@ -204,6 +205,7 @@ export const exclusionRules = [
matches: (path) =>
isOneOf(
'experiments/windows-sandbox/launcher/Cargo.lock',
+ 'patches/run-2.1.4-source.diff',
// Adapted from opencode under MIT; attribution pinned by #3325.
'packages/runtime/src/edit-replace.ts',
'packages/runtime/src/tool-output.ts',
diff --git a/scripts/generate-third-party-notices.mjs b/scripts/generate-third-party-notices.mjs
index 3ce4e568f2..5ce9414b01 100644
--- a/scripts/generate-third-party-notices.mjs
+++ b/scripts/generate-third-party-notices.mjs
@@ -105,14 +105,14 @@ const LICENSE_METADATA_OVERRIDES = new Map([
// The published tarball omits the repository LICENSE; package.json declares Apache-2.0.
// Keyed by exact version so a bump re-checks the license rather than inheriting this.
const APACHE_TEXT_OVERRIDE_KEYS = new Set([
- '@ai-sdk/provider-utils@5.0.34',
+ '@ai-sdk/provider-utils@5.0.40',
'@sigstore/verify@4.1.2',
]);
const EMBEDDED_COMPONENT_LICENSES = new Map([
[
'@ai-sdk/code-mode',
{
- version: '1.0.42',
+ version: '1.0.56',
components: [
{
name: 'quickjs-emscripten (embedded runtime)',
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org