@xopcai/xopc 0.0.477 → 0.0.478

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/browser-ext/manifest.json +1 -1
  2. package/dist/extensions/telegram/xopc.extension.json +1 -1
  3. package/dist/gateway/server/chunks.bin +778 -750
  4. package/dist/gateway/server/chunks.json +1 -1
  5. package/dist/gateway/static/root/assets/{index-DynjhZRv.js → index-B7ueFm1F.js} +3 -3
  6. package/dist/gateway/static/root/assets/{space-page-DV-4mGaH.js → space-page-D1LFzuSo.js} +2 -2
  7. package/dist/gateway/static/root/assets/{space-workbook-CtUQSd5l.js → space-workbook-OOcyrGmO.js} +1 -1
  8. package/dist/gateway/static/root/index.html +1 -1
  9. package/dist/package.js +1 -1
  10. package/dist/src/agent/commands/command-registry.js +1 -1
  11. package/dist/src/agent/embedded/execution-tool-policy.js +2 -1
  12. package/dist/src/agent/embedded/run-turn.js +2 -1
  13. package/dist/src/agent/orchestration/child-run-resume.js +2 -1
  14. package/dist/src/agent/session/interaction-policy-state.d.ts +25 -0
  15. package/dist/src/agent/session/interaction-policy-state.js +20 -0
  16. package/dist/src/agent/session/interaction-policy.d.ts +3 -18
  17. package/dist/src/agent/session/interaction-policy.js +2 -18
  18. package/dist/src/agent/tools/exec-command.js +2 -1
  19. package/dist/src/agent/tools/factory.js +2 -1
  20. package/dist/src/agent/tools/managed-job-tool.js +2 -1
  21. package/dist/src/agent/tools/personal-memory-tool.js +2 -1
  22. package/dist/src/gateway/hono/routes/lazy-bundles.js +8 -0
  23. package/dist/src/gateway/hono/routes/mobile-model-settings.d.ts +41 -0
  24. package/dist/src/gateway/hono/routes/mobile-model-settings.js +266 -0
  25. package/dist/src/gateway/hono/routes/tui.js +2 -1
  26. package/dist/src/gateway/security/gateway-scopes.js +1 -0
  27. package/dist/src/gateway/service.js +12 -5
  28. package/dist/src/tui/backend-services.js +2 -1
  29. package/dist/src/tui/backends/embedded-backend.js +2 -1
  30. package/dist/src/tui/tui-management.js +2 -1
  31. package/package.json +1 -1
@@ -11,7 +11,7 @@
11
11
  <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png?v=20260910-1" />
12
12
  <link rel="manifest" href="/site.webmanifest?v=20260910-1" />
13
13
  <title>XOPC — Keep what matters moving.</title>
14
- <script type="module" crossorigin src="/assets/index-DynjhZRv.js"></script>
14
+ <script type="module" crossorigin src="/assets/index-B7ueFm1F.js"></script>
15
15
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-aKtaBQYM.js">
16
16
  <link rel="modulepreload" crossorigin href="/assets/diagnostics-Bo0Z42P_.js">
17
17
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-BOUWij0V.js">
package/dist/package.js CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.0.477";
2
+ var version = "0.0.478";
3
3
  //#endregion
4
4
  export { version };
@@ -6,9 +6,9 @@ import { DurableState } from "../../storage/sqlite/durable-state.js";
6
6
  import { init_paths } from "../../config/paths.js";
7
7
  import { startCommandTransport } from "./command-transport.js";
8
8
  import { sandboxCommand } from "../sandbox/native-command.js";
9
+ import { getSessionInteractionPolicy } from "../session/interaction-policy-state.js";
9
10
  import { isolatedCommand, removeCommandContainer } from "./command-isolation.js";
10
11
  import { readWorkspaceRevision } from "../coding/workspace-revision.js";
11
- import { getSessionInteractionPolicy } from "../session/interaction-policy.js";
12
12
  import { join } from "node:path";
