gestalt-mobile 0.42.1 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +64 -0
  2. package/dist/client/assets/index-7g7-CxvF.js +107 -0
  3. package/dist/client/assets/index-BKls66uM.css +1 -0
  4. package/dist/client/index.html +2 -2
  5. package/dist/server/server/app.js +2 -3
  6. package/dist/server/server/composition.contracts.js +107 -0
  7. package/dist/server/server/composition.js +45 -10
  8. package/dist/server/server/features/catalog/get-bootstrap/use-case.js +11 -0
  9. package/dist/server/server/features/catalog/register-routes.js +13 -0
  10. package/dist/server/server/features/catalog/session-defaults/endpoint.js +16 -0
  11. package/dist/server/server/features/files/check-references/endpoint.js +36 -0
  12. package/dist/server/server/features/files/read-entry/endpoint.js +28 -0
  13. package/dist/server/server/features/files/register-routes.js +4 -0
  14. package/dist/server/server/features/plans/application/parse-supervised-plan.js +11 -0
  15. package/dist/server/server/features/plans/archive-workspace-plan/endpoint.js +26 -0
  16. package/dist/server/server/features/plans/list-workspace-plans/endpoint.js +1 -1
  17. package/dist/server/server/features/plans/register-routes.js +6 -0
  18. package/dist/server/server/features/sessions/model/relay-session.js +2 -0
  19. package/dist/server/server/features/sessions/start-session/endpoint.js +6 -0
  20. package/dist/server/server/features/sessions/start-session/request.js +4 -0
  21. package/dist/server/server/features/sessions/start-session/use-case.js +12 -0
  22. package/dist/server/server/platform/catalog/filesystem-workspace-catalog.js +3 -0
  23. package/dist/server/server/platform/codex/recent-thread-lister.js +2 -1
  24. package/dist/server/server/platform/codex/session-model-config.js +104 -0
  25. package/dist/server/server/platform/codex/session-runtime.js +33 -13
  26. package/dist/server/server/platform/filesystem/filesystem-workspace-files.js +99 -0
  27. package/dist/server/server/platform/persistence/filesystem-session-defaults.js +42 -0
  28. package/dist/server/server/platform/persistence/migrate.js +2 -0
  29. package/dist/server/server/platform/persistence/sqlite-session-repository.js +7 -2
  30. package/dist/server/server/platform/plans/filesystem-plan-archiver.js +109 -0
  31. package/dist/server/server/platform/plans/filesystem-plan-status-source.js +42 -1
  32. package/dist/server/server/platform/plans/filesystem-workspace-plan-catalog.js +96 -68
  33. package/dist/server/server/platform/plans/org-plan-archive-tag.js +17 -0
  34. package/dist/server/server/platform/plans/org-plan-discovery.js +53 -0
  35. package/dist/server/shared/contracts/session-defaults.js +20 -0
  36. package/dist/server/shared/contracts/session-model-settings.js +6 -0
  37. package/package.json +3 -1
  38. package/dist/client/assets/index-BRly-q56.js +0 -38
  39. package/dist/client/assets/index-D57mr3B1.css +0 -1