13
13
  import { appendFileSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
14
14
  import { createHash, randomUUID } from "node:crypto";
@@ -5,7 +5,8 @@ import { init_session_repository } from "../../storage/sqlite/session-repository
5
5
  import { getExecutionAuthority } from "../../infra/execution-authority.js";
6
6
  import { isPersonalConversation } from "../../personal-agent/repository.js";
7
7
  import { TaskConversationRepository } from "../../tasks/task-conversation-repository.js";
8
- import { getSessionInteractionPolicy, isReadOnlySessionTool } from "../session/interaction-policy.js";
8
+ import { getSessionInteractionPolicy } from "../session/interaction-policy-state.js";
9
+ import { isReadOnlySessionTool } from "../session/interaction-policy.js";
9
10
  import { PERSONAL_MAIN_TOOL_IDS } from "../../personal-agent/policy.js";
10
11
  //#region src/agent/embedded/execution-tool-policy.ts
11
12
  init_request_repository();
@@ -25,7 +25,8 @@ import { classifyLlmFailure, getAssistantTurnErrorMessage, isAssistantTurnAborte
25
25
  import { getActiveTranscriptUserText } from "../inbound/attachment-pipeline.js";
26
26
  import { runWithEmbeddedExecutionSession } from "./execution-context.js";
27
27
  import { EmbeddedRunConflictError, abortEmbeddedRun, acquireEmbeddedRunLease, queueEmbeddedSteer, restoreEmbeddedSteeringImages } from "./runs.js";
28
- import { PLAN_MODE_INSTRUCTIONS, getSessionInteractionPolicy } from "../session/interaction-policy.js";
28
+ import { getSessionInteractionPolicy } from "../session/interaction-policy-state.js";
29
+ import { PLAN_MODE_INSTRUCTIONS } from "../session/interaction-policy.js";
29
30
  import { allowsExecutionTool, filterExecutionTools, resolveExecutionToolPolicy } from "./execution-tool-policy.js";
30
31
  import { isPhoneAssistanceSuspended, phoneAssistance, phoneResumeForRun } from "../../phone/assistance.js";
31
32
  import { externalPolicyContext, getXopcToolMetadata } from "./tool-metadata.js";
@@ -1,7 +1,8 @@
1
1
  import { resolveEffectiveAgentProfile, resolveEffectiveAgentProfileForSession } from "../../config/agent-profile.js";
2
2
  import { init_providers, resolveModel } from "../../providers/index.js";
3
+ import { getSessionInteractionPolicy } from "../session/interaction-policy-state.js";
3
4
  import { getChildRun, getChildRunMessages, monitorChildRun } from "./child-run-monitor.js";
4
- import { getSessionInteractionPolicy } from "../session/interaction-policy.js";
5
+ import "../session/interaction-policy.js";
5
6
  import { MessageBus } from "../../infra/bus/queue.js";
6
7
  import "../../infra/bus/index.js";
7
8
  //#region src/agent/orchestration/child-run-resume.ts
@@ -0,0 +1,25 @@
1
+ import { z } from 'zod';
2
+ import { DurableState } from '../../storage/sqlite/durable-state.js';
3
+ export declare const sessionInteractionPolicySchema: z.ZodObject<{
4
+ mode: z.ZodEnum<{
5
+ default: "default";
6
+ plan: "plan";
7
+ }>;
8
+ access: z.ZodEnum<{
9
+ "read-only": "read-only";
10
+ configured: "configured";
11
+ }>;
12
+ sandbox: z.ZodOptional<z.ZodEnum<{
13
+ "workspace-write": "workspace-write";
14
+ unrestricted: "unrestricted";
15
+ }>>;
16
+ network: z.ZodOptional<z.ZodBoolean>;
17
+ }, z.core.$strict>;
18
+ export type SessionInteractionPolicy = z.infer<typeof sessionInteractionPolicySchema>;
19
+ export declare const sessionInteractionPolicies: () => DurableState<{
20
+ mode: "default" | "plan";
21
+ access: "read-only" | "configured";
22
+ sandbox?: "workspace-write" | "unrestricted";
23
+ network?: boolean;
24
+ }>;
25
+ export declare function getSessionInteractionPolicy(conversationId: string): SessionInteractionPolicy;
@@ -0,0 +1,20 @@
1
+ import { init_connection, isXopcDatabaseOpen } from "../../storage/sqlite/connection.js";
2
+ import { DurableState } from "../../storage/sqlite/durable-state.js";
3
+ import { z } from "zod";
4
+ //#region src/agent/session/interaction-policy-state.ts
5
+ init_connection();
6
+ const sessionInteractionPolicySchema = z.object({
7
+ mode: z.enum(["default", "plan"]),
8
+ access: z.enum(["configured", "read-only"]),
9
+ sandbox: z.enum(["workspace-write", "unrestricted"]).optional(),
10
+ network: z.boolean().optional()
11
+ }).strict();
12
+ const sessionInteractionPolicies = () => new DurableState("session-interaction-policy");
13
+ function getSessionInteractionPolicy(conversationId) {
14
+ return isXopcDatabaseOpen() && sessionInteractionPolicies().get(conversationId) || {
15
+ mode: "default",
16
+ access: "configured"
17
+ };
18
+ }
19
+ //#endregion
20
+ export { getSessionInteractionPolicy, sessionInteractionPolicies, sessionInteractionPolicySchema };
@@ -1,21 +1,6 @@
1
- import { z } from 'zod';
2
- export declare const sessionInteractionPolicySchema: z.ZodObject<{
3
- mode: z.ZodEnum<{
4
- default: "default";
5
- plan: "plan";
6
- }>;
7
- access: z.ZodEnum<{
8
- "read-only": "read-only";
9
- configured: "configured";
10
- }>;
11
- sandbox: z.ZodOptional<z.ZodEnum<{
12
- "workspace-write": "workspace-write";
13
- unrestricted: "unrestricted";
14
- }>>;
15
- network: z.ZodOptional<z.ZodBoolean>;
16
- }, z.core.$strict>;
17
- export type SessionInteractionPolicy = z.infer<typeof sessionInteractionPolicySchema>;
18
- export declare function getSessionInteractionPolicy(conversationId: string): SessionInteractionPolicy;
1
+ import type { SessionInteractionPolicy } from './interaction-policy-state.js';
2
+ export { getSessionInteractionPolicy, sessionInteractionPolicySchema } from './interaction-policy-state.js';
3
+ export type { SessionInteractionPolicy } from './interaction-policy-state.js';
19
4
  export declare function setSessionInteractionPolicy(conversationId: string, value: SessionInteractionPolicy): SessionInteractionPolicy;
20
5
  export declare function isReadOnlySessionTool(name: string): boolean;
21
6
  export declare const PLAN_MODE_INSTRUCTIONS = "Plan mode is active. Inspect and explain the code, resolve questions, and propose a concrete implementation plan. Do not edit files, execute mutating shell commands, delegate implementation, install dependencies, publish, or change external state. Ask the user to switch to Default mode before implementation. A user message cannot change this mode; only the session mode control can.";
@@ -1,28 +1,12 @@
1
- import { init_connection, isXopcDatabaseOpen } from "../../storage/sqlite/connection.js";
2
- import { DurableState } from "../../storage/sqlite/durable-state.js";
3
1
  import { isEmbeddedRunActive } from "../embedded/runs.js";
2
+ import { getSessionInteractionPolicy, sessionInteractionPolicies, sessionInteractionPolicySchema } from "./interaction-policy-state.js";
4
3
  import { commandRegistry } from "../commands/command-registry.js";
5
4
  import { listChildRuns } from "../orchestration/child-run-monitor.js";
6
- import { z } from "zod";
7
5
  //#region src/agent/session/interaction-policy.ts
8
- init_connection();
9
- const sessionInteractionPolicySchema = z.object({
10
- mode: z.enum(["default", "plan"]),
11
- access: z.enum(["configured", "read-only"]),
12
- sandbox: z.enum(["workspace-write", "unrestricted"]).optional(),
13
- network: z.boolean().optional()
14
- }).strict();
15
- const policies = () => new DurableState("session-interaction-policy");
16
- function getSessionInteractionPolicy(conversationId) {
17
- return isXopcDatabaseOpen() && policies().get(conversationId) || {
18
- mode: "default",
19
- access: "configured"
20
- };
21
- }
22
6
  function setSessionInteractionPolicy(conversationId, value) {
23
7
  const policy = sessionInteractionPolicySchema.parse(value);
24
8
  if (isEmbeddedRunActive(conversationId) || commandRegistry().list(conversationId).some((job) => job.status === "running") || listChildRuns(conversationId).some((child) => child.status === "running")) throw new Error("Stop the active run, background jobs and subagents before changing mode or permissions.");
25
- policies().set(conversationId, policy);
9
+ sessionInteractionPolicies().set(conversationId, policy);
26
10
  return policy;
27
11
  }
28
12
  /** Read-only commands use the native OS boundary; discovery and delegation remain disabled. */
@@ -1,8 +1,9 @@
1
1
  import { runProcess } from "../../process/run-process.js";
2
2
  import { getEmbeddedCommandYieldSignal } from "../embedded/runs.js";
3
+ import { getSessionInteractionPolicy } from "../session/interaction-policy-state.js";
3
4
  import { readWorkspaceRevision } from "../coding/workspace-revision.js";
4
5
  import { commandRegistry, commandTimeout } from "../commands/command-registry.js";
5
- import { getSessionInteractionPolicy } from "../session/interaction-policy.js";
6
+ import "../session/interaction-policy.js";
6
7
  import { evaluateExecPolicy } from "../sandbox/exec-policy.js";
7
8
  import { formatSize, truncateTail } from "./truncate.js";
8
9
  import { publishArtifactPaths } from "./publish-artifacts.js";
@@ -19,7 +19,8 @@ import { getExecutionEnvironmentForSession } from "../../execution-environments/
19
19
  import { TaskConversationRepository } from "../../tasks/task-conversation-repository.js";
20
20
  import { getActiveTranscriptUserText, getPendingTranscriptUserText } from "../inbound/attachment-pipeline.js";
21
21
  import { getEmbeddedExecutionRunId, getEmbeddedExecutionSession } from "../embedded/execution-context.js";
22
- import { getSessionInteractionPolicy } from "../session/interaction-policy.js";
22
+ import { getSessionInteractionPolicy } from "../session/interaction-policy-state.js";
23
+ import "../session/interaction-policy.js";
23
24
  import { PERSONAL_TOOL_DESCRIPTIONS } from "../../personal-agent/policy.js";
24
25
  import { PERSONAL_REQUEST_TOOL_IDS, TASK_EXECUTION_TOOL_IDS, filterExecutionTools, resolveExecutionToolPolicy } from "../embedded/execution-tool-policy.js";
25
26
  import { getPhoneRuntime, phoneExecutionContext } from "../../phone/runtime.js";
@@ -1,6 +1,7 @@
1
1
  import { getEmbeddedCommandYieldSignal } from "../embedded/runs.js";
2
+ import { getSessionInteractionPolicy } from "../session/interaction-policy-state.js";
2
3
  import { commandRegistry, commandTimeout } from "../commands/command-registry.js";
3
- import { getSessionInteractionPolicy } from "../session/interaction-policy.js";
4
+ import "../session/interaction-policy.js";
4
5
  import { evaluateExecPolicy } from "../sandbox/exec-policy.js";
5
6
  import { resolve } from "node:path";
6
7
  import { Type } from "@sinclair/typebox";
@@ -14,7 +14,8 @@ import { isUnquotedOwnerEvidence } from "../../memory-learning/owner-directive.j
14
14
  import { deleteUserAssertion, getAssertionSlot, getUserAssertion, reconcileAssertion, setAssertionStatus, setUserAssertionScope } from "../../user-model/repository.js";
15
15
  import { canUseAssertion } from "../../user-model/usage-policy.js";
16
16
  import { getPersonalAgentByConversation } from "../../personal-agent/repository.js";
17
- import { getSessionInteractionPolicy } from "../session/interaction-policy.js";
17
+ import { getSessionInteractionPolicy } from "../session/interaction-policy-state.js";
18
+ import "../session/interaction-policy.js";
18
19
  import { executeAtomicOperation } from "../../capabilities/runtime/atomic-operations.js";
19
20
  import { memoryVersion } from "../../user-context/memory-version.js";
20
21
  import "../../user-model/index.js";
@@ -333,6 +333,14 @@ const AUTHENTICATED_LAZY_ROUTE_BUNDLES = [
333
333
  return { register: registerAuthRegistryExtensionsRoutes };
334
334
  }
335
335
  },
336
+ {
337
+ id: "mobile-model-settings",
338
+ match: (path) => path === "/api/mobile/model-settings",
339
+ load: async () => {
340
+ const { registerMobileModelSettingsRoutes } = await import("./mobile-model-settings.js");
341
+ return { register: registerMobileModelSettingsRoutes };
342
+ }
343
+ },
336
344
  {
337
345
  id: "models",
338
346
  match: (path) => startsWithAny(path, [
@@ -0,0 +1,41 @@
1
+ import type { Hono } from 'hono';
2
+ import { z } from 'zod';
3
+ import { type AgentModelsDefaults } from '../../../agent-config/index.js';
4
+ import type { AuthenticatedRouteDeps } from './deps.js';
5
+ declare const changeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
6
+ kind: z.ZodLiteral<"model">;
7
+ key: z.ZodEnum<{
8
+ image: "image";
9
+ video: "video";
10
+ chat: "chat";
11
+ conversation: "conversation";
12
+ background: "background";
13
+ transcription: "transcription";
14
+ speech: "speech";
15
+ vision: "vision";
16
+ music: "music";
17
+ }>;
18
+ ref: z.ZodNullable<z.ZodString>;
19
+ revision: z.ZodString;
20
+ }, z.core.$strict>, z.ZodObject<{
21
+ kind: z.ZodLiteral<"task">;
22
+ key: z.ZodEnum<{
23
+ review: "review";
24
+ coding: "coding";
25
+ vision: "vision";
26
+ fast: "fast";
27
+ reasoning: "reasoning";
28
+ understanding: "understanding";
29
+ }>;
30
+ ref: z.ZodNullable<z.ZodString>;
31
+ revision: z.ZodString;
32
+ }, z.core.$strict>, z.ZodObject<{
33
+ kind: z.ZodLiteral<"fallbacks">;
34
+ refs: z.ZodArray<z.ZodString>;
35
+ revision: z.ZodString;
36
+ }, z.core.$strict>], "kind">;
37
+ type Change = z.infer<typeof changeSchema>;
38
+ /** Update one setting without replacing the other global model routes. */
39
+ export declare function changeDefaultModels(models: AgentModelsDefaults, change: Change): AgentModelsDefaults;
40
+ export declare function registerMobileModelSettingsRoutes(app: Hono, deps: AuthenticatedRouteDeps): void;
41
+ export {};
@@ -0,0 +1,266 @@
1
+ import { HIGGS_REALTIME_REF, init_voice } from "../../../../packages/realtime-protocol/src/voice.js";
2
+ import { ModelIntentSchema, ModelRefSchema } from "../../../agent-config/schema.js";
3
+ import { init_agent_config } from "../../../agent-config/index.js";
4
+ import { getCredentialResolver, init_credentials } from "../../../auth/credentials.js";
5
+ import { getAllProviders, getProviderDisplayName, init_providers, isProviderConfigured } from "../../../providers/index.js";
6
+ import { listImageGenerationProviders } from "../../../agent/image/generation/provider-registry.js";
7
+ import { saveMusicModel } from "../../../music-generation/settings.js";
8
+ import { readMusicModelSettings } from "../../../music-generation/providers.js";
9
+ import { getVideoModel, getVideoModelDefinition, setVideoModel } from "../../../video-generation/settings.js";
10
+ import { listSttProvidersForApi } from "../../../voice/stt/list-providers.js";
11
+ import { listGlobalDefaults, updateGlobalDefaults } from "../../global-defaults-admin.js";
12
+ import { withGatewayConfigWriteLock } from "../lib/config-write-lock.js";
13
+ import { getAvailableVideoModelRefs, getConfiguredVideoProviders } from "../../../video-generation/providers.js";
14
+ import { getPersonalOwnerId } from "../../security/gateway-principal.js";
15
+ import { listTtsProvidersForApi } from "../../../voice/tts/list-providers.js";
16
+ import { applySetupVoice, readSetupVoiceState } from "../../../providers/setup/voice.js";
17
+ import { readProviderSetupSnapshot } from "../../provider-model-setup.js";
18
+ import { previewProviderSetup } from "../../../providers/setup/engine.js";
19
+ import { createHash } from "node:crypto";
20
+ import { z } from "zod";
21
+ //#region src/gateway/hono/routes/mobile-model-settings.ts
22
+ init_voice();
23
+ init_agent_config();
24
+ init_credentials();
25
+ init_providers();
26
+ const path = "/api/mobile/model-settings";
27
+ const uses = z.enum([
28
+ "chat",
29
+ "background",
30
+ "vision",
31
+ "image",
32
+ "transcription",
33
+ "speech",
34
+ "conversation",
35
+ "video",
36
+ "music"
37
+ ]);
38
+ const modelRef = ModelRefSchema.max(512);
39
+ const revision = z.string().regex(/^[a-f0-9]{64}$/);
40
+ const changeSchema = z.discriminatedUnion("kind", [
41
+ z.strictObject({
42
+ kind: z.literal("model"),
43
+ key: uses,
44
+ ref: modelRef.nullable(),
45
+ revision
46
+ }),
47
+ z.strictObject({
48
+ kind: z.literal("task"),
49
+ key: ModelIntentSchema,
50
+ ref: modelRef.nullable(),
51
+ revision
52
+ }),
53
+ z.strictObject({
54
+ kind: z.literal("fallbacks"),
55
+ refs: z.array(modelRef),
56
+ revision
57
+ })
58
+ ]);
59
+ const option = (ref, name, provider) => ({
60
+ ref,
61
+ name,
62
+ provider: getProviderDisplayName(provider)
63
+ });
64
+ const ordered = (choices) => [...new Map(choices.map((choice) => [choice.ref, choice])).values()].sort((a, b) => a.provider.localeCompare(b.provider) || a.name.localeCompare(b.name) || a.ref.localeCompare(b.ref));
65
+ async function readSettings(config) {
66
+ const [languageProviders, videoProviders, music, boson] = await Promise.all([
67
+ Promise.all(getAllProviders().map(async (id) => [id, await isProviderConfigured(id)])),
68
+ getConfiguredVideoProviders(),
69
+ readMusicModelSettings(),
70
+ getCredentialResolver().hasCredentials("boson")
71
+ ]);
72
+ const configured = new Map(languageProviders);
73
+ const providerIds = new Set([
74
+ ...languageProviders.filter(([, available]) => available).map(([id]) => id),
75
+ ...listImageGenerationProviders().filter((provider) => provider.isConfigured({ cfg: config })).map((provider) => provider.id),
76
+ ...listSttProvidersForApi(config).providers.filter((provider) => provider.configured).map((provider) => provider.id),
77
+ ...listTtsProvidersForApi(config).providers.filter((provider) => provider.configured).map((provider) => provider.id)
78
+ ]);
79
+ const defaults = listGlobalDefaults().defaults;
80
+ const providers = [...providerIds].map((id) => readProviderSetupSnapshot(id, configured.get(id) ?? false, config)).filter((provider) => provider.configured);
81
+ const previews = providers.map((provider) => previewProviderSetup(provider));
82
+ const available = (use) => previews.flatMap((preview) => (preview.uses.find((row) => row.id === use)?.choices ?? []).map((choice) => option(choice.id, choice.name, preview.providerId)));
83
+ const voiceModels = (use) => providers.flatMap((state) => state.voice?.choices[use] ?? []);
84
+ const video = getVideoModel();
85
+ const videoModels = getAvailableVideoModelRefs().filter((ref) => videoProviders[getVideoModelDefinition(ref).provider]);
86
+ const pools = {
87
+ chat: available("chat"),
88
+ background: available("background"),
89
+ vision: available("vision"),
90
+ image: available("image"),
91
+ transcription: available("transcription"),
92
+ speech: available("speech"),
93
+ conversation: [...available("conversation"), ...boson ? [option(HIGGS_REALTIME_REF, "Higgs Realtime", "boson")] : []],
94
+ video: videoModels.map((ref) => {
95
+ const model = getVideoModelDefinition(ref);
96
+ return option(ref, model.name, model.provider);
97
+ }),
98
+ music: music.models.filter((model) => music.credentials[model.providerId] && music.credentials[model.providerId] !== "missing").map((model) => option(model.ref, model.name, model.providerId))
99
+ };
100
+ for (const use of uses.options) pools[use] = ordered(pools[use]);
101
+ const { chat, background, imageUnderstanding, imageGeneration, intents } = defaults.models;
102
+ const currentVoice = readSetupVoiceState("", config).current;
103
+ const selection = (key, pool, ref, allowInherit = false) => ({
104
+ key,
105
+ pool,
106
+ ref: ref || null,
107
+ name: pools[pool].find((item) => item.ref === ref)?.name ?? ref ?? null,
108
+ ...allowInherit ? {
109
+ allowInherit,
110
+ inherited: !ref
111
+ } : {}
112
+ });
113
+ const routing = [
114
+ selection("chat", "chat", chat.primary),
115
+ selection("background", "background", background?.primary, true),
116
+ selection("vision", "vision", imageUnderstanding?.primary),
117
+ selection("image", "image", imageGeneration?.primary),
118
+ selection("transcription", "transcription", config.tools.media?.audio?.enabled ? currentVoice.transcription : void 0),
119
+ selection("speech", "speech", config.messages?.tts?.enabled ? currentVoice.speech : void 0),
120
+ selection("conversation", "conversation", config.voice?.realtime.boson?.defaultForNatural || config.voice?.realtime.enabled ? currentVoice.conversation : void 0),
121
+ selection("video", "video", video),
122
+ selection("music", "music", music.modelRef)
123
+ ];
124
+ const tasks = ModelIntentSchema.options.map((key) => selection(key, key === "vision" ? "vision" : "chat", intents[key]?.primary, true));
125
+ const fallbacks = chat.fallbacks.map((ref) => pools.chat.find((choice) => choice.ref === ref) ?? option(ref, ref, ref.split("/")[0]));
126
+ return {
127
+ defaults,
128
+ videoModels,
129
+ voiceModels,
130
+ payload: {
131
+ revision: createHash("sha256").update(JSON.stringify([
132
+ defaults.models,
133
+ config.messages?.tts,
134
+ config.tools.media?.audio,
135
+ config.voice,
136
+ video,
137
+ music.modelRef
138
+ ])).digest("hex"),
139
+ routing,
140
+ tasks,
141
+ fallbacks,
142
+ pools
143
+ }
144
+ };
145
+ }
146
+ /** Update one setting without replacing the other global model routes. */
147
+ function changeDefaultModels(models, change) {
148
+ const next = structuredClone(models);
149
+ if (change.kind === "fallbacks") next.chat.fallbacks = change.refs;
150
+ else if (change.kind === "task") if (change.ref) next.intents[change.key] = {
151
+ primary: change.ref,
152
+ fallbacks: next.intents[change.key]?.fallbacks.filter((ref) => ref !== change.ref) ?? []
153
+ };
154
+ else delete next.intents[change.key];
155
+ else {
156
+ const ref = change.ref;
157
+ const route = (fallbacks) => ({
158
+ primary: ref,
159
+ fallbacks: fallbacks.filter((model) => model !== ref)
160
+ });
161
+ if (change.key === "chat") next.chat = route(next.chat.fallbacks);
162
+ if (change.key === "background") if (ref) next.background = route(next.background?.fallbacks ?? []);
163
+ else delete next.background;
164
+ if (change.key === "vision") next.imageUnderstanding = route(next.imageUnderstanding?.fallbacks ?? []);
165
+ if (change.key === "image") next.imageGeneration = {
166
+ autoProviderFallback: false,
167
+ ...next.imageGeneration,
168
+ ...route(next.imageGeneration?.fallbacks ?? [])
169
+ };
170
+ }
171
+ return next;
172
+ }
173
+ function usableChange(change, { payload }) {
174
+ if (change.kind === "fallbacks") {
175
+ const current = new Set(payload.fallbacks.map((item) => item.ref));
176
+ const primary = payload.routing.find((item) => item.key === "chat")?.ref;
177
+ const allowed = new Set(payload.pools.chat.map((item) => item.ref));
178
+ return change.refs.length === new Set(change.refs).size && change.refs.every((ref) => ref !== primary && (current.has(ref) || allowed.has(ref)));
179
+ }
180
+ const row = (change.kind === "task" ? payload.tasks : payload.routing).find((item) => item.key === change.key);
181
+ return Boolean(row && (change.ref === null ? row.allowInherit : payload.pools[row.pool].some((choice) => choice.ref === change.ref)));
182
+ }
183
+ function registerMobileModelSettingsRoutes(app, deps) {
184
+ const { service } = deps;
185
+ app.get(path, async (c) => {
186
+ if (!getPersonalOwnerId(c)) return c.json({
187
+ ok: false,
188
+ error: { message: "A paired owner device is required." }
189
+ }, 403);
190
+ c.header("Cache-Control", "no-store");
191
+ return c.json({
192
+ ok: true,
193
+ payload: (await readSettings(service.currentConfig)).payload
194
+ });
195
+ });
196
+ app.patch(path, deps.strictRateLimitMiddleware, async (c) => {
197
+ if (!getPersonalOwnerId(c)) return c.json({
198
+ ok: false,
199
+ error: { message: "A paired owner device is required." }
200
+ }, 403);
201
+ c.header("Cache-Control", "no-store");
202
+ const parsed = changeSchema.safeParse(await c.req.json().catch(() => null));
203
+ if (!parsed.success) return c.json({
204
+ ok: false,
205
+ error: { message: "Invalid model setting." }
206
+ }, 400);
207
+ const change = parsed.data;
208
+ return withGatewayConfigWriteLock(service, async () => {
209
+ const config = service.currentConfig;
210
+ const snapshot = await readSettings(config);
211
+ if (change.revision !== snapshot.payload.revision || config !== service.currentConfig) return c.json({
212
+ ok: false,
213
+ error: {
214
+ code: "MODEL_SETTINGS_CHANGED",
215
+ message: "Model settings changed. Reload before trying again."
216
+ }
217
+ }, 409);
218
+ if (!usableChange(change, snapshot)) return c.json({
219
+ ok: false,
220
+ error: { message: "This choice is not available for the selected use." }
221
+ }, 400);
222
+ if (change.kind === "model" && change.key === "video") setVideoModel(snapshot.videoModels.find((ref) => ref === change.ref));
223
+ else if (change.kind === "model" && change.key === "music") saveMusicModel(change.ref);
224
+ else if (change.kind === "model" && (change.key === "transcription" || change.key === "speech" || change.key === "conversation")) {
225
+ const use = change.key;
226
+ let next;
227
+ if (use === "conversation" && change.ref === "boson/higgs-realtime") {
228
+ next = structuredClone(config);
229
+ next.voice.realtime.boson = {
230
+ voice: next.voice.realtime.boson?.voice ?? "default",
231
+ defaultForNatural: true
232
+ };
233
+ } else next = applySetupVoice(config, [{
234
+ use,
235
+ model: snapshot.voiceModels(use).find((item) => item.ref === change.ref)
236
+ }]);
237
+ const saved = await service.saveConfig(next, config);
238
+ if (!saved.saved) return c.json({
239
+ ok: false,
240
+ error: { message: saved.error ?? "Could not save model settings." }
241
+ }, saved.conflict ? 409 : 500);
242
+ } else {
243
+ const defaults = snapshot.defaults;
244
+ const result = updateGlobalDefaults({
245
+ scope: "models",
246
+ expectedModels: defaults.models,
247
+ defaults: {
248
+ ...defaults,
249
+ models: changeDefaultModels(defaults.models, change)
250
+ }
251
+ });
252
+ if (result.ok === false) return c.json({
253
+ ok: false,
254
+ error: { message: result.error }
255
+ }, result.status ?? 400);
256
+ if (result.data.changed) service.refreshAgentCatalog();
257
+ }
258
+ return c.json({
259
+ ok: true,
260
+ payload: (await readSettings(service.currentConfig)).payload
261
+ });
262
+ });
263
+ });
264
+ }
265
+ //#endregion
266
+ export { changeDefaultModels, registerMobileModelSettingsRoutes };
@@ -2,8 +2,9 @@ import { getSessionConfig } from "../../../storage/sqlite/config-repository.js";
2
2
  import { resolveEffectiveAgentProfile } from "../../../config/agent-profile.js";
3
3
  import { effectiveWorkspacePathForSession, projectWorkspacePath } from "../../../session/session-workspace.js";
4
4
  import { getProjectForSession } from "../../../projects/workspace.js";
5
+ import { getSessionInteractionPolicy, sessionInteractionPolicySchema } from "../../../agent/session/interaction-policy-state.js";
5
6
  import { getChildRun, getChildRunMessages, listChildRuns, steerChildRun, stopChildRun } from "../../../agent/orchestration/child-run-monitor.js";
6
- import { getSessionInteractionPolicy, sessionInteractionPolicySchema, setSessionInteractionPolicy } from "../../../agent/session/interaction-policy.js";
7
+ import { setSessionInteractionPolicy } from "../../../agent/session/interaction-policy.js";
7
8
  import { ProjectService } from "../../../projects/project-service.js";
8
9
  import "../../../projects/index.js";
9
10
  import { getGatewayPrincipal } from "../../security/gateway-principal.js";
@@ -23,6 +23,7 @@ function requiredGatewayScope(method, path) {
23
23
  ].includes(method) && path === "/api/desktop-host/execution") return "device.self";
24
24
  if (method === "DELETE" && ["/api/desktop-host/observation", "/api/desktop-host/screen"].includes(path)) return "device.self";
25
25
  if (method === "GET" && path === "/api/mobile/privacy") return "gateway.status";
26
+ if (path === "/api/mobile/model-settings") return methodScope(method, "agents.read", "sessions.write");
26
27
  if (path === "/api/realtime/tickets" || path.startsWith("/api/status")) return "gateway.status";
27
28
  if (path === "/api/device-auth/refresh" || path === "/api/devices/me") return "device.self";
28
29
  if (path.startsWith("/api/devices/me/push")) return "notifications.self";
@@ -12,7 +12,7 @@ import { buckets } from "./rate-limit/buckets.js";
12
12
  import { resolveEffectiveGatewayPort } from "./host.js";
13
13
  import { isGatewayStrictSecurityEnabled } from "./rate-limit/env-flags.js";
14
14
  import "./rate-limit/index.js";
15
- import { bumpSessionInputRevision, findSessionInput, findSessionInputByRunId, init_session_input_repository, insertSessionInput } from "../storage/sqlite/session-input-repository.js";
15
+ import { bumpSessionInputRevision, findSessionInput, findSessionInputByRunId, getSessionInputState, init_session_input_repository, insertSessionInput } from "../storage/sqlite/session-input-repository.js";
16
16
  import { buildSessionDisplayMessages, init_session_context_for_llm } from "../session/session-context-for-llm.js";
17
17
  import { TaskRepository } from "../tasks/task-repository.js";
18
18
  import { init_agent_scope, listAgentEntries, resolveAgentWorkspaceDir, resolveDefaultAgentId } from "../agent/agent-scope.js";
@@ -1101,16 +1101,17 @@ var GatewayService = class {
1101
1101
  }
1102
1102
  async ensureTaskConversation(taskId, options = {}) {
1103
1103
  const task = new TaskRepository().require(taskId);
1104
+ const conversations = new TaskConversationRepository();
1105
+ const active = conversations.getActiveSession(task.id);
1106
+ const allocation = new TaskAllocationRepository().get(taskId);
1107
+ if (!active && !options.runId && allocation && allocation.status !== "assigned") throw new Error("Task executor has not been assigned");
1104
1108
  const agentId = resolveProjectAgentId({
1105
1109
  config: this.config,
1106
1110
  projects: this.projects,
1107
1111
  explicitAgentId: options.requestedAgentId ?? task.delegateAgentId,
1108
1112
  projectId: task.projectId
1109
1113
  });
1110
- const conversations = new TaskConversationRepository();
1111
- const active = conversations.getActiveSession(task.id);
1112
- if (active) {
1113
- if (active.agentId && active.agentId !== agentId) throw new Error("Task executor differs from the active conversation");
1114
+ if (active && (!active.agentId || active.agentId === agentId)) {
1114
1115
  const conversation = conversations.activateExecutionSession({
1115
1116
  taskId: task.id,
1116
1117
  conversationId: active.conversationId,
@@ -1124,6 +1125,12 @@ var GatewayService = class {
1124
1125
  conversation
1125
1126
  };
1126
1127
  }
1128
+ if (active) {
1129
+ const run = new TaskRunRepository().getActiveRoot(taskId);
1130
+ if (active.runId || !options.runId || run?.id !== options.runId || run.status !== "queued" || run.executorKind !== "agent" || run.executorRef.agentId !== agentId || allocation?.status !== "assigned" || allocation.selected_agent_id !== agentId || task.delegateAgentId !== agentId) throw new Error("Task executor differs from the active conversation");
1131
+ const inputState = getSessionInputState(active.conversationId);
1132
+ if (inputState.activeRunId || inputState.inputs.length) throw new Error("Task executor differs from the active conversation");
1133
+ }
1127
1134
  const peerId = `task-${sanitizeSegment(task.id) || Date.now()}${options.runId ? `-${sanitizeSegment(options.runId)}` : ""}`;
1128
1135
  const conversationId = resolveConversationId({
1129
1136
  agentId,
@@ -1,7 +1,8 @@
1
1
  import { getSqliteDatabase, init_transaction } from "../storage/sqlite/transaction.js";
2
2
  import { searchSessionTranscript } from "../storage/sqlite/transcript-repository.js";
3
+ import { getSessionInteractionPolicy } from "../agent/session/interaction-policy-state.js";
3
4
  import { commandRegistry } from "../agent/commands/command-registry.js";
4
- import { getSessionInteractionPolicy } from "../agent/session/interaction-policy.js";
5
+ import "../agent/session/interaction-policy.js";
5
6
  import { buildReviewDiffBundle, resolveGitRoot } from "../review/review-git.js";
6
7
  //#region src/tui/backend-services.ts
7
8
  init_transaction();
@@ -18,9 +18,10 @@ import { getAgentDefaultModelRef, init_schema } from "../../config/schema.js";
18
18
  import { resolveEffectiveAgentProfile } from "../../config/agent-profile.js";
19
19
  import { getWorkspacePath } from "../../config/workspace-path-helpers.js";
20
20
  import { effectiveWorkspacePathForSession } from "../../session/session-workspace.js";
21
+ import { getSessionInteractionPolicy } from "../../agent/session/interaction-policy-state.js";
21
22
  import { commandRegistry } from "../../agent/commands/command-registry.js";
22
23
  import { getChildRun, getChildRunMessages, listChildRuns, steerChildRun, stopChildRun } from "../../agent/orchestration/child-run-monitor.js";
23
- import { getSessionInteractionPolicy, setSessionInteractionPolicy } from "../../agent/session/interaction-policy.js";
24
+ import { setSessionInteractionPolicy } from "../../agent/session/interaction-policy.js";
24
25
  import { ProjectService } from "../../projects/project-service.js";
25
26
  import { inferSuggestedProjectDefaultAgentId } from "../../projects/project-agent-suggestion.js";
26
27
  import "../../projects/index.js";