@@ -54,6 +54,8 @@ export function parseSupervisedPlan(input) {
54
54
  if (!closed)
55
55
  return unavailable('MALFORMED_ORG');
56
56
  const descriptions = new Map();
57
+ let descriptionKey;
58
+ let blankLines = 0;
57
59
  while (index < lines.length && !lines[index].startsWith('*')) {
58
60
  const description = descriptionPattern.exec(lines[index]);
59
61
  if (description) {
@@ -61,6 +63,15 @@ export function parseSupervisedPlan(input) {
61
63
  if (descriptions.has(key))
62
64
  return unavailable('MALFORMED_ORG');
63
65
  descriptions.set(key, description[2] ?? '');
66
+ descriptionKey = key;
67
+ blankLines = 0;
68
+ }
69
+ else if (descriptionKey && /^[ \t]+\S/.test(lines[index])) {
70
+ descriptions.set(descriptionKey, `${descriptions.get(descriptionKey)}${'\n'.repeat(blankLines + 1)}${lines[index].replace(/^(?: |\t)/, '')}`);
71
+ blankLines = 0;
72
+ }
73
+ else if (lines[index].trim() === '') {
74
+ blankLines += 1;
64
75
  }
65
76
  else if (lines[index].trim() !== '') {
66
77
  return unavailable('MALFORMED_ORG');
@@ -0,0 +1,26 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ export function registerArchiveWorkspacePlan(app, deps) {
7
+ app.post('/api/workspaces/:workspaceId/plans/:planName/archive', async (request, reply) => {
8
+ try {
9
+ const { workspaceId, planName } = request.params;
10
+ const workspace = await deps.workspaces.resolve(workspaceId);
11
+ const result = await deps.archiver.archive(workspace.realPath, planName);
12
+ if (result.kind === 'archived')
13
+ return reply.send({ archived: true });
14
+ if (result.kind === 'missing')
15
+ return reply.code(404).send({ code: 'PLAN_NOT_FOUND' });
16
+ if (result.kind === 'conflict')
17
+ return reply.code(409).send({ code: 'PLAN_ARCHIVE_CONFLICT' });
18
+ return reply.code(422).send({ code: 'PLAN_ARCHIVE_UNAVAILABLE' });
19
+ }
20
+ catch (error) {
21
+ if (error instanceof Error && error.message === 'WORKSPACE_NOT_FOUND')
22
+ return reply.code(404).send({ code: 'WORKSPACE_NOT_FOUND' });
23
+ return reply.code(503).send({ code: 'PLAN_ARCHIVE_UNAVAILABLE' });
24
+ }
25
+ });
26
+ }
@@ -7,7 +7,7 @@ export function registerListWorkspacePlans(app, deps) {
7
7
  app.get('/api/workspaces/:workspaceId/plans', async (request, reply) => {
8
8
  try {
9
9
  const workspace = await deps.workspaces.resolve(request.params.workspaceId);
10
- return reply.send(await deps.plans.list(workspace.realPath));
10
+ return reply.send(await deps.plans.list(workspace.realPath, true));
11
11
  }
12
12
  catch (error) {
13
13
  if (error instanceof Error && error.message === 'WORKSPACE_NOT_FOUND')
@@ -9,6 +9,7 @@ import { registerGetPlan } from './get-plan/endpoint.js';
9
9
  import { registerGetWorkspacePlan } from './get-workspace-plan/endpoint.js';
10
10
  import { registerListWorkspacePlans } from './list-workspace-plans/endpoint.js';
11
11
  import { registerOpenPlan } from './open-plan/endpoint.js';
12
+ import { registerArchiveWorkspacePlan } from './archive-workspace-plan/endpoint.js';
12
13
  export function registerPlanRoutes(app, deps) {
13
14
  if (deps.planRoutes) {
14
15
  registerGetPlan(app, deps.planRoutes);
@@ -18,6 +19,11 @@ export function registerPlanRoutes(app, deps) {
18
19
  if (deps.workspacePlanRoutes) {
19
20
  registerListWorkspacePlans(app, deps.workspacePlanRoutes);
20
21
  registerGetWorkspacePlan(app, deps.workspacePlanRoutes);
22
+ if (deps.workspacePlanRoutes.archiver)
23
+ registerArchiveWorkspacePlan(app, {
24
+ workspaces: deps.workspacePlanRoutes.workspaces,
25
+ archiver: deps.workspacePlanRoutes.archiver,
26
+ });
21
27
  }
22
28
  if (deps.planMeasurementRoutes)
23
29
  registerGetPlanMeasurement(app, deps.planMeasurementRoutes);
@@ -59,6 +59,7 @@ export class RelaySession {
59
59
  provider: input.provider,
60
60
  profile: profileName(input.profile),
61
61
  ...(input.model === undefined ? {} : { model: input.model }),
62
+ ...(input.modelSettings === undefined ? {} : { modelSettings: { ...input.modelSettings } }),
62
63
  ...(input.branch === undefined ? {} : { branch: input.branch }),
63
64
  effectiveSkillSelection: createEffectiveSkillSelection(input.effectiveSkillSelection),
64
65
  executionPolicy: createSessionExecutionPolicy(input),
@@ -173,6 +174,7 @@ export class RelaySession {
173
174
  function copy(snapshot) {
174
175
  return {
175
176
  ...snapshot,
177
+ ...(snapshot.modelSettings ? { modelSettings: { ...snapshot.modelSettings } } : {}),
176
178
  ...(snapshot.effectiveSkillSelection === undefined
177
179
  ? {}
178
180
  : {
@@ -30,6 +30,12 @@ export function registerStartSession(app, deps) {
30
30
  }
31
31
  catch (error) {
32
32
  deps.reportFailure?.('start-session', error);
33
+ if (error instanceof Error &&
34
+ ['ORG_EXECUTOR_PROFILE_UNAVAILABLE', 'ORG_EXECUTOR_PROFILE_INVALID'].includes(error.message))
35
+ return reply
36
+ .code(503)
37
+ .type('application/problem+json')
38
+ .send(problem(error.message, 503, 'The installed Org-plan executor profile could not be configured. Restore the Gestalt agent profile and retry.'));
33
39
  if (error instanceof SkillProfileError)
34
40
  return reply
35
41
  .code(400)
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { z } from 'zod';
7
+ import { thinkingLevels } from '../../../../shared/contracts/session-model-settings.js';
7
8
  const schema = z.object({
8
9
  workspaceId: z.string().min(1),
9
10
  provider: z.enum(['codex', 'kimi']),
@@ -14,6 +15,9 @@ const schema = z.object({
14
15
  .trim()
15
16
  .optional()
16
17
  .transform((value) => value || undefined),
18
+ reasoningEffort: z.enum(thinkingLevels).optional(),
19
+ executorModel: z.string().trim().min(1).max(256).optional(),
20
+ executorReasoningEffort: z.enum(thinkingLevels).optional(),
17
21
  sandbox: z
18
22
  .enum(['workspace-git', 'read-only', 'workspace-write', 'danger-full-access'])
19
23
  .optional(),
@@ -62,6 +62,18 @@ export async function startSession(input, deps) {
62
62
  provider: input.provider,
63
63
  profile: input.profile,
64
64
  model,
65
+ ...(input.provider === 'codex' &&
66
+ (input.reasoningEffort || input.executorModel || input.executorReasoningEffort)
67
+ ? {
68
+ modelSettings: {
69
+ ...(input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {}),
70
+ ...(input.executorModel ? { executorModel: input.executorModel } : {}),
71
+ ...(input.executorReasoningEffort
72
+ ? { executorReasoningEffort: input.executorReasoningEffort }
73
+ : {}),
74
+ },
75
+ }
76
+ : {}),
65
77
  ...(branch ? { branch } : {}),
66
78
  sandbox: input.sandbox,
67
79
  approvalPolicy: input.approvalPolicy,
@@ -15,6 +15,9 @@ export class FilesystemWorkspaceCatalog {
15
15
  return [(await this.tree()).option];
16
16
  }
17
17
  async resolve(id) {
18
+ const root = await this.root;
19
+ if (id === this.id(root))
20
+ return { id, name: '/', realPath: root };
18
21
  const found = this.find(await this.tree(), id);
19
22
  if (!found)
20
23
  throw new Error('WORKSPACE_NOT_FOUND');
@@ -47,7 +47,8 @@ async function listProfileThreads(launch, profile, cwd) {
47
47
  limit: 20,
48
48
  sortKey: 'recency_at',
49
49
  sortDirection: 'desc',
50
- sourceKinds: ['cli', 'appServer'],
50
+ sourceKinds: ['cli', 'vscode', 'appServer'],
51
+ modelProviders: [],
51
52
  }));
52
53
  return (result.data ?? []).flatMap((thread) => {
53
54
  if (typeof thread.id !== 'string' || typeof thread.cwd !== 'string')
@@ -0,0 +1,104 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ import { createHash, randomUUID } from 'node:crypto';
7
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
8
+ import { join } from 'node:path';
9
+ /** Finds root assignments without treating instruction strings or TOML tables as settings. */
10
+ function replaceRootSetting(profile, key, value) {
11
+ const lines = profile.split('\n');
12
+ let stringDelimiter = null;
13
+ let rootEnd = lines.length;
14
+ const assignments = [];
15
+ for (let index = 0; index < lines.length; index += 1) {
16
+ const line = lines[index];
17
+ if (!stringDelimiter) {
18
+ if (/^\s*\[/.test(line)) {
19
+ rootEnd = index;
20
+ break;
21
+ }
22
+ if (new RegExp(`^\\s*${key}\\s*=`).test(line))
23
+ assignments.push(index);
24
+ }
25
+ for (let offset = 0; offset < line.length; offset += 1) {
26
+ const character = line[offset];
27
+ if (stringDelimiter) {
28
+ if (stringDelimiter.startsWith('"') && character === '\\') {
29
+ offset += 1;
30
+ }
31
+ else if (line.startsWith(stringDelimiter, offset)) {
32
+ offset += stringDelimiter.length - 1;
33
+ stringDelimiter = null;
34
+ }
35
+ }
36
+ else if (character === '#') {
37
+ break;
38
+ }
39
+ else if (character === '"' || character === "'") {
40
+ stringDelimiter = line.startsWith(character.repeat(3), offset)
41
+ ? character.repeat(3)
42
+ : character;
43
+ offset += stringDelimiter.length - 1;
44
+ }
45
+ }
46
+ if (stringDelimiter?.length === 1)
47
+ throw new Error('ORG_EXECUTOR_PROFILE_INVALID');
48
+ }
49
+ if (stringDelimiter || assignments.length > 1)
50
+ throw new Error('ORG_EXECUTOR_PROFILE_INVALID');
51
+ const assignment = `${key} = ${JSON.stringify(value)}`;
52
+ if (assignments.length)
53
+ lines[assignments[0]] = assignment;
54
+ else
55
+ lines.splice(rootEnd, 0, assignment);
56
+ return lines.join('\n');
57
+ }
58
+ /** Keeps installed Org role instructions while pinning settings only for the owning session. */
59
+ export class SessionModelConfig {
60
+ codexHome;
61
+ stateDirectory;
62
+ constructor(codexHome, stateDirectory) {
63
+ this.codexHome = codexHome;
64
+ this.stateDirectory = stateDirectory;
65
+ }
66
+ async resolve(session) {
67
+ const settings = session.modelSettings;
68
+ if (!settings)
69
+ return {};
70
+ const config = settings.reasoningEffort
71
+ ? { model_reasoning_effort: settings.reasoningEffort }
72
+ : {};
73
+ if (!settings.executorModel && !settings.executorReasoningEffort)
74
+ return config;
75
+ let profile;
76
+ try {
77
+ profile = await readFile(join(this.codexHome, 'agents', 'org-plan-executor.toml'), 'utf8');
78
+ }
79
+ catch {
80
+ throw new Error('ORG_EXECUTOR_PROFILE_UNAVAILABLE');
81
+ }
82
+ for (const [key, value] of [
83
+ ['model', settings.executorModel],
84
+ ['model_reasoning_effort', settings.executorReasoningEffort],
85
+ ]) {
86
+ if (!value)
87
+ continue;
88
+ profile = replaceRootSetting(profile, key, value);
89
+ }
90
+ const directory = join(this.stateDirectory, 'agent-profiles');
91
+ await mkdir(directory, { recursive: true, mode: 0o700 });
92
+ const name = createHash('sha256').update(session.id).digest('hex');
93
+ const path = join(directory, `${name}.toml`);
94
+ const temporary = `${path}.${randomUUID()}.tmp`;
95
+ try {
96
+ await writeFile(temporary, profile, { flag: 'wx', mode: 0o600 });
97
+ await rename(temporary, path);
98
+ }
99
+ finally {
100
+ await rm(temporary, { force: true });
101
+ }
102
+ return { ...config, agents: { 'org-plan-executor': { config_file: path } } };
103
+ }
104
+ }
@@ -18,14 +18,22 @@ import { WriterAcquisitionError, } from '../../features/sessions/application/wri
18
18
  import { isCodexThreadWriterBusy, isMissingCodexThreadRollout } from './json-rpc-client.js';
19
19
  import { resolvedServerRequestId } from './server-request.js';
20
20
  /** Sticky thread config keeps skill paths out of the app-server process argv. */
21
- export function threadSkillConfig(skillsConfig) {
22
- return skillsConfig === undefined ? {} : { config: { skills: { config: skillsConfig } } };
21
+ export function threadSkillConfig(skillsConfig, modelConfig = {}) {
22
+ return skillsConfig === undefined && !Object.keys(modelConfig).length
23
+ ? {}
24
+ : {
25
+ config: {
26
+ ...modelConfig,
27
+ ...(skillsConfig === undefined ? {} : { skills: { config: skillsConfig } }),
28
+ },
29
+ };
23
30
  }
24
31
  /** One private owner for every resource acquired for a live Codex child. */
25
32
  class SessionResource {
26
33
  sessionId;
27
34
  process;
28
35
  skillsConfig;
36
+ modelConfig;
29
37
  planStatusLease;
30
38
  planMeasurementToken;
31
39
  unregister;
@@ -44,10 +52,11 @@ class SessionResource {
44
52
  completedProcessActions = new Map();
45
53
  turnThreads = new Map();
46
54
  childThreads = new Set();
47
- constructor(sessionId, process, skillsConfig, planStatusLease, planMeasurementToken, unregister, onDisposed) {
55
+ constructor(sessionId, process, skillsConfig, modelConfig, planStatusLease, planMeasurementToken, unregister, onDisposed) {
48
56
  this.sessionId = sessionId;
49
57
  this.process = process;
50
58
  this.skillsConfig = skillsConfig;
59
+ this.modelConfig = modelConfig;
51
60
  this.planStatusLease = planStatusLease;
52
61
  this.planMeasurementToken = planMeasurementToken;
53
62
  this.unregister = unregister;
@@ -92,13 +101,14 @@ export class CodexSessionRuntime {
92
101
  planMeasurementBaseUrl;
93
102
  maxPendingRequests;
94
103
  readerCwd;
104
+ resolveModelConfig;
95
105
  serverResponseListeners = new Set();
96
106
  constructor(launch,
97
107
  // Kept as an ignored compatibility slot while callers migrate from the old
98
108
  // correlated-map constructor shape. Live ownership is `sessions` only.
99
109
  _legacyProcesses = undefined, onNotification, onServerRequest, onProcessExit, resolveSkills, planStatusSource, onPlanStatus, planMeasurementBaseUrl,
100
110
  // Compatibility slot: blocking app-server requests wait for explicit input.
101
- _legacyRequestTimeoutMs = undefined, maxPendingRequests = 64, readerCwd) {
111
+ _legacyRequestTimeoutMs = undefined, maxPendingRequests = 64, readerCwd, resolveModelConfig) {
102
112
  this.launch = launch;
103
113
  this.onNotification = onNotification;
104
114
  this.onServerRequest = onServerRequest;
@@ -109,6 +119,7 @@ export class CodexSessionRuntime {
109
119
  this.planMeasurementBaseUrl = planMeasurementBaseUrl;
110
120
  this.maxPendingRequests = maxPendingRequests;
111
121
  this.readerCwd = readerCwd;
122
+ this.resolveModelConfig = resolveModelConfig;
112
123
  void _legacyProcesses;
113
124
  void _legacyRequestTimeoutMs;
114
125
  }
@@ -123,7 +134,7 @@ export class CodexSessionRuntime {
123
134
  clientInfo: { name: 'gestalt-mobile', version: '0.1.0' },
124
135
  capabilities: { experimentalApi: true },
125
136
  });
126
- const startedThreadId = await this.startThread(resource.process, session, resource.skillsConfig);
137
+ const startedThreadId = await this.startThread(resource.process, session, resource.skillsConfig, resource.modelConfig);
127
138
  resource.threadId = startedThreadId;
128
139
  this.sessions.set(session.id, resource);
129
140
  await this.writePendingThreadName(session.id);
@@ -224,6 +235,9 @@ export class CodexSessionRuntime {
224
235
  input: [{ type: 'text', text, text_elements: [] }],
225
236
  ...(clientUserMessageId ? { clientUserMessageId } : {}),
226
237
  ...(session.model ? { model: session.model } : {}),
238
+ ...(session.modelSettings?.reasoningEffort
239
+ ? { effort: session.modelSettings.reasoningEffort }
240
+ : {}),
227
241
  }));
228
242
  resource.turnThreads.set(result, session.threadId);
229
243
  return RelaySession.rehydrate(session).startTurn(result, now).snapshot;
@@ -236,7 +250,12 @@ export class CodexSessionRuntime {
236
250
  threadId: childThreadId,
237
251
  input: [{ type: 'text', text, text_elements: [] }],
238
252
  clientUserMessageId,
239
- ...(session.model ? { model: session.model } : {}),
253
+ ...(session.modelSettings?.executorModel
254
+ ? { model: session.modelSettings.executorModel }
255
+ : {}),
256
+ ...(session.modelSettings?.executorReasoningEffort
257
+ ? { effort: session.modelSettings.executorReasoningEffort }
258
+ : {}),
240
259
  }));
241
260
  if (resource.turnThreads.has(result) || resource.turnThreads.size < 256)
242
261
  resource.turnThreads.set(result, childThreadId);
@@ -677,7 +696,7 @@ export class CodexSessionRuntime {
677
696
  await resource.process.rpc.request('thread/resume', {
678
697
  threadId: session.threadId,
679
698
  cwd: session.workspacePath,
680
- ...threadSkillConfig(resource.skillsConfig),
699
+ ...threadSkillConfig(resource.skillsConfig, resource.modelConfig),
681
700
  ...(session.executionPolicy?.approvalPolicy
682
701
  ? { approvalPolicy: session.executionPolicy.approvalPolicy }
683
702
  : {}),
@@ -699,7 +718,7 @@ export class CodexSessionRuntime {
699
718
  catch (error) {
700
719
  if (!canRebindMissingRollout(session, error))
701
720
  throw error;
702
- const replacementThreadId = await this.startThread(resource.process, session, resource.skillsConfig);
721
+ const replacementThreadId = await this.startThread(resource.process, session, resource.skillsConfig, resource.modelConfig);
703
722
  result = rebindMissingRollout(session, error, replacementThreadId, now);
704
723
  }
705
724
  resource.threadId = result.session.threadId;
@@ -767,13 +786,13 @@ export class CodexSessionRuntime {
767
786
  reject(new Error('CODEX_SERVER_REQUEST_UNSUPPORTED'));
768
787
  });
769
788
  }
770
- async startThread(process, session, skillsConfig) {
771
- return decodeThreadStart(await process.rpc.request('thread/start', this.threadStartParams(session, skillsConfig)));
789
+ async startThread(process, session, skillsConfig, modelConfig = {}) {
790
+ return decodeThreadStart(await process.rpc.request('thread/start', this.threadStartParams(session, skillsConfig, modelConfig)));
772
791
  }
773
- threadStartParams(session, skillsConfig) {
792
+ threadStartParams(session, skillsConfig, modelConfig = {}) {
774
793
  return {
775
794
  cwd: session.workspacePath,
776
- ...threadSkillConfig(skillsConfig),
795
+ ...threadSkillConfig(skillsConfig, modelConfig),
777
796
  approvalPolicy: session.executionPolicy?.approvalPolicy ?? 'on-request',
778
797
  dynamicTools: [
779
798
  gestaltQuizDynamicTool,
@@ -801,6 +820,7 @@ export class CodexSessionRuntime {
801
820
  try {
802
821
  const token = randomUUID();
803
822
  const skillsConfig = await this.resolveSkills?.(session);
823
+ const modelConfig = (await this.resolveModelConfig?.(session)) ?? {};
804
824
  const process = this.launch({
805
825
  profile: session.profile,
806
826
  cwd: session.workspacePath,
@@ -820,7 +840,7 @@ export class CodexSessionRuntime {
820
840
  }
821
841
  : {}),
822
842
  });
823
- const resource = new SessionResource(session.id, process, skillsConfig, lease, token, [], () => {
843
+ const resource = new SessionResource(session.id, process, skillsConfig, modelConfig, lease, token, [], () => {
824
844
  if (this.sessions.get(session.id) === resource)
825
845
  this.sessions.delete(session.id);
826
846
  });
@@ -94,6 +94,105 @@ export class FilesystemWorkspaceFiles {
94
94
  : { kind: 'unreadable' };
95
95
  }
96
96
  }
97
+ async exists(rootPath, requestedPath) {
98
+ const root = await this.canonicalDirectory(rootPath);
99
+ if (!root)
100
+ return false;
101
+ const target = resolve(root, requestedPath);
102
+ if (!within(root, target))
103
+ return false;
104
+ const path = relative(root, target).split(sep).join('/');
105
+ if (path !== '' && !validRelative(path))
106
+ return false;
107
+ const parent = await anchoredDirectory(root, dirnameRelative(path));
108
+ if (!parent)
109
+ return false;
110
+ try {
111
+ if (!(await stableAnchor(root, dirnameRelative(path), parent.path)))
112
+ return false;
113
+ const handle = await open(path ? join(parent.path, basename(path)) : `${parent.path}/.`, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
114
+ try {
115
+ const metadata = await handle.stat();
116
+ return ((metadata.isFile() || metadata.isDirectory()) &&
117
+ within(root, await realpath(procPath(handle.fd))));
118
+ }
119
+ finally {
120
+ await handle.close();
121
+ }
122
+ }
123
+ catch {
124
+ return false;
125
+ }
126
+ finally {
127
+ await parent.close();
128
+ }
129
+ }
130
+ async read(rootPath, requestedPath) {
131
+ const root = await this.canonicalDirectory(rootPath);
132
+ if (!root)
133
+ return { kind: 'unreadable' };
134
+ const target = resolve(root, requestedPath);
135
+ if (!within(root, target))
136
+ return { kind: 'unreadable' };
137
+ const path = relative(root, target).split(sep).join('/');
138
+ if (path !== '' && !validRelative(path))
139
+ return { kind: 'unreadable' };
140
+ const parentPath = dirnameRelative(path);
141
+ const parent = await anchoredDirectory(root, parentPath);
142
+ if (!parent)
143
+ return { kind: 'unreadable' };
144
+ try {
145
+ if (!(await stableAnchor(root, parentPath, parent.path)))
146
+ return { kind: 'unreadable' };
147
+ const handle = await open(path ? join(parent.path, basename(path)) : `${parent.path}/.`, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
148
+ try {
149
+ const metadata = await handle.stat();
150
+ if (!within(root, await realpath(procPath(handle.fd))))
151
+ return { kind: 'unreadable' };
152
+ if (metadata.isDirectory())
153
+ return { kind: 'available', preview: { kind: 'directory', path } };
154
+ if (!metadata.isFile())
155
+ return { kind: 'unsupported' };
156
+ const limit = 1024 * 1024;
157
+ if (metadata.size > limit)
158
+ return { kind: 'too-large' };
159
+ const buffer = Buffer.alloc(limit + 1);
160
+ let size = 0;
161
+ while (size < buffer.length) {
162
+ const read = await handle.read(buffer, size, buffer.length - size, size);
163
+ if (!read.bytesRead)
164
+ break;
165
+ size += read.bytesRead;
166
+ }
167
+ if (size > limit)
168
+ return { kind: 'too-large' };
169
+ if (!(await stableAnchor(root, parentPath, parent.path)) ||
170
+ !within(root, await realpath(procPath(handle.fd))))
171
+ return { kind: 'unreadable' };
172
+ const bytes = buffer.subarray(0, size);
173
+ if (bytes.includes(0))
174
+ return { kind: 'unsupported' };
175
+ try {
176
+ const content = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
177
+ return { kind: 'available', preview: { kind: 'file', path, content, size } };
178
+ }
179
+ catch {
180
+ return { kind: 'unsupported' };
181
+ }
182
+ }
183
+ finally {
184
+ await handle.close();
185
+ }
186
+ }
187
+ catch (error) {
188
+ return {
189
+ kind: error.code === 'ENOENT' ? 'missing' : 'unreadable',
190
+ };
191
+ }
192
+ finally {
193
+ await parent.close();
194
+ }
195
+ }
97
196
  async copy(rootPath, input) {
98
197
  return this.transfer(rootPath, input, false);
99
198
  }
@@ -0,0 +1,42 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
7
+ import { join } from 'node:path';
8
+ import { randomUUID } from 'node:crypto';
9
+ import { sessionDefaultsSchema, } from '../../../shared/contracts/session-defaults.js';
10
+ export class FilesystemSessionDefaults {
11
+ directory;
12
+ path;
13
+ constructor(homeDirectory) {
14
+ this.directory = join(homeDirectory, '.gestalt');
15
+ this.path = join(this.directory, 'session-defaults.json');
16
+ }
17
+ async read() {
18
+ try {
19
+ return sessionDefaultsSchema.parse(JSON.parse(await readFile(this.path, 'utf8')));
20
+ }
21
+ catch (error) {
22
+ if (error.code === 'ENOENT')
23
+ return null;
24
+ throw error;
25
+ }
26
+ }
27
+ async save(defaults) {
28
+ const validated = sessionDefaultsSchema.parse(defaults);
29
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
30
+ const temporary = `${this.path}.${randomUUID()}.tmp`;
31
+ try {
32
+ await writeFile(temporary, `${JSON.stringify(validated, null, 2)}\n`, {
33
+ mode: 0o600,
34
+ flag: 'wx',
35
+ });
36
+ await rename(temporary, this.path);
37
+ }
38
+ finally {
39
+ await rm(temporary, { force: true });
40
+ }
41
+ }
42
+ }
@@ -34,6 +34,8 @@ export function migrate(database) {
34
34
  database.exec('ALTER TABLE relay_sessions ADD COLUMN effective_skill_selection_json TEXT');
35
35
  if (!columns.some((column) => column.name === 'last_org_plan_json'))
36
36
  database.exec('ALTER TABLE relay_sessions ADD COLUMN last_org_plan_json TEXT');
37
+ if (!columns.some((column) => column.name === 'model_settings_json'))
38
+ database.exec('ALTER TABLE relay_sessions ADD COLUMN model_settings_json TEXT');
37
39
  if (!columns.some((column) => column.name === 'model'))
38
40
  database.exec('ALTER TABLE relay_sessions ADD COLUMN model TEXT');
39
41
  if (!columns.some((column) => column.name === 'branch'))
@@ -11,10 +11,10 @@ export class SqliteSessionRepository {
11
11
  }
12
12
  save(session) {
13
13
  this.db
14
- .prepare('INSERT INTO relay_sessions (id,workspace_id,workspace_path,provider,profile,model,branch,sandbox,approval_policy,thread_id,state,desired_state,active_turn_id,protocol_version,attention_tool_capability,failure_count,effective_skill_selection_json,last_org_plan_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET workspace_id=excluded.workspace_id,workspace_path=excluded.workspace_path,provider=excluded.provider,profile=excluded.profile,model=excluded.model,branch=excluded.branch,sandbox=excluded.sandbox,approval_policy=excluded.approval_policy,thread_id=excluded.thread_id,state=excluded.state,desired_state=excluded.desired_state,active_turn_id=excluded.active_turn_id,protocol_version=excluded.protocol_version,attention_tool_capability=excluded.attention_tool_capability,failure_count=excluded.failure_count,effective_skill_selection_json=excluded.effective_skill_selection_json,last_org_plan_json=excluded.last_org_plan_json,updated_at=excluded.updated_at')
14
+ .prepare('INSERT INTO relay_sessions (id,workspace_id,workspace_path,provider,profile,model,branch,sandbox,approval_policy,thread_id,state,desired_state,active_turn_id,protocol_version,attention_tool_capability,failure_count,effective_skill_selection_json,last_org_plan_json,model_settings_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET workspace_id=excluded.workspace_id,workspace_path=excluded.workspace_path,provider=excluded.provider,profile=excluded.profile,model=excluded.model,branch=excluded.branch,sandbox=excluded.sandbox,approval_policy=excluded.approval_policy,thread_id=excluded.thread_id,state=excluded.state,desired_state=excluded.desired_state,active_turn_id=excluded.active_turn_id,protocol_version=excluded.protocol_version,attention_tool_capability=excluded.attention_tool_capability,failure_count=excluded.failure_count,effective_skill_selection_json=excluded.effective_skill_selection_json,last_org_plan_json=excluded.last_org_plan_json,model_settings_json=excluded.model_settings_json,updated_at=excluded.updated_at')
15
15
  .run(session.id, session.workspaceId, session.workspacePath, session.provider, session.profile, session.model ?? null, session.branch ?? null, session.executionPolicy?.sandbox ?? null, session.executionPolicy?.approvalPolicy ?? null, session.threadId, session.state, session.desiredState, session.activeTurnId, session.protocolVersion, session.attentionToolCapability ?? null, session.failureCount, session.effectiveSkillSelection === undefined
16
16
  ? null
17
- : JSON.stringify(session.effectiveSkillSelection), session.lastOrgPlan === undefined ? null : JSON.stringify(session.lastOrgPlan), session.createdAt, session.updatedAt);
17
+ : JSON.stringify(session.effectiveSkillSelection), session.lastOrgPlan === undefined ? null : JSON.stringify(session.lastOrgPlan), session.modelSettings === undefined ? null : JSON.stringify(session.modelSettings), session.createdAt, session.updatedAt);
18
18
  }
19
19
  find(id) {
20
20
  const row = this.db.prepare('SELECT * FROM relay_sessions WHERE id = ?').get(id);
@@ -48,6 +48,11 @@ function map(row) {
48
48
  provider: row.provider === 'kimi' ? 'kimi' : 'codex',
49
49
  profile: row.profile,
50
50
  ...(row.model === null ? {} : { model: row.model }),
51
+ ...(row.model_settings_json
52
+ ? {
53
+ modelSettings: JSON.parse(row.model_settings_json),
54
+ }
55
+ : {}),
51
56
  ...(row.branch === null ? {} : { branch: row.branch }),
52
57
  ...(executionPolicy === undefined ? {} : { executionPolicy }),
53
58
  threadId: row.thread_id,